diff --git a/data/research/comfy-contract-resolution.v1.json b/data/research/comfy-contract-resolution.v1.json index 24afe07..85c3238 100644 --- a/data/research/comfy-contract-resolution.v1.json +++ b/data/research/comfy-contract-resolution.v1.json @@ -13,7 +13,7 @@ "publishesTemplates": false, "researchOnly": true }, - "contentHash": "sha256:425d20ad21a3c8b86d66d7e254f65be47a98999758f5ffdf71e0ea79c8725214", + "contentHash": "sha256:ed9cf2796b2d9468d520e85f79ac834ffc2a18cadd17dff8ce00de23fc797d81", "contractKind": "non_executable_comfy_contract_resolution_ledger", "resolutions": [ { @@ -16499,14 +16499,14 @@ "sha256": "sha256:d743007946b424026f86f0890bf7926953ad4808512b91018d100b4ea2940c75" }, "templateAuthoringSpecs": { - "contentHash": "sha256:f7b2e5cdf11ffe88f38d298357d48641275c69d240ff13cf6b3d39eee3cdc522", + "contentHash": "sha256:25433f08dc2d43521b16c1b6ab53e9d0dfaeb78a1e794fee7c1695df65fa0dea", "path": "data/template-authoring-specs.v1.json", - "sha256": "sha256:b4fa65929304f22cba6f6d13bb138f7188d49115f81a859b29b9b603614d2f4b" + "sha256": "sha256:17ff9c9bbe8b7283c8ff960699d4f1cbe6baae15aaa8e487328ded4601359321" }, "upstreamCoverage": { - "contentHash": "sha256:a7d36b205241f21d4067de7cc3b877c2c29538d3e2a2d965c03d670b9135f9ca", + "contentHash": "sha256:ed25c084c7fb0be603cc00e79e49d3b6dc53b053c88cd2bcd97711811eb239d1", "path": "data/upstream-coverage.v1.json", - "sha256": "sha256:6f5d0b3551c5c4c8e4f109947c8527c23f9c04d7d595ed134e2d8c82a6005cf0" + "sha256": "sha256:bfd3e3c6a565549bea2b7d545f78b89eda39129b14213f4323e73c94c8acfb83" }, "workflowManifest": { "path": "data/workflow-library-manifest.json", diff --git a/data/research/comfy-evidence-resolution.v1.json b/data/research/comfy-evidence-resolution.v1.json index 2131e5d..39b1475 100644 --- a/data/research/comfy-evidence-resolution.v1.json +++ b/data/research/comfy-evidence-resolution.v1.json @@ -16,7 +16,7 @@ "presentationMediaHints" ] }, - "contentHash": "sha256:f7fc575517953e6a7c0296851e9dde211de498a92aca36696867a50512f0634c", + "contentHash": "sha256:f18ffca9fe31ed2690729c1dad6cf4d82959a4f9b45c02b2336467c078cdc9a8", "contractKind": "non_executable_comfy_evidence_resolution_ledger", "resolutions": [ { @@ -7483,14 +7483,14 @@ "sha256": "sha256:d743007946b424026f86f0890bf7926953ad4808512b91018d100b4ea2940c75" }, "templateAuthoringSpecs": { - "contentHash": "sha256:f7b2e5cdf11ffe88f38d298357d48641275c69d240ff13cf6b3d39eee3cdc522", + "contentHash": "sha256:25433f08dc2d43521b16c1b6ab53e9d0dfaeb78a1e794fee7c1695df65fa0dea", "path": "data/template-authoring-specs.v1.json", - "sha256": "sha256:b4fa65929304f22cba6f6d13bb138f7188d49115f81a859b29b9b603614d2f4b" + "sha256": "sha256:17ff9c9bbe8b7283c8ff960699d4f1cbe6baae15aaa8e487328ded4601359321" }, "upstreamCoverage": { - "contentHash": "sha256:a7d36b205241f21d4067de7cc3b877c2c29538d3e2a2d965c03d670b9135f9ca", + "contentHash": "sha256:ed25c084c7fb0be603cc00e79e49d3b6dc53b053c88cd2bcd97711811eb239d1", "path": "data/upstream-coverage.v1.json", - "sha256": "sha256:6f5d0b3551c5c4c8e4f109947c8527c23f9c04d7d595ed134e2d8c82a6005cf0" + "sha256": "sha256:bfd3e3c6a565549bea2b7d545f78b89eda39129b14213f4323e73c94c8acfb83" }, "workflowManifest": { "path": "data/workflow-library-manifest.json", diff --git a/data/template-authoring-specs.v1.json b/data/template-authoring-specs.v1.json index f48a7d0..fc386c2 100644 --- a/data/template-authoring-specs.v1.json +++ b/data/template-authoring-specs.v1.json @@ -14,14 +14,14 @@ "selectsInputAssets": false, "studioVisible": false }, - "contentHash": "sha256:f7b2e5cdf11ffe88f38d298357d48641275c69d240ff13cf6b3d39eee3cdc522", + "contentHash": "sha256:25433f08dc2d43521b16c1b6ab53e9d0dfaeb78a1e794fee7c1695df65fa0dea", "contractKind": "non_public_template_authoring_spec_ledger", "schemaVersion": 1, "sources": { "candidateContracts": { - "contentHash": "sha256:419ecd358329d4ee720c319bb634598870f8cd463fd3f832f0f23ff1b7818679", + "contentHash": "sha256:27df3a3e7b79a359a8333700983f334398a6317ee0427784204f5edc5682f331", "path": "data/template-candidate-contracts.v1.json", - "sha256": "sha256:61546d67c49ea8dfc089522fb222a6a024750fb11aea22df3274cbbf41da2e05" + "sha256": "sha256:144696f2c50db52b6b958d92b6b2fca4e366a4137d16f96dd29ec0d1abeb22ba" }, "workflowManifest": { "path": "data/workflow-library-manifest.json", diff --git a/data/template-candidate-contracts.v1.json b/data/template-candidate-contracts.v1.json index 189306e..b292c76 100644 --- a/data/template-candidate-contracts.v1.json +++ b/data/template-candidate-contracts.v1.json @@ -11,7 +11,7 @@ "qualificationMetadataMeaning": "exact_manifest_binding_not_candidate_evidence", "studioVisible": false }, - "contentHash": "sha256:419ecd358329d4ee720c319bb634598870f8cd463fd3f832f0f23ff1b7818679", + "contentHash": "sha256:27df3a3e7b79a359a8333700983f334398a6317ee0427784204f5edc5682f331", "contractKind": "non_public_template_candidate_contract_ledger", "contracts": [ { @@ -6687,9 +6687,9 @@ "sha256": "sha256:f278e24ed314a1ab997b5521cc4c8b9576c67cdbbe76e19ffa3ce58a4593dc0e" }, "upstreamCoverage": { - "contentHash": "sha256:a7d36b205241f21d4067de7cc3b877c2c29538d3e2a2d965c03d670b9135f9ca", + "contentHash": "sha256:ed25c084c7fb0be603cc00e79e49d3b6dc53b053c88cd2bcd97711811eb239d1", "path": "data/upstream-coverage.v1.json", - "sha256": "sha256:6f5d0b3551c5c4c8e4f109947c8527c23f9c04d7d595ed134e2d8c82a6005cf0" + "sha256": "sha256:bfd3e3c6a565549bea2b7d545f78b89eda39129b14213f4323e73c94c8acfb83" }, "workflowManifest": { "path": "data/workflow-library-manifest.json", diff --git a/data/upstream-coverage.v1.json b/data/upstream-coverage.v1.json index 5af91ae..328e1a8 100644 --- a/data/upstream-coverage.v1.json +++ b/data/upstream-coverage.v1.json @@ -2339,7 +2339,7 @@ "status": "executable" } ], - "contentHash": "sha256:a7d36b205241f21d4067de7cc3b877c2c29538d3e2a2d965c03d670b9135f9ca", + "contentHash": "sha256:ed25c084c7fb0be603cc00e79e49d3b6dc53b053c88cd2bcd97711811eb239d1", "diffusersPipelines": [ { "artifactReviews": [], @@ -8667,7 +8667,7 @@ }, "qualificationBoundary": "Executable means source/graph admission only; it does not imply live output, Auto, Gallery, hardware, license, or release qualification.", "templateBundle": "web/assets/studio-templates.js", - "templateBundleSha256": "e554ddc034cb069918936aae7641bf08345d86c5d3670494dee7e13739c570b8", + "templateBundleSha256": "015acbe27676173560cb135be77e5681f9cef766ab8f29fc0f0494840ad0275b", "transformers": { "productionRuntime": { "byteSize": 11625234, diff --git a/docs/workflow-authoring-ux.md b/docs/workflow-authoring-ux.md index 2e05734..11d443b 100644 --- a/docs/workflow-authoring-ux.md +++ b/docs/workflow-authoring-ux.md @@ -27,6 +27,35 @@ conditioning or audio operations. Whole-pipeline routes expose Generate/Edit operations instead; those nodes do not claim independently replaceable denoising. Qwen-Image 2.1 uses its supported whole-pipeline route at the reviewed Diffusers pin. +## Group nodes into a reusable Block + +Select nodes and choose **Create block**. New definitions use Block V2 and can +contain existing Blocks such as Encode Inputs. Their nested contents, values and +crossing connections are retained. Existing saved definitions are not rewritten. +Creation errors appear inside the dialog. Public sockets and controls remain +available; the dialog lets you choose controls and rename ports. + +Connection validation follows executable nodes inside containers. A loader and +denoiser grouped around an external encoder can exchange values without creating +an execution cycle. Required input checks also inspect these internal nodes; a +missing model connection blocks Run and identifies the affected node or Block. + +When changing a model inside a Block, the change preview may retire untouched, +automatically derived outputs that the new route cannot provide and nobody uses. +Connected outputs, configured interfaces and preview bindings remain protected. +Incompatible contracts require repair before the change can be applied. + +Scalar inputs declared with an editor (text, number, toggle or choices) retain +both their editor and optional socket. A connection supplies the execution value +and disables the literal editor; disconnecting restores the saved fallback. +The source is shown when available. Model and media inputs retain their sockets. + +For a custom graph using Auto memory, **Graph ready · Auto check at Run** means +static graph checks passed. Run checks the exact backend resource plan before +submission. Use **Resources → Check Auto execution plan** to inspect it earlier. +Installed model files alone do not qualify a recipe; Custom memory retains your +chosen settings without claiming Auto qualification. + ## Change the model ### Guidance control visibility diff --git a/modiff/workflow_auto_resource.py b/modiff/workflow_auto_resource.py index 11a2762..f22a5db 100644 --- a/modiff/workflow_auto_resource.py +++ b/modiff/workflow_auto_resource.py @@ -310,7 +310,15 @@ def _build_workflow_auto_plan( "Use a covered batch size or select Expert." if form.get("batchSize", 1) > 1 else None ) - raise ValueError(plan.get("blockingReason") or batch_reason or "No accepted recipe preserves this graph's model, precision and requested workload.") + reason = plan.get("blockingReason") or batch_reason or ( + "No accepted recipe preserves this graph's model, precision and requested workload. " + f"Requested {repo}, {form['dtype']}, {form['quantizationMode']} quantization, " + f"{form.get('width', 'default')}x{form.get('height', 'default')}, " + f"{form.get('steps', 'default')} steps. " + "Installed model files do not establish Auto resource qualification. " + "Review the model's resource recipes or select Custom memory to keep your settings." + ) + raise ValueError(reason) candidate = candidates[0] envelope = candidate.get("requirements", {}) requirements = envelope diff --git a/modules/ModularDiffusers/embeddings.py b/modules/ModularDiffusers/embeddings.py index 8ec34db..629bccf 100644 --- a/modules/ModularDiffusers/embeddings.py +++ b/modules/ModularDiffusers/embeddings.py @@ -86,6 +86,7 @@ class EncodePrompt(NodeBase): params = { "text_encoders": { "label": "Text Encoders *", + "required": True, "type": "diffusers_auto_models", "display": "input", "onSignal": "update_node", diff --git a/tests/test_required_encoder_contract.py b/tests/test_required_encoder_contract.py new file mode 100644 index 0000000..ed8312b --- /dev/null +++ b/tests/test_required_encoder_contract.py @@ -0,0 +1,8 @@ +"""The registry must expose the model dependency before graph execution.""" +from modules.ModularDiffusers.embeddings import EncodePrompt + + +def test_prompt_encoder_requires_models_but_accepts_inline_prompt(): + assert EncodePrompt.params['text_encoders']['required'] is True + assert EncodePrompt.params['text_encoders']['display'] == 'input' + assert not EncodePrompt.params['prompt_input'].get('required', False) diff --git a/tests/test_workflow_auto_resource.py b/tests/test_workflow_auto_resource.py index 30d2b77..9285670 100644 --- a/tests/test_workflow_auto_resource.py +++ b/tests/test_workflow_auto_resource.py @@ -629,3 +629,18 @@ def test_owner_retention_normalizes_numeric_hardware_values(setup): result = plan(graph(two=True)) assert result['canAutoRun'] assert result['schedule'] is None + + +def test_unqualified_recipe_explains_installed_files_are_not_auto_proof(setup): + plan, candidate, _, _ = setup + candidate['canAutoRun'] = False + g = graph() + before = deepcopy(g) + result = plan(g) + assert not result['canAutoRun'] + message = ' '.join(result['issues']) + assert 'Installed model files do not establish Auto resource qualification' in message + assert 'test/model' in message + assert 'bfloat16' in message + assert 'Custom memory' in message + assert g == before diff --git a/web/assets/AlertDialog.js b/web/assets/AlertDialog.js index 3643370..70c6b04 100644 --- a/web/assets/AlertDialog.js +++ b/web/assets/AlertDialog.js @@ -1 +1 @@ -import{R as e,cr as n}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{in as s,rn as a}from"./studio-templates.js?v=cc046c26d6fe7aa4";var r=n();function i({opener:n,onClose:i}){return n?(0,r.jsx)(s,{open:!0,onClose:i,title:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(e,{size:20,className:"shrink-0 text-modiff-warning","aria-hidden":"true"}),(0,r.jsx)("span",{children:n.title||"Confirm action"})]}),panelClassName:"max-w-lg",footer:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a,{onClick:()=>{n?.onCancel?.(),i()},children:n.cancelText||"Cancel"}),(0,r.jsx)(a,{onClick:()=>{n?.onConfirm(),i()},tone:"primary",children:n.confirmText||"Confirm"})]}),children:(0,r.jsx)("p",{className:"text-sm leading-6 text-modiff-text",children:n.message})}):null}export{i as default}; \ No newline at end of file +import{R as e,cr as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{an as s,in as a}from"./studio-templates.js?v=ca6b74e6a02eedb3";var r=n();function i({opener:n,onClose:i}){return n?(0,r.jsx)(s,{open:!0,onClose:i,title:(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)(e,{size:20,className:"shrink-0 text-modiff-warning","aria-hidden":"true"}),(0,r.jsx)("span",{children:n.title||"Confirm action"})]}),panelClassName:"max-w-lg",footer:(0,r.jsxs)(r.Fragment,{children:[(0,r.jsx)(a,{onClick:()=>{n?.onCancel?.(),i()},children:n.cancelText||"Cancel"}),(0,r.jsx)(a,{onClick:()=>{n?.onConfirm(),i()},tone:"primary",children:n.confirmText||"Confirm"})]}),children:(0,r.jsx)("p",{className:"text-sm leading-6 text-modiff-text",children:n.message})}):null}export{i as default}; \ No newline at end of file diff --git a/web/assets/BlockInterfaceDialogContentV2.js b/web/assets/BlockInterfaceDialogContentV2.js index 660dbac..7178d86 100644 --- a/web/assets/BlockInterfaceDialogContentV2.js +++ b/web/assets/BlockInterfaceDialogContentV2.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{En as t,cr as r,dr as n,kn as i,ot as o,z as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$o as s,Hs as l,Ls as d,an as c,bs as u,un as p,ys as f}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{u as m}from"./block-composition-tools.js?v=cc046c26d6fe7aa4";var h=e(n(),1),b=r();function v({value:e,options:t,onValueChange:r,placeholder:n,disabled:i,...o}){let[a,s]=(0,h.useState)(null),l=t.find(t=>t.value===e)?.label??"";return(0,b.jsxs)("div",{className:"min-w-0",title:"string"==typeof l?l:void 0,children:[(0,b.jsx)(p,{openOnFocus:!0,wrapOptions:!0,id:o.id,invalid:o.invalid,readOnly:o.readOnly,required:o.required,size:o.size,"aria-describedby":o["aria-describedby"],"aria-label":o["aria-label"]??("string"==typeof n?n:"Search internal fields"),"data-testid":o["data-testid"],disabled:i,value:e||null,query:a??("string"==typeof l?l:""),onQueryChange:s,onFocus:e=>e.currentTarget.select(),onBlur:()=>s(null),onValueChange:e=>{"string"==typeof e&&r(e),s(null)},options:t.map(e=>({...e,label:String(e.label)})),placeholder:"string"==typeof n?n:"Search internal fields",emptyMessage:"No matching internal fields"}),"string"==typeof l&&l?(0,b.jsx)("p",{className:"mt-1 break-words text-xs text-modiff-subtle-text",children:l}):null]})}function g(e,t){if(!t)return new Set(e.effectiveGraph.nodes.map(({nodeId:e})=>e));if(!e.effectiveGraph.nodes.some(e=>e.nodeId===t))throw Error("This internal Block no longer exists. Reopen Configure Interface.");let r=s(e),n=new Set([t]);for(let i of e.effectiveGraph.nodes){let e=r.get(i.nodeId);for(;e;)e===t&&n.add(i.nodeId),e=r.get(e)}return n}function y(e,t){return[e.binding,...e.mirrorBindings??[]].every(({nodeId:e})=>t.has(e))}function x(e,t){if(t){let{boundary:r,controls:n,previews:i}=u(e,t);return structuredClone({boundary:r,controls:n,previews:i??[]})}let r=g(e,t);return structuredClone({boundary:{mode:"explicit",inputs:e.effectiveInterface.boundary.inputs.filter(e=>y(e,r)),outputs:e.effectiveInterface.boundary.outputs.filter(e=>y(e,r))},controls:e.effectiveInterface.controls.filter(e=>y(e,r))})}function w(e,t,r,n){for(let r of["instanceId","definitionRef","effectiveGraph","effectiveInterface","values"])if(JSON.stringify(e[r])!==JSON.stringify(t[r]))throw Error("This Block changed while Configure Interface was open. Reopen it before applying.");let i=g(t,n);if(n){let e=r.previews??u(t,n).previews,{boundary:i,controls:o,previews:a}=l({schemaVersion:1,boundary:r.boundary,controls:r.controls.map(e=>{let t=structuredClone(e);return delete t.defaultValue,t}),...void 0===e?{}:{previews:e}},t.effectiveGraph,n);return{boundary:i,controls:o,...void 0===a?{}:{previews:a}}}if(void 0!==r.previews)throw Error("Root preview bindings belong to the Block definition, not its effective interface.");let o=(e,t,r)=>{let n=new Set(e.filter(e=>!y(e,i)).map(r));if(t.some(e=>!y(e,i)||n.has(r(e))))throw Error("This interface change would affect another branch. Use the owning Block interface editor.");if(new Set(t.map(r)).size!==t.length)throw Error("Interface entries must have unique IDs.");let o=0;return[...e.flatMap(e=>y(e,i)?oe.portId),outputs:o(t.effectiveInterface.boundary.outputs,r.boundary.outputs,e=>e.portId)},controls:o(t.effectiveInterface.controls,r.controls,e=>e.controlId).map((e,t)=>({...e,order:t}))}}function I(e,t,r){return f(e,t,r)}function j(e){return`${e.nodeId}\0${e.outputPortId}\0${e.mediaType}`}function k(e,t){let r=d(e.effectiveGraph,t);return e.effectiveGraph.nodes.flatMap(n=>{if(!r.has(n.nodeId))return[];let i=n.data.params;return!i||"object"!=typeof i||Array.isArray(i)?[]:Object.entries(i).flatMap(([r,i])=>!i||"object"!=typeof i||Array.isArray(i)||"output"!==i.display&&!String(i.display??"").startsWith("ui_")?[]:["image","video","audio","text","file"].flatMap(o=>{let a={nodeId:n.nodeId,outputPortId:r,mediaType:o};try{l({schemaVersion:1,boundary:{mode:"explicit",inputs:[],outputs:[]},controls:[],previews:[a]},e.effectiveGraph,t)}catch{return[]}return[{key:j(a),label:`${String(n.data.label||n.nodeId)} / ${String(i.label||r)} (${o})`,binding:a}]}))})}function C({snapshot:e,subtreeId:r,previews:n,onChange:s}){let l=(0,h.useMemo)(()=>k(e,r),[e,r]),[d,u]=(0,h.useState)(""),p=l.filter(({binding:e})=>!n.some(t=>t.nodeId===e.nodeId&&t.outputPortId===e.outputPortId)),f=new Map(l.map(({key:e,label:t})=>[e,t])),m=e=>f.get(j(e))??`${e.nodeId} / ${e.outputPortId} (${e.mediaType})`,g=(e,t)=>{let r=e+t;if(r<0||r>=n.length)return;let i=[...n];[i[e],i[r]]=[i[r],i[e]],s(i)},y=n.find(e=>e.primary);return(0,b.jsxs)("section",{className:"grid gap-2","data-testid":"block-interface-previews",children:[(0,b.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Collapsed previews"}),(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Choose outputs from this Block's own nodes. This changes its preview surface only, not connections, generation settings, or the root Block's previews. Existing generated files are not deleted."}),n.map((e,r)=>(0,b.jsxs)("div",{className:"flex min-w-0 items-center gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,b.jsx)("span",{className:"min-w-0 flex-1 break-words text-sm text-modiff-text",children:m(e)}),(0,b.jsx)(c,{label:`Move preview ${m(e)} up`,size:"compact",disabled:0===r,onClick:()=>g(r,-1),children:(0,b.jsx)(t,{size:14})}),(0,b.jsx)(c,{label:`Move preview ${m(e)} down`,size:"compact",disabled:r===n.length-1,onClick:()=>g(r,1),children:(0,b.jsx)(i,{size:14})}),(0,b.jsx)(c,{label:`Remove preview ${m(e)}`,size:"compact",onClick:()=>s(n.filter((e,t)=>t!==r)),children:(0,b.jsx)(a,{size:14})})]},j(e))),n.length?null:(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No previews selected for this Block."}),(0,b.jsx)(v,{"aria-label":"Primary collapsed preview",value:y?j(y):"none",options:[{value:"none",label:"No primary preview"},...n.map(e=>({value:j(e),label:m(e)}))],onValueChange:e=>s(n.map(t=>{let r={...t};return delete r.primary,j(r)===e?{...r,primary:!0}:r}))}),(0,b.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,b.jsx)(v,{"aria-label":"Internal preview source",value:d,onValueChange:u,options:p.map(({key:e,label:t})=>({value:e,label:t})),placeholder:"Choose an internal media or text output",disabled:!p.length}),(0,b.jsx)(c,{label:"Add collapsed preview",size:"compact",disabled:!p.some(({key:e})=>e===d),onClick:()=>{let e=p.find(({key:e})=>e===d);e&&(s([...n,{...e.binding,...n.length?{}:{primary:!0}}]),u(""))},children:(0,b.jsx)(o,{size:14})})]}),l.length?null:(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No compatible media or text outputs are declared inside this Block."})]})}export{w as a,m as default,g as i,x as n,v as o,I as r,C as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{En as t,cr as r,dr as n,kn as i,ot as o,z as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Bs as s,Cs as l,Gs as d,Ss as c,dn as u,ns as p,on as f}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{u as m}from"./block-composition-tools.js?v=ca6b74e6a02eedb3";var h=e(n(),1),b=r();function v({value:e,options:t,onValueChange:r,placeholder:n,disabled:i,...o}){let[a,s]=(0,h.useState)(null),l=t.find(t=>t.value===e)?.label??"";return(0,b.jsxs)("div",{className:"min-w-0",title:"string"==typeof l?l:void 0,children:[(0,b.jsx)(u,{openOnFocus:!0,wrapOptions:!0,id:o.id,invalid:o.invalid,readOnly:o.readOnly,required:o.required,size:o.size,"aria-describedby":o["aria-describedby"],"aria-label":o["aria-label"]??("string"==typeof n?n:"Search internal fields"),"data-testid":o["data-testid"],disabled:i,value:e||null,query:a??("string"==typeof l?l:""),onQueryChange:s,onFocus:e=>e.currentTarget.select(),onBlur:()=>s(null),onValueChange:e=>{"string"==typeof e&&r(e),s(null)},options:t.map(e=>({...e,label:String(e.label)})),placeholder:"string"==typeof n?n:"Search internal fields",emptyMessage:"No matching internal fields"}),"string"==typeof l&&l?(0,b.jsx)("p",{className:"mt-1 break-words text-xs text-modiff-subtle-text",children:l}):null]})}function g(e,t){if(!t)return new Set(e.effectiveGraph.nodes.map(({nodeId:e})=>e));if(!e.effectiveGraph.nodes.some(e=>e.nodeId===t))throw Error("This internal Block no longer exists. Reopen Configure Interface.");let r=p(e),n=new Set([t]);for(let i of e.effectiveGraph.nodes){let e=r.get(i.nodeId);for(;e;)e===t&&n.add(i.nodeId),e=r.get(e)}return n}function y(e,t){return[e.binding,...e.mirrorBindings??[]].every(({nodeId:e})=>t.has(e))}function x(e,t){if(t){let{boundary:r,controls:n,previews:i}=l(e,t);return structuredClone({boundary:r,controls:n,previews:i??[]})}let r=g(e,t);return structuredClone({boundary:{mode:"explicit",inputs:e.effectiveInterface.boundary.inputs.filter(e=>y(e,r)),outputs:e.effectiveInterface.boundary.outputs.filter(e=>y(e,r))},controls:e.effectiveInterface.controls.filter(e=>y(e,r))})}function w(e,t,r,n){for(let r of["instanceId","definitionRef","effectiveGraph","effectiveInterface","values"])if(JSON.stringify(e[r])!==JSON.stringify(t[r]))throw Error("This Block changed while Configure Interface was open. Reopen it before applying.");let i=g(t,n);if(n){let e=r.previews??l(t,n).previews,{boundary:i,controls:o,previews:a}=d({schemaVersion:1,boundary:r.boundary,controls:r.controls.map(e=>{let t=structuredClone(e);return delete t.defaultValue,t}),...void 0===e?{}:{previews:e}},t.effectiveGraph,n);return{boundary:i,controls:o,...void 0===a?{}:{previews:a}}}if(void 0!==r.previews)throw Error("Root preview bindings belong to the Block definition, not its effective interface.");let o=(e,t,r)=>{let n=new Set(e.filter(e=>!y(e,i)).map(r));if(t.some(e=>!y(e,i)||n.has(r(e))))throw Error("This interface change would affect another branch. Use the owning Block interface editor.");if(new Set(t.map(r)).size!==t.length)throw Error("Interface entries must have unique IDs.");let o=0;return[...e.flatMap(e=>y(e,i)?oe.portId),outputs:o(t.effectiveInterface.boundary.outputs,r.boundary.outputs,e=>e.portId)},controls:o(t.effectiveInterface.controls,r.controls,e=>e.controlId).map((e,t)=>({...e,order:t}))}}function I(e,t,r){return c(e,t,r)}function j(e){return`${e.nodeId}\0${e.outputPortId}\0${e.mediaType}`}function k(e,t){let r=s(e.effectiveGraph,t);return e.effectiveGraph.nodes.flatMap(n=>{if(!r.has(n.nodeId))return[];let i=n.data.params;return!i||"object"!=typeof i||Array.isArray(i)?[]:Object.entries(i).flatMap(([r,i])=>!i||"object"!=typeof i||Array.isArray(i)||"output"!==i.display&&!String(i.display??"").startsWith("ui_")?[]:["image","video","audio","text","file"].flatMap(o=>{let a={nodeId:n.nodeId,outputPortId:r,mediaType:o};try{d({schemaVersion:1,boundary:{mode:"explicit",inputs:[],outputs:[]},controls:[],previews:[a]},e.effectiveGraph,t)}catch{return[]}return[{key:j(a),label:`${String(n.data.label||n.nodeId)} / ${String(i.label||r)} (${o})`,binding:a}]}))})}function C({snapshot:e,subtreeId:r,previews:n,onChange:s}){let l=(0,h.useMemo)(()=>k(e,r),[e,r]),[d,c]=(0,h.useState)(""),u=l.filter(({binding:e})=>!n.some(t=>t.nodeId===e.nodeId&&t.outputPortId===e.outputPortId)),p=new Map(l.map(({key:e,label:t})=>[e,t])),m=e=>p.get(j(e))??`${e.nodeId} / ${e.outputPortId} (${e.mediaType})`,g=(e,t)=>{let r=e+t;if(r<0||r>=n.length)return;let i=[...n];[i[e],i[r]]=[i[r],i[e]],s(i)},y=n.find(e=>e.primary);return(0,b.jsxs)("section",{className:"grid gap-2","data-testid":"block-interface-previews",children:[(0,b.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Collapsed previews"}),(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Choose outputs from this Block's own nodes. This changes its preview surface only, not connections, generation settings, or the root Block's previews. Existing generated files are not deleted."}),n.map((e,r)=>(0,b.jsxs)("div",{className:"flex min-w-0 items-center gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,b.jsx)("span",{className:"min-w-0 flex-1 break-words text-sm text-modiff-text",children:m(e)}),(0,b.jsx)(f,{label:`Move preview ${m(e)} up`,size:"compact",disabled:0===r,onClick:()=>g(r,-1),children:(0,b.jsx)(t,{size:14})}),(0,b.jsx)(f,{label:`Move preview ${m(e)} down`,size:"compact",disabled:r===n.length-1,onClick:()=>g(r,1),children:(0,b.jsx)(i,{size:14})}),(0,b.jsx)(f,{label:`Remove preview ${m(e)}`,size:"compact",onClick:()=>s(n.filter((e,t)=>t!==r)),children:(0,b.jsx)(a,{size:14})})]},j(e))),n.length?null:(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No previews selected for this Block."}),(0,b.jsx)(v,{"aria-label":"Primary collapsed preview",value:y?j(y):"none",options:[{value:"none",label:"No primary preview"},...n.map(e=>({value:j(e),label:m(e)}))],onValueChange:e=>s(n.map(t=>{let r={...t};return delete r.primary,j(r)===e?{...r,primary:!0}:r}))}),(0,b.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,b.jsx)(v,{"aria-label":"Internal preview source",value:d,onValueChange:c,options:u.map(({key:e,label:t})=>({value:e,label:t})),placeholder:"Choose an internal media or text output",disabled:!u.length}),(0,b.jsx)(f,{label:"Add collapsed preview",size:"compact",disabled:!u.some(({key:e})=>e===d),onClick:()=>{let e=u.find(({key:e})=>e===d);e&&(s([...n,{...e.binding,...n.length?{}:{primary:!0}}]),c(""))},children:(0,b.jsx)(o,{size:14})})]}),l.length?null:(0,b.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No compatible media or text outputs are declared inside this Block."})]})}export{w as a,m as default,g as i,x as n,v as o,I as r,C as t}; \ No newline at end of file diff --git a/web/assets/BlockModelTaskControls.js b/web/assets/BlockModelTaskControls.js index b5a6298..f4bc7e1 100644 --- a/web/assets/BlockModelTaskControls.js +++ b/web/assets/BlockModelTaskControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ci as i,Ei as n,Eo as r,Hr as s,Kr as l,Ti as o,Vr as d,Xr as c,Ya as u,bn as f,dn as p,fn as h,in as m,is as g,ji as b,la as w,qr as x,rn as k}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as j}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";var v=e(a(),1),C=t();function y({node:e}){let t=c(e=>e.library),a=c(e=>e.error),y=b(e=>e.activeWorkflowTabId),[S,I]=(0,v.useState)(""),[R,N]=(0,v.useState)(!1),[E,T]=(0,v.useState)(null),[F,V]=(0,v.useState)(null),O=(0,v.useRef)(null),q=e.data.blockInstanceV2,_=(t?.definitions??[]).flatMap(e=>e.executionAdmissions.filter(t=>"admitted"===t.status&&t.publication.insertable&&"graph_qualified"===t.publication.readiness&&w(e,t)).map(t=>({definition:e,admission:t}))),A=Object.entries(q.routeSelection?.inactiveDrafts??{});return(0,v.useEffect)(()=>(O.current?.abort(),O.current=null,N(!1),T(null),V(null),()=>{O.current?.abort()}),[y,e.id,S]),(0,C.jsxs)(p,{label:"Change model / task",panelClassName:"grid gap-2 py-2",children:[(0,C.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Choose a reviewed workflow. The current composition and custom edits remain available as a saved draft in this workflow; compatible public values carry across."}),(0,C.jsx)(k,{onClick:()=>{c.getState().fetchLibrary()},disabled:R,children:t?"Refresh workflows":"Load workflows"}),a?(0,C.jsx)("p",{role:"alert",children:a}):null,(0,C.jsx)(h,{label:"Workflow",children:(0,C.jsx)(f,{"aria-label":"Replacement Block workflow",value:S,onValueChange:I,options:[{value:"",label:"Select a model and task"},...A.map(([e,t])=>({value:`draft:${e}`,label:`Restore draft · ${t.definitionSnapshot.displayName}`})),..._.filter(e=>e.admission.id!==q.definitionRef.definitionId).map(e=>({value:e.admission.id,label:`${e.definition.label} · ${e.admission.studioMode??e.definition.workflowId}`}))]})}),(0,C.jsx)(k,{disabled:R||!S,onClick:()=>{!async function(){if(O.current||!S)return;let t=new AbortController;O.current=t;let a=n(),c=d.getState().toObject(),f=JSON.stringify(c);N(!0),T(null);try{let n,r=c.nodes.find(t=>t.id===e.id)?.data.blockInstanceV2;if(!r)throw Error("The owning Block is unavailable.");if(S.startsWith("draft:"))n=l(r,S.slice(6));else{let e=_.find(e=>e.admission.id===S);if(!e)throw Error("Reload the catalog and select an available workflow.");let{createHuggingFaceClusterForGraph:a}=await i(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=cc046c26d6fe7aa4`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]),s=u(e.admission.studioMode,e.definition.pipelineClass),l=await a(e.definition,r.presentation.position,s,{insert:!1,signal:t.signal});if(!l.data.blockInstanceV2||l.data.blockInstanceV2.definitionRef.definitionId!==e.admission.id)throw Error("The compiler returned a different workflow. No changes were applied.");n=x(r,l.data.blockInstanceV2)}if(t.signal.aborted)return;if(o(a,{includeForm:!1}),JSON.stringify(d.getState().toObject())!==f)throw Error("The graph changed. Request a fresh preview.");s(r,n,c.edges),V({destination:n,context:a,signature:f})}catch(e){t.signal.aborted||T(r(e,"Could not prepare the model/task change."))}finally{O.current===t&&(O.current=null,N(!1))}}()},children:"Preview model / task change"}),R?(0,C.jsx)(k,{onClick:()=>{O.current?.abort(),O.current=null,N(!1)},children:"Cancel preparation"}):null,E?(0,C.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:E}):null,F?(0,C.jsx)(m,{open:!0,title:"Review Block model / task change",onClose:()=>{V(null),T(null)},children:(0,C.jsxs)("div",{className:"grid gap-3 text-sm",children:[(0,C.jsxs)("p",{children:[q.definitionSnapshot.displayName," → ",F.destination.definitionSnapshot.displayName]}),(0,C.jsx)("p",{children:"The current edited graph is retained outside execution. Restore its draft to recover custom nodes, unsupported settings and internal connections. External connections must fit the destination interface. Undo restores the entire change."}),(0,C.jsxs)("p",{children:["Required inputs:"," ",F.destination.effectiveInterface.boundary.inputs.filter(e=>e.required).map(e=>e.label).join(", ")||"No required public media inputs declared."]}),E?(0,C.jsx)("p",{role:"alert",children:E}):null,(0,C.jsx)(k,{onClick:function(){if(F)try{let t=d.getState().toObject(),a=g(F.destination);j({...t,nodes:t.nodes.map(t=>t.id===e.id?{...t,data:{...t.data,...a.data}}:t)},F.context,F.signature,"Change Block model or task"),V(null),I("")}catch(e){T(r(e,"Could not apply the model/task change."))}},children:"Apply graph change"})]})}):null]})}export{y as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Di as i,Hr as n,Jr as r,Ni as s,Oi as l,Oo as o,Ti as d,Ur as c,Za as u,Zr as f,an as p,da as h,fn as m,in as g,pn as b,qr as w,ss as x,xn as k}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as j}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";var v=e(a(),1),C=t();function y({node:e}){let t=f(e=>e.library),a=f(e=>e.error),y=s(e=>e.activeWorkflowTabId),[S,I]=(0,v.useState)(""),[N,R]=(0,v.useState)(!1),[O,T]=(0,v.useState)(null),[E,F]=(0,v.useState)(null),V=(0,v.useRef)(null),q=e.data.blockInstanceV2,_=(t?.definitions??[]).flatMap(e=>e.executionAdmissions.filter(t=>"admitted"===t.status&&t.publication.insertable&&"graph_qualified"===t.publication.readiness&&h(e,t)).map(t=>({definition:e,admission:t}))),A=Object.entries(q.routeSelection?.inactiveDrafts??{});return(0,v.useEffect)(()=>(V.current?.abort(),V.current=null,R(!1),T(null),F(null),()=>{V.current?.abort()}),[y,e.id,S]),(0,C.jsxs)(m,{label:"Change model / task",panelClassName:"grid gap-2 py-2",children:[(0,C.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Choose a reviewed workflow. The current composition and custom edits remain available as a saved draft in this workflow; compatible public values carry across."}),(0,C.jsx)(g,{onClick:()=>{f.getState().fetchLibrary()},disabled:N,children:t?"Refresh workflows":"Load workflows"}),a?(0,C.jsx)("p",{role:"alert",children:a}):null,(0,C.jsx)(b,{label:"Workflow",children:(0,C.jsx)(k,{"aria-label":"Replacement Block workflow",value:S,onValueChange:I,options:[{value:"",label:"Select a model and task"},...A.map(([e,t])=>({value:`draft:${e}`,label:`Restore draft · ${t.definitionSnapshot.displayName}`})),..._.filter(e=>e.admission.id!==q.definitionRef.definitionId).map(e=>({value:e.admission.id,label:`${e.definition.label} · ${e.admission.studioMode??e.definition.workflowId}`}))]})}),(0,C.jsx)(g,{disabled:N||!S,onClick:()=>{!async function(){if(V.current||!S)return;let t=new AbortController;V.current=t;let a=l(),s=n.getState().toObject(),f=JSON.stringify(s);R(!0),T(null);try{let l,o=s.nodes.find(t=>t.id===e.id)?.data.blockInstanceV2;if(!o)throw Error("The owning Block is unavailable.");if(S.startsWith("draft:"))l=w(o,S.slice(6));else{let e=_.find(e=>e.admission.id===S);if(!e)throw Error("Reload the catalog and select an available workflow.");let{createHuggingFaceClusterForGraph:a}=await d(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=ca6b74e6a02eedb3`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]),i=u(e.admission.studioMode,e.definition.pipelineClass),n=await a(e.definition,o.presentation.position,i,{insert:!1,signal:t.signal});if(!n.data.blockInstanceV2||n.data.blockInstanceV2.definitionRef.definitionId!==e.admission.id)throw Error("The compiler returned a different workflow. No changes were applied.");l=r(o,n.data.blockInstanceV2)}if(t.signal.aborted)return;if(i(a,{includeForm:!1}),JSON.stringify(n.getState().toObject())!==f)throw Error("The graph changed. Request a fresh preview.");c(o,l,s.edges),F({destination:l,context:a,signature:f})}catch(e){t.signal.aborted||T(o(e,"Could not prepare the model/task change."))}finally{V.current===t&&(V.current=null,R(!1))}}()},children:"Preview model / task change"}),N?(0,C.jsx)(g,{onClick:()=>{V.current?.abort(),V.current=null,R(!1)},children:"Cancel preparation"}):null,O?(0,C.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:O}):null,E?(0,C.jsx)(p,{open:!0,title:"Review Block model / task change",onClose:()=>{F(null),T(null)},children:(0,C.jsxs)("div",{className:"grid gap-3 text-sm",children:[(0,C.jsxs)("p",{children:[q.definitionSnapshot.displayName," → ",E.destination.definitionSnapshot.displayName]}),(0,C.jsx)("p",{children:"The current edited graph is retained outside execution. Restore its draft to recover custom nodes, unsupported settings and internal connections. External connections must fit the destination interface. Undo restores the entire change."}),(0,C.jsxs)("p",{children:["Required inputs:"," ",E.destination.effectiveInterface.boundary.inputs.filter(e=>e.required).map(e=>e.label).join(", ")||"No required public media inputs declared."]}),O?(0,C.jsx)("p",{role:"alert",children:O}):null,(0,C.jsx)(g,{onClick:function(){if(E)try{let t=n.getState().toObject(),a=x(E.destination);j({...t,nodes:t.nodes.map(t=>t.id===e.id?{...t,data:{...t.data,...a.data}}:t)},E.context,E.signature,"Change Block model or task"),F(null),I("")}catch(e){T(o(e,"Could not apply the model/task change."))}},children:"Apply graph change"})]})}):null]})}export{y as default}; \ No newline at end of file diff --git a/web/assets/CompositeMigrationCard.js b/web/assets/CompositeMigrationCard.js index cc0cc3c..89633c7 100644 --- a/web/assets/CompositeMigrationCard.js +++ b/web/assets/CompositeMigrationCard.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$ as t,G as i,H as n,R as o,cr as a,dr as s,rn as r,rt as c}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Bs as d,Ei as l,Eo as u,In as p,Mi as m,Mo as h,Oo as f,Rs as g,Si as v,Sn as y,Ws as x,Xr as b,Ya as I,Yr as C,Zr as w,Zt as $,cn as N,dn as S,fn as j,in as k,ji as H,la as P,mn as A,oc as E,oi as R,qs as _,rn as M,vi as F,wo as D}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as O}from"./huggingFaceClusterInsertion.js?v=cc046c26d6fe7aa4";var B=e(s(),1),T="APPLY_BLOCK_V2_MIGRATION",V="ROLLBACK_BLOCK_V2_MIGRATION",L=/^block-v2-migration-[a-f0-9]{24}$/u,q=/^sha256:[a-f0-9]{64}$/u,z=/^block-definition-v2-[a-f0-9]{8}$/u,K=/^block-graph-v2-[a-f0-9]{8}$/u,G=/^block-interface-v2-[a-f0-9]{8}$/u,J=/^[a-f0-9]{40}$/u,Z=/^(?:user-workflows\/[^/]+\.json|studio\/blocks\/[^/]+\.json)$/u,W=/^user-workflows\/[^/]+\.json$/u,Y=new Set(["legacy_registered_cluster_instance","reusable_v1_definition","workflow_v1_instance","workflow_v1_instances","registered_cluster_compiler_output"]),U=new Set(["reusable_v1_definition","workflow_v1_instances","workflow_composite_instances"]),X=new Set(["applied","applying","prepared","recovery_required","rolled_back","rolling_back"]),Q=new Set(["applied","conflict","interrupted","rolled_back"]),ee=new Set(["applied","conflict","missing","source"]);function te(e,t="is invalid"){throw Error(`Invalid composite migration response: ${e} ${t}.`)}function ie(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&te(t,"must be an object"),e}function ne(e,t,i,n=[]){let o=new Set([...i,...n]),a=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t)),s=Object.keys(e).filter(e=>!o.has(e));a.length&&te(t,`is missing ${a.join(", ")}`),s.length&&te(t,`contains unknown keys ${s.join(", ")}`)}function oe(e,t,i,n=4096){return("string"!=typeof e||!e||e.length>n||i&&!i.test(e))&&te(t),e}function ae(e,t){return null===e?null:oe(e,t,void 0,512)}function se(e,t){return"boolean"!=typeof e&&te(t,"must be a boolean"),e}function re(e,t){return(!Number.isSafeInteger(e)||Number(e)<0)&&te(t,"must be a nonnegative integer"),Number(e)}function ce(e,t){return Array.isArray(e)||te(t,"must be an array"),e}function de(e,t){new Set(e).size!==e.length&&te(t,"contains duplicate entries")}function le(e,t,i){return e.summary.hasChanges&&"APPLY_BLOCK_V2_MIGRATION"===t&&(0===e.summary.blockedCandidateCount||i)}function ue(e,t){for(let i=1;i=(e[i]??"")&&te(t,"must be unique and canonically ordered")}function pe(e,t){let i=ce(e,t).map((e,i)=>oe(e,`${t}[${i}]`,void 0,512));return ue(i,t),i}function me(e,t){let i=ie(e,t);return ne(i,t,["id","contentHash","executionProfileId"]),{id:oe(i.id,`${t}.id`,void 0,512),contentHash:oe(i.contentHash,`${t}.contentHash`,void 0,128),executionProfileId:oe(i.executionProfileId,`${t}.executionProfileId`,void 0,512)}}function he(e,t){let i=ie(e,t);ne(i,t,["receiptId","receiptHash","historical","destination","review"]);let n=ie(i.historical,`${t}.historical`);ne(n,`${t}.historical`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","studioExecutionSpec","executionGraphHash","interfaceHash"]);let o=ie(i.destination,`${t}.destination`);ne(o,`${t}.destination`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","blockDefinitionId","blockDefinitionContentHash","blockDefinitionCanonicalSha256","executionGraphHash","interfaceHash"]);let a=ie(i.review,`${t}.review`);ne(a,`${t}.review`,["decision","issuer","reviewedAt","notes"]),"semantic_equivalent"!==a.decision&&te(`${t}.review.decision`);let s=oe(a.reviewedAt,`${t}.review.reviewedAt`,void 0,64);return(!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(s)||Number.isNaN(Date.parse(s)))&&te(`${t}.review.reviewedAt`,"must be an offset ISO-8601 timestamp"),{receiptId:oe(i.receiptId,`${t}.receiptId`,void 0,256),receiptHash:oe(i.receiptHash,`${t}.receiptHash`,q),historical:{manifestDefinitionId:oe(n.manifestDefinitionId,`${t}.historical.manifestDefinitionId`,void 0,512),libraryRevision:oe(n.libraryRevision,`${t}.historical.libraryRevision`,J),manifestContentHash:oe(n.manifestContentHash,`${t}.historical.manifestContentHash`,q),executionAdmissionId:oe(n.executionAdmissionId,`${t}.historical.executionAdmissionId`,void 0,1024),studioExecutionSpec:me(n.studioExecutionSpec,`${t}.historical.studioExecutionSpec`),executionGraphHash:oe(n.executionGraphHash,`${t}.historical.executionGraphHash`,q),interfaceHash:oe(n.interfaceHash,`${t}.historical.interfaceHash`,q)},destination:{manifestDefinitionId:oe(o.manifestDefinitionId,`${t}.destination.manifestDefinitionId`,void 0,512),libraryRevision:oe(o.libraryRevision,`${t}.destination.libraryRevision`,J),manifestContentHash:oe(o.manifestContentHash,`${t}.destination.manifestContentHash`,q),executionAdmissionId:oe(o.executionAdmissionId,`${t}.destination.executionAdmissionId`,void 0,1024),blockDefinitionId:oe(o.blockDefinitionId,`${t}.destination.blockDefinitionId`,void 0,384),blockDefinitionContentHash:oe(o.blockDefinitionContentHash,`${t}.destination.blockDefinitionContentHash`,z),blockDefinitionCanonicalSha256:oe(o.blockDefinitionCanonicalSha256,`${t}.destination.blockDefinitionCanonicalSha256`,q),executionGraphHash:oe(o.executionGraphHash,`${t}.destination.executionGraphHash`,K),interfaceHash:oe(o.interfaceHash,`${t}.destination.interfaceHash`,G)},review:{decision:"semantic_equivalent",issuer:oe(a.issuer,`${t}.review.issuer`,void 0,256),reviewedAt:s,notes:oe(a.notes,`${t}.review.notes`,void 0,4096)}}}function fe(e,t){let i=ie(e,t);ne(i,t,["mappingId","mappingHash","historical","destination","review"]);let n=ie(i.historical,`${t}.historical`);ne(n,`${t}.historical`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","studioExecutionSpec","archivedDefinitionRecordHash","blockContractHash","rootBlockDefinitionId"]);let o=ie(i.destination,`${t}.destination`);ne(o,`${t}.destination`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","blockDefinitionId","blockDefinitionContentHash","blockDefinitionCanonicalSha256","executionGraphHash","interfaceHash"]);let a=ie(i.review,`${t}.review`);ne(a,`${t}.review`,["decision","issuer","reviewedAt","notes"]),"historical_compiler_mapping_reviewed"!==a.decision&&te(`${t}.review.decision`);let s=oe(a.reviewedAt,`${t}.review.reviewedAt`,void 0,64);return(!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(s)||Number.isNaN(Date.parse(s)))&&te(`${t}.review.reviewedAt`,"must be an offset ISO-8601 timestamp"),{mappingId:oe(i.mappingId,`${t}.mappingId`,void 0,256),mappingHash:oe(i.mappingHash,`${t}.mappingHash`,q),historical:{manifestDefinitionId:oe(n.manifestDefinitionId,`${t}.historical.manifestDefinitionId`,void 0,512),libraryRevision:oe(n.libraryRevision,`${t}.historical.libraryRevision`,J),manifestContentHash:oe(n.manifestContentHash,`${t}.historical.manifestContentHash`,q),executionAdmissionId:oe(n.executionAdmissionId,`${t}.historical.executionAdmissionId`,void 0,1024),studioExecutionSpec:me(n.studioExecutionSpec,`${t}.historical.studioExecutionSpec`),archivedDefinitionRecordHash:oe(n.archivedDefinitionRecordHash,`${t}.historical.archivedDefinitionRecordHash`,q),blockContractHash:oe(n.blockContractHash,`${t}.historical.blockContractHash`,q),rootBlockDefinitionId:oe(n.rootBlockDefinitionId,`${t}.historical.rootBlockDefinitionId`,void 0,1024)},destination:{manifestDefinitionId:oe(o.manifestDefinitionId,`${t}.destination.manifestDefinitionId`,void 0,512),libraryRevision:oe(o.libraryRevision,`${t}.destination.libraryRevision`,J),manifestContentHash:oe(o.manifestContentHash,`${t}.destination.manifestContentHash`,q),executionAdmissionId:oe(o.executionAdmissionId,`${t}.destination.executionAdmissionId`,void 0,1024),blockDefinitionId:oe(o.blockDefinitionId,`${t}.destination.blockDefinitionId`,void 0,384),blockDefinitionContentHash:oe(o.blockDefinitionContentHash,`${t}.destination.blockDefinitionContentHash`,z),blockDefinitionCanonicalSha256:oe(o.blockDefinitionCanonicalSha256,`${t}.destination.blockDefinitionCanonicalSha256`,q),executionGraphHash:oe(o.executionGraphHash,`${t}.destination.executionGraphHash`,K),interfaceHash:oe(o.interfaceHash,`${t}.destination.interfaceHash`,G)},review:{decision:"historical_compiler_mapping_reviewed",issuer:oe(a.issuer,`${t}.review.issuer`,void 0,256),reviewedAt:s,notes:oe(a.notes,`${t}.review.notes`,void 0,4096)}}}function ge(e){let t=ie(e,"compiler supplement");ne(t,"compiler supplement",["schemaVersion","kind","compilerOutputs"]),(1!==t.schemaVersion||"registered_cluster_v2_compiler_supplement"!==t.kind)&&te("compiler supplement","uses an unsupported contract");let i=ce(t.compilerOutputs,"compiler supplement.compilerOutputs").map((e,t)=>{let i=`compiler supplement.compilerOutputs[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","sourceSha256","conversions"]);let o=ce(n.conversions,`${i}.conversions`).map((e,t)=>function(e,t){let i=ie(e,t);ne(i,t,["legacyInstanceId","legacyCompositeHash","admissionId","compiledDefinitionContentHash","compiledDefinitionCanonicalSha256","blockInstanceV2","ownedNodeMappings","portMappings","valueMappings","previewMappings","absorbedInternalEdgeIds"],["semanticEquivalenceReceipt","historicalCompilerMapping"]);let n=ce(i.ownedNodeMappings,`${t}.ownedNodeMappings`).map((e,i)=>{let n=`${t}.ownedNodeMappings[${i}]`,o=ie(e,n);return ne(o,n,["legacyNodeId","semanticNodeId"]),{legacyNodeId:oe(o.legacyNodeId,`${n}.legacyNodeId`,void 0,512),semanticNodeId:oe(o.semanticNodeId,`${n}.semanticNodeId`,void 0,512)}});ue(n.map(({legacyNodeId:e,semanticNodeId:t})=>`${e}\0${t}`),`${t}.ownedNodeMappings`);let o=ce(i.portMappings,`${t}.portMappings`).map((e,i)=>{let n=`${t}.portMappings[${i}]`,o=ie(e,n);ne(o,n,["direction","legacyNodeId","legacyPortId","v2PortId"]);let a=oe(o.direction,`${n}.direction`);return"input"!==a&&"output"!==a&&te(`${n}.direction`),{direction:a,legacyNodeId:oe(o.legacyNodeId,`${n}.legacyNodeId`,void 0,512),legacyPortId:oe(o.legacyPortId,`${n}.legacyPortId`,void 0,512),v2PortId:oe(o.v2PortId,`${n}.v2PortId`,void 0,512)}});ue(o.map(({direction:e,legacyNodeId:t,legacyPortId:i,v2PortId:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.portMappings`);let a=ce(i.valueMappings,`${t}.valueMappings`).map((e,i)=>{let n=`${t}.valueMappings[${i}]`,o=ie(e,n),a=oe(o.targetKind,`${n}.targetKind`),s={sourceKind:oe(o.sourceKind,`${n}.sourceKind`,void 0,512),sourceNodeId:oe(o.sourceNodeId,`${n}.sourceNodeId`,void 0,512),sourceFieldId:oe(o.sourceFieldId,`${n}.sourceFieldId`,void 0,512)};return"instance_value"===a?(ne(o,n,["sourceKind","sourceNodeId","sourceFieldId","targetKind","targetValueId"]),{...s,targetKind:"instance_value",targetValueId:oe(o.targetValueId,`${n}.targetValueId`,void 0,512)}):"graph_param"===a?(ne(o,n,["sourceKind","sourceNodeId","sourceFieldId","targetKind","targetNodeId","targetFieldId"]),{...s,targetKind:"graph_param",targetNodeId:oe(o.targetNodeId,`${n}.targetNodeId`,void 0,512),targetFieldId:oe(o.targetFieldId,`${n}.targetFieldId`,void 0,512)}):void te(`${n}.targetKind`)});ue(a.map(({sourceKind:e,sourceNodeId:t,sourceFieldId:i,targetKind:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.valueMappings`);let s=ce(i.previewMappings,`${t}.previewMappings`).map((e,i)=>{let n=`${t}.previewMappings[${i}]`,o=ie(e,n);return ne(o,n,["sourceNodeId","sourceFieldId","targetNodeId","targetOutputPortId"]),{sourceNodeId:oe(o.sourceNodeId,`${n}.sourceNodeId`,void 0,512),sourceFieldId:oe(o.sourceFieldId,`${n}.sourceFieldId`,void 0,512),targetNodeId:oe(o.targetNodeId,`${n}.targetNodeId`,void 0,512),targetOutputPortId:oe(o.targetOutputPortId,`${n}.targetOutputPortId`,void 0,512)}});ue(s.map(({sourceNodeId:e,sourceFieldId:t,targetNodeId:i,targetOutputPortId:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.previewMappings`);let r=void 0===i.semanticEquivalenceReceipt?void 0:(()=>{let e=ie(i.semanticEquivalenceReceipt,`${t}.semanticEquivalenceReceipt`);return ne(e,`${t}.semanticEquivalenceReceipt`,["receiptId","receiptHash"]),{receiptId:oe(e.receiptId,`${t}.semanticEquivalenceReceipt.receiptId`,void 0,256),receiptHash:oe(e.receiptHash,`${t}.semanticEquivalenceReceipt.receiptHash`,q)}})(),c=void 0===i.historicalCompilerMapping?void 0:(()=>{let e=ie(i.historicalCompilerMapping,`${t}.historicalCompilerMapping`);return ne(e,`${t}.historicalCompilerMapping`,["mappingId","mappingHash"]),{mappingId:oe(e.mappingId,`${t}.historicalCompilerMapping.mappingId`,void 0,256),mappingHash:oe(e.mappingHash,`${t}.historicalCompilerMapping.mappingHash`,q)}})();return r&&c&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),{legacyInstanceId:oe(i.legacyInstanceId,`${t}.legacyInstanceId`,void 0,512),legacyCompositeHash:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),admissionId:oe(i.admissionId,`${t}.admissionId`,void 0,1024),compiledDefinitionContentHash:oe(i.compiledDefinitionContentHash,`${t}.compiledDefinitionContentHash`,z),compiledDefinitionCanonicalSha256:oe(i.compiledDefinitionCanonicalSha256,`${t}.compiledDefinitionCanonicalSha256`,q),blockInstanceV2:x(i.blockInstanceV2),ownedNodeMappings:n,portMappings:o,valueMappings:a,previewMappings:s,absorbedInternalEdgeIds:pe(i.absorbedInternalEdgeIds,`${t}.absorbedInternalEdgeIds`),...r?{semanticEquivalenceReceipt:r}:{},...c?{historicalCompilerMapping:c}:{}}}(e,`${i}.conversions[${t}]`));return o.length||te(`${i}.conversions`,"must not be empty"),ue(o.map(({legacyInstanceId:e})=>e),`${i}.conversions`),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,W),sourceSha256:oe(n.sourceSha256,`${i}.sourceSha256`,q),conversions:o}});return ue(i.map(({sourcePath:e})=>e),"compiler supplement.compilerOutputs"),{schemaVersion:1,kind:"registered_cluster_v2_compiler_supplement",compilerOutputs:i}}function ve(e,t){let i=ie(e,`preview.targets[${t}]`);ne(i,`preview.targets[${t}]`,["sourcePath","kind","beforeSha256","afterSha256","convertedIds","byteLength"]);let n=oe(i.kind,`preview.targets[${t}].kind`);U.has(n)||te(`preview.targets[${t}].kind`);let o=ce(i.convertedIds,`preview.targets[${t}].convertedIds`).map((e,i)=>oe(e,`preview.targets[${t}].convertedIds[${i}]`,void 0,512));return o.length||te(`preview.targets[${t}].convertedIds`,"must not be empty"),de(o,`preview.targets[${t}].convertedIds`),{sourcePath:oe(i.sourcePath,`preview.targets[${t}].sourcePath`,Z),kind:n,beforeSha256:oe(i.beforeSha256,`preview.targets[${t}].beforeSha256`,q),afterSha256:oe(i.afterSha256,`preview.targets[${t}].afterSha256`,q),convertedIds:o,byteLength:re(i.byteLength,`preview.targets[${t}].byteLength`)}}function ye(e,t){let i=ie(e,t);ne(i,t,["kind","sourcePath","id","status"],["reason","targetAfterSha256","sourceSha256","legacyCompositeHash","compilerReceipt","semanticEquivalenceAuthority","historicalCompilerMappingAuthority"]);let n=oe(i.kind,`${t}.kind`);Y.has(n)||te(`${t}.kind`);let o=oe(i.status,`${t}.status`);"blocked"!==o&&"convertible"!==o&&te(`${t}.status`);let a=void 0===i.reason?void 0:oe(i.reason,`${t}.reason`,void 0,8192),s=void 0===i.targetAfterSha256?void 0:oe(i.targetAfterSha256,`${t}.targetAfterSha256`,q),r=void 0===i.sourceSha256?void 0:oe(i.sourceSha256,`${t}.sourceSha256`,q),c=void 0===i.legacyCompositeHash?void 0:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),d=void 0===i.compilerReceipt?void 0:function(e,t){let i=ie(e,t);ne(i,t,["instanceId","definitionId","admissionId","compiledDefinitionContentHash","compiledDefinitionCanonicalSha256","legacyCompositeHash","absorbedProjectionNodeIds","absorbedInternalEdgeIds"],["semanticEquivalenceAuthority","historicalCompilerMappingAuthority"]);let n=void 0===i.semanticEquivalenceAuthority?void 0:he(i.semanticEquivalenceAuthority,`${t}.semanticEquivalenceAuthority`),o=void 0===i.historicalCompilerMappingAuthority?void 0:fe(i.historicalCompilerMappingAuthority,`${t}.historicalCompilerMappingAuthority`);return n&&o&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),{instanceId:oe(i.instanceId,`${t}.instanceId`,void 0,512),definitionId:oe(i.definitionId,`${t}.definitionId`,void 0,512),admissionId:oe(i.admissionId,`${t}.admissionId`,void 0,1024),compiledDefinitionContentHash:oe(i.compiledDefinitionContentHash,`${t}.compiledDefinitionContentHash`,z),compiledDefinitionCanonicalSha256:oe(i.compiledDefinitionCanonicalSha256,`${t}.compiledDefinitionCanonicalSha256`,q),legacyCompositeHash:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),absorbedProjectionNodeIds:pe(i.absorbedProjectionNodeIds,`${t}.absorbedProjectionNodeIds`),absorbedInternalEdgeIds:pe(i.absorbedInternalEdgeIds,`${t}.absorbedInternalEdgeIds`),...n?{semanticEquivalenceAuthority:n}:{},...o?{historicalCompilerMappingAuthority:o}:{}}}(i.compilerReceipt,`${t}.compilerReceipt`),l=void 0===i.semanticEquivalenceAuthority?void 0:he(i.semanticEquivalenceAuthority,`${t}.semanticEquivalenceAuthority`),u=void 0===i.historicalCompilerMappingAuthority?void 0:fe(i.historicalCompilerMappingAuthority,`${t}.historicalCompilerMappingAuthority`);return l&&u&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),("blocked"===o!=!!a||"convertible"===o!=!!s)&&te(t,"has inconsistent status details"),{kind:n,sourcePath:oe(i.sourcePath,`${t}.sourcePath`,Z),id:ae(i.id,`${t}.id`),status:o,...a?{reason:a}:{},...s?{targetAfterSha256:s}:{},...r?{sourceSha256:r}:{},...c?{legacyCompositeHash:c}:{},...d?{compilerReceipt:d}:{},...l?{semanticEquivalenceAuthority:l}:{},...u?{historicalCompilerMappingAuthority:u}:{}}}function xe(e,t){let i=`preview.inventoryIssues[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","path","code","severity","message"]);let o=oe(n.severity,`${i}.severity`);return"error"!==o&&"warning"!==o&&te(`${i}.severity`),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,void 0,4096),path:oe(n.path,`${i}.path`,void 0,4096),code:oe(n.code,`${i}.code`,void 0,512),severity:o,message:oe(n.message,`${i}.message`,void 0,8192)}}function be(e){let t=ie(e,"preview response");ne(t,"preview response",["error","preview"]),!1!==t.error&&te("preview response.error","must be false");let i=ie(t.preview,"preview");ne(i,"preview",["schemaVersion","kind","mode","boundary","inventoryReportHash","sourceSetHash","summary","targets","candidates","blocked","inventoryIssues","migrationId","planHash"],["compilerSupplement"]),(1!==i.schemaVersion||"legacy_composite_to_block_v2_migration"!==i.kind||"read_only_preview"!==i.mode)&&te("preview","uses an unsupported contract");let n=ie(i.boundary,"preview.boundary");ne(n,"preview.boundary",["writesFiles","requiresExplicitApplyAuthority","createsExactBackupsBeforeReplacement","deletesRecords","mergesRecords","legacyClusterConversionRequiresRegisteredCompiler","containsPromptAndParameterValues"],["compilerSupplementRequiredForRegisteredClusters"]),(!1!==n.writesFiles||!0!==n.requiresExplicitApplyAuthority||!0!==n.createsExactBackupsBeforeReplacement||!1!==n.deletesRecords||!1!==n.mergesRecords||!0!==n.legacyClusterConversionRequiresRegisteredCompiler||!1!==n.containsPromptAndParameterValues)&&te("preview.boundary","does not preserve the read-only safety contract");let o=ie(i.summary,"preview.summary");ne(o,"preview.summary",["sourceCount","targetFileCount","convertibleCandidateCount","blockedCandidateCount","legacyClusterBlockedCount","hasChanges"],["registeredClusterConvertibleCount"]);let a=ce(i.targets,"preview.targets").map(ve),s=ce(i.candidates,"preview.candidates").map((e,t)=>ye(e,`preview.candidates[${t}]`)),r=ce(i.blocked,"preview.blocked").map((e,t)=>ye(e,`preview.blocked[${t}]`)),c=ce(i.inventoryIssues,"preview.inventoryIssues").map(xe),d={sourceCount:re(o.sourceCount,"preview.summary.sourceCount"),targetFileCount:re(o.targetFileCount,"preview.summary.targetFileCount"),convertibleCandidateCount:re(o.convertibleCandidateCount,"preview.summary.convertibleCandidateCount"),blockedCandidateCount:re(o.blockedCandidateCount,"preview.summary.blockedCandidateCount"),legacyClusterBlockedCount:re(o.legacyClusterBlockedCount,"preview.summary.legacyClusterBlockedCount"),hasChanges:se(o.hasChanges,"preview.summary.hasChanges"),...void 0===o.registeredClusterConvertibleCount?{}:{registeredClusterConvertibleCount:re(o.registeredClusterConvertibleCount,"preview.summary.registeredClusterConvertibleCount")}},l=void 0===i.compilerSupplement?void 0:(()=>{let e=ie(i.compilerSupplement,"preview.compilerSupplement");ne(e,"preview.compilerSupplement",["provided","contentHash","sourceCount","conversionCount"]);let t=se(e.provided,"preview.compilerSupplement.provided"),n=null===e.contentHash?null:oe(e.contentHash,"preview.compilerSupplement.contentHash",q);return t!==!!n&&te("preview.compilerSupplement","has an inconsistent provided/contentHash pair"),{provided:t,contentHash:n,sourceCount:re(e.sourceCount,"preview.compilerSupplement.sourceCount"),conversionCount:re(e.conversionCount,"preview.compilerSupplement.conversionCount")}})();(!!l!=(!0===n.compilerSupplementRequiredForRegisteredClusters)||!!l!=(void 0!==d.registeredClusterConvertibleCount))&&te("preview.compilerSupplement","is inconsistent with the compiler-preview boundary and summary"),de(a.map(({sourcePath:e})=>e),"preview.targets");let u=s.filter(({status:e})=>"blocked"===e);(d.targetFileCount!==a.length||d.convertibleCandidateCount!==s.filter(({status:e})=>"convertible"===e).length||d.blockedCandidateCount!==u.length||d.blockedCandidateCount!==r.length||d.legacyClusterBlockedCount!==r.filter(({kind:e})=>"legacy_registered_cluster_instance"===e).length||void 0!==d.registeredClusterConvertibleCount&&d.registeredClusterConvertibleCount!==s.filter(({kind:e,status:t})=>"legacy_registered_cluster_instance"===e&&"convertible"===t).length||d.hasChanges!==!!a.length||JSON.stringify(u)!==JSON.stringify(r))&&te("preview.summary","does not match the listed targets and candidates");let p=new Map(a.map(e=>[e.sourcePath,e.afterSha256]));return s.some(e=>"convertible"===e.status&&p.get(e.sourcePath)!==e.targetAfterSha256)&&te("preview.candidates","does not match the target hashes"),{schemaVersion:1,kind:"legacy_composite_to_block_v2_migration",mode:"read_only_preview",boundary:{writesFiles:!1,requiresExplicitApplyAuthority:!0,createsExactBackupsBeforeReplacement:!0,deletesRecords:!1,mergesRecords:!1,legacyClusterConversionRequiresRegisteredCompiler:!0,...l?{compilerSupplementRequiredForRegisteredClusters:!0}:{},containsPromptAndParameterValues:!1},...l?{compilerSupplement:l}:{},inventoryReportHash:oe(i.inventoryReportHash,"preview.inventoryReportHash",q),sourceSetHash:oe(i.sourceSetHash,"preview.sourceSetHash",q),summary:d,targets:a,candidates:s,blocked:r,inventoryIssues:c,migrationId:oe(i.migrationId,"preview.migrationId",L),planHash:oe(i.planHash,"preview.planHash",q)}}function Ie(e,t){let i=`migration status.targets[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","currentSha256","state"]);let o=oe(n.state,`${i}.state`);ee.has(o)||te(`${i}.state`);let a=null===n.currentSha256?null:oe(n.currentSha256,`${i}.currentSha256`,q);return"missing"===o!=(null===a)&&te(i,"has an inconsistent current file hash"),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,Z),currentSha256:a,state:o}}function Ce(e){let t=ie(e,"migration status");ne(t,"migration status",["migrationId","journalState","effectiveState","planHash","inventoryReportHash","targets","rollbackAvailable","resumeAvailable"]);let i=oe(t.journalState,"migration status.journalState"),n=oe(t.effectiveState,"migration status.effectiveState");X.has(i)||te("migration status.journalState"),Q.has(n)||te("migration status.effectiveState");let o=ce(t.targets,"migration status.targets").map(Ie);o.length||te("migration status.targets","must not be empty"),de(o.map(({sourcePath:e})=>e),"migration status.targets");let a=se(t.rollbackAvailable,"migration status.rollbackAvailable"),s=se(t.resumeAvailable,"migration status.resumeAvailable"),r=new Set(o.map(({state:e})=>e));return(n!==(1===r.size&&r.has("applied")?"applied":1===r.size&&r.has("source")?"rolled_back":[...r].every(e=>"source"===e||"applied"===e)?"interrupted":"conflict")||!1!==s||a!==["applied","interrupted","rolled_back"].includes(n))&&te("migration status","has inconsistent recovery actions"),{migrationId:oe(t.migrationId,"migration status.migrationId",L),journalState:i,effectiveState:n,planHash:oe(t.planHash,"migration status.planHash",q),inventoryReportHash:oe(t.inventoryReportHash,"migration status.inventoryReportHash",q),targets:o,rollbackAvailable:a,resumeAvailable:!1}}function we(e){let t=ie(e,"migration list response");ne(t,"migration list response",["error","schemaVersion","migrations"]),(!1!==t.error||1!==t.schemaVersion)&&te("migration list response","uses an unsupported contract");let i=ce(t.migrations,"migration list response.migrations").map(Ce);return de(i.map(({migrationId:e})=>e),"migration list response.migrations"),{schemaVersion:1,migrations:i}}function $e(e){let t=ie(e,"migration status response");return ne(t,"migration status response",["error","status"]),!1!==t.error&&te("migration status response.error","must be false"),Ce(t.status)}function Ne(e,t){let i=ie(e,"migration mutation response");ne(i,"migration mutation response",["error","idempotent","status"],[t]),!1!==i.error&&te("migration mutation response.error","must be false");let n=Ce(i.status),o=void 0===i[t]?void 0:ce(i[t],`migration mutation response.${t}`).map((e,i)=>oe(e,`migration mutation response.${t}[${i}]`,Z));if(o){de(o,`migration mutation response.${t}`);let e=new Set(n.targets.map(({sourcePath:e})=>e));o.some(t=>!e.has(t))&&te(`migration mutation response.${t}`,"is not a target")}return{idempotent:se(i.idempotent,"migration mutation response.idempotent"),..."changedPaths"===t&&o?{changedPaths:o}:{},..."restoredPaths"===t&&o?{restoredPaths:o}:{},status:n}}function Se(e){let t=Ne(e,"changedPaths");return"applied"!==t.status.effectiveState&&te("migration apply result.status","did not reach the applied state"),t}function je(e){let t=Ne(e,"restoredPaths");return"rolled_back"!==t.status.effectiveState&&te("migration rollback result.status","did not reach the rolled-back state"),t}function ke(e,t){let i=u(e,t);return e instanceof D&&403===e.status?`Authorization rejected (HTTP 403): ${i}`:e instanceof D&&409===e.status?`Migration state conflict (HTTP 409): ${i}`:i}function He(e){let t=void 0===e?void 0:ge(e);return f(`${E.serverAddress}/studio/composite-migrations/preview`,{...t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({compilerSupplement:t})}:{},timeoutMs:3e4,parse:be})}function Pe(){return f(`${E.serverAddress}/studio/composite-migrations`,{timeoutMs:3e4,parse:we})}async function Ae(e){oe(e,"migrationId",L);let t=await f(`${E.serverAddress}/studio/composite-migrations/${encodeURIComponent(e)}`,{timeoutMs:3e4,parse:$e});return t.migrationId!==e&&te("migration status.migrationId","does not match the request"),t}async function Ee(e,t){if("APPLY_BLOCK_V2_MIGRATION"!==t.confirmation)throw Error(`Type ${T} exactly before applying.`);if("boolean"!=typeof t.allowBlockedCandidates)throw Error("Choose explicitly whether blocked candidates may remain before applying.");let i=be({error:!1,preview:e}),n=void 0===t.compilerSupplement?void 0:ge(t.compilerSupplement);if(!!i.compilerSupplement!=!!n)throw Error("Apply must reuse the exact compiler supplement from the reviewed preview.");if(i.compilerSupplement&&n&&(i.compilerSupplement.sourceCount!==n.compilerOutputs.length||i.compilerSupplement.conversionCount!==n.compilerOutputs.reduce((e,t)=>e+t.conversions.length,0)))throw Error("Apply compiler supplement does not match the reviewed preview counts.");if(i.summary.blockedCandidateCount>0&&!t.allowBlockedCandidates)throw Error("Explicitly allow blocked candidates to remain unchanged before applying safe targets.");let o=await f(`${E.serverAddress}/studio/composite-migrations/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({migrationId:i.migrationId,planHash:i.planHash,confirmation:t.confirmation,allowBlockedCandidates:t.allowBlockedCandidates,...n?{compilerSupplement:n}:{}}),timeoutMs:12e4,parse:Se});return(o.status.migrationId!==i.migrationId||o.status.planHash!==i.planHash)&&te("migration apply result","does not match the reviewed preview"),o}async function Re(e,t){if(oe(e,"migrationId",L),"ROLLBACK_BLOCK_V2_MIGRATION"!==t)throw Error(`Type ${V} exactly before rollback.`);let i=await f(`${E.serverAddress}/studio/composite-migrations/${encodeURIComponent(e)}/rollback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirmation:t}),timeoutMs:12e4,parse:je});return i.status.migrationId!==e&&te("migration rollback result","does not match the requested journal"),i}var _e=/^sha256:[a-f0-9]{64}$/u,Me=/^[a-f0-9]{40}$/u,Fe=/^studio-spec-v1-[a-f0-9]{8}$/u;function De(e,t="is invalid"){throw Error(`Invalid legacy Cluster recovery-audit response: ${e} ${t}.`)}function Oe(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&De(t,"must be an object"),e}function Be(e,t,i,n=[]){let o=new Set([...i,...n]),a=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t)),s=Object.keys(e).filter(e=>!o.has(e));(a.length||s.length)&&De(t,"has missing or unknown fields")}function Te(e,t,i,n=8192){return("string"!=typeof e||!e||e.length>n||i&&!i.test(e))&&De(t),e}function Ve(e,t,i,n=8192){return null===e?null:Te(e,t,i,n)}function Le(e,t){return(!Number.isSafeInteger(e)||Number(e)<0)&&De(t,"must be a nonnegative integer"),Number(e)}function qe(e,t){return"boolean"!=typeof e&&De(t,"must be a boolean"),e}function ze(e,t){return Array.isArray(e)||De(t,"must be an array"),e}function Ke(e,t){let i=ze(e,t).map((e,i)=>Te(e,`${t}[${i}]`,void 0,1024));return new Set(i).size!==i.length&&De(t,"contains duplicates"),i}var Ge=new Set(["identity_malformed","execution_receipt_missing","execution_receipt_incomplete","current_manifest_exact","archived_manifest_exact","semantic_equivalence_reviewed","historical_manifest_evidence_required"]),Je="legacyClusterInstanceCount.definitionIdentityCount.currentManifestExactInstanceCount.currentManifestExactIdentityCount.currentExecutionTupleExactInstanceCount.currentExecutionTupleExactIdentityCount.archivedManifestExactInstanceCount.archivedManifestExactIdentityCount.semanticEquivalenceReviewedInstanceCount.semanticEquivalenceReviewedIdentityCount.compilerMappingEligibleInstanceCount.compilerMappingEligibleIdentityCount.remainingBlockedHistoricalInstanceCount.remainingBlockedHistoricalIdentityCount.historicalEvidenceRequiredInstanceCount.historicalEvidenceRequiredIdentityCount.completeExecutionReceiptInstanceCount.missingExecutionReceiptInstanceCount.missingExecutionReceiptIdentityCount.incompleteExecutionReceiptInstanceCount.incompleteExecutionReceiptIdentityCount.identityReferenceOnlyInstanceCount.embeddedCompleteDefinitionInstanceCount.presentationProjectionInstanceCount.presentationProjectionNodeCount.malformedIdentityInstanceCount.malformedIdentityCount.recoveredStudioSpecBodyCount.recoveredStudioSpecManifestIdentityCount.recoveredStudioSpecExecutionTupleCount.recoveredStudioSpecInstanceCount.partialReviewVerifiedExecutionTupleCount.partialReviewRejectedExecutionTupleCount".split(".");function Ze(e,t){let i=Oe(e,t);return Be(i,t,["id","contentHash","executionProfileId"]),{id:Te(i.id,`${t}.id`,void 0,512),contentHash:Te(i.contentHash,`${t}.contentHash`,Fe),executionProfileId:Te(i.executionProfileId,`${t}.executionProfileId`,void 0,512)}}function We(e,t){return ze(e,t).map((e,i)=>{let n=`${t}[${i}]`,o=Oe(e,n);return Be(o,n,["code","message"]),{code:Te(o.code,`${n}.code`,void 0,512),message:Te(o.message,`${n}.message`)}})}function Ye(e,t){let i=Oe(e,t),n=Te(i.status,`${t}.status`);return"missing"===n?(Be(i,t,["status","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,authorizesConversion:!1}):("self_hash_valid_partial_evidence"!==n&&De(`${t}.status`),Be(i,t,["status","canonicalBodySha256","sourceIds","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,canonicalBodySha256:Te(i.canonicalBodySha256,`${t}.canonicalBodySha256`,_e),sourceIds:Ke(i.sourceIds,`${t}.sourceIds`),authorizesConversion:!1})}function Ue(e,t){let i=Oe(e,t),n=Te(i.status,`${t}.status`);if("evidence_missing"===n||"unreviewed"===n)return Be(i,t,["status","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,authorizesConversion:!1};"verified_partial_evidence"!==n&&"rejected_evidence"!==n&&De(`${t}.status`),Be(i,t,["status","reviewId","reviewer","reviewedAt","notes","reviewHash","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority");let o=Te(i.reviewedAt,`${t}.reviewedAt`,void 0,64);return(Number.isNaN(Date.parse(o))||!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(o))&&De(`${t}.reviewedAt`),{status:n,reviewId:Te(i.reviewId,`${t}.reviewId`,void 0,512),reviewer:Te(i.reviewer,`${t}.reviewer`,void 0,256),reviewedAt:o,notes:Te(i.notes,`${t}.notes`,void 0,4096),reviewHash:Te(i.reviewHash,`${t}.reviewHash`,_e),authorizesConversion:!1}}function Xe(e,t){let i=Oe(e,t);Be(i,t,["status","specificationBodyCount","executionTupleCount","instanceCount","verifiedPartialReviewExecutionTupleCount","rejectedPartialReviewExecutionTupleCount","isManifestDefinitionOrConversionAuthority"]);let n=Te(i.status,`${t}.status`);return"partial_evidence_available"!==n&&"missing"!==n&&De(`${t}.status`),!1!==qe(i.isManifestDefinitionOrConversionAuthority,`${t}.isManifestDefinitionOrConversionAuthority`)&&De(t,"grants authority"),{status:n,specificationBodyCount:Le(i.specificationBodyCount,`${t}.specificationBodyCount`),executionTupleCount:Le(i.executionTupleCount,`${t}.executionTupleCount`),instanceCount:Le(i.instanceCount,`${t}.instanceCount`),verifiedPartialReviewExecutionTupleCount:Le(i.verifiedPartialReviewExecutionTupleCount,`${t}.verifiedPartialReviewExecutionTupleCount`),rejectedPartialReviewExecutionTupleCount:Le(i.rejectedPartialReviewExecutionTupleCount,`${t}.rejectedPartialReviewExecutionTupleCount`),isManifestDefinitionOrConversionAuthority:!1}}function Qe(e,t){let i=`audit.identities[${t}]`,n=Oe(e,i);Be(n,i,["definitionId","libraryRevision","manifestContentHash","admissionIds","instanceCount","disposition","sourceEvidence","executionTuples","missingEvidence","safeNextActions"]);let o=Te(n.disposition,`${i}.disposition`);Ge.has(o)||De(`${i}.disposition`);let a=Oe(n.sourceEvidence,`${i}.sourceEvidence`);Be(a,`${i}.sourceEvidence`,["embeddedManifest","executionReceipt","presentationProjection","currentCatalog","registeredArchive","reviewedSemanticEquivalence","recoveredStudioSpecs"]);for(let e of["embeddedManifest","executionReceipt","presentationProjection","currentCatalog","registeredArchive","reviewedSemanticEquivalence"])Oe(a[e],`${i}.sourceEvidence.${e}`);return{definitionId:Ve(n.definitionId,`${i}.definitionId`,void 0,512),libraryRevision:Ve(n.libraryRevision,`${i}.libraryRevision`,Me),manifestContentHash:Ve(n.manifestContentHash,`${i}.manifestContentHash`,_e),admissionIds:Ke(n.admissionIds,`${i}.admissionIds`),instanceCount:Le(n.instanceCount,`${i}.instanceCount`),disposition:o,recoveredStudioSpecs:Xe(a.recoveredStudioSpecs,`${i}.sourceEvidence.recoveredStudioSpecs`),executionTuples:ze(n.executionTuples,`${i}.executionTuples`).map((e,t)=>function(e,t){let i=Oe(e,t);return Be(i,t,["admissionId","studioExecutionSpec","instanceCount","recoveredStudioSpec","manualReview"]),{admissionId:Ve(i.admissionId,`${t}.admissionId`,void 0,1024),studioExecutionSpec:null===i.studioExecutionSpec?null:Ze(i.studioExecutionSpec,`${t}.studioExecutionSpec`),instanceCount:Le(i.instanceCount,`${t}.instanceCount`),recoveredStudioSpec:Ye(i.recoveredStudioSpec,`${t}.recoveredStudioSpec`),manualReview:Ue(i.manualReview,`${t}.manualReview`)}}(e,`${i}.executionTuples[${t}]`)),missingEvidence:We(n.missingEvidence,`${i}.missingEvidence`),safeNextActions:We(n.safeNextActions,`${i}.safeNextActions`)}}function et(e,t){let i=`audit.partialStudioSpecEvidence.sources[${t}]`,n=Oe(e,i);return Be(n,i,["sourceId","artifactLabel","compressedSha256","compressedBytes","uncompressedSha256","uncompressedBytes","selector","candidateSpecificationCount"]),Te(n.compressedSha256,`${i}.compressedSha256`,_e),Le(n.compressedBytes,`${i}.compressedBytes`),Te(n.uncompressedSha256,`${i}.uncompressedSha256`,_e),Le(n.uncompressedBytes,`${i}.uncompressedBytes`),Te(n.selector,`${i}.selector`,void 0,512),Le(n.candidateSpecificationCount,`${i}.candidateSpecificationCount`),{sourceId:Te(n.sourceId,`${i}.sourceId`,void 0,160),artifactLabel:Te(n.artifactLabel,`${i}.artifactLabel`,void 0,512)}}function tt(e,t){let i=`audit.partialStudioSpecEvidence.specifications[${t}]`,n=Oe(e,i);Be(n,i,["identity","canonicalBodySha256","specification","sourceIds","authorizesConversion"]),!1!==qe(n.authorizesConversion,`${i}.authorizesConversion`)&&De(i,"grants authority");let o=Ze(n.identity,`${i}.identity`),a=Oe(n.specification,`${i}.specification`);Be(a,`${i}.specification`,["schemaVersion","canonicalizationVersion","id","modelType","mode","executionProfileId","loaderModule","loaderAction","executionPath","pipelineClass","defaultRepo","roles","edges","bindings","autoFields","actions","contentHash"],["auxiliaryTerminalRoles"]),(1!==a.schemaVersion||a.id!==o.id||a.contentHash!==o.contentHash||a.executionProfileId!==o.executionProfileId)&&De(`${i}.specification`,"does not match its evidence identity");let s=ze(a.roles,`${i}.specification.roles`),r=ze(a.edges,`${i}.specification.edges`),c=ze(a.bindings,`${i}.specification.bindings`),d=ze(a.actions,`${i}.specification.actions`);return ze(a.autoFields,`${i}.specification.autoFields`),void 0!==a.auxiliaryTerminalRoles&&Ke(a.auxiliaryTerminalRoles,`${i}.specification.auxiliaryTerminalRoles`),{identity:o,canonicalBodySha256:Te(n.canonicalBodySha256,`${i}.canonicalBodySha256`,_e),sourceIds:Ke(n.sourceIds,`${i}.sourceIds`),modelType:Te(a.modelType,`${i}.specification.modelType`,void 0,512),mode:Te(a.mode,`${i}.specification.mode`,void 0,512),pipelineClass:Te(a.pipelineClass,`${i}.specification.pipelineClass`,void 0,512),roleCount:s.length,edgeCount:r.length,bindingCount:c.length,actionCount:d.length}}function it(e){let t=Oe(e,"response");Be(t,"response",["error","audit"]),!1!==t.error&&De("response.error","must be false");let i=Oe(t.audit,"audit");Be(i,"audit",["schemaVersion","kind","boundary","localEvidence","summary","partialStudioSpecEvidence","identities","contentHash"]),(4!==i.schemaVersion||"registered_cluster_manifest_recovery_audit"!==i.kind)&&De("audit","uses an unsupported contract");let n=Oe(i.boundary,"audit.boundary");Be(n,"audit.boundary",["readOnly","containsWorkflowPaths","containsInstanceIds","containsPromptOrParameterValues","historicalHashAloneIsNotExecutionAuthority","presentationProjectionIsNotDefinitionAuthority","recoveredStudioSpecEvidenceDoesNotAuthorizeConversion","compilerMappingPresenceAloneDoesNotAuthorizeConversion"]);let o=qe(n.readOnly,"audit.boundary.readOnly"),a=qe(n.containsWorkflowPaths,"audit.boundary.containsWorkflowPaths"),s=qe(n.containsInstanceIds,"audit.boundary.containsInstanceIds"),r=qe(n.containsPromptOrParameterValues,"audit.boundary.containsPromptOrParameterValues"),c=qe(n.historicalHashAloneIsNotExecutionAuthority,"audit.boundary.historicalHashAloneIsNotExecutionAuthority"),d=qe(n.presentationProjectionIsNotDefinitionAuthority,"audit.boundary.presentationProjectionIsNotDefinitionAuthority"),l=qe(n.recoveredStudioSpecEvidenceDoesNotAuthorizeConversion,"audit.boundary.recoveredStudioSpecEvidenceDoesNotAuthorizeConversion"),u=qe(n.compilerMappingPresenceAloneDoesNotAuthorizeConversion,"audit.boundary.compilerMappingPresenceAloneDoesNotAuthorizeConversion");(!0!==o||!1!==a||!1!==s||!1!==r||!0!==c||!0!==d||!0!==l||!0!==u)&&De("audit.boundary","weakens the read-only evidence boundary"),Oe(i.localEvidence,"audit.localEvidence");let p=Oe(i.summary,"audit.summary");Be(p,"audit.summary",Je);let m=Object.fromEntries(Je.map(e=>[e,Le(p[e],`audit.summary.${e}`)]));(m.compilerMappingEligibleInstanceCount+m.remainingBlockedHistoricalInstanceCount!==m.legacyClusterInstanceCount-m.currentExecutionTupleExactInstanceCount-m.semanticEquivalenceReviewedInstanceCount||m.compilerMappingEligibleIdentityCount+m.remainingBlockedHistoricalIdentityCount!==m.definitionIdentityCount-m.currentExecutionTupleExactIdentityCount-m.semanticEquivalenceReviewedIdentityCount)&&De("audit.summary","has inconsistent historical compiler-mapping progress");let h=Oe(i.partialStudioSpecEvidence,"audit.partialStudioSpecEvidence");Be(h,"audit.partialStudioSpecEvidence",["status","authorizesConversion","sources","specifications","manualReviews"]);let f=Te(h.status,"audit.partialStudioSpecEvidence.status");"matched"!==f&&"no_matching_evidence"!==f&&De("audit.partialStudioSpecEvidence.status"),!1!==qe(h.authorizesConversion,"audit.partialStudioSpecEvidence.authorizesConversion")&&De("audit.partialStudioSpecEvidence","grants authority");let g=ze(h.sources,"audit.partialStudioSpecEvidence.sources").map(et),v=ze(h.specifications,"audit.partialStudioSpecEvidence.specifications").map(tt);ze(h.manualReviews,"audit.partialStudioSpecEvidence.manualReviews").forEach((e,t)=>Oe(e,`audit.partialStudioSpecEvidence.manualReviews[${t}]`));let y=ze(i.identities,"audit.identities").map(Qe);return m.definitionIdentityCount!==y.length&&De("audit.summary.definitionIdentityCount"),m.recoveredStudioSpecBodyCount!==v.length&&De("audit.summary.recoveredStudioSpecBodyCount"),{schemaVersion:4,kind:"registered_cluster_manifest_recovery_audit",contentHash:Te(i.contentHash,"audit.contentHash",_e),boundary:{readOnly:!0,containsWorkflowPaths:!1,containsInstanceIds:!1,containsPromptOrParameterValues:!1,historicalHashAloneIsNotExecutionAuthority:!0,presentationProjectionIsNotDefinitionAuthority:!0,recoveredStudioSpecEvidenceDoesNotAuthorizeConversion:!0,compilerMappingPresenceAloneDoesNotAuthorizeConversion:!0},summary:m,evidenceStatus:f,evidenceSources:g,specifications:v,identities:y}}function nt(){return f(`${E.serverAddress}/studio/composite-migrations/recovery-audit`,{timeoutMs:6e4,parse:it})}var ot=/^user-workflows\/([A-Za-z0-9_-]{1,96})\.json$/u;function at(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function st(e,t){return et)}function rt(...e){return e.join("\0")}function ct(e,t){return d(e)===d(t)}function dt(e){throw Error(e)}function lt(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function ut(e,t){return(!e.position||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y))&&dt(`${t} has no exact finite persisted position.`),{x:e.position.x,y:e.position.y}}function pt(e){let t=ot.exec(e);return t||dt(`Compiler candidate source path ${e} is not a saved workflow path.`),t[1]}async function mt(e,t){let i=pt(e);return f(`${E.serverAddress}/workflows/${encodeURIComponent(i)}`,{timeoutMs:12e4,signal:t,parse:t=>function(e,t){(!at(e)||"string"!=typeof e.id||!at(e.snapshot))&&dt(`Saved workflow ${t} is malformed.`);let i=pt(t);e.id!==i&&dt(`Saved workflow ${t} returned a different workflow id.`);let n=e.snapshot.nodes,o=e.snapshot.edges;return(!Array.isArray(n)||!Array.isArray(o))&&dt(`Saved workflow ${t} has no exact graph snapshot.`),{id:i,sourcePath:t,snapshot:{nodes:structuredClone(n),edges:structuredClone(o)}}}(t,e)})}function ht(e,t){return e.snapshot.nodes.filter(e=>e.id!==t&&(e.parentId===t||e.data?.huggingFaceClusterInstanceId===t)).sort((e,t)=>st(e.id,t.id))}function ft(e,t,i){e.id||dt("Legacy registered Cluster candidate has no instance id."),(!e.sourceSha256||!e.legacyCompositeHash)&&dt("Backend preview did not provide the exact source and legacy composite hashes.");let n=t.snapshot.nodes.filter(t=>t.id===e.id);1!==n.length&&dt(`Legacy Cluster ${e.id} does not resolve to exactly one saved root.`);let o=n[0],a=o.data?.huggingFaceClusterInstance;("cluster"!==o.type||"cluster"!==o.data?.type||"root"!==o.data?.huggingFaceClusterRole||!a||a.instanceId!==o.id)&&dt(`Saved node ${e.id} is not one exact legacy registered Cluster root.`),null!==a.structuralFork&&dt(`Legacy Cluster ${e.id} is structurally forked.`);let s=a.execution;s||dt(`Legacy Cluster ${e.id} has no execution receipt.`);let r=i.filter(({id:e})=>e===a.definition.id),c=r.find(e=>e.libraryRevision===a.definition.libraryRevision&&e.contentHash===a.definition.contentHash),d=e.semanticEquivalenceAuthority??null,l=e.historicalCompilerMappingAuthority??null;d&&l&&dt(`Legacy Cluster ${e.id} has conflicting historical review authorities.`);let u=d??l;if(!c){u||(r.length&&dt(`Legacy Cluster ${e.id} uses historical manifest ${a.definition.contentHash}; no reviewed archived definition or equivalence receipt is registered.`),dt(`Legacy Cluster ${e.id} references an unavailable catalog definition ${a.definition.id}.`));let t=u.historical;(t.manifestDefinitionId!==a.definition.id||t.libraryRevision!==a.definition.libraryRevision||t.manifestContentHash!==a.definition.contentHash||t.executionAdmissionId!==s.admissionId||!ct(t.studioExecutionSpec,s.studioExecutionSpec))&&dt(`Legacy Cluster ${e.id} does not match the reviewed historical compiler authority.`);let n=u.destination,o=i.filter(e=>e.id===n.manifestDefinitionId&&e.libraryRevision===n.libraryRevision&&e.contentHash===n.manifestContentHash);1!==o.length&&dt(`Legacy Cluster ${e.id} historical compiler destination is unavailable or ambiguous.`),c=o[0]}let p=u?u.destination.executionAdmissionId:s.admissionId,m=c.executionAdmissions.find(({id:e})=>e===p);m||dt(`Legacy Cluster ${e.id} references an unavailable execution admission.`),!u&&(m.studioExecutionSpec?.id!==s.studioExecutionSpec.id||m.studioExecutionSpec?.contentHash!==s.studioExecutionSpec.contentHash||m.studioExecutionSpec?.executionProfileId!==s.studioExecutionSpec.executionProfileId)&&dt(`Legacy Cluster ${e.id} has a stale Studio execution specification receipt.`);let h=P(c,m);return h||dt(`Legacy Cluster ${e.id} is not an exact current registered Block V2 route.`),(!lt(o.width)||!lt(o.height))&&dt(`Legacy Cluster ${e.id} has no exact positive persisted width and height.`),ut(o,`Legacy Cluster ${e.id}`),{candidate:e,workflow:t,root:o,children:ht(t,o.id),edges:t.snapshot.edges,instance:a,definition:c,route:h,semanticEquivalenceAuthority:d,historicalCompilerMappingAuthority:l}}function gt(e,t,i){let n=new Map(i.map(e=>[e.legacyNodeId,e.semanticNodeId])),o=new Set;return t.effectiveGraph.nodes.forEach(t=>{if(!t.semanticRole)return;o.has(t.semanticRole)&&dt(`Compiled graph has duplicate semantic role ${t.semanticRole}; legacy endpoint ownership is ambiguous.`),o.add(t.semanticRole);let i=F(e.root.id,`diffusers.cluster-execution:${encodeURIComponent(t.semanticRole)}`),a=n.get(i);a&&a!==t.nodeId&&dt(`Legacy execution endpoint ${i} maps to conflicting semantic nodes.`),n.set(i,t.nodeId)}),n}function vt(e,t,i,n){let o=("input"===t?e.effectiveInterface.boundary.inputs:e.effectiveInterface.boundary.outputs).filter(e=>function(e){return[e.binding,...e.mirrorBindings??[]].map(({nodeId:e,fieldOrPortId:t})=>({nodeId:e,fieldId:t}))}(e).some(e=>e.nodeId===i&&e.fieldId===n));return 1!==o.length&&dt(`Legacy ${t} endpoint ${i}.${n} does not resolve to exactly one V2 public port.`),o[0]}function yt(e,t,i){let n=gt(e,t,i),o=new Set([e.root.id,...e.children.map(({id:e})=>e)]),a=new Map;return Object.entries(e.root.data.params??{}).forEach(([t,i])=>{let n=i.fieldOptions?.huggingFaceClusterPortDirection;if("input"!==n&&"output"!==n)return;let o={direction:n,legacyNodeId:e.root.id,legacyPortId:t};a.set(rt(n,e.root.id,t),o)}),e.edges.forEach(e=>{let t=o.has(e.source),i=o.has(e.target);if(t!==i){if(t){e.sourceHandle||dt(`Crossing edge ${e.id} has no exact source handle.`);let t={direction:"output",legacyNodeId:e.source,legacyPortId:e.sourceHandle};a.set(rt(t.direction,t.legacyNodeId,t.legacyPortId),t)}if(i){e.targetHandle||dt(`Crossing edge ${e.id} has no exact target handle.`);let t={direction:"input",legacyNodeId:e.target,legacyPortId:e.targetHandle};a.set(rt(t.direction,t.legacyNodeId,t.legacyPortId),t)}}}),[...a.values()].map(i=>{let o=function(e,t,i,n,o){if(n!==e.root.id){let e=t.get(n);return e||dt(`Legacy boundary endpoint ${n}.${o} is not an owned projection.`),{semanticNodeId:e,fieldId:o}}let a=e.root.data.params?.[o],s=at(a?.fieldOptions)?a.fieldOptions:{};(s.huggingFaceClusterPortDirection!==i||"string"!=typeof s.huggingFaceClusterPortNodeId||"string"!=typeof s.huggingFaceClusterPortField)&&dt(`Legacy root port ${o} has incomplete ${i} metadata.`);let r=t.get(s.huggingFaceClusterPortNodeId);return r||dt(`Legacy root port ${o} targets a projection that is absent from the saved snapshot.`),{semanticNodeId:r,fieldId:s.huggingFaceClusterPortField}}(e,n,i.direction,i.legacyNodeId,i.legacyPortId);return{...i,v2PortId:vt(t,i.direction,o.semanticNodeId,o.fieldId).portId}}).sort((e,t)=>st(rt(e.direction,e.legacyNodeId,e.legacyPortId,e.v2PortId),rt(t.direction,t.legacyNodeId,t.legacyPortId,t.v2PortId)))}function xt(e,t,i){let n=e.effectiveInterface.controls.filter(e=>[e.binding,...e.mirrorBindings??[]].some(e=>e.nodeId===t&&e.fieldId===i));return 1===n.length?n[0]:null}function bt(e){return null===e?"null":Array.isArray(e)?"array":"object"==typeof e?"object":"number"==typeof e?Number.isInteger(e)?"integer":"number":typeof e}function It(e,t,i={}){if(null===e)return!0!==i.required||null===i.defaultValue;let n=_(t);return!!(Array.isArray(n)?n:[n]).some(t=>{if("string"!=typeof t)return!1;let i=t.trim().toLowerCase();return"string"===i||"text"===i||"str"===i||"dropdown"===i?"string"==typeof e:"bool"===i||"boolean"===i?"boolean"==typeof e:"int"===i||"integer"===i?"number"==typeof e&&Number.isInteger(e):"float"===i||"double"===i||"number"===i?"number"==typeof e&&Number.isFinite(e):"minimax_h3_references"===i||/^(?:list|array|sequence|tuple|set)(?:\[|$)/u.test(i)?Array.isArray(e):/^(?:dict|mapping|object|json)(?:\[|$)/u.test(i)?at(e):!!/^(?:image|video|audio|file|path|uri|url|media)(?:\b|_)/u.test(i)&&("string"==typeof e||at(e))})||void 0!==i.defaultValue&&null!==i.defaultValue&&function(e,t){let i=bt(e),n=bt(t);return i===n||"integer"===i&&"number"===n}(e,i.defaultValue)}async function Ct(e,t){let i=await O(e.definition,function(e){if(!e.semanticEquivalenceAuthority&&!e.historicalCompilerMappingAuthority)return e.root;let t=e.definition.executionAdmissions.find(({id:t})=>t===e.route.admissionId);t||dt(`Current destination admission ${e.route.admissionId} is unavailable.`);let i={...I(t.studioMode,e.definition.pipelineClass),modelType:e.definition.pipelineClass,mode:t.studioMode},{parameterOverrides:n,executionParameterOverrides:o}=R(e.definition,t,i),a=e.definition.suggestedInputs?.values??{},s=Object.fromEntries(Object.entries(n).filter(([e,t])=>!(""===t&&Object.prototype.hasOwnProperty.call(a,e)))),r=w(e.definition,e.root.id,ut(e.root,`Legacy Cluster ${e.root.id}`),{...a,...s},t.id,o);r.width=e.root.width,r.height=e.root.height;let c=r.data.huggingFaceClusterInstance;return c?.execution||dt(`Current destination compiler root ${e.root.id} has no execution receipt.`),r.data.huggingFaceClusterInstance={...c,presentation:{...c.presentation,expanded:e.instance.presentation.expanded}},r}(e),{timeoutMs:t}),n=[...i.definition.contentHash===e.route.compiledDefinitionContentHash?[]:["definition content hash"],...i.instance.definitionSnapshot.source.executionAdmissionId===e.route.admissionId?[]:["execution admission"],...i.instance.authorities.length?["instance authorities"]:[],...i.instance.effectiveGraph.graphHash===i.definition.graph.graphHash?[]:["effective graph"]];n.length&&dt(`Compiled registered definition for ${e.root.id} is stale or structurally customized (${n.join(", ")}).`);let o=e.semanticEquivalenceAuthority??e.historicalCompilerMappingAuthority;o&&(ct(o.destination,{manifestDefinitionId:e.route.definitionId,libraryRevision:e.route.libraryRevision,manifestContentHash:e.route.definitionContentHash,executionAdmissionId:e.route.admissionId,blockDefinitionId:i.definition.definitionId,blockDefinitionContentHash:i.definition.contentHash,blockDefinitionCanonicalSha256:e.route.compiledDefinitionCanonicalSha256,executionGraphHash:i.definition.graph.graphHash,interfaceHash:g({boundary:i.definition.boundary,controls:i.definition.controls})})||dt(`Reviewed historical compiler authority for ${e.root.id} is stale for the compiled BlockDefinitionV2 graph or interface.`));let a=function(e,t){let i=new Map;t.effectiveGraph.nodes.forEach(e=>{let t=e.semanticRole;t&&i.set(t,[...i.get(t)??[],e.nodeId])});let n=e.children.map(t=>{let n=t.data,o=n?.huggingFaceClusterExecutionRole;("execution"!==n?.huggingFaceClusterRole||n.huggingFaceClusterInstanceId!==e.root.id||n.huggingFaceClusterExecutionAdmissionId!==e.instance.execution?.admissionId||n.huggingFaceClusterExecutionSpecId!==e.instance.execution.studioExecutionSpec.id||!o)&&dt(`Legacy projection ${t.id} has incomplete or stale execution ownership.`);let a=i.get(o)??[];return 1!==a.length&&dt(`Legacy projection ${t.id} cannot be mapped one-to-one to semantic role ${o}.`),{legacyNodeId:t.id,semanticNodeId:a[0]}}),o=n.map(({semanticNodeId:e})=>e);return new Set(o).size!==o.length&&dt(`Legacy Cluster ${e.root.id} would merge multiple projection nodes.`),n.sort((e,t)=>st(rt(e.legacyNodeId,e.semanticNodeId),rt(t.legacyNodeId,t.semanticNodeId)))}(e,i.instance),s=function(e,t,i){let n={...t.presentation.internalLayout};return i.forEach(({legacyNodeId:t,semanticNodeId:i})=>{let o=e.children.find(({id:e})=>e===t);n[i]={...ut(o,`Legacy projection ${t}`),...lt(o.width)?{width:o.width}:{},...lt(o.height)?{height:o.height}:{}}}),x({...t,presentation:{...t.presentation,internalLayout:n}})}(e,i.instance,a),r=function(e,t,i){let n=gt(e,t,i),o=[],a={...t.values},s=new Map;(function(e){let t=[];return[e.root,...e.children].sort((e,t)=>st(e.id,t.id)).forEach(e=>{Object.entries(e.data.params??{}).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>{Object.prototype.hasOwnProperty.call(n,"value")&&"output"!==n.display&&t.push({sourceKind:"node_param",sourceNodeId:e.id,sourceFieldId:i,value:structuredClone(n.value)})})}),Object.entries(e.instance.parameterOverrides).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>t.push({sourceKind:"instance_parameter_override",sourceNodeId:e.root.id,sourceFieldId:i,value:structuredClone(n)})),Object.entries(e.instance.execution?.parameterOverrides??{}).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>t.push({sourceKind:"execution_parameter_override",sourceNodeId:e.root.id,sourceFieldId:i,value:structuredClone(n)})),t})(e).forEach(i=>{let r=function(e,t,i,n){if("instance_parameter_override"===n.sourceKind||"execution_parameter_override"===n.sourceKind)return new Set([...t.effectiveInterface.controls.map(({controlId:e})=>e),...t.effectiveInterface.boundary.inputs.map(({portId:e})=>e)]).has(n.sourceFieldId)||dt(`Legacy override ${n.sourceKind}/${n.sourceFieldId} has no exact V2 input/control.`),{targetKind:"instance_value",targetValueId:n.sourceFieldId};if(n.sourceNodeId===e.root.id){let o=e.root.data.params[n.sourceFieldId]?.fieldOptions;if("input"===o?.huggingFaceClusterPortDirection&&"string"==typeof o.huggingFaceClusterPortNodeId&&"string"==typeof o.huggingFaceClusterPortField){let e=i.get(o.huggingFaceClusterPortNodeId),a=e?xt(t,e,o.huggingFaceClusterPortField):null;return a||dt(`Legacy root value ${n.sourceFieldId} has ambiguous input-port ownership.`),{targetKind:"instance_value",targetValueId:a.controlId}}return new Set([...t.effectiveInterface.controls.map(({controlId:e})=>e),...t.effectiveInterface.boundary.inputs.map(({portId:e})=>e)]).has(n.sourceFieldId)||dt(`Legacy root value ${n.sourceFieldId} has no exact V2 input/control.`),{targetKind:"instance_value",targetValueId:n.sourceFieldId}}let o=i.get(n.sourceNodeId);o||dt(`Legacy value ${n.sourceNodeId}.${n.sourceFieldId} is outside the owned projection.`);let a=function(e){let t=e?.fieldOptions?.huggingFaceClusterBinding;return!at(t)||1!==t.schemaVersion||"string"!=typeof t.source||"instance_input"!==t.persistence&&"execution_parameter"!==t.persistence&&"sealed"!==t.persistence||void 0!==t.input&&"string"!=typeof t.input?null:t}(e.children.find(({id:e})=>e===n.sourceNodeId).data.params[n.sourceFieldId]);if("instance_input"===a?.persistence||"execution_parameter"===a?.persistence){let e=xt(t,o,n.sourceFieldId);return e||dt(`Legacy mutable field ${n.sourceNodeId}.${n.sourceFieldId} has no exact V2 control.`),{targetKind:"instance_value",targetValueId:e.controlId}}let s=t.effectiveGraph.nodes.find(({nodeId:e})=>e===o),r=(at(s?.data.params)?s.data.params:{})[n.sourceFieldId];return(!at(r)||!Object.prototype.hasOwnProperty.call(r,"value"))&&dt(`Legacy static field ${n.sourceNodeId}.${n.sourceFieldId} has no exact V2 graph parameter.`),{targetKind:"graph_param",targetNodeId:o,targetFieldId:n.sourceFieldId}}(e,t,n,i);if("instance_value"===r.targetKind){!function(e,t,i){let n=e.effectiveInterface.controls.filter(({controlId:e})=>e===t),o=e.effectiveInterface.boundary.inputs.filter(({portId:e})=>e===t);n.length+o.length===0&&dt(`Legacy value ${t} does not target a declared V2 input/control.`),n.forEach(e=>{e.sealed&&!ct(i,e.defaultValue)&&dt(`Legacy value ${t} attempts to rewrite a sealed V2 control.`),It(i,e.valueType,{...void 0===e.defaultValue?{}:{defaultValue:e.defaultValue},required:e.required})||dt(`Legacy value ${t} is incompatible with V2 control type ${String(e.valueType)}.`)}),o.forEach(e=>{It(i,e.valueType,{required:e.required})||dt(`Legacy value ${t} is incompatible with V2 input type ${String(e.valueType)}.`)})}(t,r.targetValueId,i.value);let e=s.get(r.targetValueId);void 0!==e&&!ct(e,i.value)&&dt(`Legacy sources disagree for V2 input/control ${r.targetValueId}.`),s.set(r.targetValueId,i.value),a[r.targetValueId]=i.value}else{let e=t.effectiveGraph.nodes.find(({nodeId:e})=>e===r.targetNodeId).data.params[r.targetFieldId];(!at(e)||!ct(e.value,i.value))&&dt(`Legacy static value ${i.sourceNodeId}.${i.sourceFieldId} differs from the pinned definition.`)}o.push({sourceKind:i.sourceKind,sourceNodeId:i.sourceNodeId,sourceFieldId:i.sourceFieldId,...r})}),o.sort((e,t)=>st(rt(e.sourceKind,e.sourceNodeId,e.sourceFieldId,e.targetKind),rt(t.sourceKind,t.sourceNodeId,t.sourceFieldId,t.targetKind)));let r=t.effectiveInterface.boundary.inputs.some(({portId:e})=>Object.prototype.hasOwnProperty.call(a,e))||t.effectiveInterface.controls.some(e=>Object.prototype.hasOwnProperty.call(a,e.controlId)&&!ct(a[e.controlId],e.defaultValue));return{mappings:o,instance:x({...t,values:a,customization:{...t.customization,state:r?"parameters_changed":"unchanged"}})}}(e,s,a);s=r.instance;let c=function(e,t,i){let n=gt(e,t,i),o=structuredClone(t.previewStates),a=[];return function(e){return[e.root,...e.children].flatMap(e=>Object.entries(e.data.params??{}).flatMap(([t,i])=>"output"!==i.display||null===i.value||void 0===i.value?[]:(("string"!=typeof i.value||!i.value)&&dt(`Legacy output ${e.id}.${t} is not a persistable media reference.`),[{node:e,fieldId:t,mediaReference:i.value}])))}(e).forEach(({node:t,fieldId:i,mediaReference:s})=>{let r,c=i;if(t.id===e.root.id){let e=t.data.params[i]?.fieldOptions,o="string"==typeof e?.huggingFaceClusterPreviewSourceNodeId?e.huggingFaceClusterPreviewSourceNodeId:"output"===e?.huggingFaceClusterPortDirection&&"string"==typeof e.huggingFaceClusterPortNodeId?e.huggingFaceClusterPortNodeId:null,a="string"==typeof e?.huggingFaceClusterPreviewSourceField?e.huggingFaceClusterPreviewSourceField:"output"===e?.huggingFaceClusterPortDirection&&"string"==typeof e.huggingFaceClusterPortField?e.huggingFaceClusterPortField:null;(!o||!a)&&dt(`Legacy root output ${i} has no exact preview-source metadata.`),r=n.get(o),c=a}else r=n.get(t.id);r||dt(`Legacy output ${t.id}.${i} targets an absent projection.`);let d=o.map((e,t)=>({state:e,index:t})).filter(({state:e})=>e.binding.nodeId===r&&e.binding.outputPortId===c);1!==d.length&&dt(`Legacy output ${t.id}.${i} does not resolve to exactly one V2 preview binding.`);let l=d[0];l.state.mediaReference&&l.state.mediaReference!==s&&dt(`Legacy outputs conflict for V2 preview ${r}.${c}.`),o[l.index]={...l.state,mediaReference:s,status:"complete"},a.push({sourceNodeId:t.id,sourceFieldId:i,targetNodeId:r,targetOutputPortId:c})}),a.sort((e,t)=>st(rt(e.sourceNodeId,e.sourceFieldId,e.targetNodeId,e.targetOutputPortId),rt(t.sourceNodeId,t.sourceFieldId,t.targetNodeId,t.targetOutputPortId))),{mappings:a,instance:x({...t,previewStates:o})}}(e,s,a);s=c.instance;let d=new Set([e.root.id,...e.children.map(({id:e})=>e)]),l=e.edges.filter(e=>d.has(e.source)&&d.has(e.target)).map(t=>(t.id||dt(`Legacy Cluster ${e.root.id} has an internal edge without an id.`),t.id)).sort(st);return new Set(l).size!==l.length&&dt(`Legacy Cluster ${e.root.id} has duplicate internal edge ids.`),{legacyInstanceId:e.root.id,legacyCompositeHash:e.candidate.legacyCompositeHash,admissionId:e.route.admissionId,compiledDefinitionContentHash:e.route.compiledDefinitionContentHash,compiledDefinitionCanonicalSha256:e.route.compiledDefinitionCanonicalSha256,blockInstanceV2:s,ownedNodeMappings:a,portMappings:yt(e,s,a),valueMappings:r.mappings,previewMappings:c.mappings,absorbedInternalEdgeIds:l,...e.semanticEquivalenceAuthority?{semanticEquivalenceReceipt:{receiptId:e.semanticEquivalenceAuthority.receiptId,receiptHash:e.semanticEquivalenceAuthority.receiptHash}}:{},...e.historicalCompilerMappingAuthority?{historicalCompilerMapping:{mappingId:e.historicalCompilerMappingAuthority.mappingId,mappingHash:e.historicalCompilerMappingAuthority.mappingHash}}:{}}}function wt(e,t){let i=e instanceof Error?e.message:String(e),n=i.includes("historical manifest")?"historical_manifest_unavailable":i.includes("no execution receipt")?"execution_receipt_missing":i.includes("source and legacy composite hashes")?"candidate_receipt_missing":i.includes("saved root")||i.includes("projection")||i.includes("ambiguous")?"legacy_snapshot_ambiguous":i.includes("route")||i.includes("admission")||i.includes("catalog definition")?"registered_route_unavailable":i.includes("workflow")?"workflow_unavailable":"compiler_failed";return{sourcePath:t.sourcePath,instanceId:t.id,code:n,message:i}}async function $t(e){let t=l(),i=e.candidates.filter(({kind:e,status:t})=>"legacy_registered_cluster_instance"===e&&"blocked"===t).sort((e,t)=>st(rt(e.sourcePath,e.id??""),rt(t.sourcePath,t.id??""))),n=await async function(){let e=b.getState(),t=v.getState();await Promise.all([e.loaded?Promise.resolve():e.fetchLibrary(),Object.keys(t.nodesRegistry).length?Promise.resolve():t.fetchNodes(),t.studioModelCapabilities.length?Promise.resolve():t.fetchStudioModelCapabilities()]);let i=b.getState();return i.library||dt(i.error||"The Hugging Face node library is unavailable."),Object.keys(v.getState().nodesRegistry).length||dt("The backend node registry is unavailable."),i.library}();if(n.definitions.some(({provider:e})=>"diffusers"===e)){let e=C.getState();e.loaded||await e.fetchSnapshot()}m(t,{includeForm:!1})||dt("The active workflow changed while compiler dependencies were loading. Generate a fresh supplement.");let o=null,a=[],s=new Map,r=0;for(let c of i){if(e.signal?.aborted)throw new DOMException("Compiler supplement generation was cancelled.","AbortError");m(t,{includeForm:!1})||dt("The active workflow changed during compiler supplement generation. Generate a fresh supplement.");try{o?.sourcePath!==c.sourcePath&&(o=await mt(c.sourcePath,e.signal));let i=o;m(t,{includeForm:!1})||dt("The active workflow changed while a saved workflow was loading. Generate a fresh supplement.");let a=await Ct(ft(c,i,n.definitions),e.timeoutMs);m(t,{includeForm:!1})||dt("The active workflow changed during compiler supplement generation. Generate a fresh supplement."),s.set(c.sourcePath,[...s.get(c.sourcePath)??[],a])}catch(e){if(!m(t,{includeForm:!1}))throw e;a.push(wt(e,c))}finally{r+=1,e.onProgress?.({completed:r,total:i.length,sourcePath:c.sourcePath,instanceId:c.id})}}let c=ge({schemaVersion:1,kind:"registered_cluster_v2_compiler_supplement",compilerOutputs:[...s.entries()].sort(([e],[t])=>st(e,t)).map(([e,t])=>({sourcePath:e,sourceSha256:i.find(({sourcePath:t})=>t===e).sourceSha256,conversions:t.sort((e,t)=>st(e.legacyInstanceId,t.legacyInstanceId))}))});return(new TextEncoder).encode(JSON.stringify(c)).byteLength>33554432&&dt("Generated compiler supplement exceeds the reviewed 32 MiB request limit."),{supplement:c,diagnostics:a.sort((e,t)=>st(rt(e.sourcePath,e.instanceId??"",e.code),rt(t.sourcePath,t.instanceId??"",t.code))),candidateCount:i.length,conversionCount:c.compilerOutputs.reduce((e,t)=>e+t.conversions.length,0)}}var Nt=a();function St(e){return e.replace(/_/g," ")}function jt(e){return"applied"===e||"rolled_back"===e?"success":"interrupted"===e?"warning":"error"}function kt({audit:e,error:t,loading:i,onRefresh:n}){let a=e?.identities.filter(e=>"partial_evidence_available"===e.recoveredStudioSpecs.status)??[];return(0,Nt.jsxs)("div",{className:"grid gap-3","data-testid":"legacy-cluster-recovery-evidence-panel",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"This read-only audit reports historical recovery evidence and checked-in compiler-mapping coverage. It does not compile, convert, execute, approve, or mutate a Block by itself. Mapping-ready instances still require an exact compiler supplement, reviewed preview, and explicit apply confirmation."}),(0,Nt.jsx)(M,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(c,{size:14}),loading:i,disabled:i,onClick:n,"data-testid":"legacy-cluster-recovery-evidence-refresh",children:"Refresh evidence"})]}),t?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/5 p-2 text-xs text-modiff-red",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{className:"break-words",children:t})]}):null,e?(0,Nt.jsxs)(Nt.Fragment,{children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2","data-testid":"legacy-cluster-recovery-evidence-summary",children:[(0,Nt.jsx)($,{label:`${e.summary.legacyClusterInstanceCount} saved Blocks`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.compilerMappingEligibleInstanceCount} mapping-ready instances`,tone:e.summary.compilerMappingEligibleInstanceCount?"success":"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.compilerMappingEligibleIdentityCount} mapping-ready ${1===e.summary.compilerMappingEligibleIdentityCount?"identity":"identities"}`,tone:e.summary.compilerMappingEligibleIdentityCount?"success":"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.remainingBlockedHistoricalInstanceCount} historical still blocked`,tone:e.summary.remainingBlockedHistoricalInstanceCount?"warning":"success"}),(0,Nt.jsx)($,{label:`${e.summary.remainingBlockedHistoricalIdentityCount} blocked ${1===e.summary.remainingBlockedHistoricalIdentityCount?"identity":"identities"}`,tone:e.summary.remainingBlockedHistoricalIdentityCount?"warning":"success"}),(0,Nt.jsx)($,{label:`${e.summary.recoveredStudioSpecBodyCount} recovered bodies`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.recoveredStudioSpecManifestIdentityCount} identities`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.recoveredStudioSpecExecutionTupleCount} execution tuples`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.recoveredStudioSpecInstanceCount} covered instances`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.partialReviewVerifiedExecutionTupleCount} partially reviewed`,tone:e.summary.partialReviewVerifiedExecutionTupleCount?"warning":"neutral"})]}),(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2 text-xs leading-5 text-modiff-text",children:"Read-only boundary: no workflow paths, instance IDs, prompts, or parameter values are included. A valid historical Studio-spec self-hash is partial evidence only; it is not manifest, interface, artifact, or execution authority. A checked-in compiler mapping covers only its exact archived tuple and does not, by its presence alone, authorize conversion or workflow mutation."}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:["Recovered Studio bodies (",e.specifications.length,")"]}),e.specifications.length?(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto","data-testid":"legacy-cluster-recovered-specifications",children:e.specifications.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"min-w-0",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.identity.id}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.modelType," · ",e.mode," · ",e.identity.executionProfileId]})]}),(0,Nt.jsx)($,{label:`${e.roleCount} roles · ${e.edgeCount} edges`,tone:"neutral"})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-subtle-text",children:[e.identity.contentHash," · ",e.canonicalBodySha256]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.bindingCount," bindings · ",e.actionCount," dynamic actions · sources:"," ",e.sourceIds.join(", ")]})]},e.canonicalBodySha256))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No exact local capture contains a matching body."})]}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:["Historical identities with partial evidence (",a.length,")"]}),a.length?(0,Nt.jsx)("div",{className:"grid max-h-80 gap-2 overflow-auto","data-testid":"legacy-cluster-recovered-identities",children:a.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1.5 rounded-modiff-compact border border-hf-orange/30 bg-modiff-bg p-2 text-xs",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.definitionId??"Malformed identity"}),(0,Nt.jsx)($,{label:`${e.instanceCount} instances`,tone:"warning"})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-subtle-text",children:[e.libraryRevision??"missing revision"," ·"," ",e.manifestContentHash??"missing hash"]}),e.executionTuples.filter(e=>"self_hash_valid_partial_evidence"===e.recoveredStudioSpec.status).map((e,t)=>(0,Nt.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border p-2",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.studioExecutionSpec?.id??"Missing Studio receipt"}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.instanceCount," instances · review ",St(e.manualReview.status)," · conversion authority: none"]})]},`${e.admissionId??"missing"}:${e.studioExecutionSpec?.contentHash??t}`)),(0,Nt.jsxs)("p",{className:"text-hf-orange",children:["Still missing: ",e.missingEvidence.map(({code:e})=>St(e)).join("; ")]})]},`${e.definitionId}:${e.libraryRevision}:${e.manifestContentHash}`))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No historical identity has recovered partial evidence."})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-xs text-modiff-subtle-text",children:["Audit: ",e.contentHash]})]}):i||t?null:(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No historical recovery audit is available."})]})}function Ht({preview:e}){let t=[...new Map(e.candidates.flatMap(e=>{let t=e.compilerReceipt?.semanticEquivalenceAuthority??e.semanticEquivalenceAuthority;return t?[[t.receiptHash,t]]:[]})).values()],i=[...new Map(e.candidates.flatMap(e=>{let t=e.compilerReceipt?.historicalCompilerMappingAuthority??e.historicalCompilerMappingAuthority;return t?[[t.mappingHash,t]]:[]})).values()];return(0,Nt.jsxs)("div",{className:"grid gap-3","data-testid":"composite-migration-preview-details",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)($,{label:`${e.summary.targetFileCount} target files`,tone:"neutral"}),(0,Nt.jsx)($,{label:`${e.summary.convertibleCandidateCount} convertible`,tone:e.summary.convertibleCandidateCount?"success":"neutral"}),e.compilerSupplement?(0,Nt.jsx)($,{label:`${e.summary.registeredClusterConvertibleCount??0} registered Blocks compiled`,tone:e.compilerSupplement.provided?"success":"neutral"}):null,(0,Nt.jsx)($,{label:`${e.summary.blockedCandidateCount} blocked`,tone:e.summary.blockedCandidateCount?"warning":"success"})]}),(0,Nt.jsxs)("div",{className:"grid gap-1 text-xs text-modiff-subtle-text",children:[(0,Nt.jsxs)("p",{className:"break-all",children:["Preview: ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.migrationId})]}),(0,Nt.jsxs)("p",{className:"break-all",children:["Plan hash: ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.planHash})]}),e.compilerSupplement?.contentHash?(0,Nt.jsxs)("p",{className:"break-all",children:["Compiler supplement:"," ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.compilerSupplement.contentHash})]}):null]}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Exact files that would change"}),e.targets.length?(0,Nt.jsx)("ul",{className:"max-h-44 space-y-1 overflow-auto rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:e.targets.map(e=>(0,Nt.jsx)("li",{className:"break-all font-mono text-xs text-modiff-text",children:e.sourcePath},e.sourcePath))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No safe conversion target is present."})]}),t.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-equivalence-diffs",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-yellow",children:"Reviewed historical equivalence (preview only)"}),(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto",children:t.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-hf-yellow/30 bg-hf-yellow/5 p-2 text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.receiptId}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Historical manifest: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.manifestContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Historical graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.historical.executionGraphHash," · ",e.historical.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination definition:"," ",(0,Nt.jsx)("span",{className:"font-mono",children:e.destination.blockDefinitionContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.destination.executionGraphHash," · ",e.destination.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:["Reviewed by ",e.review.issuer," at ",e.review.reviewedAt,": ",e.review.notes]}),(0,Nt.jsx)("p",{className:"text-hf-yellow",children:"This checked-in review enables exact compiler validation only; it does not apply or mutate a workflow."})]},e.receiptHash))})]}):null,i.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-archived-compiler-mappings",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-yellow",children:"Reviewed archived compiler mapping (preview only)"}),(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto",children:i.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-hf-yellow/30 bg-hf-yellow/5 p-2 text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.mappingId}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Archived manifest: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.manifestContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Archive record: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.archivedDefinitionRecordHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination definition:"," ",(0,Nt.jsx)("span",{className:"font-mono",children:e.destination.blockDefinitionContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.destination.executionGraphHash," · ",e.destination.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:["Reviewed by ",e.review.issuer," at ",e.review.reviewedAt,": ",e.review.notes]}),(0,Nt.jsx)("p",{className:"text-hf-yellow",children:"This maps one exact archived body to one exact compiler destination. Per-instance preservation, explicit Apply, byte backup, and rollback are still required."})]},e.mappingHash))})]}):null,e.blocked.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-blockers",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:"Blocked candidates remain unchanged"}),(0,Nt.jsx)("ul",{className:"max-h-44 space-y-2 overflow-auto rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2",children:e.blocked.map((e,t)=>(0,Nt.jsxs)("li",{className:"text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.id?`${e.id}: `:"",e.reason]})]},`${e.sourcePath}:${e.kind}:${e.id??t}`))})]}):null,e.inventoryIssues.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:"Inventory issues"}),(0,Nt.jsx)("ul",{className:"max-h-36 space-y-1 overflow-auto text-xs text-modiff-subtle-text",children:e.inventoryIssues.map((e,t)=>(0,Nt.jsxs)("li",{children:[(0,Nt.jsx)("span",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),": ",e.message]},`${e.sourcePath}:${e.path}:${e.code}:${t}`))})]}):null]})}function Pt({allowBlockedCandidates:e,busy:t,confirmation:i,error:n,onAllowBlockedCandidatesChange:o,onApply:a,onCancel:s,onConfirmationChange:r,preview:c}){let d=le(c,i,e);return(0,Nt.jsxs)("div",{className:"grid gap-4","data-testid":"composite-migration-apply-review",children:[(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-3 text-xs leading-5 text-modiff-text",children:"This action creates exact backups and replaces only the listed safe Block or workflow files. It never deletes, renames, or merges records. Blocked candidates remain unchanged."}),(0,Nt.jsx)(Ht,{preview:c}),c.summary.blockedCandidateCount>0?(0,Nt.jsx)(N,{checked:e,onCheckedChange:o,label:`Apply only the ${c.summary.targetFileCount} safe target files and leave all ${c.summary.blockedCandidateCount} blocked candidates unchanged.`,"data-testid":"composite-migration-allow-blocked"}):null,(0,Nt.jsx)(j,{label:(0,Nt.jsxs)("span",{children:["Type ",(0,Nt.jsx)("code",{className:"font-mono text-hf-yellow",children:T})]}),required:!0,error:n??void 0,children:(0,Nt.jsx)(A,{autoComplete:"off",spellCheck:!1,value:i,onChange:e=>r(e.currentTarget.value),"data-testid":"composite-migration-apply-confirmation"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 border-t border-modiff-border pt-3",children:[(0,Nt.jsx)(M,{disabled:t,onClick:s,children:"Cancel"}),(0,Nt.jsx)(M,{tone:"primary",loading:t,disabled:t||!d,onClick:a,"data-testid":"composite-migration-apply",children:"Apply reviewed migration"})]})]})}function At({busyId:e,migrations:i,onInspectRollback:n}){return i.length?(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto","data-testid":"composite-migration-recovery-list",children:i.map(i=>(0,Nt.jsxs)("section",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"min-w-0",children:[(0,Nt.jsx)("p",{className:"truncate font-mono text-xs text-modiff-text",title:i.migrationId,children:i.migrationId}),(0,Nt.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:[i.targets.length," targets · ",St(i.journalState)," journal"]})]}),(0,Nt.jsx)($,{label:St(i.effectiveState),tone:jt(i.effectiveState)})]}),(0,Nt.jsx)("ul",{className:"space-y-1",children:i.targets.map(e=>(0,Nt.jsxs)("li",{className:"flex min-w-0 items-start justify-between gap-2 text-xs",children:[(0,Nt.jsx)("span",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),(0,Nt.jsx)("span",{className:p("shrink-0 font-semibold","conflict"===e.state||"missing"===e.state?"text-modiff-red":"applied"===e.state?"text-modiff-green":"text-modiff-subtle-text"),children:e.state})]},e.sourcePath))}),i.rollbackAvailable?(0,Nt.jsx)("div",{children:(0,Nt.jsx)(M,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(t,{size:14}),loading:e===i.migrationId,disabled:!!e,onClick:()=>n(i),"data-testid":`composite-migration-inspect-${i.migrationId}`,children:"Review rollback"})}):null]},i.migrationId))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No migration recovery journals are present."})}function Et({busy:e,confirmation:t,error:i,onCancel:n,onConfirmationChange:o,onRollback:a,status:s}){return(0,Nt.jsxs)("div",{className:"grid gap-4","data-testid":"composite-migration-rollback-review",children:[(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-3 text-xs leading-5 text-modiff-text",children:"Rollback restores the exact backups for this journal. It refuses missing or independently changed files and has no force option."}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Exact files to restore"}),(0,Nt.jsx)("ul",{className:"max-h-44 space-y-1 overflow-auto rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:s.targets.map(e=>(0,Nt.jsxs)("li",{className:"break-all font-mono text-xs text-modiff-text",children:[e.sourcePath," ",(0,Nt.jsxs)("span",{className:"text-modiff-subtle-text",children:["(",e.state,")"]})]},e.sourcePath))})]}),(0,Nt.jsx)(j,{label:(0,Nt.jsxs)("span",{children:["Type ",(0,Nt.jsx)("code",{className:"font-mono text-hf-yellow",children:V})]}),required:!0,error:i??void 0,children:(0,Nt.jsx)(A,{autoComplete:"off",spellCheck:!1,value:t,onChange:e=>o(e.currentTarget.value),"data-testid":"composite-migration-rollback-confirmation"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 border-t border-modiff-border pt-3",children:[(0,Nt.jsx)(M,{disabled:e,onClick:n,children:"Cancel"}),(0,Nt.jsx)(M,{tone:"danger",loading:e,disabled:e||"ROLLBACK_BLOCK_V2_MIGRATION"!==t,onClick:a,"data-testid":"composite-migration-rollback",children:"Restore exact backups"})]})]})}function Rt(){let e=H(e=>e.workflowTabs.some(({dirty:e})=>e)),[t,a]=(0,B.useState)(null),[s,d]=(0,B.useState)([]),[l,u]=(0,B.useState)(!0),[p,m]=(0,B.useState)(null),[f,g]=(0,B.useState)(null),[v,x]=(0,B.useState)(!0),[b,I]=(0,B.useState)(null),[C,w]=(0,B.useState)(null),[N,P]=(0,B.useState)(null),[A,E]=(0,B.useState)(""),[R,_]=(0,B.useState)(null),[F,D]=(0,B.useState)([]),[O,T]=(0,B.useState)(null),[V,L]=(0,B.useState)(!1),[q,z]=(0,B.useState)(""),[K,G]=(0,B.useState)(!1),[J,Z]=(0,B.useState)(null),[W,Y]=(0,B.useState)(""),[U,X]=(0,B.useState)(null),Q=(0,B.useRef)(0),ee=(0,B.useRef)(0),te=(0,B.useRef)(0),ie=(0,B.useRef)(null),ne=(0,B.useRef)(!1),oe=(0,B.useRef)(null),ae=(0,B.useCallback)(async()=>{let e=++Q.current;u(!0);try{let[t,i]=await Promise.all([He(oe.current??void 0),Pe()]);if(e!==Q.current)return;a(t),d(i.migrations),m(null)}catch(t){e===Q.current&&m(ke(t,"Could not inspect legacy composite migrations."))}finally{e===Q.current&&u(!1)}},[]),se=(0,B.useCallback)(async()=>{let e=++ee.current;x(!0);try{let t=await nt();if(e!==ee.current)return;g(t),I(null)}catch(t){e===ee.current&&I(ke(t,"Could not inspect historical Block recovery evidence."))}finally{e===ee.current&&x(!1)}},[]);(0,B.useEffect)(()=>(ae(),se(),()=>{Q.current+=1,ee.current+=1,te.current+=1,ie.current?.abort()}),[ae,se]);let re=async(e,t)=>{if(!ne.current){ne.current=!0,X(e),w(null);try{await t()}catch(e){let t=ke(e,"Composite migration action failed.");w(t),m(t),h(t,{variant:"error"})}finally{ne.current=!1,X(null)}}},ce=t?.summary.blockedCandidateCount??0;return(0,Nt.jsxs)("section",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3","data-testid":"composite-migration-card",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(i,{size:15,className:"text-hf-yellow"}),(0,Nt.jsxs)("div",{children:[(0,Nt.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Legacy composite migration"}),(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Read-only preview and exact-backup recovery"})]})]}),(0,Nt.jsx)($,{label:l&&!t?"Checking":ce?`${ce} blocked`:"Reviewed",tone:p?"error":ce?"warning":t?"success":"neutral"})]}),(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Previewing writes nothing. Apply and rollback are available only after reviewing exact paths and typing the required literal confirmation."}),p?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/5 p-2 text-xs text-modiff-red",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{className:"break-words",children:p})]}):null,t?(0,Nt.jsx)(S,{label:(0,Nt.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(r,{size:14,className:"text-hf-yellow"}),"Current read-only preview"]}),className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-preview-disclosure",children:(0,Nt.jsx)(Ht,{preview:t})}):l||p?null:(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No migration preview is available."}),(0,Nt.jsx)(S,{label:(0,Nt.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(r,{size:14,className:"text-hf-orange"}),"Historical definition recovery evidence"]}),className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"legacy-cluster-recovery-evidence-disclosure",children:(0,Nt.jsx)(kt,{audit:f,error:b,loading:v,onRefresh:()=>{se()}})}),(0,Nt.jsx)(S,{label:"Registered Block compiler supplement",className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-compiler-disclosure",children:(0,Nt.jsxs)("div",{className:"grid gap-3",children:[(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Generate exact compiler evidence from saved legacy Blocks, or paste externally produced evidence below. Generation and preview are read-only. The exact parsed supplement is retained only for this reviewed preview and resent unchanged on Apply."}),e?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2 text-xs text-hf-orange","data-testid":"composite-migration-unsaved-warning",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{children:"Generation reads saved backend workflow bytes only. Save dirty workflow tabs first if their current canvas changes should be included."})]}):null,(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,Nt.jsx)(M,{size:"compact",tone:"primary",icon:(0,Nt.jsx)(n,{size:14}),loading:"compiler-generate"===U,disabled:!!U,onClick:()=>{re("compiler-generate",async()=>{let e=++te.current,t=new AbortController;ie.current?.abort(),ie.current=t,P(null),D([]),T(null);try{let i=await He();if(t.signal.aborted||e!==te.current)return;let n=await $t({candidates:i.candidates,signal:t.signal,onProgress:i=>{!t.signal.aborted&&e===te.current&&T(i)}});if(t.signal.aborted||e!==te.current)return;let o=JSON.stringify(n.supplement,null,2);if(E(o),D(n.diagnostics),!n.conversionCount){oe.current=null,_(null),a(i);let e=n.candidateCount?`No legacy registered Block matched an exact current compiler route. Review ${n.diagnostics.length} blocker${1===n.diagnostics.length?"":"s"} below.`:"No legacy registered Block candidates are present in saved workflows.";return P(e),void h(e,{variant:"warning"})}let s=ge(n.supplement),r=await He(s);if(t.signal.aborted||e!==te.current)return;oe.current=s,_(s),a(r),m(null),h(`Generated and previewed ${n.conversionCount} exact registered-Block conversion${1===n.conversionCount?"":"s"}; no files were changed.`,{variant:"success"})}catch(i){if(t.signal.aborted||e!==te.current)return void h("Compiler supplement generation cancelled; no files were changed.",{variant:"info"});throw i}finally{ie.current===t&&(ie.current=null)}})},"data-testid":"composite-migration-compiler-generate",children:"Generate exact supplement"}),"compiler-generate"===U?(0,Nt.jsx)(M,{size:"compact",tone:"secondary",onClick:()=>{te.current+=1,ie.current?.abort(),ie.current=null,T(null)},"data-testid":"composite-migration-compiler-cancel",children:"Cancel generation"}):null,O?(0,Nt.jsxs)("span",{className:"text-xs text-modiff-subtle-text","data-testid":"composite-migration-compiler-progress",children:["Reviewed ",O.completed,"/",O.total," saved Block candidates"]}):null]}),F.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5 rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2","data-testid":"composite-migration-compiler-diagnostics",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:["Candidates left unchanged (",F.length,")"]}),(0,Nt.jsx)("ul",{className:"max-h-40 space-y-2 overflow-auto",children:F.map((e,t)=>(0,Nt.jsxs)("li",{className:"text-xs",children:[(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-text",children:[e.sourcePath,e.instanceId?` · ${e.instanceId}`:""]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.code,": ",e.message]})]},`${e.sourcePath}:${e.instanceId??""}:${e.code}:${t}`))})]}):null,(0,Nt.jsx)(j,{label:"Compiler supplement JSON",error:N??void 0,description:"Presentation children never become execution authority; the backend verifies pinned V2 definitions and every preservation receipt.",children:(0,Nt.jsx)(y,{value:A,onChange:e=>{E(e.target.value),P(null),D([]),T(null),oe.current&&(oe.current=null,_(null),a(null),ae())},rows:8,spellCheck:!1,disabled:!!U,className:"font-mono text-xs",placeholder:'{"schemaVersion":1,"kind":"registered_cluster_v2_compiler_supplement","compilerOutputs":[]}',"data-testid":"composite-migration-compiler-json"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)(M,{size:"compact",tone:"primary",loading:"compiler-preview"===U,disabled:!!U||!A.trim(),onClick:()=>{re("compiler-preview",async()=>{let e;try{e=ge(JSON.parse(A))}catch(e){let t=e instanceof Error?e.message:"Compiler supplement JSON is invalid.";throw P(t),Error(t)}let t=await He(e);oe.current=e,_(e),a(t),P(null),m(null),h("Exact registered-Block compiler supplement previewed; no files were changed.",{variant:"success"})})},"data-testid":"composite-migration-compiler-preview",children:"Preview exact supplement"}),(0,Nt.jsx)(M,{size:"compact",tone:"secondary",disabled:!!U||!R,onClick:()=>{oe.current=null,_(null),E(""),P(null),D([]),T(null),ae()},"data-testid":"composite-migration-compiler-clear",children:"Return to default preview"})]})]})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)(M,{size:"compact",tone:"primary",disabled:l||!!U||!t?.summary.hasChanges||!(!t.compilerSupplement||R),onClick:()=>{!t?.summary.hasChanges||t.compilerSupplement&&!R||(z(""),G(!1),w(null),L(!0))},"data-testid":"composite-migration-review",children:"Review migration"}),(0,Nt.jsx)(M,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(c,{size:14}),loading:l,disabled:l||!!U,onClick:()=>{ae()},"data-testid":"composite-migration-refresh",children:"Refresh preview"})]}),(0,Nt.jsx)(S,{label:`Recovery journals (${s.length})`,className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-recovery-disclosure",children:(0,Nt.jsx)(At,{migrations:s,busyId:U,onInspectRollback:e=>{re(e.migrationId,async()=>{let t=await Ae(e.migrationId);Z(t),Y(""),w(null)})}})}),(0,Nt.jsx)(k,{open:V&&!!t,onClose:()=>{U||L(!1)},title:"Review legacy composite migration",description:"Only the listed files can change. Exact backups are created before migration.",panelClassName:"max-w-4xl",dismissible:!U,testId:"composite-migration-review-dialog",children:t?(0,Nt.jsx)(Pt,{preview:t,confirmation:q,allowBlockedCandidates:K,busy:"apply"===U,error:C,onConfirmationChange:z,onAllowBlockedCandidatesChange:G,onCancel:()=>L(!1),onApply:()=>{!t||!le(t,q,K)||re("apply",async()=>{let e=await Ee(t,{confirmation:q,allowBlockedCandidates:K,...R?{compilerSupplement:R}:{}});h(e.idempotent?"This exact migration was already applied.":`Converted ${e.changedPaths?.length??0} reviewed files and created exact backups.`,{variant:"success"}),L(!1),z(""),G(!1),oe.current=null,_(null),E(""),D([]),T(null),await ae()})}}):null}),(0,Nt.jsx)(k,{open:!!J,onClose:()=>{U||Z(null)},title:"Review exact-backup rollback",description:"Restore the exact backed-up files. Review conflicts before confirming rollback.",panelClassName:"max-w-3xl",dismissible:!U,testId:"composite-migration-rollback-dialog",children:J?(0,Nt.jsx)(Et,{status:J,confirmation:W,busy:U===J.migrationId,error:C,onConfirmationChange:Y,onCancel:()=>Z(null),onRollback:()=>{!J||"ROLLBACK_BLOCK_V2_MIGRATION"!==W||re(J.migrationId,async()=>{let e=await Re(J.migrationId,W);h(e.idempotent?"This migration was already rolled back.":`Restored ${e.restoredPaths?.length??0} files from exact backups.`,{variant:"success"}),Z(null),Y(""),await ae()})}}):null})]})}export{Rt as CompositeMigrationCard}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$ as t,G as i,H as n,R as o,cr as a,dr as s,rn as r,rt as c}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ao as d,Cn as l,Eo as u,Ln as p,Ni as m,Oi as h,Oo as f,Pi as g,Po as v,Qr as y,Qt as x,Us as b,Vs as I,Xr as C,Xs as w,Za as $,Zr as N,an as S,bi as j,da as k,fn as H,hn as P,in as A,lc as E,ln as R,pn as _,qs as M,si as F,wi as D}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as O}from"./huggingFaceClusterInsertion.js?v=ca6b74e6a02eedb3";var B=e(s(),1),T="APPLY_BLOCK_V2_MIGRATION",V="ROLLBACK_BLOCK_V2_MIGRATION",L=/^block-v2-migration-[a-f0-9]{24}$/u,q=/^sha256:[a-f0-9]{64}$/u,z=/^block-definition-v2-[a-f0-9]{8}$/u,K=/^block-graph-v2-[a-f0-9]{8}$/u,G=/^block-interface-v2-[a-f0-9]{8}$/u,J=/^[a-f0-9]{40}$/u,Z=/^(?:user-workflows\/[^/]+\.json|studio\/blocks\/[^/]+\.json)$/u,U=/^user-workflows\/[^/]+\.json$/u,W=new Set(["legacy_registered_cluster_instance","reusable_v1_definition","workflow_v1_instance","workflow_v1_instances","registered_cluster_compiler_output"]),Y=new Set(["reusable_v1_definition","workflow_v1_instances","workflow_composite_instances"]),Q=new Set(["applied","applying","prepared","recovery_required","rolled_back","rolling_back"]),X=new Set(["applied","conflict","interrupted","rolled_back"]),ee=new Set(["applied","conflict","missing","source"]);function te(e,t="is invalid"){throw Error(`Invalid composite migration response: ${e} ${t}.`)}function ie(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&te(t,"must be an object"),e}function ne(e,t,i,n=[]){let o=new Set([...i,...n]),a=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t)),s=Object.keys(e).filter(e=>!o.has(e));a.length&&te(t,`is missing ${a.join(", ")}`),s.length&&te(t,`contains unknown keys ${s.join(", ")}`)}function oe(e,t,i,n=4096){return("string"!=typeof e||!e||e.length>n||i&&!i.test(e))&&te(t),e}function ae(e,t){return null===e?null:oe(e,t,void 0,512)}function se(e,t){return"boolean"!=typeof e&&te(t,"must be a boolean"),e}function re(e,t){return(!Number.isSafeInteger(e)||Number(e)<0)&&te(t,"must be a nonnegative integer"),Number(e)}function ce(e,t){return Array.isArray(e)||te(t,"must be an array"),e}function de(e,t){new Set(e).size!==e.length&&te(t,"contains duplicate entries")}function le(e,t,i){return e.summary.hasChanges&&"APPLY_BLOCK_V2_MIGRATION"===t&&(0===e.summary.blockedCandidateCount||i)}function ue(e,t){for(let i=1;i=(e[i]??"")&&te(t,"must be unique and canonically ordered")}function pe(e,t){let i=ce(e,t).map((e,i)=>oe(e,`${t}[${i}]`,void 0,512));return ue(i,t),i}function me(e,t){let i=ie(e,t);return ne(i,t,["id","contentHash","executionProfileId"]),{id:oe(i.id,`${t}.id`,void 0,512),contentHash:oe(i.contentHash,`${t}.contentHash`,void 0,128),executionProfileId:oe(i.executionProfileId,`${t}.executionProfileId`,void 0,512)}}function he(e,t){let i=ie(e,t);ne(i,t,["receiptId","receiptHash","historical","destination","review"]);let n=ie(i.historical,`${t}.historical`);ne(n,`${t}.historical`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","studioExecutionSpec","executionGraphHash","interfaceHash"]);let o=ie(i.destination,`${t}.destination`);ne(o,`${t}.destination`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","blockDefinitionId","blockDefinitionContentHash","blockDefinitionCanonicalSha256","executionGraphHash","interfaceHash"]);let a=ie(i.review,`${t}.review`);ne(a,`${t}.review`,["decision","issuer","reviewedAt","notes"]),"semantic_equivalent"!==a.decision&&te(`${t}.review.decision`);let s=oe(a.reviewedAt,`${t}.review.reviewedAt`,void 0,64);return(!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(s)||Number.isNaN(Date.parse(s)))&&te(`${t}.review.reviewedAt`,"must be an offset ISO-8601 timestamp"),{receiptId:oe(i.receiptId,`${t}.receiptId`,void 0,256),receiptHash:oe(i.receiptHash,`${t}.receiptHash`,q),historical:{manifestDefinitionId:oe(n.manifestDefinitionId,`${t}.historical.manifestDefinitionId`,void 0,512),libraryRevision:oe(n.libraryRevision,`${t}.historical.libraryRevision`,J),manifestContentHash:oe(n.manifestContentHash,`${t}.historical.manifestContentHash`,q),executionAdmissionId:oe(n.executionAdmissionId,`${t}.historical.executionAdmissionId`,void 0,1024),studioExecutionSpec:me(n.studioExecutionSpec,`${t}.historical.studioExecutionSpec`),executionGraphHash:oe(n.executionGraphHash,`${t}.historical.executionGraphHash`,q),interfaceHash:oe(n.interfaceHash,`${t}.historical.interfaceHash`,q)},destination:{manifestDefinitionId:oe(o.manifestDefinitionId,`${t}.destination.manifestDefinitionId`,void 0,512),libraryRevision:oe(o.libraryRevision,`${t}.destination.libraryRevision`,J),manifestContentHash:oe(o.manifestContentHash,`${t}.destination.manifestContentHash`,q),executionAdmissionId:oe(o.executionAdmissionId,`${t}.destination.executionAdmissionId`,void 0,1024),blockDefinitionId:oe(o.blockDefinitionId,`${t}.destination.blockDefinitionId`,void 0,384),blockDefinitionContentHash:oe(o.blockDefinitionContentHash,`${t}.destination.blockDefinitionContentHash`,z),blockDefinitionCanonicalSha256:oe(o.blockDefinitionCanonicalSha256,`${t}.destination.blockDefinitionCanonicalSha256`,q),executionGraphHash:oe(o.executionGraphHash,`${t}.destination.executionGraphHash`,K),interfaceHash:oe(o.interfaceHash,`${t}.destination.interfaceHash`,G)},review:{decision:"semantic_equivalent",issuer:oe(a.issuer,`${t}.review.issuer`,void 0,256),reviewedAt:s,notes:oe(a.notes,`${t}.review.notes`,void 0,4096)}}}function fe(e,t){let i=ie(e,t);ne(i,t,["mappingId","mappingHash","historical","destination","review"]);let n=ie(i.historical,`${t}.historical`);ne(n,`${t}.historical`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","studioExecutionSpec","archivedDefinitionRecordHash","blockContractHash","rootBlockDefinitionId"]);let o=ie(i.destination,`${t}.destination`);ne(o,`${t}.destination`,["manifestDefinitionId","libraryRevision","manifestContentHash","executionAdmissionId","blockDefinitionId","blockDefinitionContentHash","blockDefinitionCanonicalSha256","executionGraphHash","interfaceHash"]);let a=ie(i.review,`${t}.review`);ne(a,`${t}.review`,["decision","issuer","reviewedAt","notes"]),"historical_compiler_mapping_reviewed"!==a.decision&&te(`${t}.review.decision`);let s=oe(a.reviewedAt,`${t}.review.reviewedAt`,void 0,64);return(!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(s)||Number.isNaN(Date.parse(s)))&&te(`${t}.review.reviewedAt`,"must be an offset ISO-8601 timestamp"),{mappingId:oe(i.mappingId,`${t}.mappingId`,void 0,256),mappingHash:oe(i.mappingHash,`${t}.mappingHash`,q),historical:{manifestDefinitionId:oe(n.manifestDefinitionId,`${t}.historical.manifestDefinitionId`,void 0,512),libraryRevision:oe(n.libraryRevision,`${t}.historical.libraryRevision`,J),manifestContentHash:oe(n.manifestContentHash,`${t}.historical.manifestContentHash`,q),executionAdmissionId:oe(n.executionAdmissionId,`${t}.historical.executionAdmissionId`,void 0,1024),studioExecutionSpec:me(n.studioExecutionSpec,`${t}.historical.studioExecutionSpec`),archivedDefinitionRecordHash:oe(n.archivedDefinitionRecordHash,`${t}.historical.archivedDefinitionRecordHash`,q),blockContractHash:oe(n.blockContractHash,`${t}.historical.blockContractHash`,q),rootBlockDefinitionId:oe(n.rootBlockDefinitionId,`${t}.historical.rootBlockDefinitionId`,void 0,1024)},destination:{manifestDefinitionId:oe(o.manifestDefinitionId,`${t}.destination.manifestDefinitionId`,void 0,512),libraryRevision:oe(o.libraryRevision,`${t}.destination.libraryRevision`,J),manifestContentHash:oe(o.manifestContentHash,`${t}.destination.manifestContentHash`,q),executionAdmissionId:oe(o.executionAdmissionId,`${t}.destination.executionAdmissionId`,void 0,1024),blockDefinitionId:oe(o.blockDefinitionId,`${t}.destination.blockDefinitionId`,void 0,384),blockDefinitionContentHash:oe(o.blockDefinitionContentHash,`${t}.destination.blockDefinitionContentHash`,z),blockDefinitionCanonicalSha256:oe(o.blockDefinitionCanonicalSha256,`${t}.destination.blockDefinitionCanonicalSha256`,q),executionGraphHash:oe(o.executionGraphHash,`${t}.destination.executionGraphHash`,K),interfaceHash:oe(o.interfaceHash,`${t}.destination.interfaceHash`,G)},review:{decision:"historical_compiler_mapping_reviewed",issuer:oe(a.issuer,`${t}.review.issuer`,void 0,256),reviewedAt:s,notes:oe(a.notes,`${t}.review.notes`,void 0,4096)}}}function ge(e){let t=ie(e,"compiler supplement");ne(t,"compiler supplement",["schemaVersion","kind","compilerOutputs"]),(1!==t.schemaVersion||"registered_cluster_v2_compiler_supplement"!==t.kind)&&te("compiler supplement","uses an unsupported contract");let i=ce(t.compilerOutputs,"compiler supplement.compilerOutputs").map((e,t)=>{let i=`compiler supplement.compilerOutputs[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","sourceSha256","conversions"]);let o=ce(n.conversions,`${i}.conversions`).map((e,t)=>function(e,t){let i=ie(e,t);ne(i,t,["legacyInstanceId","legacyCompositeHash","admissionId","compiledDefinitionContentHash","compiledDefinitionCanonicalSha256","blockInstanceV2","ownedNodeMappings","portMappings","valueMappings","previewMappings","absorbedInternalEdgeIds"],["semanticEquivalenceReceipt","historicalCompilerMapping"]);let n=ce(i.ownedNodeMappings,`${t}.ownedNodeMappings`).map((e,i)=>{let n=`${t}.ownedNodeMappings[${i}]`,o=ie(e,n);return ne(o,n,["legacyNodeId","semanticNodeId"]),{legacyNodeId:oe(o.legacyNodeId,`${n}.legacyNodeId`,void 0,512),semanticNodeId:oe(o.semanticNodeId,`${n}.semanticNodeId`,void 0,512)}});ue(n.map(({legacyNodeId:e,semanticNodeId:t})=>`${e}\0${t}`),`${t}.ownedNodeMappings`);let o=ce(i.portMappings,`${t}.portMappings`).map((e,i)=>{let n=`${t}.portMappings[${i}]`,o=ie(e,n);ne(o,n,["direction","legacyNodeId","legacyPortId","v2PortId"]);let a=oe(o.direction,`${n}.direction`);return"input"!==a&&"output"!==a&&te(`${n}.direction`),{direction:a,legacyNodeId:oe(o.legacyNodeId,`${n}.legacyNodeId`,void 0,512),legacyPortId:oe(o.legacyPortId,`${n}.legacyPortId`,void 0,512),v2PortId:oe(o.v2PortId,`${n}.v2PortId`,void 0,512)}});ue(o.map(({direction:e,legacyNodeId:t,legacyPortId:i,v2PortId:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.portMappings`);let a=ce(i.valueMappings,`${t}.valueMappings`).map((e,i)=>{let n=`${t}.valueMappings[${i}]`,o=ie(e,n),a=oe(o.targetKind,`${n}.targetKind`),s={sourceKind:oe(o.sourceKind,`${n}.sourceKind`,void 0,512),sourceNodeId:oe(o.sourceNodeId,`${n}.sourceNodeId`,void 0,512),sourceFieldId:oe(o.sourceFieldId,`${n}.sourceFieldId`,void 0,512)};return"instance_value"===a?(ne(o,n,["sourceKind","sourceNodeId","sourceFieldId","targetKind","targetValueId"]),{...s,targetKind:"instance_value",targetValueId:oe(o.targetValueId,`${n}.targetValueId`,void 0,512)}):"graph_param"===a?(ne(o,n,["sourceKind","sourceNodeId","sourceFieldId","targetKind","targetNodeId","targetFieldId"]),{...s,targetKind:"graph_param",targetNodeId:oe(o.targetNodeId,`${n}.targetNodeId`,void 0,512),targetFieldId:oe(o.targetFieldId,`${n}.targetFieldId`,void 0,512)}):void te(`${n}.targetKind`)});ue(a.map(({sourceKind:e,sourceNodeId:t,sourceFieldId:i,targetKind:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.valueMappings`);let s=ce(i.previewMappings,`${t}.previewMappings`).map((e,i)=>{let n=`${t}.previewMappings[${i}]`,o=ie(e,n);return ne(o,n,["sourceNodeId","sourceFieldId","targetNodeId","targetOutputPortId"]),{sourceNodeId:oe(o.sourceNodeId,`${n}.sourceNodeId`,void 0,512),sourceFieldId:oe(o.sourceFieldId,`${n}.sourceFieldId`,void 0,512),targetNodeId:oe(o.targetNodeId,`${n}.targetNodeId`,void 0,512),targetOutputPortId:oe(o.targetOutputPortId,`${n}.targetOutputPortId`,void 0,512)}});ue(s.map(({sourceNodeId:e,sourceFieldId:t,targetNodeId:i,targetOutputPortId:n})=>`${e}\0${t}\0${i}\0${n}`),`${t}.previewMappings`);let r=void 0===i.semanticEquivalenceReceipt?void 0:(()=>{let e=ie(i.semanticEquivalenceReceipt,`${t}.semanticEquivalenceReceipt`);return ne(e,`${t}.semanticEquivalenceReceipt`,["receiptId","receiptHash"]),{receiptId:oe(e.receiptId,`${t}.semanticEquivalenceReceipt.receiptId`,void 0,256),receiptHash:oe(e.receiptHash,`${t}.semanticEquivalenceReceipt.receiptHash`,q)}})(),c=void 0===i.historicalCompilerMapping?void 0:(()=>{let e=ie(i.historicalCompilerMapping,`${t}.historicalCompilerMapping`);return ne(e,`${t}.historicalCompilerMapping`,["mappingId","mappingHash"]),{mappingId:oe(e.mappingId,`${t}.historicalCompilerMapping.mappingId`,void 0,256),mappingHash:oe(e.mappingHash,`${t}.historicalCompilerMapping.mappingHash`,q)}})();return r&&c&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),{legacyInstanceId:oe(i.legacyInstanceId,`${t}.legacyInstanceId`,void 0,512),legacyCompositeHash:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),admissionId:oe(i.admissionId,`${t}.admissionId`,void 0,1024),compiledDefinitionContentHash:oe(i.compiledDefinitionContentHash,`${t}.compiledDefinitionContentHash`,z),compiledDefinitionCanonicalSha256:oe(i.compiledDefinitionCanonicalSha256,`${t}.compiledDefinitionCanonicalSha256`,q),blockInstanceV2:M(i.blockInstanceV2),ownedNodeMappings:n,portMappings:o,valueMappings:a,previewMappings:s,absorbedInternalEdgeIds:pe(i.absorbedInternalEdgeIds,`${t}.absorbedInternalEdgeIds`),...r?{semanticEquivalenceReceipt:r}:{},...c?{historicalCompilerMapping:c}:{}}}(e,`${i}.conversions[${t}]`));return o.length||te(`${i}.conversions`,"must not be empty"),ue(o.map(({legacyInstanceId:e})=>e),`${i}.conversions`),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,U),sourceSha256:oe(n.sourceSha256,`${i}.sourceSha256`,q),conversions:o}});return ue(i.map(({sourcePath:e})=>e),"compiler supplement.compilerOutputs"),{schemaVersion:1,kind:"registered_cluster_v2_compiler_supplement",compilerOutputs:i}}function ve(e,t){let i=ie(e,`preview.targets[${t}]`);ne(i,`preview.targets[${t}]`,["sourcePath","kind","beforeSha256","afterSha256","convertedIds","byteLength"]);let n=oe(i.kind,`preview.targets[${t}].kind`);Y.has(n)||te(`preview.targets[${t}].kind`);let o=ce(i.convertedIds,`preview.targets[${t}].convertedIds`).map((e,i)=>oe(e,`preview.targets[${t}].convertedIds[${i}]`,void 0,512));return o.length||te(`preview.targets[${t}].convertedIds`,"must not be empty"),de(o,`preview.targets[${t}].convertedIds`),{sourcePath:oe(i.sourcePath,`preview.targets[${t}].sourcePath`,Z),kind:n,beforeSha256:oe(i.beforeSha256,`preview.targets[${t}].beforeSha256`,q),afterSha256:oe(i.afterSha256,`preview.targets[${t}].afterSha256`,q),convertedIds:o,byteLength:re(i.byteLength,`preview.targets[${t}].byteLength`)}}function ye(e,t){let i=ie(e,t);ne(i,t,["kind","sourcePath","id","status"],["reason","targetAfterSha256","sourceSha256","legacyCompositeHash","compilerReceipt","semanticEquivalenceAuthority","historicalCompilerMappingAuthority"]);let n=oe(i.kind,`${t}.kind`);W.has(n)||te(`${t}.kind`);let o=oe(i.status,`${t}.status`);"blocked"!==o&&"convertible"!==o&&te(`${t}.status`);let a=void 0===i.reason?void 0:oe(i.reason,`${t}.reason`,void 0,8192),s=void 0===i.targetAfterSha256?void 0:oe(i.targetAfterSha256,`${t}.targetAfterSha256`,q),r=void 0===i.sourceSha256?void 0:oe(i.sourceSha256,`${t}.sourceSha256`,q),c=void 0===i.legacyCompositeHash?void 0:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),d=void 0===i.compilerReceipt?void 0:function(e,t){let i=ie(e,t);ne(i,t,["instanceId","definitionId","admissionId","compiledDefinitionContentHash","compiledDefinitionCanonicalSha256","legacyCompositeHash","absorbedProjectionNodeIds","absorbedInternalEdgeIds"],["semanticEquivalenceAuthority","historicalCompilerMappingAuthority"]);let n=void 0===i.semanticEquivalenceAuthority?void 0:he(i.semanticEquivalenceAuthority,`${t}.semanticEquivalenceAuthority`),o=void 0===i.historicalCompilerMappingAuthority?void 0:fe(i.historicalCompilerMappingAuthority,`${t}.historicalCompilerMappingAuthority`);return n&&o&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),{instanceId:oe(i.instanceId,`${t}.instanceId`,void 0,512),definitionId:oe(i.definitionId,`${t}.definitionId`,void 0,512),admissionId:oe(i.admissionId,`${t}.admissionId`,void 0,1024),compiledDefinitionContentHash:oe(i.compiledDefinitionContentHash,`${t}.compiledDefinitionContentHash`,z),compiledDefinitionCanonicalSha256:oe(i.compiledDefinitionCanonicalSha256,`${t}.compiledDefinitionCanonicalSha256`,q),legacyCompositeHash:oe(i.legacyCompositeHash,`${t}.legacyCompositeHash`,q),absorbedProjectionNodeIds:pe(i.absorbedProjectionNodeIds,`${t}.absorbedProjectionNodeIds`),absorbedInternalEdgeIds:pe(i.absorbedInternalEdgeIds,`${t}.absorbedInternalEdgeIds`),...n?{semanticEquivalenceAuthority:n}:{},...o?{historicalCompilerMappingAuthority:o}:{}}}(i.compilerReceipt,`${t}.compilerReceipt`),l=void 0===i.semanticEquivalenceAuthority?void 0:he(i.semanticEquivalenceAuthority,`${t}.semanticEquivalenceAuthority`),u=void 0===i.historicalCompilerMappingAuthority?void 0:fe(i.historicalCompilerMappingAuthority,`${t}.historicalCompilerMappingAuthority`);return l&&u&&te(t,"must not combine semantic-equivalence and historical compiler-mapping authority"),("blocked"===o!=!!a||"convertible"===o!=!!s)&&te(t,"has inconsistent status details"),{kind:n,sourcePath:oe(i.sourcePath,`${t}.sourcePath`,Z),id:ae(i.id,`${t}.id`),status:o,...a?{reason:a}:{},...s?{targetAfterSha256:s}:{},...r?{sourceSha256:r}:{},...c?{legacyCompositeHash:c}:{},...d?{compilerReceipt:d}:{},...l?{semanticEquivalenceAuthority:l}:{},...u?{historicalCompilerMappingAuthority:u}:{}}}function xe(e,t){let i=`preview.inventoryIssues[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","path","code","severity","message"]);let o=oe(n.severity,`${i}.severity`);return"error"!==o&&"warning"!==o&&te(`${i}.severity`),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,void 0,4096),path:oe(n.path,`${i}.path`,void 0,4096),code:oe(n.code,`${i}.code`,void 0,512),severity:o,message:oe(n.message,`${i}.message`,void 0,8192)}}function be(e){let t=ie(e,"preview response");ne(t,"preview response",["error","preview"]),!1!==t.error&&te("preview response.error","must be false");let i=ie(t.preview,"preview");ne(i,"preview",["schemaVersion","kind","mode","boundary","inventoryReportHash","sourceSetHash","summary","targets","candidates","blocked","inventoryIssues","migrationId","planHash"],["compilerSupplement"]),(1!==i.schemaVersion||"legacy_composite_to_block_v2_migration"!==i.kind||"read_only_preview"!==i.mode)&&te("preview","uses an unsupported contract");let n=ie(i.boundary,"preview.boundary");ne(n,"preview.boundary",["writesFiles","requiresExplicitApplyAuthority","createsExactBackupsBeforeReplacement","deletesRecords","mergesRecords","legacyClusterConversionRequiresRegisteredCompiler","containsPromptAndParameterValues"],["compilerSupplementRequiredForRegisteredClusters"]),(!1!==n.writesFiles||!0!==n.requiresExplicitApplyAuthority||!0!==n.createsExactBackupsBeforeReplacement||!1!==n.deletesRecords||!1!==n.mergesRecords||!0!==n.legacyClusterConversionRequiresRegisteredCompiler||!1!==n.containsPromptAndParameterValues)&&te("preview.boundary","does not preserve the read-only safety contract");let o=ie(i.summary,"preview.summary");ne(o,"preview.summary",["sourceCount","targetFileCount","convertibleCandidateCount","blockedCandidateCount","legacyClusterBlockedCount","hasChanges"],["registeredClusterConvertibleCount"]);let a=ce(i.targets,"preview.targets").map(ve),s=ce(i.candidates,"preview.candidates").map((e,t)=>ye(e,`preview.candidates[${t}]`)),r=ce(i.blocked,"preview.blocked").map((e,t)=>ye(e,`preview.blocked[${t}]`)),c=ce(i.inventoryIssues,"preview.inventoryIssues").map(xe),d={sourceCount:re(o.sourceCount,"preview.summary.sourceCount"),targetFileCount:re(o.targetFileCount,"preview.summary.targetFileCount"),convertibleCandidateCount:re(o.convertibleCandidateCount,"preview.summary.convertibleCandidateCount"),blockedCandidateCount:re(o.blockedCandidateCount,"preview.summary.blockedCandidateCount"),legacyClusterBlockedCount:re(o.legacyClusterBlockedCount,"preview.summary.legacyClusterBlockedCount"),hasChanges:se(o.hasChanges,"preview.summary.hasChanges"),...void 0===o.registeredClusterConvertibleCount?{}:{registeredClusterConvertibleCount:re(o.registeredClusterConvertibleCount,"preview.summary.registeredClusterConvertibleCount")}},l=void 0===i.compilerSupplement?void 0:(()=>{let e=ie(i.compilerSupplement,"preview.compilerSupplement");ne(e,"preview.compilerSupplement",["provided","contentHash","sourceCount","conversionCount"]);let t=se(e.provided,"preview.compilerSupplement.provided"),n=null===e.contentHash?null:oe(e.contentHash,"preview.compilerSupplement.contentHash",q);return t!==!!n&&te("preview.compilerSupplement","has an inconsistent provided/contentHash pair"),{provided:t,contentHash:n,sourceCount:re(e.sourceCount,"preview.compilerSupplement.sourceCount"),conversionCount:re(e.conversionCount,"preview.compilerSupplement.conversionCount")}})();(!!l!=(!0===n.compilerSupplementRequiredForRegisteredClusters)||!!l!=(void 0!==d.registeredClusterConvertibleCount))&&te("preview.compilerSupplement","is inconsistent with the compiler-preview boundary and summary"),de(a.map(({sourcePath:e})=>e),"preview.targets");let u=s.filter(({status:e})=>"blocked"===e);(d.targetFileCount!==a.length||d.convertibleCandidateCount!==s.filter(({status:e})=>"convertible"===e).length||d.blockedCandidateCount!==u.length||d.blockedCandidateCount!==r.length||d.legacyClusterBlockedCount!==r.filter(({kind:e})=>"legacy_registered_cluster_instance"===e).length||void 0!==d.registeredClusterConvertibleCount&&d.registeredClusterConvertibleCount!==s.filter(({kind:e,status:t})=>"legacy_registered_cluster_instance"===e&&"convertible"===t).length||d.hasChanges!==!!a.length||JSON.stringify(u)!==JSON.stringify(r))&&te("preview.summary","does not match the listed targets and candidates");let p=new Map(a.map(e=>[e.sourcePath,e.afterSha256]));return s.some(e=>"convertible"===e.status&&p.get(e.sourcePath)!==e.targetAfterSha256)&&te("preview.candidates","does not match the target hashes"),{schemaVersion:1,kind:"legacy_composite_to_block_v2_migration",mode:"read_only_preview",boundary:{writesFiles:!1,requiresExplicitApplyAuthority:!0,createsExactBackupsBeforeReplacement:!0,deletesRecords:!1,mergesRecords:!1,legacyClusterConversionRequiresRegisteredCompiler:!0,...l?{compilerSupplementRequiredForRegisteredClusters:!0}:{},containsPromptAndParameterValues:!1},...l?{compilerSupplement:l}:{},inventoryReportHash:oe(i.inventoryReportHash,"preview.inventoryReportHash",q),sourceSetHash:oe(i.sourceSetHash,"preview.sourceSetHash",q),summary:d,targets:a,candidates:s,blocked:r,inventoryIssues:c,migrationId:oe(i.migrationId,"preview.migrationId",L),planHash:oe(i.planHash,"preview.planHash",q)}}function Ie(e,t){let i=`migration status.targets[${t}]`,n=ie(e,i);ne(n,i,["sourcePath","currentSha256","state"]);let o=oe(n.state,`${i}.state`);ee.has(o)||te(`${i}.state`);let a=null===n.currentSha256?null:oe(n.currentSha256,`${i}.currentSha256`,q);return"missing"===o!=(null===a)&&te(i,"has an inconsistent current file hash"),{sourcePath:oe(n.sourcePath,`${i}.sourcePath`,Z),currentSha256:a,state:o}}function Ce(e){let t=ie(e,"migration status");ne(t,"migration status",["migrationId","journalState","effectiveState","planHash","inventoryReportHash","targets","rollbackAvailable","resumeAvailable"]);let i=oe(t.journalState,"migration status.journalState"),n=oe(t.effectiveState,"migration status.effectiveState");Q.has(i)||te("migration status.journalState"),X.has(n)||te("migration status.effectiveState");let o=ce(t.targets,"migration status.targets").map(Ie);o.length||te("migration status.targets","must not be empty"),de(o.map(({sourcePath:e})=>e),"migration status.targets");let a=se(t.rollbackAvailable,"migration status.rollbackAvailable"),s=se(t.resumeAvailable,"migration status.resumeAvailable"),r=new Set(o.map(({state:e})=>e));return(n!==(1===r.size&&r.has("applied")?"applied":1===r.size&&r.has("source")?"rolled_back":[...r].every(e=>"source"===e||"applied"===e)?"interrupted":"conflict")||!1!==s||a!==["applied","interrupted","rolled_back"].includes(n))&&te("migration status","has inconsistent recovery actions"),{migrationId:oe(t.migrationId,"migration status.migrationId",L),journalState:i,effectiveState:n,planHash:oe(t.planHash,"migration status.planHash",q),inventoryReportHash:oe(t.inventoryReportHash,"migration status.inventoryReportHash",q),targets:o,rollbackAvailable:a,resumeAvailable:!1}}function we(e){let t=ie(e,"migration list response");ne(t,"migration list response",["error","schemaVersion","migrations"]),(!1!==t.error||1!==t.schemaVersion)&&te("migration list response","uses an unsupported contract");let i=ce(t.migrations,"migration list response.migrations").map(Ce);return de(i.map(({migrationId:e})=>e),"migration list response.migrations"),{schemaVersion:1,migrations:i}}function $e(e){let t=ie(e,"migration status response");return ne(t,"migration status response",["error","status"]),!1!==t.error&&te("migration status response.error","must be false"),Ce(t.status)}function Ne(e,t){let i=ie(e,"migration mutation response");ne(i,"migration mutation response",["error","idempotent","status"],[t]),!1!==i.error&&te("migration mutation response.error","must be false");let n=Ce(i.status),o=void 0===i[t]?void 0:ce(i[t],`migration mutation response.${t}`).map((e,i)=>oe(e,`migration mutation response.${t}[${i}]`,Z));if(o){de(o,`migration mutation response.${t}`);let e=new Set(n.targets.map(({sourcePath:e})=>e));o.some(t=>!e.has(t))&&te(`migration mutation response.${t}`,"is not a target")}return{idempotent:se(i.idempotent,"migration mutation response.idempotent"),..."changedPaths"===t&&o?{changedPaths:o}:{},..."restoredPaths"===t&&o?{restoredPaths:o}:{},status:n}}function Se(e){let t=Ne(e,"changedPaths");return"applied"!==t.status.effectiveState&&te("migration apply result.status","did not reach the applied state"),t}function je(e){let t=Ne(e,"restoredPaths");return"rolled_back"!==t.status.effectiveState&&te("migration rollback result.status","did not reach the rolled-back state"),t}function ke(e,t){let i=f(e,t);return e instanceof u&&403===e.status?`Authorization rejected (HTTP 403): ${i}`:e instanceof u&&409===e.status?`Migration state conflict (HTTP 409): ${i}`:i}function He(e){let t=void 0===e?void 0:ge(e);return d(`${E.serverAddress}/studio/composite-migrations/preview`,{...t?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({compilerSupplement:t})}:{},timeoutMs:3e4,parse:be})}function Pe(){return d(`${E.serverAddress}/studio/composite-migrations`,{timeoutMs:3e4,parse:we})}async function Ae(e){oe(e,"migrationId",L);let t=await d(`${E.serverAddress}/studio/composite-migrations/${encodeURIComponent(e)}`,{timeoutMs:3e4,parse:$e});return t.migrationId!==e&&te("migration status.migrationId","does not match the request"),t}async function Ee(e,t){if("APPLY_BLOCK_V2_MIGRATION"!==t.confirmation)throw Error(`Type ${T} exactly before applying.`);if("boolean"!=typeof t.allowBlockedCandidates)throw Error("Choose explicitly whether blocked candidates may remain before applying.");let i=be({error:!1,preview:e}),n=void 0===t.compilerSupplement?void 0:ge(t.compilerSupplement);if(!!i.compilerSupplement!=!!n)throw Error("Apply must reuse the exact compiler supplement from the reviewed preview.");if(i.compilerSupplement&&n&&(i.compilerSupplement.sourceCount!==n.compilerOutputs.length||i.compilerSupplement.conversionCount!==n.compilerOutputs.reduce((e,t)=>e+t.conversions.length,0)))throw Error("Apply compiler supplement does not match the reviewed preview counts.");if(i.summary.blockedCandidateCount>0&&!t.allowBlockedCandidates)throw Error("Explicitly allow blocked candidates to remain unchanged before applying safe targets.");let o=await d(`${E.serverAddress}/studio/composite-migrations/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({migrationId:i.migrationId,planHash:i.planHash,confirmation:t.confirmation,allowBlockedCandidates:t.allowBlockedCandidates,...n?{compilerSupplement:n}:{}}),timeoutMs:12e4,parse:Se});return(o.status.migrationId!==i.migrationId||o.status.planHash!==i.planHash)&&te("migration apply result","does not match the reviewed preview"),o}async function Re(e,t){if(oe(e,"migrationId",L),"ROLLBACK_BLOCK_V2_MIGRATION"!==t)throw Error(`Type ${V} exactly before rollback.`);let i=await d(`${E.serverAddress}/studio/composite-migrations/${encodeURIComponent(e)}/rollback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirmation:t}),timeoutMs:12e4,parse:je});return i.status.migrationId!==e&&te("migration rollback result","does not match the requested journal"),i}var _e=/^sha256:[a-f0-9]{64}$/u,Me=/^[a-f0-9]{40}$/u,Fe=/^studio-spec-v1-[a-f0-9]{8}$/u;function De(e,t="is invalid"){throw Error(`Invalid legacy Cluster recovery-audit response: ${e} ${t}.`)}function Oe(e,t){return(!e||"object"!=typeof e||Array.isArray(e))&&De(t,"must be an object"),e}function Be(e,t,i,n=[]){let o=new Set([...i,...n]),a=i.filter(t=>!Object.prototype.hasOwnProperty.call(e,t)),s=Object.keys(e).filter(e=>!o.has(e));(a.length||s.length)&&De(t,"has missing or unknown fields")}function Te(e,t,i,n=8192){return("string"!=typeof e||!e||e.length>n||i&&!i.test(e))&&De(t),e}function Ve(e,t,i,n=8192){return null===e?null:Te(e,t,i,n)}function Le(e,t){return(!Number.isSafeInteger(e)||Number(e)<0)&&De(t,"must be a nonnegative integer"),Number(e)}function qe(e,t){return"boolean"!=typeof e&&De(t,"must be a boolean"),e}function ze(e,t){return Array.isArray(e)||De(t,"must be an array"),e}function Ke(e,t){let i=ze(e,t).map((e,i)=>Te(e,`${t}[${i}]`,void 0,1024));return new Set(i).size!==i.length&&De(t,"contains duplicates"),i}var Ge=new Set(["identity_malformed","execution_receipt_missing","execution_receipt_incomplete","current_manifest_exact","archived_manifest_exact","semantic_equivalence_reviewed","historical_manifest_evidence_required"]),Je="legacyClusterInstanceCount.definitionIdentityCount.currentManifestExactInstanceCount.currentManifestExactIdentityCount.currentExecutionTupleExactInstanceCount.currentExecutionTupleExactIdentityCount.archivedManifestExactInstanceCount.archivedManifestExactIdentityCount.semanticEquivalenceReviewedInstanceCount.semanticEquivalenceReviewedIdentityCount.compilerMappingEligibleInstanceCount.compilerMappingEligibleIdentityCount.remainingBlockedHistoricalInstanceCount.remainingBlockedHistoricalIdentityCount.historicalEvidenceRequiredInstanceCount.historicalEvidenceRequiredIdentityCount.completeExecutionReceiptInstanceCount.missingExecutionReceiptInstanceCount.missingExecutionReceiptIdentityCount.incompleteExecutionReceiptInstanceCount.incompleteExecutionReceiptIdentityCount.identityReferenceOnlyInstanceCount.embeddedCompleteDefinitionInstanceCount.presentationProjectionInstanceCount.presentationProjectionNodeCount.malformedIdentityInstanceCount.malformedIdentityCount.recoveredStudioSpecBodyCount.recoveredStudioSpecManifestIdentityCount.recoveredStudioSpecExecutionTupleCount.recoveredStudioSpecInstanceCount.partialReviewVerifiedExecutionTupleCount.partialReviewRejectedExecutionTupleCount".split(".");function Ze(e,t){let i=Oe(e,t);return Be(i,t,["id","contentHash","executionProfileId"]),{id:Te(i.id,`${t}.id`,void 0,512),contentHash:Te(i.contentHash,`${t}.contentHash`,Fe),executionProfileId:Te(i.executionProfileId,`${t}.executionProfileId`,void 0,512)}}function Ue(e,t){return ze(e,t).map((e,i)=>{let n=`${t}[${i}]`,o=Oe(e,n);return Be(o,n,["code","message"]),{code:Te(o.code,`${n}.code`,void 0,512),message:Te(o.message,`${n}.message`)}})}function We(e,t){let i=Oe(e,t),n=Te(i.status,`${t}.status`);return"missing"===n?(Be(i,t,["status","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,authorizesConversion:!1}):("self_hash_valid_partial_evidence"!==n&&De(`${t}.status`),Be(i,t,["status","canonicalBodySha256","sourceIds","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,canonicalBodySha256:Te(i.canonicalBodySha256,`${t}.canonicalBodySha256`,_e),sourceIds:Ke(i.sourceIds,`${t}.sourceIds`),authorizesConversion:!1})}function Ye(e,t){let i=Oe(e,t),n=Te(i.status,`${t}.status`);if("evidence_missing"===n||"unreviewed"===n)return Be(i,t,["status","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority"),{status:n,authorizesConversion:!1};"verified_partial_evidence"!==n&&"rejected_evidence"!==n&&De(`${t}.status`),Be(i,t,["status","reviewId","reviewer","reviewedAt","notes","reviewHash","authorizesConversion"]),!1!==qe(i.authorizesConversion,`${t}.authorizesConversion`)&&De(t,"grants authority");let o=Te(i.reviewedAt,`${t}.reviewedAt`,void 0,64);return(Number.isNaN(Date.parse(o))||!/(?:Z|[+-][0-9]{2}:[0-9]{2})$/u.test(o))&&De(`${t}.reviewedAt`),{status:n,reviewId:Te(i.reviewId,`${t}.reviewId`,void 0,512),reviewer:Te(i.reviewer,`${t}.reviewer`,void 0,256),reviewedAt:o,notes:Te(i.notes,`${t}.notes`,void 0,4096),reviewHash:Te(i.reviewHash,`${t}.reviewHash`,_e),authorizesConversion:!1}}function Qe(e,t){let i=Oe(e,t);Be(i,t,["status","specificationBodyCount","executionTupleCount","instanceCount","verifiedPartialReviewExecutionTupleCount","rejectedPartialReviewExecutionTupleCount","isManifestDefinitionOrConversionAuthority"]);let n=Te(i.status,`${t}.status`);return"partial_evidence_available"!==n&&"missing"!==n&&De(`${t}.status`),!1!==qe(i.isManifestDefinitionOrConversionAuthority,`${t}.isManifestDefinitionOrConversionAuthority`)&&De(t,"grants authority"),{status:n,specificationBodyCount:Le(i.specificationBodyCount,`${t}.specificationBodyCount`),executionTupleCount:Le(i.executionTupleCount,`${t}.executionTupleCount`),instanceCount:Le(i.instanceCount,`${t}.instanceCount`),verifiedPartialReviewExecutionTupleCount:Le(i.verifiedPartialReviewExecutionTupleCount,`${t}.verifiedPartialReviewExecutionTupleCount`),rejectedPartialReviewExecutionTupleCount:Le(i.rejectedPartialReviewExecutionTupleCount,`${t}.rejectedPartialReviewExecutionTupleCount`),isManifestDefinitionOrConversionAuthority:!1}}function Xe(e,t){let i=`audit.identities[${t}]`,n=Oe(e,i);Be(n,i,["definitionId","libraryRevision","manifestContentHash","admissionIds","instanceCount","disposition","sourceEvidence","executionTuples","missingEvidence","safeNextActions"]);let o=Te(n.disposition,`${i}.disposition`);Ge.has(o)||De(`${i}.disposition`);let a=Oe(n.sourceEvidence,`${i}.sourceEvidence`);Be(a,`${i}.sourceEvidence`,["embeddedManifest","executionReceipt","presentationProjection","currentCatalog","registeredArchive","reviewedSemanticEquivalence","recoveredStudioSpecs"]);for(let e of["embeddedManifest","executionReceipt","presentationProjection","currentCatalog","registeredArchive","reviewedSemanticEquivalence"])Oe(a[e],`${i}.sourceEvidence.${e}`);return{definitionId:Ve(n.definitionId,`${i}.definitionId`,void 0,512),libraryRevision:Ve(n.libraryRevision,`${i}.libraryRevision`,Me),manifestContentHash:Ve(n.manifestContentHash,`${i}.manifestContentHash`,_e),admissionIds:Ke(n.admissionIds,`${i}.admissionIds`),instanceCount:Le(n.instanceCount,`${i}.instanceCount`),disposition:o,recoveredStudioSpecs:Qe(a.recoveredStudioSpecs,`${i}.sourceEvidence.recoveredStudioSpecs`),executionTuples:ze(n.executionTuples,`${i}.executionTuples`).map((e,t)=>function(e,t){let i=Oe(e,t);return Be(i,t,["admissionId","studioExecutionSpec","instanceCount","recoveredStudioSpec","manualReview"]),{admissionId:Ve(i.admissionId,`${t}.admissionId`,void 0,1024),studioExecutionSpec:null===i.studioExecutionSpec?null:Ze(i.studioExecutionSpec,`${t}.studioExecutionSpec`),instanceCount:Le(i.instanceCount,`${t}.instanceCount`),recoveredStudioSpec:We(i.recoveredStudioSpec,`${t}.recoveredStudioSpec`),manualReview:Ye(i.manualReview,`${t}.manualReview`)}}(e,`${i}.executionTuples[${t}]`)),missingEvidence:Ue(n.missingEvidence,`${i}.missingEvidence`),safeNextActions:Ue(n.safeNextActions,`${i}.safeNextActions`)}}function et(e,t){let i=`audit.partialStudioSpecEvidence.sources[${t}]`,n=Oe(e,i);return Be(n,i,["sourceId","artifactLabel","compressedSha256","compressedBytes","uncompressedSha256","uncompressedBytes","selector","candidateSpecificationCount"]),Te(n.compressedSha256,`${i}.compressedSha256`,_e),Le(n.compressedBytes,`${i}.compressedBytes`),Te(n.uncompressedSha256,`${i}.uncompressedSha256`,_e),Le(n.uncompressedBytes,`${i}.uncompressedBytes`),Te(n.selector,`${i}.selector`,void 0,512),Le(n.candidateSpecificationCount,`${i}.candidateSpecificationCount`),{sourceId:Te(n.sourceId,`${i}.sourceId`,void 0,160),artifactLabel:Te(n.artifactLabel,`${i}.artifactLabel`,void 0,512)}}function tt(e,t){let i=`audit.partialStudioSpecEvidence.specifications[${t}]`,n=Oe(e,i);Be(n,i,["identity","canonicalBodySha256","specification","sourceIds","authorizesConversion"]),!1!==qe(n.authorizesConversion,`${i}.authorizesConversion`)&&De(i,"grants authority");let o=Ze(n.identity,`${i}.identity`),a=Oe(n.specification,`${i}.specification`);Be(a,`${i}.specification`,["schemaVersion","canonicalizationVersion","id","modelType","mode","executionProfileId","loaderModule","loaderAction","executionPath","pipelineClass","defaultRepo","roles","edges","bindings","autoFields","actions","contentHash"],["auxiliaryTerminalRoles"]),(1!==a.schemaVersion||a.id!==o.id||a.contentHash!==o.contentHash||a.executionProfileId!==o.executionProfileId)&&De(`${i}.specification`,"does not match its evidence identity");let s=ze(a.roles,`${i}.specification.roles`),r=ze(a.edges,`${i}.specification.edges`),c=ze(a.bindings,`${i}.specification.bindings`),d=ze(a.actions,`${i}.specification.actions`);return ze(a.autoFields,`${i}.specification.autoFields`),void 0!==a.auxiliaryTerminalRoles&&Ke(a.auxiliaryTerminalRoles,`${i}.specification.auxiliaryTerminalRoles`),{identity:o,canonicalBodySha256:Te(n.canonicalBodySha256,`${i}.canonicalBodySha256`,_e),sourceIds:Ke(n.sourceIds,`${i}.sourceIds`),modelType:Te(a.modelType,`${i}.specification.modelType`,void 0,512),mode:Te(a.mode,`${i}.specification.mode`,void 0,512),pipelineClass:Te(a.pipelineClass,`${i}.specification.pipelineClass`,void 0,512),roleCount:s.length,edgeCount:r.length,bindingCount:c.length,actionCount:d.length}}function it(e){let t=Oe(e,"response");Be(t,"response",["error","audit"]),!1!==t.error&&De("response.error","must be false");let i=Oe(t.audit,"audit");Be(i,"audit",["schemaVersion","kind","boundary","localEvidence","summary","partialStudioSpecEvidence","identities","contentHash"]),(4!==i.schemaVersion||"registered_cluster_manifest_recovery_audit"!==i.kind)&&De("audit","uses an unsupported contract");let n=Oe(i.boundary,"audit.boundary");Be(n,"audit.boundary",["readOnly","containsWorkflowPaths","containsInstanceIds","containsPromptOrParameterValues","historicalHashAloneIsNotExecutionAuthority","presentationProjectionIsNotDefinitionAuthority","recoveredStudioSpecEvidenceDoesNotAuthorizeConversion","compilerMappingPresenceAloneDoesNotAuthorizeConversion"]);let o=qe(n.readOnly,"audit.boundary.readOnly"),a=qe(n.containsWorkflowPaths,"audit.boundary.containsWorkflowPaths"),s=qe(n.containsInstanceIds,"audit.boundary.containsInstanceIds"),r=qe(n.containsPromptOrParameterValues,"audit.boundary.containsPromptOrParameterValues"),c=qe(n.historicalHashAloneIsNotExecutionAuthority,"audit.boundary.historicalHashAloneIsNotExecutionAuthority"),d=qe(n.presentationProjectionIsNotDefinitionAuthority,"audit.boundary.presentationProjectionIsNotDefinitionAuthority"),l=qe(n.recoveredStudioSpecEvidenceDoesNotAuthorizeConversion,"audit.boundary.recoveredStudioSpecEvidenceDoesNotAuthorizeConversion"),u=qe(n.compilerMappingPresenceAloneDoesNotAuthorizeConversion,"audit.boundary.compilerMappingPresenceAloneDoesNotAuthorizeConversion");(!0!==o||!1!==a||!1!==s||!1!==r||!0!==c||!0!==d||!0!==l||!0!==u)&&De("audit.boundary","weakens the read-only evidence boundary"),Oe(i.localEvidence,"audit.localEvidence");let p=Oe(i.summary,"audit.summary");Be(p,"audit.summary",Je);let m=Object.fromEntries(Je.map(e=>[e,Le(p[e],`audit.summary.${e}`)]));(m.compilerMappingEligibleInstanceCount+m.remainingBlockedHistoricalInstanceCount!==m.legacyClusterInstanceCount-m.currentExecutionTupleExactInstanceCount-m.semanticEquivalenceReviewedInstanceCount||m.compilerMappingEligibleIdentityCount+m.remainingBlockedHistoricalIdentityCount!==m.definitionIdentityCount-m.currentExecutionTupleExactIdentityCount-m.semanticEquivalenceReviewedIdentityCount)&&De("audit.summary","has inconsistent historical compiler-mapping progress");let h=Oe(i.partialStudioSpecEvidence,"audit.partialStudioSpecEvidence");Be(h,"audit.partialStudioSpecEvidence",["status","authorizesConversion","sources","specifications","manualReviews"]);let f=Te(h.status,"audit.partialStudioSpecEvidence.status");"matched"!==f&&"no_matching_evidence"!==f&&De("audit.partialStudioSpecEvidence.status"),!1!==qe(h.authorizesConversion,"audit.partialStudioSpecEvidence.authorizesConversion")&&De("audit.partialStudioSpecEvidence","grants authority");let g=ze(h.sources,"audit.partialStudioSpecEvidence.sources").map(et),v=ze(h.specifications,"audit.partialStudioSpecEvidence.specifications").map(tt);ze(h.manualReviews,"audit.partialStudioSpecEvidence.manualReviews").forEach((e,t)=>Oe(e,`audit.partialStudioSpecEvidence.manualReviews[${t}]`));let y=ze(i.identities,"audit.identities").map(Xe);return m.definitionIdentityCount!==y.length&&De("audit.summary.definitionIdentityCount"),m.recoveredStudioSpecBodyCount!==v.length&&De("audit.summary.recoveredStudioSpecBodyCount"),{schemaVersion:4,kind:"registered_cluster_manifest_recovery_audit",contentHash:Te(i.contentHash,"audit.contentHash",_e),boundary:{readOnly:!0,containsWorkflowPaths:!1,containsInstanceIds:!1,containsPromptOrParameterValues:!1,historicalHashAloneIsNotExecutionAuthority:!0,presentationProjectionIsNotDefinitionAuthority:!0,recoveredStudioSpecEvidenceDoesNotAuthorizeConversion:!0,compilerMappingPresenceAloneDoesNotAuthorizeConversion:!0},summary:m,evidenceStatus:f,evidenceSources:g,specifications:v,identities:y}}function nt(){return d(`${E.serverAddress}/studio/composite-migrations/recovery-audit`,{timeoutMs:6e4,parse:it})}var ot=/^user-workflows\/([A-Za-z0-9_-]{1,96})\.json$/u;function at(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function st(e,t){return et)}function rt(...e){return e.join("\0")}function ct(e,t){return b(e)===b(t)}function dt(e){throw Error(e)}function lt(e){return"number"==typeof e&&Number.isFinite(e)&&e>0}function ut(e,t){return(!e.position||!Number.isFinite(e.position.x)||!Number.isFinite(e.position.y))&&dt(`${t} has no exact finite persisted position.`),{x:e.position.x,y:e.position.y}}function pt(e){let t=ot.exec(e);return t||dt(`Compiler candidate source path ${e} is not a saved workflow path.`),t[1]}async function mt(e,t){let i=pt(e);return d(`${E.serverAddress}/workflows/${encodeURIComponent(i)}`,{timeoutMs:12e4,signal:t,parse:t=>function(e,t){(!at(e)||"string"!=typeof e.id||!at(e.snapshot))&&dt(`Saved workflow ${t} is malformed.`);let i=pt(t);e.id!==i&&dt(`Saved workflow ${t} returned a different workflow id.`);let n=e.snapshot.nodes,o=e.snapshot.edges;return(!Array.isArray(n)||!Array.isArray(o))&&dt(`Saved workflow ${t} has no exact graph snapshot.`),{id:i,sourcePath:t,snapshot:{nodes:structuredClone(n),edges:structuredClone(o)}}}(t,e)})}function ht(e,t){return e.snapshot.nodes.filter(e=>e.id!==t&&(e.parentId===t||e.data?.huggingFaceClusterInstanceId===t)).sort((e,t)=>st(e.id,t.id))}function ft(e,t,i){e.id||dt("Legacy registered Cluster candidate has no instance id."),(!e.sourceSha256||!e.legacyCompositeHash)&&dt("Backend preview did not provide the exact source and legacy composite hashes.");let n=t.snapshot.nodes.filter(t=>t.id===e.id);1!==n.length&&dt(`Legacy Cluster ${e.id} does not resolve to exactly one saved root.`);let o=n[0],a=o.data?.huggingFaceClusterInstance;("cluster"!==o.type||"cluster"!==o.data?.type||"root"!==o.data?.huggingFaceClusterRole||!a||a.instanceId!==o.id)&&dt(`Saved node ${e.id} is not one exact legacy registered Cluster root.`),null!==a.structuralFork&&dt(`Legacy Cluster ${e.id} is structurally forked.`);let s=a.execution;s||dt(`Legacy Cluster ${e.id} has no execution receipt.`);let r=i.filter(({id:e})=>e===a.definition.id),c=r.find(e=>e.libraryRevision===a.definition.libraryRevision&&e.contentHash===a.definition.contentHash),d=e.semanticEquivalenceAuthority??null,l=e.historicalCompilerMappingAuthority??null;d&&l&&dt(`Legacy Cluster ${e.id} has conflicting historical review authorities.`);let u=d??l;if(!c){u||(r.length&&dt(`Legacy Cluster ${e.id} uses historical manifest ${a.definition.contentHash}; no reviewed archived definition or equivalence receipt is registered.`),dt(`Legacy Cluster ${e.id} references an unavailable catalog definition ${a.definition.id}.`));let t=u.historical;(t.manifestDefinitionId!==a.definition.id||t.libraryRevision!==a.definition.libraryRevision||t.manifestContentHash!==a.definition.contentHash||t.executionAdmissionId!==s.admissionId||!ct(t.studioExecutionSpec,s.studioExecutionSpec))&&dt(`Legacy Cluster ${e.id} does not match the reviewed historical compiler authority.`);let n=u.destination,o=i.filter(e=>e.id===n.manifestDefinitionId&&e.libraryRevision===n.libraryRevision&&e.contentHash===n.manifestContentHash);1!==o.length&&dt(`Legacy Cluster ${e.id} historical compiler destination is unavailable or ambiguous.`),c=o[0]}let p=u?u.destination.executionAdmissionId:s.admissionId,m=c.executionAdmissions.find(({id:e})=>e===p);m||dt(`Legacy Cluster ${e.id} references an unavailable execution admission.`),!u&&(m.studioExecutionSpec?.id!==s.studioExecutionSpec.id||m.studioExecutionSpec?.contentHash!==s.studioExecutionSpec.contentHash||m.studioExecutionSpec?.executionProfileId!==s.studioExecutionSpec.executionProfileId)&&dt(`Legacy Cluster ${e.id} has a stale Studio execution specification receipt.`);let h=k(c,m);return h||dt(`Legacy Cluster ${e.id} is not an exact current registered Block V2 route.`),(!lt(o.width)||!lt(o.height))&&dt(`Legacy Cluster ${e.id} has no exact positive persisted width and height.`),ut(o,`Legacy Cluster ${e.id}`),{candidate:e,workflow:t,root:o,children:ht(t,o.id),edges:t.snapshot.edges,instance:a,definition:c,route:h,semanticEquivalenceAuthority:d,historicalCompilerMappingAuthority:l}}function gt(e,t,i){let n=new Map(i.map(e=>[e.legacyNodeId,e.semanticNodeId])),o=new Set;return t.effectiveGraph.nodes.forEach(t=>{if(!t.semanticRole)return;o.has(t.semanticRole)&&dt(`Compiled graph has duplicate semantic role ${t.semanticRole}; legacy endpoint ownership is ambiguous.`),o.add(t.semanticRole);let i=j(e.root.id,`diffusers.cluster-execution:${encodeURIComponent(t.semanticRole)}`),a=n.get(i);a&&a!==t.nodeId&&dt(`Legacy execution endpoint ${i} maps to conflicting semantic nodes.`),n.set(i,t.nodeId)}),n}function vt(e,t,i,n){let o=("input"===t?e.effectiveInterface.boundary.inputs:e.effectiveInterface.boundary.outputs).filter(e=>function(e){return[e.binding,...e.mirrorBindings??[]].map(({nodeId:e,fieldOrPortId:t})=>({nodeId:e,fieldId:t}))}(e).some(e=>e.nodeId===i&&e.fieldId===n));return 1!==o.length&&dt(`Legacy ${t} endpoint ${i}.${n} does not resolve to exactly one V2 public port.`),o[0]}function yt(e,t,i){let n=gt(e,t,i),o=new Set([e.root.id,...e.children.map(({id:e})=>e)]),a=new Map;return Object.entries(e.root.data.params??{}).forEach(([t,i])=>{let n=i.fieldOptions?.huggingFaceClusterPortDirection;if("input"!==n&&"output"!==n)return;let o={direction:n,legacyNodeId:e.root.id,legacyPortId:t};a.set(rt(n,e.root.id,t),o)}),e.edges.forEach(e=>{let t=o.has(e.source),i=o.has(e.target);if(t!==i){if(t){e.sourceHandle||dt(`Crossing edge ${e.id} has no exact source handle.`);let t={direction:"output",legacyNodeId:e.source,legacyPortId:e.sourceHandle};a.set(rt(t.direction,t.legacyNodeId,t.legacyPortId),t)}if(i){e.targetHandle||dt(`Crossing edge ${e.id} has no exact target handle.`);let t={direction:"input",legacyNodeId:e.target,legacyPortId:e.targetHandle};a.set(rt(t.direction,t.legacyNodeId,t.legacyPortId),t)}}}),[...a.values()].map(i=>{let o=function(e,t,i,n,o){if(n!==e.root.id){let e=t.get(n);return e||dt(`Legacy boundary endpoint ${n}.${o} is not an owned projection.`),{semanticNodeId:e,fieldId:o}}let a=e.root.data.params?.[o],s=at(a?.fieldOptions)?a.fieldOptions:{};(s.huggingFaceClusterPortDirection!==i||"string"!=typeof s.huggingFaceClusterPortNodeId||"string"!=typeof s.huggingFaceClusterPortField)&&dt(`Legacy root port ${o} has incomplete ${i} metadata.`);let r=t.get(s.huggingFaceClusterPortNodeId);return r||dt(`Legacy root port ${o} targets a projection that is absent from the saved snapshot.`),{semanticNodeId:r,fieldId:s.huggingFaceClusterPortField}}(e,n,i.direction,i.legacyNodeId,i.legacyPortId);return{...i,v2PortId:vt(t,i.direction,o.semanticNodeId,o.fieldId).portId}}).sort((e,t)=>st(rt(e.direction,e.legacyNodeId,e.legacyPortId,e.v2PortId),rt(t.direction,t.legacyNodeId,t.legacyPortId,t.v2PortId)))}function xt(e,t,i){let n=e.effectiveInterface.controls.filter(e=>[e.binding,...e.mirrorBindings??[]].some(e=>e.nodeId===t&&e.fieldId===i));return 1===n.length?n[0]:null}function bt(e){return null===e?"null":Array.isArray(e)?"array":"object"==typeof e?"object":"number"==typeof e?Number.isInteger(e)?"integer":"number":typeof e}function It(e,t,i={}){if(null===e)return!0!==i.required||null===i.defaultValue;let n=w(t);return!!(Array.isArray(n)?n:[n]).some(t=>{if("string"!=typeof t)return!1;let i=t.trim().toLowerCase();return"string"===i||"text"===i||"str"===i||"dropdown"===i?"string"==typeof e:"bool"===i||"boolean"===i?"boolean"==typeof e:"int"===i||"integer"===i?"number"==typeof e&&Number.isInteger(e):"float"===i||"double"===i||"number"===i?"number"==typeof e&&Number.isFinite(e):"minimax_h3_references"===i||/^(?:list|array|sequence|tuple|set)(?:\[|$)/u.test(i)?Array.isArray(e):/^(?:dict|mapping|object|json)(?:\[|$)/u.test(i)?at(e):!!/^(?:image|video|audio|file|path|uri|url|media)(?:\b|_)/u.test(i)&&("string"==typeof e||at(e))})||void 0!==i.defaultValue&&null!==i.defaultValue&&function(e,t){let i=bt(e),n=bt(t);return i===n||"integer"===i&&"number"===n}(e,i.defaultValue)}async function Ct(e,t){let i=await O(e.definition,function(e){if(!e.semanticEquivalenceAuthority&&!e.historicalCompilerMappingAuthority)return e.root;let t=e.definition.executionAdmissions.find(({id:t})=>t===e.route.admissionId);t||dt(`Current destination admission ${e.route.admissionId} is unavailable.`);let i={...$(t.studioMode,e.definition.pipelineClass),modelType:e.definition.pipelineClass,mode:t.studioMode},{parameterOverrides:n,executionParameterOverrides:o}=F(e.definition,t,i),a=e.definition.suggestedInputs?.values??{},s=Object.fromEntries(Object.entries(n).filter(([e,t])=>!(""===t&&Object.prototype.hasOwnProperty.call(a,e)))),r=y(e.definition,e.root.id,ut(e.root,`Legacy Cluster ${e.root.id}`),{...a,...s},t.id,o);r.width=e.root.width,r.height=e.root.height;let c=r.data.huggingFaceClusterInstance;return c?.execution||dt(`Current destination compiler root ${e.root.id} has no execution receipt.`),r.data.huggingFaceClusterInstance={...c,presentation:{...c.presentation,expanded:e.instance.presentation.expanded}},r}(e),{timeoutMs:t}),n=[...i.definition.contentHash===e.route.compiledDefinitionContentHash?[]:["definition content hash"],...i.instance.definitionSnapshot.source.executionAdmissionId===e.route.admissionId?[]:["execution admission"],...i.instance.authorities.length?["instance authorities"]:[],...i.instance.effectiveGraph.graphHash===i.definition.graph.graphHash?[]:["effective graph"]];n.length&&dt(`Compiled registered definition for ${e.root.id} is stale or structurally customized (${n.join(", ")}).`);let o=e.semanticEquivalenceAuthority??e.historicalCompilerMappingAuthority;o&&(ct(o.destination,{manifestDefinitionId:e.route.definitionId,libraryRevision:e.route.libraryRevision,manifestContentHash:e.route.definitionContentHash,executionAdmissionId:e.route.admissionId,blockDefinitionId:i.definition.definitionId,blockDefinitionContentHash:i.definition.contentHash,blockDefinitionCanonicalSha256:e.route.compiledDefinitionCanonicalSha256,executionGraphHash:i.definition.graph.graphHash,interfaceHash:I({boundary:i.definition.boundary,controls:i.definition.controls})})||dt(`Reviewed historical compiler authority for ${e.root.id} is stale for the compiled BlockDefinitionV2 graph or interface.`));let a=function(e,t){let i=new Map;t.effectiveGraph.nodes.forEach(e=>{let t=e.semanticRole;t&&i.set(t,[...i.get(t)??[],e.nodeId])});let n=e.children.map(t=>{let n=t.data,o=n?.huggingFaceClusterExecutionRole;("execution"!==n?.huggingFaceClusterRole||n.huggingFaceClusterInstanceId!==e.root.id||n.huggingFaceClusterExecutionAdmissionId!==e.instance.execution?.admissionId||n.huggingFaceClusterExecutionSpecId!==e.instance.execution.studioExecutionSpec.id||!o)&&dt(`Legacy projection ${t.id} has incomplete or stale execution ownership.`);let a=i.get(o)??[];return 1!==a.length&&dt(`Legacy projection ${t.id} cannot be mapped one-to-one to semantic role ${o}.`),{legacyNodeId:t.id,semanticNodeId:a[0]}}),o=n.map(({semanticNodeId:e})=>e);return new Set(o).size!==o.length&&dt(`Legacy Cluster ${e.root.id} would merge multiple projection nodes.`),n.sort((e,t)=>st(rt(e.legacyNodeId,e.semanticNodeId),rt(t.legacyNodeId,t.semanticNodeId)))}(e,i.instance),s=function(e,t,i){let n={...t.presentation.internalLayout};return i.forEach(({legacyNodeId:t,semanticNodeId:i})=>{let o=e.children.find(({id:e})=>e===t);n[i]={...ut(o,`Legacy projection ${t}`),...lt(o.width)?{width:o.width}:{},...lt(o.height)?{height:o.height}:{}}}),M({...t,presentation:{...t.presentation,internalLayout:n}})}(e,i.instance,a),r=function(e,t,i){let n=gt(e,t,i),o=[],a={...t.values},s=new Map;(function(e){let t=[];return[e.root,...e.children].sort((e,t)=>st(e.id,t.id)).forEach(e=>{Object.entries(e.data.params??{}).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>{Object.prototype.hasOwnProperty.call(n,"value")&&"output"!==n.display&&t.push({sourceKind:"node_param",sourceNodeId:e.id,sourceFieldId:i,value:structuredClone(n.value)})})}),Object.entries(e.instance.parameterOverrides).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>t.push({sourceKind:"instance_parameter_override",sourceNodeId:e.root.id,sourceFieldId:i,value:structuredClone(n)})),Object.entries(e.instance.execution?.parameterOverrides??{}).sort(([e],[t])=>st(e,t)).forEach(([i,n])=>t.push({sourceKind:"execution_parameter_override",sourceNodeId:e.root.id,sourceFieldId:i,value:structuredClone(n)})),t})(e).forEach(i=>{let r=function(e,t,i,n){if("instance_parameter_override"===n.sourceKind||"execution_parameter_override"===n.sourceKind)return new Set([...t.effectiveInterface.controls.map(({controlId:e})=>e),...t.effectiveInterface.boundary.inputs.map(({portId:e})=>e)]).has(n.sourceFieldId)||dt(`Legacy override ${n.sourceKind}/${n.sourceFieldId} has no exact V2 input/control.`),{targetKind:"instance_value",targetValueId:n.sourceFieldId};if(n.sourceNodeId===e.root.id){let o=e.root.data.params[n.sourceFieldId]?.fieldOptions;if("input"===o?.huggingFaceClusterPortDirection&&"string"==typeof o.huggingFaceClusterPortNodeId&&"string"==typeof o.huggingFaceClusterPortField){let e=i.get(o.huggingFaceClusterPortNodeId),a=e?xt(t,e,o.huggingFaceClusterPortField):null;return a||dt(`Legacy root value ${n.sourceFieldId} has ambiguous input-port ownership.`),{targetKind:"instance_value",targetValueId:a.controlId}}return new Set([...t.effectiveInterface.controls.map(({controlId:e})=>e),...t.effectiveInterface.boundary.inputs.map(({portId:e})=>e)]).has(n.sourceFieldId)||dt(`Legacy root value ${n.sourceFieldId} has no exact V2 input/control.`),{targetKind:"instance_value",targetValueId:n.sourceFieldId}}let o=i.get(n.sourceNodeId);o||dt(`Legacy value ${n.sourceNodeId}.${n.sourceFieldId} is outside the owned projection.`);let a=function(e){let t=e?.fieldOptions?.huggingFaceClusterBinding;return!at(t)||1!==t.schemaVersion||"string"!=typeof t.source||"instance_input"!==t.persistence&&"execution_parameter"!==t.persistence&&"sealed"!==t.persistence||void 0!==t.input&&"string"!=typeof t.input?null:t}(e.children.find(({id:e})=>e===n.sourceNodeId).data.params[n.sourceFieldId]);if("instance_input"===a?.persistence||"execution_parameter"===a?.persistence){let e=xt(t,o,n.sourceFieldId);return e||dt(`Legacy mutable field ${n.sourceNodeId}.${n.sourceFieldId} has no exact V2 control.`),{targetKind:"instance_value",targetValueId:e.controlId}}let s=t.effectiveGraph.nodes.find(({nodeId:e})=>e===o),r=(at(s?.data.params)?s.data.params:{})[n.sourceFieldId];return(!at(r)||!Object.prototype.hasOwnProperty.call(r,"value"))&&dt(`Legacy static field ${n.sourceNodeId}.${n.sourceFieldId} has no exact V2 graph parameter.`),{targetKind:"graph_param",targetNodeId:o,targetFieldId:n.sourceFieldId}}(e,t,n,i);if("instance_value"===r.targetKind){!function(e,t,i){let n=e.effectiveInterface.controls.filter(({controlId:e})=>e===t),o=e.effectiveInterface.boundary.inputs.filter(({portId:e})=>e===t);n.length+o.length===0&&dt(`Legacy value ${t} does not target a declared V2 input/control.`),n.forEach(e=>{e.sealed&&!ct(i,e.defaultValue)&&dt(`Legacy value ${t} attempts to rewrite a sealed V2 control.`),It(i,e.valueType,{...void 0===e.defaultValue?{}:{defaultValue:e.defaultValue},required:e.required})||dt(`Legacy value ${t} is incompatible with V2 control type ${String(e.valueType)}.`)}),o.forEach(e=>{It(i,e.valueType,{required:e.required})||dt(`Legacy value ${t} is incompatible with V2 input type ${String(e.valueType)}.`)})}(t,r.targetValueId,i.value);let e=s.get(r.targetValueId);void 0!==e&&!ct(e,i.value)&&dt(`Legacy sources disagree for V2 input/control ${r.targetValueId}.`),s.set(r.targetValueId,i.value),a[r.targetValueId]=i.value}else{let e=t.effectiveGraph.nodes.find(({nodeId:e})=>e===r.targetNodeId).data.params[r.targetFieldId];(!at(e)||!ct(e.value,i.value))&&dt(`Legacy static value ${i.sourceNodeId}.${i.sourceFieldId} differs from the pinned definition.`)}o.push({sourceKind:i.sourceKind,sourceNodeId:i.sourceNodeId,sourceFieldId:i.sourceFieldId,...r})}),o.sort((e,t)=>st(rt(e.sourceKind,e.sourceNodeId,e.sourceFieldId,e.targetKind),rt(t.sourceKind,t.sourceNodeId,t.sourceFieldId,t.targetKind)));let r=t.effectiveInterface.boundary.inputs.some(({portId:e})=>Object.prototype.hasOwnProperty.call(a,e))||t.effectiveInterface.controls.some(e=>Object.prototype.hasOwnProperty.call(a,e.controlId)&&!ct(a[e.controlId],e.defaultValue));return{mappings:o,instance:M({...t,values:a,customization:{...t.customization,state:r?"parameters_changed":"unchanged"}})}}(e,s,a);s=r.instance;let c=function(e,t,i){let n=gt(e,t,i),o=structuredClone(t.previewStates),a=[];return function(e){return[e.root,...e.children].flatMap(e=>Object.entries(e.data.params??{}).flatMap(([t,i])=>"output"!==i.display||null===i.value||void 0===i.value?[]:(("string"!=typeof i.value||!i.value)&&dt(`Legacy output ${e.id}.${t} is not a persistable media reference.`),[{node:e,fieldId:t,mediaReference:i.value}])))}(e).forEach(({node:t,fieldId:i,mediaReference:s})=>{let r,c=i;if(t.id===e.root.id){let e=t.data.params[i]?.fieldOptions,o="string"==typeof e?.huggingFaceClusterPreviewSourceNodeId?e.huggingFaceClusterPreviewSourceNodeId:"output"===e?.huggingFaceClusterPortDirection&&"string"==typeof e.huggingFaceClusterPortNodeId?e.huggingFaceClusterPortNodeId:null,a="string"==typeof e?.huggingFaceClusterPreviewSourceField?e.huggingFaceClusterPreviewSourceField:"output"===e?.huggingFaceClusterPortDirection&&"string"==typeof e.huggingFaceClusterPortField?e.huggingFaceClusterPortField:null;(!o||!a)&&dt(`Legacy root output ${i} has no exact preview-source metadata.`),r=n.get(o),c=a}else r=n.get(t.id);r||dt(`Legacy output ${t.id}.${i} targets an absent projection.`);let d=o.map((e,t)=>({state:e,index:t})).filter(({state:e})=>e.binding.nodeId===r&&e.binding.outputPortId===c);1!==d.length&&dt(`Legacy output ${t.id}.${i} does not resolve to exactly one V2 preview binding.`);let l=d[0];l.state.mediaReference&&l.state.mediaReference!==s&&dt(`Legacy outputs conflict for V2 preview ${r}.${c}.`),o[l.index]={...l.state,mediaReference:s,status:"complete"},a.push({sourceNodeId:t.id,sourceFieldId:i,targetNodeId:r,targetOutputPortId:c})}),a.sort((e,t)=>st(rt(e.sourceNodeId,e.sourceFieldId,e.targetNodeId,e.targetOutputPortId),rt(t.sourceNodeId,t.sourceFieldId,t.targetNodeId,t.targetOutputPortId))),{mappings:a,instance:M({...t,previewStates:o})}}(e,s,a);s=c.instance;let d=new Set([e.root.id,...e.children.map(({id:e})=>e)]),l=e.edges.filter(e=>d.has(e.source)&&d.has(e.target)).map(t=>(t.id||dt(`Legacy Cluster ${e.root.id} has an internal edge without an id.`),t.id)).sort(st);return new Set(l).size!==l.length&&dt(`Legacy Cluster ${e.root.id} has duplicate internal edge ids.`),{legacyInstanceId:e.root.id,legacyCompositeHash:e.candidate.legacyCompositeHash,admissionId:e.route.admissionId,compiledDefinitionContentHash:e.route.compiledDefinitionContentHash,compiledDefinitionCanonicalSha256:e.route.compiledDefinitionCanonicalSha256,blockInstanceV2:s,ownedNodeMappings:a,portMappings:yt(e,s,a),valueMappings:r.mappings,previewMappings:c.mappings,absorbedInternalEdgeIds:l,...e.semanticEquivalenceAuthority?{semanticEquivalenceReceipt:{receiptId:e.semanticEquivalenceAuthority.receiptId,receiptHash:e.semanticEquivalenceAuthority.receiptHash}}:{},...e.historicalCompilerMappingAuthority?{historicalCompilerMapping:{mappingId:e.historicalCompilerMappingAuthority.mappingId,mappingHash:e.historicalCompilerMappingAuthority.mappingHash}}:{}}}function wt(e,t){let i=e instanceof Error?e.message:String(e),n=i.includes("historical manifest")?"historical_manifest_unavailable":i.includes("no execution receipt")?"execution_receipt_missing":i.includes("source and legacy composite hashes")?"candidate_receipt_missing":i.includes("saved root")||i.includes("projection")||i.includes("ambiguous")?"legacy_snapshot_ambiguous":i.includes("route")||i.includes("admission")||i.includes("catalog definition")?"registered_route_unavailable":i.includes("workflow")?"workflow_unavailable":"compiler_failed";return{sourcePath:t.sourcePath,instanceId:t.id,code:n,message:i}}async function $t(e){let t=h(),i=e.candidates.filter(({kind:e,status:t})=>"legacy_registered_cluster_instance"===e&&"blocked"===t).sort((e,t)=>st(rt(e.sourcePath,e.id??""),rt(t.sourcePath,t.id??""))),n=await async function(){let e=N.getState(),t=D.getState();await Promise.all([e.loaded?Promise.resolve():e.fetchLibrary(),Object.keys(t.nodesRegistry).length?Promise.resolve():t.fetchNodes(),t.studioModelCapabilities.length?Promise.resolve():t.fetchStudioModelCapabilities()]);let i=N.getState();return i.library||dt(i.error||"The Hugging Face node library is unavailable."),Object.keys(D.getState().nodesRegistry).length||dt("The backend node registry is unavailable."),i.library}();if(n.definitions.some(({provider:e})=>"diffusers"===e)){let e=C.getState();e.loaded||await e.fetchSnapshot()}g(t,{includeForm:!1})||dt("The active workflow changed while compiler dependencies were loading. Generate a fresh supplement.");let o=null,a=[],s=new Map,r=0;for(let c of i){if(e.signal?.aborted)throw new DOMException("Compiler supplement generation was cancelled.","AbortError");g(t,{includeForm:!1})||dt("The active workflow changed during compiler supplement generation. Generate a fresh supplement.");try{o?.sourcePath!==c.sourcePath&&(o=await mt(c.sourcePath,e.signal));let i=o;g(t,{includeForm:!1})||dt("The active workflow changed while a saved workflow was loading. Generate a fresh supplement.");let a=await Ct(ft(c,i,n.definitions),e.timeoutMs);g(t,{includeForm:!1})||dt("The active workflow changed during compiler supplement generation. Generate a fresh supplement."),s.set(c.sourcePath,[...s.get(c.sourcePath)??[],a])}catch(e){if(!g(t,{includeForm:!1}))throw e;a.push(wt(e,c))}finally{r+=1,e.onProgress?.({completed:r,total:i.length,sourcePath:c.sourcePath,instanceId:c.id})}}let c=ge({schemaVersion:1,kind:"registered_cluster_v2_compiler_supplement",compilerOutputs:[...s.entries()].sort(([e],[t])=>st(e,t)).map(([e,t])=>({sourcePath:e,sourceSha256:i.find(({sourcePath:t})=>t===e).sourceSha256,conversions:t.sort((e,t)=>st(e.legacyInstanceId,t.legacyInstanceId))}))});return(new TextEncoder).encode(JSON.stringify(c)).byteLength>33554432&&dt("Generated compiler supplement exceeds the reviewed 32 MiB request limit."),{supplement:c,diagnostics:a.sort((e,t)=>st(rt(e.sourcePath,e.instanceId??"",e.code),rt(t.sourcePath,t.instanceId??"",t.code))),candidateCount:i.length,conversionCount:c.compilerOutputs.reduce((e,t)=>e+t.conversions.length,0)}}var Nt=a();function St(e){return e.replace(/_/g," ")}function jt(e){return"applied"===e||"rolled_back"===e?"success":"interrupted"===e?"warning":"error"}function kt({audit:e,error:t,loading:i,onRefresh:n}){let a=e?.identities.filter(e=>"partial_evidence_available"===e.recoveredStudioSpecs.status)??[];return(0,Nt.jsxs)("div",{className:"grid gap-3","data-testid":"legacy-cluster-recovery-evidence-panel",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"This read-only audit reports historical recovery evidence and checked-in compiler-mapping coverage. It does not compile, convert, execute, approve, or mutate a Block by itself. Mapping-ready instances still require an exact compiler supplement, reviewed preview, and explicit apply confirmation."}),(0,Nt.jsx)(A,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(c,{size:14}),loading:i,disabled:i,onClick:n,"data-testid":"legacy-cluster-recovery-evidence-refresh",children:"Refresh evidence"})]}),t?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/5 p-2 text-xs text-modiff-red",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{className:"break-words",children:t})]}):null,e?(0,Nt.jsxs)(Nt.Fragment,{children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2","data-testid":"legacy-cluster-recovery-evidence-summary",children:[(0,Nt.jsx)(x,{label:`${e.summary.legacyClusterInstanceCount} saved Blocks`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.compilerMappingEligibleInstanceCount} mapping-ready instances`,tone:e.summary.compilerMappingEligibleInstanceCount?"success":"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.compilerMappingEligibleIdentityCount} mapping-ready ${1===e.summary.compilerMappingEligibleIdentityCount?"identity":"identities"}`,tone:e.summary.compilerMappingEligibleIdentityCount?"success":"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.remainingBlockedHistoricalInstanceCount} historical still blocked`,tone:e.summary.remainingBlockedHistoricalInstanceCount?"warning":"success"}),(0,Nt.jsx)(x,{label:`${e.summary.remainingBlockedHistoricalIdentityCount} blocked ${1===e.summary.remainingBlockedHistoricalIdentityCount?"identity":"identities"}`,tone:e.summary.remainingBlockedHistoricalIdentityCount?"warning":"success"}),(0,Nt.jsx)(x,{label:`${e.summary.recoveredStudioSpecBodyCount} recovered bodies`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.recoveredStudioSpecManifestIdentityCount} identities`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.recoveredStudioSpecExecutionTupleCount} execution tuples`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.recoveredStudioSpecInstanceCount} covered instances`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.partialReviewVerifiedExecutionTupleCount} partially reviewed`,tone:e.summary.partialReviewVerifiedExecutionTupleCount?"warning":"neutral"})]}),(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2 text-xs leading-5 text-modiff-text",children:"Read-only boundary: no workflow paths, instance IDs, prompts, or parameter values are included. A valid historical Studio-spec self-hash is partial evidence only; it is not manifest, interface, artifact, or execution authority. A checked-in compiler mapping covers only its exact archived tuple and does not, by its presence alone, authorize conversion or workflow mutation."}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:["Recovered Studio bodies (",e.specifications.length,")"]}),e.specifications.length?(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto","data-testid":"legacy-cluster-recovered-specifications",children:e.specifications.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"min-w-0",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.identity.id}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.modelType," · ",e.mode," · ",e.identity.executionProfileId]})]}),(0,Nt.jsx)(x,{label:`${e.roleCount} roles · ${e.edgeCount} edges`,tone:"neutral"})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-subtle-text",children:[e.identity.contentHash," · ",e.canonicalBodySha256]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.bindingCount," bindings · ",e.actionCount," dynamic actions · sources:"," ",e.sourceIds.join(", ")]})]},e.canonicalBodySha256))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No exact local capture contains a matching body."})]}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:["Historical identities with partial evidence (",a.length,")"]}),a.length?(0,Nt.jsx)("div",{className:"grid max-h-80 gap-2 overflow-auto","data-testid":"legacy-cluster-recovered-identities",children:a.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1.5 rounded-modiff-compact border border-hf-orange/30 bg-modiff-bg p-2 text-xs",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.definitionId??"Malformed identity"}),(0,Nt.jsx)(x,{label:`${e.instanceCount} instances`,tone:"warning"})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-subtle-text",children:[e.libraryRevision??"missing revision"," ·"," ",e.manifestContentHash??"missing hash"]}),e.executionTuples.filter(e=>"self_hash_valid_partial_evidence"===e.recoveredStudioSpec.status).map((e,t)=>(0,Nt.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border p-2",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.studioExecutionSpec?.id??"Missing Studio receipt"}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.instanceCount," instances · review ",St(e.manualReview.status)," · conversion authority: none"]})]},`${e.admissionId??"missing"}:${e.studioExecutionSpec?.contentHash??t}`)),(0,Nt.jsxs)("p",{className:"text-hf-orange",children:["Still missing: ",e.missingEvidence.map(({code:e})=>St(e)).join("; ")]})]},`${e.definitionId}:${e.libraryRevision}:${e.manifestContentHash}`))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No historical identity has recovered partial evidence."})]}),(0,Nt.jsxs)("p",{className:"break-all font-mono text-xs text-modiff-subtle-text",children:["Audit: ",e.contentHash]})]}):i||t?null:(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No historical recovery audit is available."})]})}function Ht({preview:e}){let t=[...new Map(e.candidates.flatMap(e=>{let t=e.compilerReceipt?.semanticEquivalenceAuthority??e.semanticEquivalenceAuthority;return t?[[t.receiptHash,t]]:[]})).values()],i=[...new Map(e.candidates.flatMap(e=>{let t=e.compilerReceipt?.historicalCompilerMappingAuthority??e.historicalCompilerMappingAuthority;return t?[[t.mappingHash,t]]:[]})).values()];return(0,Nt.jsxs)("div",{className:"grid gap-3","data-testid":"composite-migration-preview-details",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)(x,{label:`${e.summary.targetFileCount} target files`,tone:"neutral"}),(0,Nt.jsx)(x,{label:`${e.summary.convertibleCandidateCount} convertible`,tone:e.summary.convertibleCandidateCount?"success":"neutral"}),e.compilerSupplement?(0,Nt.jsx)(x,{label:`${e.summary.registeredClusterConvertibleCount??0} registered Blocks compiled`,tone:e.compilerSupplement.provided?"success":"neutral"}):null,(0,Nt.jsx)(x,{label:`${e.summary.blockedCandidateCount} blocked`,tone:e.summary.blockedCandidateCount?"warning":"success"})]}),(0,Nt.jsxs)("div",{className:"grid gap-1 text-xs text-modiff-subtle-text",children:[(0,Nt.jsxs)("p",{className:"break-all",children:["Preview: ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.migrationId})]}),(0,Nt.jsxs)("p",{className:"break-all",children:["Plan hash: ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.planHash})]}),e.compilerSupplement?.contentHash?(0,Nt.jsxs)("p",{className:"break-all",children:["Compiler supplement:"," ",(0,Nt.jsx)("span",{className:"font-mono text-modiff-text",children:e.compilerSupplement.contentHash})]}):null]}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Exact files that would change"}),e.targets.length?(0,Nt.jsx)("ul",{className:"max-h-44 space-y-1 overflow-auto rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:e.targets.map(e=>(0,Nt.jsx)("li",{className:"break-all font-mono text-xs text-modiff-text",children:e.sourcePath},e.sourcePath))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No safe conversion target is present."})]}),t.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-equivalence-diffs",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-yellow",children:"Reviewed historical equivalence (preview only)"}),(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto",children:t.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-hf-yellow/30 bg-hf-yellow/5 p-2 text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.receiptId}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Historical manifest: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.manifestContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Historical graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.historical.executionGraphHash," · ",e.historical.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination definition:"," ",(0,Nt.jsx)("span",{className:"font-mono",children:e.destination.blockDefinitionContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.destination.executionGraphHash," · ",e.destination.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:["Reviewed by ",e.review.issuer," at ",e.review.reviewedAt,": ",e.review.notes]}),(0,Nt.jsx)("p",{className:"text-hf-yellow",children:"This checked-in review enables exact compiler validation only; it does not apply or mutate a workflow."})]},e.receiptHash))})]}):null,i.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-archived-compiler-mappings",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-yellow",children:"Reviewed archived compiler mapping (preview only)"}),(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto",children:i.map(e=>(0,Nt.jsxs)("article",{className:"grid gap-1 rounded-modiff-compact border border-hf-yellow/30 bg-hf-yellow/5 p-2 text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.mappingId}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Archived manifest: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.manifestContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Archive record: ",(0,Nt.jsx)("span",{className:"font-mono",children:e.historical.archivedDefinitionRecordHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination definition:"," ",(0,Nt.jsx)("span",{className:"font-mono",children:e.destination.blockDefinitionContentHash})]}),(0,Nt.jsxs)("p",{className:"break-all text-modiff-subtle-text",children:["Destination graph/interface:"," ",(0,Nt.jsxs)("span",{className:"font-mono",children:[e.destination.executionGraphHash," · ",e.destination.interfaceHash]})]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:["Reviewed by ",e.review.issuer," at ",e.review.reviewedAt,": ",e.review.notes]}),(0,Nt.jsx)("p",{className:"text-hf-yellow",children:"This maps one exact archived body to one exact compiler destination. Per-instance preservation, explicit Apply, byte backup, and rollback are still required."})]},e.mappingHash))})]}):null,e.blocked.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5","data-testid":"composite-migration-blockers",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:"Blocked candidates remain unchanged"}),(0,Nt.jsx)("ul",{className:"max-h-44 space-y-2 overflow-auto rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2",children:e.blocked.map((e,t)=>(0,Nt.jsxs)("li",{className:"text-xs",children:[(0,Nt.jsx)("p",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.id?`${e.id}: `:"",e.reason]})]},`${e.sourcePath}:${e.kind}:${e.id??t}`))})]}):null,e.inventoryIssues.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:"Inventory issues"}),(0,Nt.jsx)("ul",{className:"max-h-36 space-y-1 overflow-auto text-xs text-modiff-subtle-text",children:e.inventoryIssues.map((e,t)=>(0,Nt.jsxs)("li",{children:[(0,Nt.jsx)("span",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),": ",e.message]},`${e.sourcePath}:${e.path}:${e.code}:${t}`))})]}):null]})}function Pt({allowBlockedCandidates:e,busy:t,confirmation:i,error:n,onAllowBlockedCandidatesChange:o,onApply:a,onCancel:s,onConfirmationChange:r,preview:c}){let d=le(c,i,e);return(0,Nt.jsxs)("div",{className:"grid gap-4","data-testid":"composite-migration-apply-review",children:[(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-3 text-xs leading-5 text-modiff-text",children:"This action creates exact backups and replaces only the listed safe Block or workflow files. It never deletes, renames, or merges records. Blocked candidates remain unchanged."}),(0,Nt.jsx)(Ht,{preview:c}),c.summary.blockedCandidateCount>0?(0,Nt.jsx)(R,{checked:e,onCheckedChange:o,label:`Apply only the ${c.summary.targetFileCount} safe target files and leave all ${c.summary.blockedCandidateCount} blocked candidates unchanged.`,"data-testid":"composite-migration-allow-blocked"}):null,(0,Nt.jsx)(_,{label:(0,Nt.jsxs)("span",{children:["Type ",(0,Nt.jsx)("code",{className:"font-mono text-hf-yellow",children:T})]}),required:!0,error:n??void 0,children:(0,Nt.jsx)(P,{autoComplete:"off",spellCheck:!1,value:i,onChange:e=>r(e.currentTarget.value),"data-testid":"composite-migration-apply-confirmation"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 border-t border-modiff-border pt-3",children:[(0,Nt.jsx)(A,{disabled:t,onClick:s,children:"Cancel"}),(0,Nt.jsx)(A,{tone:"primary",loading:t,disabled:t||!d,onClick:a,"data-testid":"composite-migration-apply",children:"Apply reviewed migration"})]})]})}function At({busyId:e,migrations:i,onInspectRollback:n}){return i.length?(0,Nt.jsx)("div",{className:"grid max-h-72 gap-2 overflow-auto","data-testid":"composite-migration-recovery-list",children:i.map(i=>(0,Nt.jsxs)("section",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"min-w-0",children:[(0,Nt.jsx)("p",{className:"truncate font-mono text-xs text-modiff-text",title:i.migrationId,children:i.migrationId}),(0,Nt.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:[i.targets.length," targets · ",St(i.journalState)," journal"]})]}),(0,Nt.jsx)(x,{label:St(i.effectiveState),tone:jt(i.effectiveState)})]}),(0,Nt.jsx)("ul",{className:"space-y-1",children:i.targets.map(e=>(0,Nt.jsxs)("li",{className:"flex min-w-0 items-start justify-between gap-2 text-xs",children:[(0,Nt.jsx)("span",{className:"break-all font-mono text-modiff-text",children:e.sourcePath}),(0,Nt.jsx)("span",{className:p("shrink-0 font-semibold","conflict"===e.state||"missing"===e.state?"text-modiff-red":"applied"===e.state?"text-modiff-green":"text-modiff-subtle-text"),children:e.state})]},e.sourcePath))}),i.rollbackAvailable?(0,Nt.jsx)("div",{children:(0,Nt.jsx)(A,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(t,{size:14}),loading:e===i.migrationId,disabled:!!e,onClick:()=>n(i),"data-testid":`composite-migration-inspect-${i.migrationId}`,children:"Review rollback"})}):null]},i.migrationId))}):(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No migration recovery journals are present."})}function Et({busy:e,confirmation:t,error:i,onCancel:n,onConfirmationChange:o,onRollback:a,status:s}){return(0,Nt.jsxs)("div",{className:"grid gap-4","data-testid":"composite-migration-rollback-review",children:[(0,Nt.jsx)("div",{className:"rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-3 text-xs leading-5 text-modiff-text",children:"Rollback restores the exact backups for this journal. It refuses missing or independently changed files and has no force option."}),(0,Nt.jsxs)("section",{className:"grid gap-1.5",children:[(0,Nt.jsx)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Exact files to restore"}),(0,Nt.jsx)("ul",{className:"max-h-44 space-y-1 overflow-auto rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:s.targets.map(e=>(0,Nt.jsxs)("li",{className:"break-all font-mono text-xs text-modiff-text",children:[e.sourcePath," ",(0,Nt.jsxs)("span",{className:"text-modiff-subtle-text",children:["(",e.state,")"]})]},e.sourcePath))})]}),(0,Nt.jsx)(_,{label:(0,Nt.jsxs)("span",{children:["Type ",(0,Nt.jsx)("code",{className:"font-mono text-hf-yellow",children:V})]}),required:!0,error:i??void 0,children:(0,Nt.jsx)(P,{autoComplete:"off",spellCheck:!1,value:t,onChange:e=>o(e.currentTarget.value),"data-testid":"composite-migration-rollback-confirmation"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap justify-end gap-2 border-t border-modiff-border pt-3",children:[(0,Nt.jsx)(A,{disabled:e,onClick:n,children:"Cancel"}),(0,Nt.jsx)(A,{tone:"danger",loading:e,disabled:e||"ROLLBACK_BLOCK_V2_MIGRATION"!==t,onClick:a,"data-testid":"composite-migration-rollback",children:"Restore exact backups"})]})]})}function Rt(){let e=m(e=>e.workflowTabs.some(({dirty:e})=>e)),[t,a]=(0,B.useState)(null),[s,d]=(0,B.useState)([]),[u,p]=(0,B.useState)(!0),[h,f]=(0,B.useState)(null),[g,y]=(0,B.useState)(null),[b,I]=(0,B.useState)(!0),[C,w]=(0,B.useState)(null),[$,N]=(0,B.useState)(null),[j,k]=(0,B.useState)(null),[P,E]=(0,B.useState)(""),[R,M]=(0,B.useState)(null),[F,D]=(0,B.useState)([]),[O,T]=(0,B.useState)(null),[V,L]=(0,B.useState)(!1),[q,z]=(0,B.useState)(""),[K,G]=(0,B.useState)(!1),[J,Z]=(0,B.useState)(null),[U,W]=(0,B.useState)(""),[Y,Q]=(0,B.useState)(null),X=(0,B.useRef)(0),ee=(0,B.useRef)(0),te=(0,B.useRef)(0),ie=(0,B.useRef)(null),ne=(0,B.useRef)(!1),oe=(0,B.useRef)(null),ae=(0,B.useCallback)(async()=>{let e=++X.current;p(!0);try{let[t,i]=await Promise.all([He(oe.current??void 0),Pe()]);if(e!==X.current)return;a(t),d(i.migrations),f(null)}catch(t){e===X.current&&f(ke(t,"Could not inspect legacy composite migrations."))}finally{e===X.current&&p(!1)}},[]),se=(0,B.useCallback)(async()=>{let e=++ee.current;I(!0);try{let t=await nt();if(e!==ee.current)return;y(t),w(null)}catch(t){e===ee.current&&w(ke(t,"Could not inspect historical Block recovery evidence."))}finally{e===ee.current&&I(!1)}},[]);(0,B.useEffect)(()=>(ae(),se(),()=>{X.current+=1,ee.current+=1,te.current+=1,ie.current?.abort()}),[ae,se]);let re=async(e,t)=>{if(!ne.current){ne.current=!0,Q(e),N(null);try{await t()}catch(e){let t=ke(e,"Composite migration action failed.");N(t),f(t),v(t,{variant:"error"})}finally{ne.current=!1,Q(null)}}},ce=t?.summary.blockedCandidateCount??0;return(0,Nt.jsxs)("section",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3","data-testid":"composite-migration-card",children:[(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Nt.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(i,{size:15,className:"text-hf-yellow"}),(0,Nt.jsxs)("div",{children:[(0,Nt.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Legacy composite migration"}),(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Read-only preview and exact-backup recovery"})]})]}),(0,Nt.jsx)(x,{label:u&&!t?"Checking":ce?`${ce} blocked`:"Reviewed",tone:h?"error":ce?"warning":t?"success":"neutral"})]}),(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Previewing writes nothing. Apply and rollback are available only after reviewing exact paths and typing the required literal confirmation."}),h?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/5 p-2 text-xs text-modiff-red",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{className:"break-words",children:h})]}):null,t?(0,Nt.jsx)(H,{label:(0,Nt.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(r,{size:14,className:"text-hf-yellow"}),"Current read-only preview"]}),className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-preview-disclosure",children:(0,Nt.jsx)(Ht,{preview:t})}):u||h?null:(0,Nt.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No migration preview is available."}),(0,Nt.jsx)(H,{label:(0,Nt.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Nt.jsx)(r,{size:14,className:"text-hf-orange"}),"Historical definition recovery evidence"]}),className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"legacy-cluster-recovery-evidence-disclosure",children:(0,Nt.jsx)(kt,{audit:g,error:C,loading:b,onRefresh:()=>{se()}})}),(0,Nt.jsx)(H,{label:"Registered Block compiler supplement",className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-compiler-disclosure",children:(0,Nt.jsxs)("div",{className:"grid gap-3",children:[(0,Nt.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Generate exact compiler evidence from saved legacy Blocks, or paste externally produced evidence below. Generation and preview are read-only. The exact parsed supplement is retained only for this reviewed preview and resent unchanged on Apply."}),e?(0,Nt.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2 text-xs text-hf-orange","data-testid":"composite-migration-unsaved-warning",children:[(0,Nt.jsx)(o,{size:14,className:"mt-0.5 shrink-0"}),(0,Nt.jsx)("span",{children:"Generation reads saved backend workflow bytes only. Save dirty workflow tabs first if their current canvas changes should be included."})]}):null,(0,Nt.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,Nt.jsx)(A,{size:"compact",tone:"primary",icon:(0,Nt.jsx)(n,{size:14}),loading:"compiler-generate"===Y,disabled:!!Y,onClick:()=>{re("compiler-generate",async()=>{let e=++te.current,t=new AbortController;ie.current?.abort(),ie.current=t,k(null),D([]),T(null);try{let i=await He();if(t.signal.aborted||e!==te.current)return;let n=await $t({candidates:i.candidates,signal:t.signal,onProgress:i=>{!t.signal.aborted&&e===te.current&&T(i)}});if(t.signal.aborted||e!==te.current)return;let o=JSON.stringify(n.supplement,null,2);if(E(o),D(n.diagnostics),!n.conversionCount){oe.current=null,M(null),a(i);let e=n.candidateCount?`No legacy registered Block matched an exact current compiler route. Review ${n.diagnostics.length} blocker${1===n.diagnostics.length?"":"s"} below.`:"No legacy registered Block candidates are present in saved workflows.";return k(e),void v(e,{variant:"warning"})}let s=ge(n.supplement),r=await He(s);if(t.signal.aborted||e!==te.current)return;oe.current=s,M(s),a(r),f(null),v(`Generated and previewed ${n.conversionCount} exact registered-Block conversion${1===n.conversionCount?"":"s"}; no files were changed.`,{variant:"success"})}catch(i){if(t.signal.aborted||e!==te.current)return void v("Compiler supplement generation cancelled; no files were changed.",{variant:"info"});throw i}finally{ie.current===t&&(ie.current=null)}})},"data-testid":"composite-migration-compiler-generate",children:"Generate exact supplement"}),"compiler-generate"===Y?(0,Nt.jsx)(A,{size:"compact",tone:"secondary",onClick:()=>{te.current+=1,ie.current?.abort(),ie.current=null,T(null)},"data-testid":"composite-migration-compiler-cancel",children:"Cancel generation"}):null,O?(0,Nt.jsxs)("span",{className:"text-xs text-modiff-subtle-text","data-testid":"composite-migration-compiler-progress",children:["Reviewed ",O.completed,"/",O.total," saved Block candidates"]}):null]}),F.length?(0,Nt.jsxs)("section",{className:"grid gap-1.5 rounded-modiff-compact border border-hf-orange/40 bg-hf-orange/5 p-2","data-testid":"composite-migration-compiler-diagnostics",children:[(0,Nt.jsxs)("h4",{className:"text-xs font-bold uppercase text-hf-orange",children:["Candidates left unchanged (",F.length,")"]}),(0,Nt.jsx)("ul",{className:"max-h-40 space-y-2 overflow-auto",children:F.map((e,t)=>(0,Nt.jsxs)("li",{className:"text-xs",children:[(0,Nt.jsxs)("p",{className:"break-all font-mono text-modiff-text",children:[e.sourcePath,e.instanceId?` · ${e.instanceId}`:""]}),(0,Nt.jsxs)("p",{className:"text-modiff-subtle-text",children:[e.code,": ",e.message]})]},`${e.sourcePath}:${e.instanceId??""}:${e.code}:${t}`))})]}):null,(0,Nt.jsx)(_,{label:"Compiler supplement JSON",error:j??void 0,description:"Presentation children never become execution authority; the backend verifies pinned V2 definitions and every preservation receipt.",children:(0,Nt.jsx)(l,{value:P,onChange:e=>{E(e.target.value),k(null),D([]),T(null),oe.current&&(oe.current=null,M(null),a(null),ae())},rows:8,spellCheck:!1,disabled:!!Y,className:"font-mono text-xs",placeholder:'{"schemaVersion":1,"kind":"registered_cluster_v2_compiler_supplement","compilerOutputs":[]}',"data-testid":"composite-migration-compiler-json"})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)(A,{size:"compact",tone:"primary",loading:"compiler-preview"===Y,disabled:!!Y||!P.trim(),onClick:()=>{re("compiler-preview",async()=>{let e;try{e=ge(JSON.parse(P))}catch(e){let t=e instanceof Error?e.message:"Compiler supplement JSON is invalid.";throw k(t),Error(t)}let t=await He(e);oe.current=e,M(e),a(t),k(null),f(null),v("Exact registered-Block compiler supplement previewed; no files were changed.",{variant:"success"})})},"data-testid":"composite-migration-compiler-preview",children:"Preview exact supplement"}),(0,Nt.jsx)(A,{size:"compact",tone:"secondary",disabled:!!Y||!R,onClick:()=>{oe.current=null,M(null),E(""),k(null),D([]),T(null),ae()},"data-testid":"composite-migration-compiler-clear",children:"Return to default preview"})]})]})}),(0,Nt.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Nt.jsx)(A,{size:"compact",tone:"primary",disabled:u||!!Y||!t?.summary.hasChanges||!(!t.compilerSupplement||R),onClick:()=>{!t?.summary.hasChanges||t.compilerSupplement&&!R||(z(""),G(!1),N(null),L(!0))},"data-testid":"composite-migration-review",children:"Review migration"}),(0,Nt.jsx)(A,{size:"compact",tone:"secondary",icon:(0,Nt.jsx)(c,{size:14}),loading:u,disabled:u||!!Y,onClick:()=>{ae()},"data-testid":"composite-migration-refresh",children:"Refresh preview"})]}),(0,Nt.jsx)(H,{label:`Recovery journals (${s.length})`,className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",buttonClassName:"p-0",panelClassName:"mt-3","data-testid":"composite-migration-recovery-disclosure",children:(0,Nt.jsx)(At,{migrations:s,busyId:Y,onInspectRollback:e=>{re(e.migrationId,async()=>{let t=await Ae(e.migrationId);Z(t),W(""),N(null)})}})}),(0,Nt.jsx)(S,{open:V&&!!t,onClose:()=>{Y||L(!1)},title:"Review legacy composite migration",description:"Only the listed files can change. Exact backups are created before migration.",panelClassName:"max-w-4xl",dismissible:!Y,testId:"composite-migration-review-dialog",children:t?(0,Nt.jsx)(Pt,{preview:t,confirmation:q,allowBlockedCandidates:K,busy:"apply"===Y,error:$,onConfirmationChange:z,onAllowBlockedCandidatesChange:G,onCancel:()=>L(!1),onApply:()=>{!t||!le(t,q,K)||re("apply",async()=>{let e=await Ee(t,{confirmation:q,allowBlockedCandidates:K,...R?{compilerSupplement:R}:{}});v(e.idempotent?"This exact migration was already applied.":`Converted ${e.changedPaths?.length??0} reviewed files and created exact backups.`,{variant:"success"}),L(!1),z(""),G(!1),oe.current=null,M(null),E(""),D([]),T(null),await ae()})}}):null}),(0,Nt.jsx)(S,{open:!!J,onClose:()=>{Y||Z(null)},title:"Review exact-backup rollback",description:"Restore the exact backed-up files. Review conflicts before confirming rollback.",panelClassName:"max-w-3xl",dismissible:!Y,testId:"composite-migration-rollback-dialog",children:J?(0,Nt.jsx)(Et,{status:J,confirmation:U,busy:Y===J.migrationId,error:$,onConfirmationChange:W,onCancel:()=>Z(null),onRollback:()=>{!J||"ROLLBACK_BLOCK_V2_MIGRATION"!==U||re(J.migrationId,async()=>{let e=await Re(J.migrationId,U);v(e.idempotent?"This migration was already rolled back.":`Restored ${e.restoredPaths?.length??0} files from exact backups.`,{variant:"success"}),Z(null),W(""),await ae()})}}):null})]})}export{Rt as CompositeMigrationCard}; \ No newline at end of file diff --git a/web/assets/CustomExtensionsDialog.js b/web/assets/CustomExtensionsDialog.js index 635aa18..a756636 100644 --- a/web/assets/CustomExtensionsDialog.js +++ b/web/assets/CustomExtensionsDialog.js @@ -1 +1 @@ -import{cr as i}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{in as n}from"./studio-templates.js?v=cc046c26d6fe7aa4";import e from"./CustomExtensionsPanel.js?v=cc046c26d6fe7aa4";var o=i();function s({onClose:i,initialKind:s,initialView:t}){return(0,o.jsx)(n,{open:!0,onClose:i,title:"manage"===t?"Manage custom nodes":"Add custom node",panelClassName:"max-w-2xl",testId:"custom-extensions-dialog",children:(0,o.jsx)(e,{initialKind:s,initialView:t})})}export{s as default}; \ No newline at end of file +import{cr as i}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{an as n}from"./studio-templates.js?v=ca6b74e6a02eedb3";import e from"./CustomExtensionsPanel.js?v=ca6b74e6a02eedb3";var o=i();function s({onClose:i,initialKind:s,initialView:t}){return(0,o.jsx)(n,{open:!0,onClose:i,title:"manage"===t?"Manage custom nodes":"Add custom node",panelClassName:"max-w-2xl",testId:"custom-extensions-dialog",children:(0,o.jsx)(e,{initialKind:s,initialView:t})})}export{s as default}; \ No newline at end of file diff --git a/web/assets/CustomExtensionsPanel.js b/web/assets/CustomExtensionsPanel.js index 5d25524..9c080ab 100644 --- a/web/assets/CustomExtensionsPanel.js +++ b/web/assets/CustomExtensionsPanel.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Wt as a,Xt as s,cr as l,dr as t,hn as d}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Eo as n,Si as o,dn as i,do as r,fn as c,fo as u,mn as m,pn as x,po as h,rn as p,sn as f}from"./studio-templates.js?v=cc046c26d6fe7aa4";var b=e(t(),1),g=l(),j=[{value:"local",label:"Local",Icon:s},{value:"hub",label:"Hugging Face",Icon:d},{value:"git",label:"Git",Icon:a}];function y({initialKind:e,busy:a,onAdd:s}){let[l,t]=(0,b.useState)(e),[d,u]=(0,b.useState)(""),[f,y]=(0,b.useState)(""),[v,N]=(0,b.useState)(""),[C,k]=(0,b.useState)(null),w=o(e=>e.customModuleRoot),S=(0,b.useRef)(null),R=f.trim()||r(d);return(0,g.jsxs)("div",{className:"grid gap-4","data-testid":"extension-source-form",children:[(0,g.jsx)("div",{className:"grid grid-cols-3 gap-2",role:"group","aria-label":"Source type",children:j.map(({value:e,label:s,Icon:d})=>(0,g.jsxs)(p,{disabled:a,"aria-pressed":l===e,className:"aria-pressed:border-hf-yellow aria-pressed:bg-hf-yellow/10 aria-pressed:text-hf-yellow",icon:(0,g.jsx)(d,{size:16}),onClick:()=>{t(e),u(""),N(""),k(null)},children:[s,l===e?" ✓":""]},e))}),"local"===l?(0,g.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,g.jsx)("p",{className:"text-sm",children:"Drop a Python node onto the canvas, or place a node file/package in your custom folder."}),(0,g.jsx)("p",{className:"break-all font-mono text-xs text-modiff-subtle-text",children:w??"custom/ on the backend"}),(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"New sources appear automatically in Custom nodes. Choose Load to enable them."}),(0,g.jsx)(x,{ref:S,accept:".py","aria-label":"Choose Python node file",className:"hidden",disabled:a,onChange:e=>{let a=e.target.files?.[0];e.target.value="",a&&h(a).then(s).catch(e=>k(n(e,"Node import failed.")))}}),(0,g.jsx)(p,{disabled:a,onClick:()=>S.current?.click(),children:"Choose Python file"})]}):(0,g.jsx)(c,{label:"hub"===l?"Hugging Face repository":"Git repository URL",children:(0,g.jsx)(m,{"aria-label":"Extension source",value:d,disabled:a,placeholder:"hub"===l?"owner/repository":"https://host/owner/repository.git",onChange:e=>u(e.target.value)})}),(0,g.jsxs)(i,{label:"Advanced options",panelClassName:"grid gap-3 pt-2",children:["local"===l?(0,g.jsx)(c,{label:"Copy an existing backend folder or Python file",children:(0,g.jsx)(m,{"aria-label":"Extension source",value:d,disabled:a,onChange:e=>u(e.target.value)})}):(0,g.jsx)(c,{label:"Branch, tag or commit (optional)",children:(0,g.jsx)(m,{"aria-label":"Extension revision",value:v,disabled:a,placeholder:"Repository default",onChange:e=>N(e.target.value)})}),(0,g.jsx)(c,{label:"Package name (optional)",children:(0,g.jsx)(m,{"aria-label":"Extension module name",value:f,placeholder:d?R:"Derived from source",disabled:a,onChange:e=>y(e.target.value)})})]}),C?(0,g.jsxs)("p",{role:"alert",className:"text-sm text-modiff-red",children:["Node import failed",(0,g.jsx)("br",{}),C]}):null,(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Only add code you trust. Python nodes run with backend permissions. Dependencies are never installed automatically."}),(0,g.jsx)(p,{tone:"primary",fullWidth:!0,loading:a,disabled:a||!d.trim()||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(R),onClick:()=>{s({kind:l,source:d.trim(),name:R,...v.trim()?{revision:v.trim()}:{}})},children:"Add node"})]})}function v({initialKind:e="local",initialView:a="add"}){let s=o(e=>e.customModules),l=o(e=>e.fetchCustomModules),t=o(e=>e.addCustomModule),d=o(e=>e.setCustomModuleEnabled),[r,c]=(0,b.useState)(a),[m,x]=(0,b.useState)(!1),[h,j]=(0,b.useState)(null),[v,N]=(0,b.useState)(null),C=(0,b.useRef)(!1),k=(0,b.useRef)(!0);async function w(e,a){if(!C.current){C.current=!0,x(!0),j(null),N(null);try{await e(),k.current&&N(a)}catch(e){k.current&&j(n(e,"Could not change this extension."))}finally{C.current=!1,k.current&&x(!1)}}}return(0,b.useEffect)(()=>(k.current=!0,l(),()=>{k.current=!1}),[l]),(0,g.jsxs)("section",{className:"grid gap-4","aria-label":"Custom nodes","data-testid":"custom-extensions-panel",children:[(0,g.jsxs)("div",{className:"flex gap-2",role:"group","aria-label":"Custom node actions",children:[(0,g.jsx)(p,{className:"aria-pressed:border-hf-yellow aria-pressed:text-hf-yellow",disabled:m,"aria-pressed":"add"===r,onClick:()=>c("add"),children:"Add node"}),(0,g.jsx)(p,{className:"aria-pressed:border-hf-yellow aria-pressed:text-hf-yellow",disabled:m,"aria-pressed":"manage"===r,onClick:()=>{c("manage"),l()},children:"Manage nodes"})]}),"add"===r?(0,g.jsx)(y,{initialKind:e,busy:m,onAdd:e=>w(()=>t(e),"Added and enabled. Find your nodes in Custom nodes or connection search.")}):(0,g.jsxs)("div",{className:"grid gap-2",children:[(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Load or reload code you trust. Wait for running and queued work to finish before changing code."}),(0,g.jsx)(p,{disabled:m,onClick:()=>{l()},children:"Refresh sources"}),0===s.length?(0,g.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"No custom nodes yet."}):s.map(e=>(0,g.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border p-3",children:[(0,g.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,g.jsx)("span",{className:"font-semibold",children:e.name}),(0,g.jsx)(f,{tone:e.enabled?"success":"warning",children:"disabled"!==e.status||e.approvedHash?e.status:"Not loaded"})]}),e.diagnostic?(0,g.jsx)("p",{className:"text-xs text-modiff-red",children:e.diagnostic}):null,(0,g.jsxs)("div",{className:"flex gap-2",children:[(0,g.jsx)(p,{disabled:m||!e.codeHash,onClick:()=>{w(async()=>{let a=await u(e.name);await d(e.name,!0,a.codeHash??void 0)},e.name+" loaded. Its nodes are available in the library.")},children:e.enabled||"changed"===e.status?"Reload":"Load"}),e.canDisable?(0,g.jsx)(p,{disabled:m,onClick:()=>{w(()=>d(e.name,!1),"Disabled. Files are preserved; import side effects may require a backend restart.")},children:"Disable"}):null]}),(0,g.jsxs)(i,{label:"Source and dependencies",panelClassName:"grid gap-1 text-xs text-modiff-subtle-text",children:[(0,g.jsxs)("p",{className:"break-all",children:["Edit source: ",e.path]}),(0,g.jsx)("p",{className:"break-all",children:e.revision??e.codeHash}),(0,g.jsxs)("p",{children:["Memory declaration: ",e.runtimeRole??"manual"]}),e.dependencies.map(e=>(0,g.jsxs)("p",{children:[e.requirement," · ",e.status," · ",e.installed??"not installed"]},e.requirement))]})]},e.name))]}),h?(0,g.jsxs)("p",{role:"alert",className:"text-sm text-modiff-red",children:["add"===r?"Node import failed":"Could not update node",(0,g.jsx)("br",{}),h]}):null,m||v?(0,g.jsx)("p",{role:"status",className:"text-sm text-modiff-subtle-text",children:m?"Resolving source and loading code…":v}):null]})}export{v as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Wt as a,Xt as s,cr as l,dr as t,hn as d}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Oo as n,cn as o,fn as i,hn as r,ho as c,in as u,mn as m,mo as x,pn as h,po as p,wi as f}from"./studio-templates.js?v=ca6b74e6a02eedb3";var b=e(t(),1),g=l(),j=[{value:"local",label:"Local",Icon:s},{value:"hub",label:"Hugging Face",Icon:d},{value:"git",label:"Git",Icon:a}];function y({initialKind:e,busy:a,onAdd:s}){let[l,t]=(0,b.useState)(e),[d,o]=(0,b.useState)(""),[x,y]=(0,b.useState)(""),[v,N]=(0,b.useState)(""),[C,k]=(0,b.useState)(null),w=f(e=>e.customModuleRoot),S=(0,b.useRef)(null),R=x.trim()||p(d);return(0,g.jsxs)("div",{className:"grid gap-4","data-testid":"extension-source-form",children:[(0,g.jsx)("div",{className:"grid grid-cols-3 gap-2",role:"group","aria-label":"Source type",children:j.map(({value:e,label:s,Icon:d})=>(0,g.jsxs)(u,{disabled:a,"aria-pressed":l===e,className:"aria-pressed:border-hf-yellow aria-pressed:bg-hf-yellow/10 aria-pressed:text-hf-yellow",icon:(0,g.jsx)(d,{size:16}),onClick:()=>{t(e),o(""),N(""),k(null)},children:[s,l===e?" ✓":""]},e))}),"local"===l?(0,g.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,g.jsx)("p",{className:"text-sm",children:"Drop a Python node onto the canvas, or place a node file/package in your custom folder."}),(0,g.jsx)("p",{className:"break-all font-mono text-xs text-modiff-subtle-text",children:w??"custom/ on the backend"}),(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"New sources appear automatically in Custom nodes. Choose Load to enable them."}),(0,g.jsx)(m,{ref:S,accept:".py","aria-label":"Choose Python node file",className:"hidden",disabled:a,onChange:e=>{let a=e.target.files?.[0];e.target.value="",a&&c(a).then(s).catch(e=>k(n(e,"Node import failed.")))}}),(0,g.jsx)(u,{disabled:a,onClick:()=>S.current?.click(),children:"Choose Python file"})]}):(0,g.jsx)(h,{label:"hub"===l?"Hugging Face repository":"Git repository URL",children:(0,g.jsx)(r,{"aria-label":"Extension source",value:d,disabled:a,placeholder:"hub"===l?"owner/repository":"https://host/owner/repository.git",onChange:e=>o(e.target.value)})}),(0,g.jsxs)(i,{label:"Advanced options",panelClassName:"grid gap-3 pt-2",children:["local"===l?(0,g.jsx)(h,{label:"Copy an existing backend folder or Python file",children:(0,g.jsx)(r,{"aria-label":"Extension source",value:d,disabled:a,onChange:e=>o(e.target.value)})}):(0,g.jsx)(h,{label:"Branch, tag or commit (optional)",children:(0,g.jsx)(r,{"aria-label":"Extension revision",value:v,disabled:a,placeholder:"Repository default",onChange:e=>N(e.target.value)})}),(0,g.jsx)(h,{label:"Package name (optional)",children:(0,g.jsx)(r,{"aria-label":"Extension module name",value:x,placeholder:d?R:"Derived from source",disabled:a,onChange:e=>y(e.target.value)})})]}),C?(0,g.jsxs)("p",{role:"alert",className:"text-sm text-modiff-red",children:["Node import failed",(0,g.jsx)("br",{}),C]}):null,(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Only add code you trust. Python nodes run with backend permissions. Dependencies are never installed automatically."}),(0,g.jsx)(u,{tone:"primary",fullWidth:!0,loading:a,disabled:a||!d.trim()||!/^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(R),onClick:()=>{s({kind:l,source:d.trim(),name:R,...v.trim()?{revision:v.trim()}:{}})},children:"Add node"})]})}function v({initialKind:e="local",initialView:a="add"}){let s=f(e=>e.customModules),l=f(e=>e.fetchCustomModules),t=f(e=>e.addCustomModule),d=f(e=>e.setCustomModuleEnabled),[r,c]=(0,b.useState)(a),[m,h]=(0,b.useState)(!1),[p,j]=(0,b.useState)(null),[v,N]=(0,b.useState)(null),C=(0,b.useRef)(!1),k=(0,b.useRef)(!0);async function w(e,a){if(!C.current){C.current=!0,h(!0),j(null),N(null);try{await e(),k.current&&N(a)}catch(e){k.current&&j(n(e,"Could not change this extension."))}finally{C.current=!1,k.current&&h(!1)}}}return(0,b.useEffect)(()=>(k.current=!0,l(),()=>{k.current=!1}),[l]),(0,g.jsxs)("section",{className:"grid gap-4","aria-label":"Custom nodes","data-testid":"custom-extensions-panel",children:[(0,g.jsxs)("div",{className:"flex gap-2",role:"group","aria-label":"Custom node actions",children:[(0,g.jsx)(u,{className:"aria-pressed:border-hf-yellow aria-pressed:text-hf-yellow",disabled:m,"aria-pressed":"add"===r,onClick:()=>c("add"),children:"Add node"}),(0,g.jsx)(u,{className:"aria-pressed:border-hf-yellow aria-pressed:text-hf-yellow",disabled:m,"aria-pressed":"manage"===r,onClick:()=>{c("manage"),l()},children:"Manage nodes"})]}),"add"===r?(0,g.jsx)(y,{initialKind:e,busy:m,onAdd:e=>w(()=>t(e),"Added and enabled. Find your nodes in Custom nodes or connection search.")}):(0,g.jsxs)("div",{className:"grid gap-2",children:[(0,g.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Load or reload code you trust. Wait for running and queued work to finish before changing code."}),(0,g.jsx)(u,{disabled:m,onClick:()=>{l()},children:"Refresh sources"}),0===s.length?(0,g.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"No custom nodes yet."}):s.map(e=>(0,g.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border p-3",children:[(0,g.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,g.jsx)("span",{className:"font-semibold",children:e.name}),(0,g.jsx)(o,{tone:e.enabled?"success":"warning",children:"disabled"!==e.status||e.approvedHash?e.status:"Not loaded"})]}),e.diagnostic?(0,g.jsx)("p",{className:"text-xs text-modiff-red",children:e.diagnostic}):null,(0,g.jsxs)("div",{className:"flex gap-2",children:[(0,g.jsx)(u,{disabled:m||!e.codeHash,onClick:()=>{w(async()=>{let a=await x(e.name);await d(e.name,!0,a.codeHash??void 0)},e.name+" loaded. Its nodes are available in the library.")},children:e.enabled||"changed"===e.status?"Reload":"Load"}),e.canDisable?(0,g.jsx)(u,{disabled:m,onClick:()=>{w(()=>d(e.name,!1),"Disabled. Files are preserved; import side effects may require a backend restart.")},children:"Disable"}):null]}),(0,g.jsxs)(i,{label:"Source and dependencies",panelClassName:"grid gap-1 text-xs text-modiff-subtle-text",children:[(0,g.jsxs)("p",{className:"break-all",children:["Edit source: ",e.path]}),(0,g.jsx)("p",{className:"break-all",children:e.revision??e.codeHash}),(0,g.jsxs)("p",{children:["Memory declaration: ",e.runtimeRole??"manual"]}),e.dependencies.map(e=>(0,g.jsxs)("p",{children:[e.requirement," · ",e.status," · ",e.installed??"not installed"]},e.requirement))]})]},e.name))]}),p?(0,g.jsxs)("p",{role:"alert",className:"text-sm text-modiff-red",children:["add"===r?"Node import failed":"Could not update node",(0,g.jsx)("br",{}),p]}):null,m||v?(0,g.jsx)("p",{role:"status",className:"text-sm text-modiff-subtle-text",children:m?"Resolving source and loading code…":v}):null]})}export{v as default}; \ No newline at end of file diff --git a/web/assets/DeveloperWorkflowLauncher.js b/web/assets/DeveloperWorkflowLauncher.js index 3cfee39..d131377 100644 --- a/web/assets/DeveloperWorkflowLauncher.js +++ b/web/assets/DeveloperWorkflowLauncher.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,dr as t}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$ as s,As as o,Bo as i,Ci as l,Ds as r,Ei as n,Eo as d,Es as c,Js as u,Mo as p,Os as m,Sa as f,Si as g,Ti as h,Vr as k,Ys as w,cn as b,in as x,ji as y,js as j,q as C,rn as S,sc as v,yn as N}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as A}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{n as I}from"./operationStarterRequest.js?v=cc046c26d6fe7aa4";import{t as M}from"./taskModelPreferences.js?v=cc046c26d6fe7aa4";import{t as T}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";var E=e(t(),1),L=[{type:"image",key:"modules.Image.Preview",input:"image"},{type:"audio",key:"modules.Audio.Preview",input:"audio"},{type:"video",key:"modules.Video.ExportAsset",input:"video"},{type:"video_asset",key:"modules.Video.ExportAsset",input:"video"}];function $(e,a){let t=T(e,{x:80,y:120}),s=[],o=[...t.nodes];if(["Image","Audio"].includes(m(e.task))){let i=new Map;for(let l of e.requiredInputs){let e=o.find(e=>e.data.operationAuthoring.operation.operationId===l.operationId),r=e?.data.operationAuthoring.operation.ports.find(e=>"input"===e.direction&&e.name===l.field),n=r?.types.includes("image")?"image":r?.types.includes("audio")?"audio":null;if(!e||!r||!n||r.hidden||t.edges.some(a=>a.target===e.id&&a.targetHandle===r.name))continue;let d=e.data.params[r.name],c="image"===n?"modules.Image.Load":"modules.Audio.Load",u=a[c]?.params[n];if(!d||d.hidden||"input"!==d.display&&!d.isInput||!u||u.hidden||"output"!==u.display||!w(u.type,d.type)){s.push(`Connect a compatible source for ${e.data.label} · ${d?.label||r.name}. The media loader is unavailable or incompatible.`);continue}let p=`${n}:${r.semanticName}`,m=i.get(p);m||(m=C(c,a,{x:80,y:800+600*i.size}),r.semanticName.includes("mask")?m.data.label="Load Mask":["image","images","audio","source_audio"].includes(r.semanticName)||(m.data.label=`Load ${String(d.label||r.semanticName.replace(/_/gu," "))}`),t.nodes.push(m),i.set(p,m)),t.edges.push({id:`edge-${v()}`,source:m.id,sourceHandle:n,target:e.id,targetHandle:r.name,type:"default"})}}let l=0;for(let e of o)for(let s of e.data.operationAuthoring.operation.ports){if("output"!==s.direction||s.hidden||"media"!==s.semantics?.kind||t.edges.some(a=>a.source===e.id&&a.sourceHandle===s.name))continue;let i=u(s.types),r=L.find(e=>i.includes(e.type));if(!r)continue;let n=a[r.key]?.params[r.input];if(!n||n.hidden||"input"!==n.display&&!n.isInput||!w(s.types,n.type))continue;let d=C(r.key,a,{x:80+420*o.length,y:120+340*l});t.nodes.push(d),t.edges.push({id:`edge-${v()}`,source:e.id,sourceHandle:s.name,target:d.id,targetHandle:r.input,type:"default"}),l++}return l||s.push("No compatible output node is registered. Connect a Preview, Save or Export node before running."),{graph:i(t),notices:s}}var O=a(),W=(0,E.lazy)(()=>l(()=>import(`./CustomExtensionsDialog.js?v=cc046c26d6fe7aa4`),[]));function _({embedded:e=!1}){let a=g(e=>e.pipelineSupport),t=g(e=>e.studioModelCapabilities),i=g(e=>e.workflowModelDescriptors),l=g(e=>e.operationContracts),u=g(e=>e.nodesRegistry),m=g(e=>e.hfCache),w=g(e=>e.localModels),C=g(e=>e.modelCacheDiagnostics),v=g(e=>e.discoveryRequests.capabilities),T=y(e=>e.activeWorkflowTabId),L=(0,E.useMemo)(()=>o(a,t,m,w,C,i),[a,t,m,w,C,i]),_=(0,E.useMemo)(()=>r(L),[L]),[H,P]=(0,E.useState)("Image"),[D,R]=(0,E.useState)(""),[V,q]=(0,E.useState)(!1),[J,B]=(0,E.useState)(null),[z,F]=(0,E.useState)(""),[G,K]=(0,E.useState)(null),Y=(0,E.useRef)(null);(0,E.useEffect)(()=>()=>{Y.current?.abort()},[T]);let Q=()=>{Y.current?.abort(),s({revealWorkspace:!1})};async function U(a){if(Y.current)return;let t=new AbortController;Y.current=t;let o=n(),i=JSON.stringify(k.getState().toObject());F(a),B(null);try{let{starter:r,unbound:d,message:c}=await I(a,l,{signal:t.signal,preferredProfileId:M(a),resourceMode:y.getState().form.resourceMode});if(t.signal.aborted)return;if(h(o,{includeForm:!1}),!e&&k.getState().nodes.length||JSON.stringify(k.getState().toObject())!==i)throw Error("The canvas changed. Start a new workflow before choosing a task.");let m=$(r,u);e?(y.getState().createWorkflowTab(j(a)),A(m.graph,n(),JSON.stringify(k.getState().toObject()),"Create workflow")):A(m.graph,o,i,"Create workflow"),y.getState().detachManagedGraph(),s();let f=y.getState().activeWorkflowTabId;f&&y.getState().renameWorkflowTab(f,j(a)),y.getState().saveActiveWorkflowTab(!0),d&&p(c,{variant:"info",autoHideDuration:8e3})}catch(e){t.signal.aborted||B(d(e,"Could not create this workflow."))}finally{Y.current===t&&(Y.current=null,F(""))}}let X=_.filter(e=>("All"===H||e.category===H)&&(!V||e.downloaded)&&`${e.label} ${e.task} ${e.description}`.toLowerCase().includes(D.trim().toLowerCase()));if(G)return(0,O.jsx)(E.Suspense,{fallback:null,children:(0,O.jsx)(W,{initialKind:G,onClose:()=>K(null)})});let Z=(0,O.jsxs)("div",{className:"space-y-4",children:[(0,O.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"Choose a task to create its connected nodes. Change the model and parameters on the canvas. Models load only when you run."}),e?null:(0,O.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,O.jsx)(S,{onClick:()=>{e&&y.getState().createWorkflowTab(""),s()},disabled:!!z,"data-testid":"launcher-mode-advanced_workflow",children:"Empty workflow"}),(0,O.jsx)(S,{onClick:()=>{Q(),f.getState().setWorkflowLibraryView("saved"),f.getState().setLeftPanelTabIndex(4),f.getState().setLeftPanelOpen(!0)},disabled:!!z,children:"Open workflow"}),(0,O.jsx)(S,{onClick:()=>{Q(),f.getState().setTemplateBrowserOpen(!0)},disabled:!!z,children:"Browse templates"})]}),(0,O.jsx)(N,{"aria-label":"Search workflow tasks",placeholder:"Search workflows and actions",value:D,onChange:e=>R(e.target.value),onClear:()=>R("")}),(0,O.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":"Workflow categories",children:["All",...c].map(e=>(0,O.jsx)(S,{tone:H===e?"primary":"secondary","aria-pressed":H===e,onClick:()=>P(e),children:e},e))}),(0,O.jsx)(b,{checked:V,onCheckedChange:q,label:"With downloaded models"}),J?(0,O.jsx)("p",{role:"alert",children:J}):null,z?(0,O.jsxs)("p",{role:"status",children:["Creating ",j(z).toLowerCase()," workflow…"]}):null,(0,O.jsx)("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:X.map(e=>(0,O.jsx)(S,{tone:"secondary",align:"left",className:"h-auto min-h-24 p-4",disabled:!!z,onClick:()=>{U(e.task)},"data-testid":`workflow-task-${e.task}`,children:(0,O.jsxs)("span",{className:"block",children:[(0,O.jsx)("span",{className:"block font-semibold",children:e.label}),(0,O.jsx)("span",{className:"mt-1 block text-sm font-normal text-modiff-subtle-text",children:e.description})]})},e.task))}),X.length?null:(0,O.jsx)("p",{role:"status",children:"loading"===v.status?"Loading workflows…":_.length?"No workflows match these filters.":"No workflow capabilities are available. Check the backend connection."}),!_.length||v.error?(0,O.jsx)(S,{onClick:()=>{g.getState().fetchStudioModelCapabilities()},children:"Retry capabilities"}):null,(0,O.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border-t border-modiff-border pt-3",children:[(0,O.jsx)("span",{className:"text-sm text-modiff-subtle-text",children:"Custom nodes"}),(0,O.jsx)(S,{disabled:!!z,onClick:()=>K("hub"),children:"Add from Hugging Face"}),(0,O.jsx)(S,{disabled:!!z,onClick:()=>K("local"),children:"Add local source"})]})]});return e?(0,O.jsx)("div",{className:"p-3","data-testid":"task-browser",children:Z}):(0,O.jsx)(x,{open:!0,onClose:Q,title:"Workflows",testId:"task-launcher",panelClassName:"max-w-5xl",bodyClassName:"max-h-[78vh]",children:Z})}export{_ as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,dr as t}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{As as s,Di as o,Hr as l,Ni as i,Ns as r,Oi as n,Oo as d,Po as c,Ps as u,Qs as p,Ti as m,Uo as f,Zs as g,an as h,bn as w,et as k,in as b,js as x,ks as y,ln as j,q as C,uc as S,wa as v,wi as N}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as A}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{n as I}from"./operationStarterRequest.js?v=ca6b74e6a02eedb3";import{t as M}from"./taskModelPreferences.js?v=ca6b74e6a02eedb3";import{t as T}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";var L=e(t(),1),O=[{type:"image",key:"modules.Image.Preview",input:"image"},{type:"audio",key:"modules.Audio.Preview",input:"audio"},{type:"video",key:"modules.Video.ExportAsset",input:"video"},{type:"video_asset",key:"modules.Video.ExportAsset",input:"video"}];function W(e,a){let t=T(e,{x:80,y:120}),s=[],o=[...t.nodes];if(["Image","Audio"].includes(x(e.task))){let l=new Map;for(let i of e.requiredInputs){let e=o.find(e=>e.data.operationAuthoring.operation.operationId===i.operationId),r=e?.data.operationAuthoring.operation.ports.find(e=>"input"===e.direction&&e.name===i.field),n=r?.types.includes("image")?"image":r?.types.includes("audio")?"audio":null;if(!e||!r||!n||r.hidden||t.edges.some(a=>a.target===e.id&&a.targetHandle===r.name))continue;let d=e.data.params[r.name],c="image"===n?"modules.Image.Load":"modules.Audio.Load",u=a[c]?.params[n];if(!d||d.hidden||"input"!==d.display&&!d.isInput||!u||u.hidden||"output"!==u.display||!p(u.type,d.type)){s.push(`Connect a compatible source for ${e.data.label} · ${d?.label||r.name}. The media loader is unavailable or incompatible.`);continue}let m=`${n}:${r.semanticName}`,f=l.get(m);f||(f=C(c,a,{x:80,y:800+600*l.size}),r.semanticName.includes("mask")?f.data.label="Load Mask":["image","images","audio","source_audio"].includes(r.semanticName)||(f.data.label=`Load ${String(d.label||r.semanticName.replace(/_/gu," "))}`),t.nodes.push(f),l.set(m,f)),t.edges.push({id:`edge-${S()}`,source:f.id,sourceHandle:n,target:e.id,targetHandle:r.name,type:"default"})}}let l=0;for(let e of o)for(let s of e.data.operationAuthoring.operation.ports){if("output"!==s.direction||s.hidden||"media"!==s.semantics?.kind||t.edges.some(a=>a.source===e.id&&a.sourceHandle===s.name))continue;let i=g(s.types),r=O.find(e=>i.includes(e.type));if(!r)continue;let n=a[r.key]?.params[r.input];if(!n||n.hidden||"input"!==n.display&&!n.isInput||!p(s.types,n.type))continue;let d=C(r.key,a,{x:80+420*o.length,y:120+340*l});t.nodes.push(d),t.edges.push({id:`edge-${S()}`,source:e.id,sourceHandle:s.name,target:d.id,targetHandle:r.input,type:"default"}),l++}return l||s.push("No compatible output node is registered. Connect a Preview, Save or Export node before running."),{graph:f(t),notices:s}}var $=a(),P=(0,L.lazy)(()=>m(()=>import(`./CustomExtensionsDialog.js?v=ca6b74e6a02eedb3`),[]));function E({embedded:e=!1}){let a=N(e=>e.pipelineSupport),t=N(e=>e.studioModelCapabilities),p=N(e=>e.workflowModelDescriptors),m=N(e=>e.operationContracts),f=N(e=>e.nodesRegistry),g=N(e=>e.hfCache),x=N(e=>e.localModels),C=N(e=>e.modelCacheDiagnostics),S=N(e=>e.discoveryRequests.capabilities),T=i(e=>e.activeWorkflowTabId),O=(0,L.useMemo)(()=>r(a,t,g,x,C,p),[a,t,g,x,C,p]),E=(0,L.useMemo)(()=>s(O),[O]),[H,_]=(0,L.useState)("Image"),[D,R]=(0,L.useState)(""),[q,V]=(0,L.useState)(!1),[J,z]=(0,L.useState)(null),[B,F]=(0,L.useState)(""),[G,K]=(0,L.useState)(null),Q=(0,L.useRef)(null);(0,L.useEffect)(()=>()=>{Q.current?.abort()},[T]);let U=()=>{Q.current?.abort(),k({revealWorkspace:!1})};async function Z(a){if(Q.current)return;let t=new AbortController;Q.current=t;let s=n(),r=JSON.stringify(l.getState().toObject());F(a),z(null);try{let{starter:d,unbound:p,message:g}=await I(a,m,{signal:t.signal,preferredProfileId:M(a),resourceMode:i.getState().form.resourceMode});if(t.signal.aborted)return;if(o(s,{includeForm:!1}),!e&&l.getState().nodes.length||JSON.stringify(l.getState().toObject())!==r)throw Error("The canvas changed. Start a new workflow before choosing a task.");let h=W(d,f);e?(i.getState().createWorkflowTab(u(a)),A(h.graph,n(),JSON.stringify(l.getState().toObject()),"Create workflow")):A(h.graph,s,r,"Create workflow"),i.getState().detachManagedGraph(),k();let w=i.getState().activeWorkflowTabId;w&&i.getState().renameWorkflowTab(w,u(a)),i.getState().saveActiveWorkflowTab(!0),p&&c(g,{variant:"info",autoHideDuration:8e3})}catch(e){t.signal.aborted||z(d(e,"Could not create this workflow."))}finally{Q.current===t&&(Q.current=null,F(""))}}let X=E.filter(e=>("All"===H||e.category===H)&&(!q||e.downloaded)&&`${e.label} ${e.task} ${e.description}`.toLowerCase().includes(D.trim().toLowerCase()));if(G)return(0,$.jsx)(L.Suspense,{fallback:null,children:(0,$.jsx)(P,{initialKind:G,onClose:()=>K(null)})});let Y=(0,$.jsxs)("div",{className:"space-y-4",children:[(0,$.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"Choose a task to create its connected nodes. Change the model and parameters on the canvas. Models load only when you run."}),e?null:(0,$.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,$.jsx)(b,{onClick:()=>{e&&i.getState().createWorkflowTab(""),k()},disabled:!!B,"data-testid":"launcher-mode-advanced_workflow",children:"Empty workflow"}),(0,$.jsx)(b,{onClick:()=>{U(),v.getState().setWorkflowLibraryView("saved"),v.getState().setLeftPanelTabIndex(4),v.getState().setLeftPanelOpen(!0)},disabled:!!B,children:"Open workflow"}),(0,$.jsx)(b,{onClick:()=>{U(),v.getState().setTemplateBrowserOpen(!0)},disabled:!!B,children:"Browse templates"})]}),(0,$.jsx)(w,{"aria-label":"Search workflow tasks",placeholder:"Search workflows and actions",value:D,onChange:e=>R(e.target.value),onClear:()=>R("")}),(0,$.jsx)("div",{className:"flex flex-wrap gap-2","aria-label":"Workflow categories",children:["All",...y].map(e=>(0,$.jsx)(b,{tone:H===e?"primary":"secondary","aria-pressed":H===e,onClick:()=>_(e),children:e},e))}),(0,$.jsx)(j,{checked:q,onCheckedChange:V,label:"With downloaded models"}),J?(0,$.jsx)("p",{role:"alert",children:J}):null,B?(0,$.jsxs)("p",{role:"status",children:["Creating ",u(B).toLowerCase()," workflow…"]}):null,(0,$.jsx)("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:X.map(e=>(0,$.jsx)(b,{tone:"secondary",align:"left",className:"h-auto min-h-24 p-4",disabled:!!B,onClick:()=>{Z(e.task)},"data-testid":`workflow-task-${e.task}`,children:(0,$.jsxs)("span",{className:"block",children:[(0,$.jsx)("span",{className:"block font-semibold",children:e.label}),(0,$.jsx)("span",{className:"mt-1 block text-sm font-normal text-modiff-subtle-text",children:e.description})]})},e.task))}),X.length?null:(0,$.jsx)("p",{role:"status",children:"loading"===S.status?"Loading workflows…":E.length?"No workflows match these filters.":"No workflow capabilities are available. Check the backend connection."}),!E.length||S.error?(0,$.jsx)(b,{onClick:()=>{N.getState().fetchStudioModelCapabilities()},children:"Retry capabilities"}):null,(0,$.jsxs)("div",{className:"flex flex-wrap items-center gap-2 border-t border-modiff-border pt-3",children:[(0,$.jsx)("span",{className:"text-sm text-modiff-subtle-text",children:"Custom nodes"}),(0,$.jsx)(b,{disabled:!!B,onClick:()=>K("hub"),children:"Add from Hugging Face"}),(0,$.jsx)(b,{disabled:!!B,onClick:()=>K("local"),children:"Add local source"})]})]});return e?(0,$.jsx)("div",{className:"p-3","data-testid":"task-browser",children:Y}):(0,$.jsx)(h,{open:!0,onClose:U,title:"Workflows",testId:"task-launcher",panelClassName:"max-w-5xl",bodyClassName:"max-h-[78vh]",children:Y})}export{E as default}; \ No newline at end of file diff --git a/web/assets/EditorPanel.js b/web/assets/EditorPanel.js index a1d3fe8..161e668 100644 --- a/web/assets/EditorPanel.js +++ b/web/assets/EditorPanel.js @@ -1 +1 @@ -import{E as e,cr as r}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{an as s}from"./studio-templates.js?v=cc046c26d6fe7aa4";var l=r();function o({title:r,children:o,footer:t,onClose:i,testId:a}){return(0,l.jsxs)("section",{className:"flex h-full min-h-0 flex-col","aria-label":r,"data-testid":a,children:[(0,l.jsxs)("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-modiff-border px-3 py-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-modiff-text",children:r}),(0,l.jsx)(s,{label:"Close Block editor",onClick:i,children:(0,l.jsx)(e,{size:16})})]}),(0,l.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:o}),t?(0,l.jsx)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t border-modiff-border bg-modiff-panel p-3",children:t}):null]})}export{o as t}; \ No newline at end of file +import{E as e,cr as r}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{on as s}from"./studio-templates.js?v=ca6b74e6a02eedb3";var l=r();function o({title:r,children:o,footer:t,onClose:i,testId:a}){return(0,l.jsxs)("section",{className:"flex h-full min-h-0 flex-col","aria-label":r,"data-testid":a,children:[(0,l.jsxs)("header",{className:"flex shrink-0 items-center justify-between gap-2 border-b border-modiff-border px-3 py-2",children:[(0,l.jsx)("h2",{className:"text-sm font-semibold text-modiff-text",children:r}),(0,l.jsx)(s,{label:"Close Block editor",onClick:i,children:(0,l.jsx)(e,{size:16})})]}),(0,l.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-3",children:o}),t?(0,l.jsx)("footer",{className:"flex shrink-0 flex-wrap justify-end gap-2 border-t border-modiff-border bg-modiff-panel p-3",children:t}):null]})}export{o as t}; \ No newline at end of file diff --git a/web/assets/EncodingNode.js b/web/assets/EncodingNode.js index 3e73ea7..1964727 100644 --- a/web/assets/EncodingNode.js +++ b/web/assets/EncodingNode.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as n,ln as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{At as s,Cs as o,Ct as i,Ei as d,Fo as r,Lo as l,Mo as c,Mt as u,Nt as m,Ot as p,Qs as g,Si as f,Ss as h,Uo as x,Vn as j,Vr as I,an as b,dn as v,es as S,et as N,ft as k,in as C,ji as y,lt as w,ns as $,rn as M,tt as P,ut as V,xs as _}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as G,t as T}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import A from"./GuidanceNodeControls.js?v=cc046c26d6fe7aa4";import E from"./NodeInspectionDetails.js?v=cc046c26d6fe7aa4";var B=e(n(),1),F=t();function O({instance:e,updateStore:t}){let n=I(e=>e.nodes),a=I(e=>e.edges),s=l(e,f(e=>e.operationContracts),f(e=>e.pipelineSupport)),o=(0,B.useMemo)(()=>$(e),[e]),d=(0,B.useMemo)(()=>S(e).nodes,[e]),r=n.find(t=>t.id===e.instanceId)?.data.uiState?.encodingSummaries,c=(0,B.useMemo)(()=>{try{let t=x({nodes:n,edges:a},new Set([e.instanceId])).graph;return new Map(d.map(n=>{let a=g(t.nodes,t.edges,`${e.instanceId}/${n.data.blockProjectionNodeId}`,"seed");return[n.data.blockProjectionNodeId,a?.members.filter(t=>t.node.id!==`${e.instanceId}/${n.data.blockProjectionNodeId}`).map(e=>e.node.data.label).filter(Boolean)??[]]}))}catch{return new Map}},[a,e.instanceId,n,d]),u=[...new Set(e.effectiveInterface.controls.map(e=>e.group??"Settings"))],m=d.filter(e=>["vae_encoder","image_encoder"].includes(e.data.operationAuthoring?.operation.nodeType??""));function p(t,s){let o=e.effectiveInterface.boundary.inputs.filter(e=>[e.binding,...e.mirrorBindings??[]].some(e=>e.nodeId===t&&e.fieldOrPortId===s)),i=a.find(t=>t.target===e.instanceId&&o.some(e=>e.portId===t.targetHandle));if(i)return n.find(e=>e.id===i.source)?.data.label??"Connected source";let d=e.effectiveGraph.edges.find(e=>e.targetNodeId===t&&e.targetPortId===s);return d?String(e.effectiveGraph.nodes.find(e=>e.nodeId===d.sourceNodeId)?.data.label??"Internal source"):null}return(m.length||s)&&!u.includes("Image")&&u.push("Image"),(0,F.jsx)("div",{className:"nodrag nowheel grid gap-2","data-encoding-content":!0,"data-testid":`encoding-controls-${e.instanceId}`,children:u.map(n=>{let a=e.effectiveInterface.controls.filter(e=>(e.group??"Settings")===n),d=[...new Set(a.filter(e=>"prompt"===e.binding.fieldId).map(e=>p(e.binding.nodeId,"prompt_input")).filter(Boolean))];return(0,F.jsxs)(v,{label:n,defaultOpen:!0,unmount:!1,panelClassName:"grid gap-2 px-1 pt-2","aria-label":`${n} encoding controls`,children:["Image"===n&&s?(0,F.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Optional — connect the Image socket to use an image input. Text-only generation remains available without it."}):null,d.length?(0,F.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:["Using Prompt Input from ",d.join(", "),". The local prompt is retained below as an inactive fallback."]}):null,"Image"===n?m.map(t=>{let n=p(t.data.blockProjectionNodeId,"image"),a=t.data.operationAuthoring?.operation.ports.some(e=>"input"===e.direction&&"image"===e.name&&e.required),s=t.data.params.image?.value??t.data.params.image?.default;return(0,F.jsxs)("div",{className:"grid gap-2",children:[!a||n||null!=s&&""!==s?n?(0,F.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:["Image from ",n]}):null:(0,F.jsx)("p",{role:"status",className:"text-xs text-modiff-invalid",children:"Image input required — connect a separate Load Image node."}),t.data.params.encode_summary||t.data.params.encode_summary_data?(0,F.jsx)(i,{nodeId:e.instanceId,params:r?.[t.id]?.graphHash===e.effectiveGraph.graphHash?{...t.data.params,encode_summary:{...t.data.params.encode_summary,value:r[t.id].value}}:t.data.params,executionStatus:t.data.executionStatus,progressMessage:t.data.progressMessage}):null]},t.id)}):null,a.map(n=>{let a=o.controlParams[n.controlId];if(!a)return null;let s=c.get(n.binding.nodeId)??[];return(0,F.jsxs)("div",{children:[(0,F.jsx)(k,{nodeId:e.instanceId,params:{[n.controlId]:_(n,a,!!p(n.binding.nodeId,"prompt_input"))},updateStore:t,module:o.source.provider??"MoDiff",action:"BlockV2",mode:"controls"}),"seed"===n.binding.fieldId?(0,F.jsxs)("p",{className:"mb-2 text-xs text-modiff-subtle-text",children:[m.some(e=>e.data.blockProjectionNodeId===n.binding.nodeId&&"vae_encoder"===e.data.operationAuthoring?.operation.nodeType)?"Seed for image-latent sampling.":"Seed declared by this encoding stage.",s.length?` Shared with ${s.join(", ")}; editing updates the linked value.`:""]}):null]},n.controlId)})]},n)})})}function q({node:e,inspect:t,save:n,canSave:i}){let[r,l]=(0,B.useState)(!1),g=o(e.data.blockInstanceV2),f=g?"Guidance":"Encode Inputs",h=`Separate ${g?"guidance":"encoding"} stages`;return(0,F.jsxs)(F.Fragment,{children:[(0,F.jsxs)(s,{className:"nodrag nowheel",children:[(0,F.jsx)(m,{children:(0,F.jsx)(b,{label:`${f} options`,size:"compact",children:(0,F.jsx)(a,{size:16})})}),(0,F.jsxs)(u,{layer:"graph",children:[(0,F.jsx)(p,{onClick:t,children:"Inspect implementation"}),(0,F.jsx)(p,{onClick:function(){try{let t=I.getState().toObject(),n=d(),a=x(t,new Set([e.id])).graph;T(a,n,G(t),h),y.getState().saveActiveWorkflowTab(!0)}catch(e){c(e instanceof Error?e.message:"Could not separate stages.",{variant:"error"})}},children:h}),i?(0,F.jsx)(p,{onClick:n,children:"Save as reusable node…"}):null,(0,F.jsx)(p,{onClick:()=>requestAnimationFrame(()=>l(!0)),children:"Documentation"})]})]}),r?(0,F.jsx)(C,{open:!0,title:`${f} documentation`,onClose:()=>l(!1),children:(0,F.jsxs)("div",{className:"grid gap-4",children:[(0,F.jsx)("p",{children:g?"Guidance combines the related Guider and Layers configuration. Schedulers and adapters remain separate nodes.":"Text and image stages both run when present. Collapsing a section only hides its fields. Load media separately and connect its output to the relevant input."}),S(e.data.blockInstanceV2).nodes.map(e=>(0,F.jsxs)("section",{children:[(0,F.jsx)("h3",{className:"mb-2 font-semibold",children:e.data.label}),(0,F.jsx)(E,{node:e,section:"docs"})]},e.id))]})}):null]})}var H=(0,B.memo)(e=>{let t=e.data.blockInstanceV2,n=o(t),a=n?"Guidance":"Encode Inputs",s=n?"guidance":"encoding",i=(0,B.useMemo)(()=>$(t),[t]),[d,l]=(0,B.useState)(!1),[c,u]=(0,B.useState)(!1),[m,p]=(0,B.useState)(!1);f(e=>e.operationContracts),f(e=>e.pipelineSupport);let g=I(j(t=>t.edges.filter(t=>t.source===e.id||t.target===e.id))),x=I(e=>e.setBlockInstanceValueV2),b=I(e=>e.ensureBlockProjectionV2),v=h(Object.fromEntries(Object.entries(r(e)).map(([t,n])=>[t,{...n,isConnected:g.some(n=>n.source===e.id&&n.sourceHandle===t||n.target===e.id&&n.targetHandle===t)}])),t.effectiveInterface.boundary.outputs),y=(0,B.useCallback)((t,n,a)=>{(void 0===a||"value"===a)&&x(e.id,t,n)},[e.id,x]);return(0,B.useLayoutEffect)(()=>{b(e.id)},[b,e.id,t.presentation.expanded]),(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(w,{...e,surface:{testId:`${n?"guidance":"encoding"}-node-${e.id}`,controls:n?(0,F.jsx)(A,{instance:t}):(0,F.jsx)(O,{instance:t,updateStore:y}),actions:(0,F.jsx)(q,{node:{...e,position:i.position},inspect:()=>requestAnimationFrame(()=>l(!0)),save:()=>requestAnimationFrame(()=>p(!0)),canSave:!0}),connectors:(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(k,{nodeId:e.id,params:v,updateStore:y,module:"MoDiff",action:"Encoding",mode:"connectors"}),(0,F.jsx)(N,{nodeId:e.id})]}),setSize:(t,n)=>I.getState().setBlockPresentationV2(e.id,{size:{width:t,height:n}})}}),d?(0,F.jsxs)(C,{open:!0,title:`${a} implementation`,onClose:()=>l(!1),footer:(0,F.jsx)(M,{onClick:()=>{l(!1),u(!0)},children:"Configure inputs, outputs and controls"}),children:[(0,F.jsxs)("p",{className:"mb-4 text-sm text-modiff-subtle-text",children:["These stages execute behind this node. To edit their connections on the canvas, use Separate ",s," ","stages."]}),(0,F.jsx)("div",{className:"grid gap-4",children:S(t).nodes.map(e=>(0,F.jsxs)("section",{children:[(0,F.jsx)("h3",{className:"mb-2 font-semibold",children:e.data.label}),(0,F.jsx)(E,{node:e,section:"implementation"})]},e.id))})]}):null,c?(0,F.jsx)(P,{nodeId:e.id,onClose:()=>u(!1)}):null,m?(0,F.jsx)(V,{nodeId:e.id,onClose:()=>p(!1)}):null]})});H.displayName="EncodingNode";export{H as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a,ln as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Es as s,Hn as o,Hr as i,Ko as d,Lo as r,Ni as l,Nt as c,Oi as u,Po as m,Pt as p,Ts as g,an as f,as as h,dt as x,fn as j,in as I,jt as b,kt as v,nt as S,on as N,pt as k,rs as C,tc as w,tt as y,ut as P,wi as $,ws as M,wt as T,zo as _}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as G,t as E}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import V from"./GuidanceNodeControls.js?v=ca6b74e6a02eedb3";import A from"./NodeInspectionDetails.js?v=ca6b74e6a02eedb3";var B=e(a(),1),H=t();function O({instance:e,updateStore:t}){let a=i(e=>e.nodes),n=i(e=>e.edges),s=_(e,$(e=>e.operationContracts),$(e=>e.pipelineSupport)),o=(0,B.useMemo)(()=>h(e),[e]),r=(0,B.useMemo)(()=>C(e).nodes,[e]),l=a.find(t=>t.id===e.instanceId)?.data.uiState?.encodingSummaries,c=(0,B.useMemo)(()=>{try{let t=d({nodes:a,edges:n},new Set([e.instanceId])).graph;return new Map(r.map(a=>{let n=w(t.nodes,t.edges,`${e.instanceId}/${a.data.blockProjectionNodeId}`,"seed");return[a.data.blockProjectionNodeId,n?.members.filter(t=>t.node.id!==`${e.instanceId}/${a.data.blockProjectionNodeId}`).map(e=>e.node.data.label).filter(Boolean)??[]]}))}catch{return new Map}},[n,e.instanceId,a,r]),u=[...new Set(e.effectiveInterface.controls.map(e=>e.group??"Settings"))],m=r.filter(e=>["vae_encoder","image_encoder"].includes(e.data.operationAuthoring?.operation.nodeType??""));function p(t,s){let o=e.effectiveInterface.boundary.inputs.filter(e=>[e.binding,...e.mirrorBindings??[]].some(e=>e.nodeId===t&&e.fieldOrPortId===s)),i=n.find(t=>t.target===e.instanceId&&o.some(e=>e.portId===t.targetHandle));if(i)return a.find(e=>e.id===i.source)?.data.label??"Connected source";let d=e.effectiveGraph.edges.find(e=>e.targetNodeId===t&&e.targetPortId===s);return d?String(e.effectiveGraph.nodes.find(e=>e.nodeId===d.sourceNodeId)?.data.label??"Internal source"):null}return(m.length||s)&&!u.includes("Image")&&u.push("Image"),(0,H.jsx)("div",{className:"nodrag nowheel grid gap-2","data-encoding-content":!0,"data-testid":`encoding-controls-${e.instanceId}`,children:u.map(a=>{let n=e.effectiveInterface.controls.filter(e=>(e.group??"Settings")===a),i=[...new Set(n.filter(e=>"prompt"===e.binding.fieldId).map(e=>p(e.binding.nodeId,"prompt_input")).filter(Boolean))];return(0,H.jsxs)(j,{label:a,defaultOpen:!0,unmount:!1,panelClassName:"grid gap-2 px-1 pt-2","aria-label":`${a} encoding controls`,children:["Image"===a&&s?(0,H.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Optional — connect the Image socket to use an image input. Text-only generation remains available without it."}):null,i.length?(0,H.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:["Using Prompt Input from ",i.join(", "),". The local prompt is retained below as an inactive fallback."]}):null,"Image"===a?m.map(t=>{let a=p(t.data.blockProjectionNodeId,"image"),n=t.data.operationAuthoring?.operation.ports.some(e=>"input"===e.direction&&"image"===e.name&&e.required),s=t.data.params.image?.value??t.data.params.image?.default;return(0,H.jsxs)("div",{className:"grid gap-2",children:[!n||a||null!=s&&""!==s?a?(0,H.jsxs)("p",{className:"text-xs text-modiff-subtle-text",children:["Image from ",a]}):null:(0,H.jsx)("p",{role:"status",className:"text-xs text-modiff-invalid",children:"Image input required — connect a separate Load Image node."}),t.data.params.encode_summary||t.data.params.encode_summary_data?(0,H.jsx)(T,{nodeId:e.instanceId,params:l?.[t.id]?.graphHash===e.effectiveGraph.graphHash?{...t.data.params,encode_summary:{...t.data.params.encode_summary,value:l[t.id].value}}:t.data.params,executionStatus:t.data.executionStatus,progressMessage:t.data.progressMessage}):null]},t.id)}):null,n.map(a=>{let n=o.controlParams[a.controlId];if(!n)return null;let s=c.get(a.binding.nodeId)??[];return(0,H.jsxs)("div",{children:[(0,H.jsx)(k,{nodeId:e.instanceId,params:{[a.controlId]:M(a,n,!!p(a.binding.nodeId,"prompt_input"))},updateStore:t,module:o.source.provider??"MoDiff",action:"BlockV2",mode:"controls"}),"seed"===a.binding.fieldId?(0,H.jsxs)("p",{className:"mb-2 text-xs text-modiff-subtle-text",children:[m.some(e=>e.data.blockProjectionNodeId===a.binding.nodeId&&"vae_encoder"===e.data.operationAuthoring?.operation.nodeType)?"Seed for image-latent sampling.":"Seed declared by this encoding stage.",s.length?` Shared with ${s.join(", ")}; editing updates the linked value.`:""]}):null]},a.controlId)})]},a)})})}function F({node:e,inspect:t,save:a,canSave:o}){let[r,g]=(0,B.useState)(!1),h=s(e.data.blockInstanceV2),x=h?"Guidance":"Encode Inputs",j=`Separate ${h?"guidance":"encoding"} stages`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(b,{className:"nodrag nowheel",children:[(0,H.jsx)(p,{children:(0,H.jsx)(N,{label:`${x} options`,size:"compact",children:(0,H.jsx)(n,{size:16})})}),(0,H.jsxs)(c,{layer:"graph",children:[(0,H.jsx)(v,{onClick:t,children:"Inspect implementation"}),(0,H.jsx)(v,{onClick:function(){try{let t=i.getState().toObject(),a=u(),n=d(t,new Set([e.id])).graph;E(n,a,G(t),j),l.getState().saveActiveWorkflowTab(!0)}catch(e){m(e instanceof Error?e.message:"Could not separate stages.",{variant:"error"})}},children:j}),o?(0,H.jsx)(v,{onClick:a,children:"Save as reusable node…"}):null,(0,H.jsx)(v,{onClick:()=>requestAnimationFrame(()=>g(!0)),children:"Documentation"})]})]}),r?(0,H.jsx)(f,{open:!0,title:`${x} documentation`,onClose:()=>g(!1),children:(0,H.jsxs)("div",{className:"grid gap-4",children:[(0,H.jsx)("p",{children:h?"Guidance combines the related Guider and Layers configuration. Schedulers and adapters remain separate nodes.":"Text and image stages both run when present. Collapsing a section only hides its fields. Load media separately and connect its output to the relevant input."}),C(e.data.blockInstanceV2).nodes.map(e=>(0,H.jsxs)("section",{children:[(0,H.jsx)("h3",{className:"mb-2 font-semibold",children:e.data.label}),(0,H.jsx)(A,{node:e,section:"docs"})]},e.id))]})}):null]})}var q=(0,B.memo)(e=>{let t=e.data.blockInstanceV2,a=s(t),n=a?"Guidance":"Encode Inputs",d=a?"guidance":"encoding",l=(0,B.useMemo)(()=>h(t),[t]),[c,u]=(0,B.useState)(!1),[m,p]=(0,B.useState)(!1),[j,b]=(0,B.useState)(!1);$(e=>e.operationContracts),$(e=>e.pipelineSupport);let v=i(o(t=>t.edges.filter(t=>t.source===e.id||t.target===e.id))),N=i(e=>e.setBlockInstanceValueV2),w=i(e=>e.ensureBlockProjectionV2),M=g(Object.fromEntries(Object.entries(r(e)).map(([t,a])=>[t,{...a,isConnected:v.some(a=>a.source===e.id&&a.sourceHandle===t||a.target===e.id&&a.targetHandle===t)}])),t.effectiveInterface.boundary.outputs),T=(0,B.useCallback)((t,a,n)=>{(void 0===n||"value"===n)&&N(e.id,t,a)},[e.id,N]);return(0,B.useLayoutEffect)(()=>{w(e.id)},[w,e.id,t.presentation.expanded]),(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(P,{...e,surface:{testId:`${a?"guidance":"encoding"}-node-${e.id}`,controls:a?(0,H.jsx)(V,{instance:t}):(0,H.jsx)(O,{instance:t,updateStore:T}),actions:(0,H.jsx)(F,{node:{...e,position:l.position},inspect:()=>requestAnimationFrame(()=>u(!0)),save:()=>requestAnimationFrame(()=>b(!0)),canSave:!0}),connectors:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(k,{nodeId:e.id,params:M,updateStore:T,module:"MoDiff",action:"Encoding",mode:"connectors"}),(0,H.jsx)(y,{nodeId:e.id})]}),setSize:(t,a)=>i.getState().setBlockPresentationV2(e.id,{size:{width:t,height:a}})}}),c?(0,H.jsxs)(f,{open:!0,title:`${n} implementation`,onClose:()=>u(!1),footer:(0,H.jsx)(I,{onClick:()=>{u(!1),p(!0)},children:"Configure inputs, outputs and controls"}),children:[(0,H.jsxs)("p",{className:"mb-4 text-sm text-modiff-subtle-text",children:["These stages execute behind this node. To edit their connections on the canvas, use Separate ",d," ","stages."]}),(0,H.jsx)("div",{className:"grid gap-4",children:C(t).nodes.map(e=>(0,H.jsxs)("section",{children:[(0,H.jsx)("h3",{className:"mb-2 font-semibold",children:e.data.label}),(0,H.jsx)(A,{node:e,section:"implementation"})]},e.id))})]}):null,m?(0,H.jsx)(S,{nodeId:e.id,onClose:()=>p(!1)}):null,j?(0,H.jsx)(x,{nodeId:e.id,onClose:()=>b(!1)}):null]})});q.displayName="EncodingNode";export{q as default}; \ No newline at end of file diff --git a/web/assets/FileBrowserDialog.js b/web/assets/FileBrowserDialog.js index b67a767..8dbb3dd 100644 --- a/web/assets/FileBrowserDialog.js +++ b/web/assets/FileBrowserDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Et as t,Jt as s,cr as a,dr as l,zt as i}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Eo as r,In as o,Oo as n,To as d,Vr as c,an as m,cn as f,in as h,ji as p,oc as x,rn as u,yn as b}from"./studio-templates.js?v=cc046c26d6fe7aa4";var g=e(l(),1),j=a(),y=d();function w(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function N(e){if(!w(e)||!Array.isArray(e.files)||"string"!=typeof e.path||"string"!=typeof e.abs_path)throw Error("The directory listing response is invalid.");return{files:e.files.map((e,t)=>{if(!w(e)||"boolean"!=typeof e.is_dir||"boolean"!=typeof e.is_hidden||"string"!=typeof e.name||"string"!=typeof e.path||"number"!=typeof e.modified)throw Error(`Directory entry ${t+1} is invalid.`);return e}),path:e.path,abs_path:e.abs_path}}function v(e){return new Intl.DateTimeFormat(void 0,{year:"2-digit",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(1e3*e))}function C(e){if(0===e||null===e)return"0 B";let t=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**t).toFixed(2)} ${["B","KB","MB","GB","TB"][t]}`}var k=(0,g.memo)(({file:e,onPathChange:t})=>(0,j.jsxs)("tr",{role:"button",tabIndex:0,className:"cursor-pointer border-b border-modiff-border hover:bg-modiff-surface-hover",onClick:()=>t(e.path),onKeyDown:s=>{s.target!==s.currentTarget||"Enter"!==s.key&&" "!==s.key||(s.preventDefault(),t(e.path))},children:[(0,j.jsx)("td",{className:"w-8 p-0 text-center",children:(0,j.jsx)(s,{size:16,className:"mx-auto text-hf-yellow"})}),(0,j.jsx)("td",{className:"px-2 py-1 text-sm text-modiff-text",children:e.name}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text"}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:v(e.modified)})]})),T=(0,g.memo)(({file:e,isSelected:t,onFileClick:s,onFileToggle:a})=>(0,j.jsxs)("tr",{role:"button",tabIndex:0,className:o("cursor-pointer border-b border-modiff-border hover:bg-modiff-surface-hover",t&&"bg-modiff-selected-surface"),onClick:t=>s(e,t),onKeyDown:t=>{t.target!==t.currentTarget||"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),s(e,t))},children:[(0,j.jsx)("td",{className:"w-8 p-0 text-center",children:(0,j.jsx)("span",{className:"inline-flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:(0,j.jsx)(f,{checked:t,label:(0,j.jsx)("span",{className:"sr-only",children:`Select ${e.name}`}),onCheckedChange:t=>a(e,t)})})}),(0,j.jsx)("td",{className:"break-all px-2 py-1 text-sm text-modiff-text",children:e.name}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:e.size?C(e.size):"-"}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:v(e.modified)})]}));function z({opener:e,onClose:s,onSelect:a}){let l=c(e=>e.setParamWithHistory),o=p(e=>e.activeWorkflowTabId),d=p(e=>e.workflowCanvasEpoch),w=!(!e||e.workflowTabId!==o||e.workflowCanvasEpoch!==d),[z,S]=(0,g.useState)("."),[E,I]=(0,g.useState)(null),[_,F]=(0,g.useState)([]),[$,D]=(0,g.useState)(!1),[A,M]=(0,g.useState)(null),[B,K]=(0,g.useState)(""),L=function(e){let[t,s]=(0,g.useState)(e);return(0,g.useEffect)(()=>{let t=setTimeout(()=>{s(e)},250);return()=>{clearTimeout(t)}},[e,250]),t}(B),P=e?.multiple??!1,V=e?.fileTypes.join(",")??"";(0,g.useEffect)(()=>{e&&!w&&s()},[s,e,w]);let R=(0,g.useCallback)(async e=>{let t=y.begin("directory");D(!0),M(null);try{let s=await n(`${x.serverAddress}/listdir?path=${encodeURIComponent(e)}&type=${V}`,{signal:t.signal,parse:N});t.isLatest()&&I(s)}catch(s){t.isLatest()&&(M(r(s,"Could not load this folder.")),I({files:[],path:e,abs_path:e}))}finally{t.isLatest()&&D(!1),t.finish()}},[V]),{directories:U,files:H}=(0,g.useMemo)(()=>{let e=E?.files||[],t=L?e.filter(e=>e.name.toLowerCase().includes(L.toLowerCase())):e;return{directories:t.filter(e=>e.is_dir).sort((e,t)=>e.name.localeCompare(t.name)),files:t.filter(e=>!e.is_dir).sort((e,t)=>e.name.localeCompare(t.name))}},[E,L]),W=(0,g.useCallback)((e,t)=>{let s=t.target,a="INPUT"===s.tagName&&"checkbox"===s.getAttribute("type");F(s=>{let l=s.some(t=>t.path===e.path);return P?a||t.shiftKey?l?s.filter(t=>t.path!==e.path):[...s,e]:[e]:l?[]:[e]})},[P]),G=(0,g.useCallback)((e,t)=>{F(s=>t?P?s.some(t=>t.path===e.path)?s:[...s,e]:[e]:s.filter(t=>t.path!==e.path))},[P]);(0,g.useEffect)(()=>{e&&R(z)},[z,R,e]),(0,g.useEffect)(()=>{if(S(e?.path||"."),K(""),e?.initialValues&&e.initialValues.length>0){let t=e.initialValues.map(e=>({is_dir:!1,is_hidden:!1,name:e.split(/[/\\]/).pop()||e,path:e,modified:0,size:null,ext:null,type:null}));F(t)}else F([])},[e]);let J=_[_.length-1],O=z.split("/"),q=()=>{s(),S("."),K("")};return(0,j.jsx)(h,{open:!!e,onClose:q,title:"File browser",description:"Choose files from the backend. Nothing is added until you select.",testId:"file-browser-dialog",panelClassName:"max-w-6xl",bodyClassName:"!p-0",footer:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)("span",{role:"status",className:"mr-auto self-center text-xs text-modiff-subtle-text",children:$?"Loading folder…":`${_.length} selected`}),(0,j.jsx)(u,{onClick:q,children:"Cancel"}),(0,j.jsx)(u,{tone:"primary",onClick:()=>{e&&w&&l(e.nodeId,e.fieldKey,_.map(e=>e.path)),w&&a?.(_.map(e=>e.path)),q()},disabled:0===_.length||$||!!A||!w,children:"Select"})]}),children:(0,j.jsxs)("div",{className:"flex min-h-0 flex-col",children:[A?(0,j.jsxs)("div",{role:"alert",className:"m-4 grid gap-2 rounded-modiff-compact border border-modiff-invalid/40 bg-modiff-invalid/10 p-3 text-sm text-modiff-text",children:[(0,j.jsx)("p",{className:"break-words",children:A}),(0,j.jsx)(u,{onClick:()=>{R(z)},children:"Retry folder"})]}):null,(0,j.jsxs)("nav",{className:"flex flex-wrap items-center gap-1 border-b border-modiff-border bg-modiff-panel px-4 py-3 text-sm text-modiff-text","aria-label":"Current folder",children:[(0,j.jsx)(m,{label:"Home",size:"compact",className:"text-hf-yellow",onClick:()=>{S("."),F([])},children:(0,j.jsx)(i,{size:16})}),O.map((e,t)=>{let s=O.slice(0,t+1).join("/");return t===O.length-1?(0,j.jsx)("span",{className:"break-all px-1 text-modiff-text",children:e},t):(0,j.jsx)(u,{tone:"ghost",size:"compact",className:"h-7 px-1 font-normal",onClick:()=>{S(s),F([])},children:e},t)})]}),(0,j.jsxs)("div",{className:"grid min-h-0 flex-1 gap-4 overflow-hidden p-4 lg:grid-cols-[minmax(0,1fr)_384px]",children:[(0,j.jsxs)("div",{className:"relative min-h-0 min-w-0 select-none overflow-auto",children:[$&&(0,j.jsx)("div",{className:"absolute inset-0 z-[2] grid place-items-center bg-modiff-panel/90",children:(0,j.jsx)(t,{className:"animate-spin text-hf-yellow",size:28})}),(0,j.jsxs)("table",{className:"w-full border-collapse text-left",children:[(0,j.jsx)("thead",{className:"sticky top-0 z-[1] bg-modiff-panel",children:(0,j.jsxs)("tr",{className:"border-b border-modiff-border",children:[(0,j.jsx)("th",{className:"w-8 p-0 text-center",children:P&&(0,j.jsx)(f,{checked:H.length>0&&_.length===H.length,indeterminate:_.length>0&&_.length{F(e?H:[])}})}),(0,j.jsx)("th",{className:"px-2 py-2",children:(0,j.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,j.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:"Name"}),(0,j.jsx)(b,{"aria-label":"Filter files",className:"min-w-0 flex-1",placeholder:"Filter",value:B,onChange:e=>K(e.currentTarget.value),onClear:()=>K("")})]})}),(0,j.jsx)("th",{className:"whitespace-nowrap px-2 py-2 text-right text-sm font-semibold text-modiff-text",children:"Size"}),(0,j.jsx)("th",{className:"whitespace-nowrap px-2 py-2 text-right text-sm font-semibold text-modiff-text",children:"Modified"})]})}),(0,j.jsxs)("tbody",{children:[U.map(e=>(0,j.jsx)(k,{file:e,onPathChange:e=>{S(e),F([]),K("")}},e.path)),H.map(e=>(0,j.jsx)(T,{file:e,isSelected:_.some(t=>t.path===e.path),onFileClick:W,onFileToggle:G},e.path))]})]}),$||A||0!==U.length||0!==H.length?null:(0,j.jsxs)("div",{className:"p-3 text-sm text-modiff-subtle-text",children:[B?"No files match your search.":"This folder has no matching files.",B?(0,j.jsx)(u,{tone:"ghost",onClick:()=>K(""),children:"Clear search"}):null]})]}),(0,j.jsxs)("aside",{className:"min-h-0 overflow-hidden break-words",children:[J&&(0,j.jsx)("img",{src:`${x.serverAddress}/preview?file=${encodeURIComponent(J.path)}&width=384&height=384`,alt:J.name,className:"w-full rounded-modiff-compact border border-modiff-border object-contain"}),(0,j.jsxs)("div",{className:"mt-2 space-y-1 text-sm text-modiff-subtle-text",children:[(0,j.jsx)("div",{className:"font-bold text-modiff-text",children:J?J.name:""}),(0,j.jsxs)("div",{children:["Size: ",J?.size?C(J.size):"-"]}),(0,j.jsxs)("div",{children:["Modified: ",J?.modified?v(J.modified):"-"]}),(0,j.jsxs)("div",{children:["Type: ",J?.type??""]})]})]})]})]})})}export{z as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Et as t,Jt as s,cr as a,dr as l,zt as i}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ao as r,Do as o,Hr as n,Ln as d,Ni as c,Oo as m,an as f,bn as h,in as p,lc as x,ln as u,on as b}from"./studio-templates.js?v=ca6b74e6a02eedb3";var g=e(l(),1),j=a(),y=o();function w(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function N(e){if(!w(e)||!Array.isArray(e.files)||"string"!=typeof e.path||"string"!=typeof e.abs_path)throw Error("The directory listing response is invalid.");return{files:e.files.map((e,t)=>{if(!w(e)||"boolean"!=typeof e.is_dir||"boolean"!=typeof e.is_hidden||"string"!=typeof e.name||"string"!=typeof e.path||"number"!=typeof e.modified)throw Error(`Directory entry ${t+1} is invalid.`);return e}),path:e.path,abs_path:e.abs_path}}function v(e){return new Intl.DateTimeFormat(void 0,{year:"2-digit",month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).format(new Date(1e3*e))}function C(e){if(0===e||null===e)return"0 B";let t=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**t).toFixed(2)} ${["B","KB","MB","GB","TB"][t]}`}var k=(0,g.memo)(({file:e,onPathChange:t})=>(0,j.jsxs)("tr",{role:"button",tabIndex:0,className:"cursor-pointer border-b border-modiff-border hover:bg-modiff-surface-hover",onClick:()=>t(e.path),onKeyDown:s=>{s.target!==s.currentTarget||"Enter"!==s.key&&" "!==s.key||(s.preventDefault(),t(e.path))},children:[(0,j.jsx)("td",{className:"w-8 p-0 text-center",children:(0,j.jsx)(s,{size:16,className:"mx-auto text-hf-yellow"})}),(0,j.jsx)("td",{className:"px-2 py-1 text-sm text-modiff-text",children:e.name}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text"}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:v(e.modified)})]})),T=(0,g.memo)(({file:e,isSelected:t,onFileClick:s,onFileToggle:a})=>(0,j.jsxs)("tr",{role:"button",tabIndex:0,className:d("cursor-pointer border-b border-modiff-border hover:bg-modiff-surface-hover",t&&"bg-modiff-selected-surface"),onClick:t=>s(e,t),onKeyDown:t=>{t.target!==t.currentTarget||"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),s(e,t))},children:[(0,j.jsx)("td",{className:"w-8 p-0 text-center",children:(0,j.jsx)("span",{className:"inline-flex",onClick:e=>e.stopPropagation(),onKeyDown:e=>e.stopPropagation(),children:(0,j.jsx)(u,{checked:t,label:(0,j.jsx)("span",{className:"sr-only",children:`Select ${e.name}`}),onCheckedChange:t=>a(e,t)})})}),(0,j.jsx)("td",{className:"break-all px-2 py-1 text-sm text-modiff-text",children:e.name}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:e.size?C(e.size):"-"}),(0,j.jsx)("td",{className:"whitespace-nowrap px-2 py-1 text-right text-sm text-modiff-subtle-text",children:v(e.modified)})]}));function z({opener:e,onClose:s,onSelect:a}){let l=n(e=>e.setParamWithHistory),o=c(e=>e.activeWorkflowTabId),d=c(e=>e.workflowCanvasEpoch),w=!(!e||e.workflowTabId!==o||e.workflowCanvasEpoch!==d),[z,S]=(0,g.useState)("."),[E,_]=(0,g.useState)(null),[F,I]=(0,g.useState)([]),[$,D]=(0,g.useState)(!1),[A,L]=(0,g.useState)(null),[M,B]=(0,g.useState)(""),K=function(e){let[t,s]=(0,g.useState)(e);return(0,g.useEffect)(()=>{let t=setTimeout(()=>{s(e)},250);return()=>{clearTimeout(t)}},[e,250]),t}(M),P=e?.multiple??!1,H=e?.fileTypes.join(",")??"";(0,g.useEffect)(()=>{e&&!w&&s()},[s,e,w]);let R=(0,g.useCallback)(async e=>{let t=y.begin("directory");D(!0),L(null);try{let s=await r(`${x.serverAddress}/listdir?path=${encodeURIComponent(e)}&type=${H}`,{signal:t.signal,parse:N});t.isLatest()&&_(s)}catch(s){t.isLatest()&&(L(m(s,"Could not load this folder.")),_({files:[],path:e,abs_path:e}))}finally{t.isLatest()&&D(!1),t.finish()}},[H]),{directories:U,files:V}=(0,g.useMemo)(()=>{let e=E?.files||[],t=K?e.filter(e=>e.name.toLowerCase().includes(K.toLowerCase())):e;return{directories:t.filter(e=>e.is_dir).sort((e,t)=>e.name.localeCompare(t.name)),files:t.filter(e=>!e.is_dir).sort((e,t)=>e.name.localeCompare(t.name))}},[E,K]),W=(0,g.useCallback)((e,t)=>{let s=t.target,a="INPUT"===s.tagName&&"checkbox"===s.getAttribute("type");I(s=>{let l=s.some(t=>t.path===e.path);return P?a||t.shiftKey?l?s.filter(t=>t.path!==e.path):[...s,e]:[e]:l?[]:[e]})},[P]),G=(0,g.useCallback)((e,t)=>{I(s=>t?P?s.some(t=>t.path===e.path)?s:[...s,e]:[e]:s.filter(t=>t.path!==e.path))},[P]);(0,g.useEffect)(()=>{e&&R(z)},[z,R,e]),(0,g.useEffect)(()=>{if(S(e?.path||"."),B(""),e?.initialValues&&e.initialValues.length>0){let t=e.initialValues.map(e=>({is_dir:!1,is_hidden:!1,name:e.split(/[/\\]/).pop()||e,path:e,modified:0,size:null,ext:null,type:null}));I(t)}else I([])},[e]);let J=F[F.length-1],O=z.split("/"),q=()=>{s(),S("."),B("")};return(0,j.jsx)(f,{open:!!e,onClose:q,title:"File browser",description:"Choose files from the backend. Nothing is added until you select.",testId:"file-browser-dialog",panelClassName:"max-w-6xl",bodyClassName:"!p-0",footer:(0,j.jsxs)(j.Fragment,{children:[(0,j.jsx)("span",{role:"status",className:"mr-auto self-center text-xs text-modiff-subtle-text",children:$?"Loading folder…":`${F.length} selected`}),(0,j.jsx)(p,{onClick:q,children:"Cancel"}),(0,j.jsx)(p,{tone:"primary",onClick:()=>{e&&w&&l(e.nodeId,e.fieldKey,F.map(e=>e.path)),w&&a?.(F.map(e=>e.path)),q()},disabled:0===F.length||$||!!A||!w,children:"Select"})]}),children:(0,j.jsxs)("div",{className:"flex min-h-0 flex-col",children:[A?(0,j.jsxs)("div",{role:"alert",className:"m-4 grid gap-2 rounded-modiff-compact border border-modiff-invalid/40 bg-modiff-invalid/10 p-3 text-sm text-modiff-text",children:[(0,j.jsx)("p",{className:"break-words",children:A}),(0,j.jsx)(p,{onClick:()=>{R(z)},children:"Retry folder"})]}):null,(0,j.jsxs)("nav",{className:"flex flex-wrap items-center gap-1 border-b border-modiff-border bg-modiff-panel px-4 py-3 text-sm text-modiff-text","aria-label":"Current folder",children:[(0,j.jsx)(b,{label:"Home",size:"compact",className:"text-hf-yellow",onClick:()=>{S("."),I([])},children:(0,j.jsx)(i,{size:16})}),O.map((e,t)=>{let s=O.slice(0,t+1).join("/");return t===O.length-1?(0,j.jsx)("span",{className:"break-all px-1 text-modiff-text",children:e},t):(0,j.jsx)(p,{tone:"ghost",size:"compact",className:"h-7 px-1 font-normal",onClick:()=>{S(s),I([])},children:e},t)})]}),(0,j.jsxs)("div",{className:"grid min-h-0 flex-1 gap-4 overflow-hidden p-4 lg:grid-cols-[minmax(0,1fr)_384px]",children:[(0,j.jsxs)("div",{className:"relative min-h-0 min-w-0 select-none overflow-auto",children:[$&&(0,j.jsx)("div",{className:"absolute inset-0 z-[2] grid place-items-center bg-modiff-panel/90",children:(0,j.jsx)(t,{className:"animate-spin text-hf-yellow",size:28})}),(0,j.jsxs)("table",{className:"w-full border-collapse text-left",children:[(0,j.jsx)("thead",{className:"sticky top-0 z-[1] bg-modiff-panel",children:(0,j.jsxs)("tr",{className:"border-b border-modiff-border",children:[(0,j.jsx)("th",{className:"w-8 p-0 text-center",children:P&&(0,j.jsx)(u,{checked:V.length>0&&F.length===V.length,indeterminate:F.length>0&&F.length{I(e?V:[])}})}),(0,j.jsx)("th",{className:"px-2 py-2",children:(0,j.jsxs)("div",{className:"flex w-full items-center gap-2",children:[(0,j.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:"Name"}),(0,j.jsx)(h,{"aria-label":"Filter files",className:"min-w-0 flex-1",placeholder:"Filter",value:M,onChange:e=>B(e.currentTarget.value),onClear:()=>B("")})]})}),(0,j.jsx)("th",{className:"whitespace-nowrap px-2 py-2 text-right text-sm font-semibold text-modiff-text",children:"Size"}),(0,j.jsx)("th",{className:"whitespace-nowrap px-2 py-2 text-right text-sm font-semibold text-modiff-text",children:"Modified"})]})}),(0,j.jsxs)("tbody",{children:[U.map(e=>(0,j.jsx)(k,{file:e,onPathChange:e=>{S(e),I([]),B("")}},e.path)),V.map(e=>(0,j.jsx)(T,{file:e,isSelected:F.some(t=>t.path===e.path),onFileClick:W,onFileToggle:G},e.path))]})]}),$||A||0!==U.length||0!==V.length?null:(0,j.jsxs)("div",{className:"p-3 text-sm text-modiff-subtle-text",children:[M?"No files match your search.":"This folder has no matching files.",M?(0,j.jsx)(p,{tone:"ghost",onClick:()=>B(""),children:"Clear search"}):null]})]}),(0,j.jsxs)("aside",{className:"min-h-0 overflow-hidden break-words",children:[J&&(0,j.jsx)("img",{src:`${x.serverAddress}/preview?file=${encodeURIComponent(J.path)}&width=384&height=384`,alt:J.name,className:"w-full rounded-modiff-compact border border-modiff-border object-contain"}),(0,j.jsxs)("div",{className:"mt-2 space-y-1 text-sm text-modiff-subtle-text",children:[(0,j.jsx)("div",{className:"font-bold text-modiff-text",children:J?J.name:""}),(0,j.jsxs)("div",{children:["Size: ",J?.size?C(J.size):"-"]}),(0,j.jsxs)("div",{children:["Modified: ",J?.modified?v(J.modified):"-"]}),(0,j.jsxs)("div",{children:["Type: ",J?.type??""]})]})]})]})]})})}export{z as default}; \ No newline at end of file diff --git a/web/assets/GalleryLibraryDialog.js b/web/assets/GalleryLibraryDialog.js index b959909..5a99728 100644 --- a/web/assets/GalleryLibraryDialog.js +++ b/web/assets/GalleryLibraryDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$ as t,Ft as a,P as s,Pt as i,Rn as r,Ut as o,Vt as l,Wt as d,Y as n,cr as c,dr as m,pn as p,rt as u,st as x,un as f,ut as h,z as g}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$n as b,Ei as j,G as v,In as k,Jn as y,K as w,Mo as N,Oi as S,Sa as $,U as C,W as I,an as z,ba as D,ea as L,hr as H,ia as T,in as O,ir as R,ji as G,kn as M,ln as F,pn as P,rn as A,sn as V,va as E,vt as q,xa as B,ya as W,za as U}from"./studio-templates.js?v=cc046c26d6fe7aa4";var J=e(m(),1),_=c();function K(e){I(`modiff-${e.modelType}-${e.id}-workflow.json`,C(e))}async function Y(e){await v(`modiff-${e.modelType}-${e.id}-workflow.png`,e.url,C(e))}function Q(e){let t=e.templateLabel?` | ${e.templateLabel}`:"",a=e.mediaItems?.find(e=>e.durationSeconds)?.durationSeconds??(e.resolvedExecutionInputs?void 0:e.formSnapshot.audioDuration),s=W(e),i=B(e,"seed"),r=X(e)?" | "+(a?`${a.toFixed(1)} sec`:"audio"):Z(e)?` | ${T(e)}`:` | ${s||"image"}`;return`${e.modelLabel}${t} | ${U[e.mode]}${r} | ${void 0===i?"Seed not captured":`Seed ${i}`}`}function X(e){return"audio"===e.displayType||/\.(wav|mp3|flac|ogg|m4a|aac)(\?.*)?$/i.test(e.url)}function Z(e){return"video"===e.displayType||/\.(mp4|webm|mov|mkv|m4v)(\?.*)?$/i.test(e.url)}function ee({output:e,aspectRatio:t,maxHeight:a,onImageClick:s}){return X(e)?(0,_.jsx)("div",{className:k("grid min-h-24 w-full place-items-center border border-modiff-border bg-modiff-surface p-3","1 / 1"===t&&"aspect-square"),children:(0,_.jsx)("audio",{src:e.url,controls:!0,className:"w-full"})}):Z(e)?(0,_.jsx)("div",{className:k("border border-transparent bg-modiff-surface","1 / 1"===t&&"aspect-square"),children:(0,_.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",className:k("block h-full w-full bg-modiff-media-backdrop object-contain",!!a&&"max-h-[460px]")})}):e.mediaItems&&e.mediaItems.length>1&&"image_collection"===e.displayType?(0,_.jsx)("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(96px,1fr))] gap-1 bg-modiff-surface",children:e.mediaItems.slice(0,12).map(i=>(0,_.jsx)(M,{src:i.url,alt:i.label||`${e.id} item ${i.index+1}`,onClick:s,aspectRatio:t??"1 / 1",maxHeight:a,bordered:!1},`${i.index}-${i.url}`))}):(0,_.jsx)(M,{src:e.url,alt:e.prompt||e.id,onClick:s,aspectRatio:t,maxHeight:a,bordered:!1})}function te({modalView:e=!1}){let[a,c]=(0,J.useState)("generated"),[m,v]=(0,J.useState)("all"),[C,I]=(0,J.useState)("grid"),[z,L]=(0,J.useState)([]),T=(0,J.useRef)(null),O=G(e=>e.outputs),M=G(e=>e.importedAssets),F=G(e=>e.galleryBackendStatus),V=G(e=>e.galleryBackendError),E=G(e=>e.fetchBackendOutputs),B=G(e=>e.toggleFavoriteOutput),W=G(e=>e.deleteOutput),U=G(e=>e.deleteImportedAsset),Q=G(e=>e.useOutputAsReference),te=G(e=>e.useImportedAssetAsReference),ae=G(e=>e.restoreWorkflowFromOutput),me=G(e=>e.createWorkflowTab),pe=$(e=>e.setRightPanelOpen),ue=$(e=>e.setRightPanelTab),xe=$(e=>e.setGalleryLibraryOpen),fe=$(e=>e.setLightboxOpener),he=$(e=>e.setMediaExportOpener),ge=y(e=>e.sid),be=y(e=>e.isConnected),je=(0,J.useMemo)(()=>{let e=new Map;return O.forEach(t=>e.set(D(t),t.modelLabel)),Array.from(e.entries())},[O]),ve=(0,J.useMemo)(()=>"favorites"===m?O.filter(e=>e.favorite):"all"===m?O:O.filter(e=>`model:${D(e)}`===m),[m,O]),ke=(0,J.useMemo)(()=>{let e=z.map(e=>ve.find(t=>t.id===e)).filter(e=>!!e);return e.length>0?e:ve.slice(0,2)},[ve,z]),ye=ke[0]??ve[0],we=ke[0],Ne=ke[1],Se=(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(P,{ref:T,"aria-label":"Import workflow package",accept:"application/json,.json,image/png,.png",className:"sr-only","data-testid":"gallery-import-workflow-input",onChange:e=>{let t=e.currentTarget.files?.[0];e.currentTarget.value="",(async e=>{if(e)try{let t=await w(e);if(!t)throw Error("No MoDiff workflow metadata was found in that file.");me(t.title,t.snapshot,"import",t.sourceLabel),ue("studio"),xe(!1),N("Workflow package imported",{variant:"success",autoHideDuration:2200}),window.setTimeout(()=>H({sid:ge,isConnected:be,includeStudio:!0,showDialog:!0}),0)}catch(e){N(String(e),{variant:"error",autoHideDuration:6e3})}})(t)}}),(0,_.jsx)(re,{title:"Import workflow package","data-testid":"gallery-import-workflow",onClick:()=>T.current?.click(),children:(0,_.jsx)(s,{size:15})})]}),$e="idle"===F?"Backend history":"syncing"===F?"Syncing history":"loading"===F?"Loading history":"History offline",Ce="generated"===a&&0===O.length&&M.length>0?"imported":a;return 0===O.length&&0===M.length?(0,_.jsxs)("section",{className:k("p-3",e&&"min-h-[520px]"),"data-testid":"gallery-panel",children:[(0,_.jsxs)("div",{className:"mb-1 flex items-center gap-2",children:[(0,_.jsx)("h2",{className:"text-sm font-bold text-modiff-text",children:"Gallery"}),(0,_.jsx)(ie,{active:"error"!==F,error:"error"===F,"data-testid":"gallery-backend-status",children:$e}),(0,_.jsx)(re,{title:"Refresh history","data-testid":"gallery-refresh-history",onClick:()=>{E()},children:(0,_.jsx)(u,{size:15})}),Se]}),(0,_.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Generated and imported media appear here."}),V&&(0,_.jsx)("p",{className:"mt-1 text-xs text-modiff-red",children:V})]}):(0,_.jsxs)("section",{className:k("p-3",e&&"min-h-[520px]"),"data-testid":"gallery-panel",children:[(0,_.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,_.jsx)(ie,{active:"error"!==F,error:"error"===F,"data-testid":"gallery-backend-status",children:$e}),(0,_.jsx)(re,{title:"Refresh history","data-testid":"gallery-refresh-history",onClick:()=>{E()},children:(0,_.jsx)(u,{size:15})}),Se,(0,_.jsxs)(ie,{active:"generated"===Ce,onClick:()=>c("generated"),"data-testid":"gallery-kind-generated",children:["Generated ",O.length]}),(0,_.jsxs)(ie,{active:"imported"===Ce,onClick:()=>c("imported"),"data-testid":"gallery-kind-imported",children:["Imported ",M.length]}),"generated"===Ce?(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(ie,{active:"all"===m,onClick:()=>v("all"),"data-testid":"gallery-filter-all",children:"All"}),(0,_.jsx)(ie,{active:"favorites"===m,onClick:()=>v("favorites"),"data-testid":"gallery-filter-favorites",children:"Favorites"}),je.map(([e,t])=>(0,_.jsx)(ie,{active:m===`model:${e}`,onClick:()=>v(`model:${e}`),"data-testid":`gallery-filter-${e}`,children:t},e))]}):null]}),"generated"===Ce?(0,_.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,_.jsx)(ie,{active:"grid"===C,onClick:()=>I("grid"),"data-testid":"gallery-view-grid",icon:(0,_.jsx)(o,{size:14}),children:"Grid"}),(0,_.jsx)(ie,{active:"inspect"===C,onClick:()=>I("inspect"),"data-testid":"gallery-view-inspect",icon:(0,_.jsx)(i,{size:14}),children:"Inspect"}),(0,_.jsx)(ie,{active:"compare"===C,onClick:()=>I("compare"),"data-testid":"gallery-view-compare",icon:(0,_.jsx)(r,{size:14}),children:"Compare"}),(0,_.jsx)(ie,{active:"lineage"===C,onClick:()=>I("lineage"),"data-testid":"gallery-view-lineage",icon:(0,_.jsx)(d,{size:14}),children:"Lineage"})]}):null,V&&(0,_.jsx)("p",{className:"mb-2 text-xs text-modiff-red",children:V}),"imported"===Ce?(0,_.jsx)(se,{assets:M,onDelete:U,onDownload:e=>{if("unknown"===e.displayType){let t=document.createElement("a");return t.href=e.url,t.download=e.name,t.rel="noopener noreferrer",document.body.append(t),t.click(),void t.remove()}he({source:e.url,filename:e.name,kind:e.displayType,defaultFormat:"audio"===e.displayType?"wav":"video"===e.displayType?"mp4":"png",title:`Download ${e.displayType}`})},onUse:e=>{te(e),ue("studio"),xe(!1)}}):0===ve.length?(0,_.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No gallery items match this filter."}):"inspect"===C&&ye?(0,_.jsx)(le,{output:ye}):"compare"===C?(0,_.jsxs)("div",{"data-testid":"gallery-compare-view",className:"grid gap-2",children:[(0,_.jsx)("div",{className:"grid gap-2 sm:grid-cols-2",children:ke.slice(0,2).map(e=>(0,_.jsx)(ne,{output:e},`compare-${e.id}`))}),we&&Ne&&(0,_.jsx)(de,{left:we,right:Ne})]}):"lineage"===C?(0,_.jsx)("div",{"data-testid":"gallery-lineage-view",className:"grid gap-2",children:O.slice(0,24).map(e=>(0,_.jsx)(ce,{output:e,onClick:()=>{L([e.id]),I("inspect")}},`lineage-full-${e.id}`))}):(0,_.jsx)("div",{className:"grid gap-2",children:ve.map((e,a)=>{let s=ve[a+1],i=z.includes(e.id);return(0,_.jsxs)("article",{"data-testid":`gallery-output-${a}`,className:k("border bg-modiff-surface",i?"border-hf-yellow":"border-modiff-border"),children:[(0,_.jsx)(ee,{output:e,maxHeight:420,onImageClick:()=>{L([e.id]),I("inspect")}}),(0,_.jsxs)("div",{className:"p-2",children:[(0,_.jsx)(oe,{output:e}),(0,_.jsx)("p",{className:"mt-1 max-h-10 overflow-hidden text-sm text-modiff-text",children:e.prompt||"No prompt recorded"}),(0,_.jsxs)("div",{className:"mt-2 flex flex-wrap gap-1",children:[(0,_.jsx)(re,{title:X(e)?"Inspect audio":Z(e)?"Inspect video":"Open full size","data-testid":`gallery-open-${a}`,onClick:()=>{Z(e)||X(e)?(L([e.id]),I("inspect")):fe(q([e.url]))},children:(0,_.jsx)(n,{size:15})}),(0,_.jsx)(re,{title:"Compare with previous visible item",disabled:!s||Z(e)||X(e)||!!s&&(Z(s)||X(s)),"data-testid":`gallery-compare-${a}`,onClick:()=>s&&fe(q([s.url,e.url],1)),children:(0,_.jsx)(n,{size:15})}),(0,_.jsx)(A,{className:"h-7 px-2 text-xs",tone:i?"primary":"secondary",onClick:()=>(e=>{L(t=>t.includes(e.id)?t.filter(t=>t!==e.id):[e.id,...t].slice(0,2))})(e),children:"Select"}),(0,_.jsx)(re,{title:"Favorite","data-testid":`gallery-favorite-${a}`,onClick:()=>B(e.id),children:(0,_.jsx)(l,{size:15,className:e.favorite?"fill-hf-yellow text-hf-yellow":void 0})}),(0,_.jsx)(re,{title:X(e)?"Download audio":Z(e)?"Download video":"Download image","data-testid":`gallery-download-image-${a}`,onClick:()=>{let t=X(e)?"audio":Z(e)?"video":"image";he({source:e.url,filename:`modiff-${e.modelType}-${e.id}${"audio"===t?".wav":"video"===t?".mp4":".png"}`,kind:t,defaultFormat:"audio"===t?"wav":"video"===t?"mp4":"png",title:`Download ${t}`})},children:(0,_.jsx)(f,{size:15})}),(0,_.jsx)(re,{title:"Download metadata package","data-testid":`gallery-download-package-${a}`,onClick:()=>K(e),children:(0,_.jsx)(f,{size:15})}),!Z(e)&&!X(e)&&(0,_.jsx)(re,{title:"Download PNG package","data-testid":`gallery-download-png-package-${a}`,onClick:()=>{Y(e).then(()=>N("PNG package exported",{variant:"success",autoHideDuration:1800})).catch(e=>N(String(e),{variant:"error",autoHideDuration:6e3}))},children:(0,_.jsx)(f,{size:15})}),(0,_.jsx)(re,{title:"Restore workflow","data-testid":`gallery-restore-${a}`,onClick:()=>(e=>{ae(e),ue("studio"),xe(!1),N("Workflow restored from gallery item",{variant:"success",autoHideDuration:2200})})(e),children:(0,_.jsx)(t,{size:15})}),(0,_.jsx)(re,{title:"Rerun this workflow","data-testid":`gallery-rerun-${a}`,onClick:()=>{(async e=>{if(!ge||!be)return void N("Connect to the MoDiff server before rerunning.",{variant:"error",autoHideDuration:4e3});ae(e);let t=j();try{if(!await b(t))return;await R({sid:ge,studioContext:{},workflowContext:t}),xe(!1),pe(!0),ue("queue")}catch(e){if(S(e))return;N(String(e),{variant:"error",autoHideDuration:7e3})}})(e)},children:(0,_.jsx)(x,{size:15})}),(0,_.jsx)(re,{title:"Send to edit","data-testid":`gallery-send-edit-${a}`,onClick:()=>{Q(e),ue("studio"),xe(!1)},children:(0,_.jsx)(h,{size:15})}),(0,_.jsx)(re,{title:"Copy metadata","data-testid":`gallery-copy-metadata-${a}`,onClick:()=>function(e){navigator.clipboard.writeText(JSON.stringify(e,null,2)),N("Metadata copied",{variant:"success",autoHideDuration:1800})}(e),children:(0,_.jsx)(p,{size:15})}),(0,_.jsx)(re,{title:"Delete record","data-testid":`gallery-delete-${a}`,onClick:()=>W(e.id),children:(0,_.jsx)(g,{size:15})})]})]})]},e.id)})}),"generated"===Ce?(0,_.jsxs)("div",{className:"mt-4",children:[(0,_.jsx)("h2",{className:"mb-2 text-sm font-bold text-modiff-text",children:"Version tree"}),(0,_.jsx)("div",{className:"grid gap-1",children:O.slice(0,12).map(e=>(0,_.jsx)(ce,{output:e,onClick:()=>{Z(e)||X(e)?(L([e.id]),I("inspect")):fe(q([e.url]))}},`lineage-${e.id}`))})]}):null]})}function ae({asset:e}){return"audio"===e.displayType?(0,_.jsx)("div",{className:"grid min-h-24 w-full place-items-center border border-modiff-border bg-modiff-surface p-3",children:(0,_.jsx)("audio",{src:e.url,controls:!0,className:"w-full"})}):"video"===e.displayType?(0,_.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",className:"block aspect-video w-full border border-modiff-border bg-modiff-media-backdrop object-contain"}):(0,_.jsx)(M,{src:e.url,alt:e.name,aspectRatio:"1 / 1",maxHeight:320,bordered:!1})}function se({assets:e,onDelete:t,onDownload:a,onUse:s}){return 0===e.length?(0,_.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-xs text-modiff-subtle-text",children:"No imported media yet."}):(0,_.jsx)("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-3","data-testid":"gallery-imported-grid",children:e.map((e,i)=>(0,_.jsxs)("article",{className:"overflow-hidden border border-modiff-border bg-modiff-surface","data-testid":`gallery-imported-${i}`,children:[(0,_.jsx)(ae,{asset:e}),(0,_.jsxs)("div",{className:"flex items-center justify-between gap-2 p-2",children:[(0,_.jsxs)("div",{className:"min-w-0",children:[(0,_.jsx)("p",{className:"truncate text-sm font-semibold text-modiff-text",children:e.name}),(0,_.jsxs)("p",{className:"flex min-w-0 items-center gap-1 text-xs text-modiff-subtle-text",children:[(0,_.jsx)("span",{children:e.displayType}),(0,_.jsx)(ie,{active:"backend"===e.storage,"data-testid":`gallery-imported-storage-${i}`,title:"backend"===e.storage?e.backendPath??"Stored through backend":"Stored in this browser",children:"backend"===e.storage?"Backend":"Local"})]})]}),(0,_.jsxs)("div",{className:"flex shrink-0 gap-1",children:[(0,_.jsx)(re,{title:"Use as input","data-testid":`gallery-imported-use-${i}`,onClick:()=>s(e),children:(0,_.jsx)(h,{size:15})}),(0,_.jsx)(re,{title:"Download asset","data-testid":`gallery-imported-download-${i}`,onClick:()=>a(e),children:(0,_.jsx)(f,{size:15})}),(0,_.jsx)(re,{title:"Remove imported asset","data-testid":`gallery-imported-delete-${i}`,onClick:()=>t(e.id),children:(0,_.jsx)(g,{size:15})})]})]})]},e.id))})}function ie({active:e,children:t,error:a=!1,icon:s,onClick:i,...r}){let o="inline-flex items-center gap-1 rounded-modiff-compact px-2 text-xs font-semibold";return i?(0,_.jsxs)(F,{active:e,tone:a?"error":"default",className:k(o,"min-h-7"),onClick:i,...r,children:[s,t]}):(0,_.jsxs)(V,{className:k(o,"min-h-6"),tone:a?"error":e?"success":"default",...r,children:[s,t]})}function re({children:e,className:t,title:a,...s}){return(0,_.jsx)(z,{label:a,size:"compact",className:k("text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",t),...s,children:e})}function oe({output:e}){return(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:Q(e)}),(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:[new Date(e.createdAt).toLocaleString()," | Run ",e.runId||"untracked"," | Task"," ",e.taskId||"untracked"]}),e.backendImagePath&&(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Stored: ",e.backendImagePath]}),e.backendMediaPath&&(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Stored: ",e.backendMediaPath]}),e.mediaItems&&e.mediaItems.length>1&&(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Media items: ",e.mediaItems.length," | Hash: ",e.mediaCollectionHash||e.mediaHash||"pending"]}),e.variationGroupId&&(0,_.jsxs)("p",{className:"break-all text-xs text-hf-orange",children:["Sweep: ",e.variationLabel||"Variant"," | ",e.variationGroupId]}),(e.sourceOutputId||e.referenceImages.length>0)&&(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Source: ",e.sourceOutputId||e.referenceImages.join(", ")]})]})}function le({output:e}){let t=Z(e)?{requestedSize:`${e.formSnapshot.width}x${e.formSnapshot.height}`,requestedNumFrames:e.formSnapshot.numFrames,requestedFps:e.formSnapshot.fps,resolvedSize:e.resolvedExecutionInputs?`${E(e,"width")}x${E(e,"height")}`:void 0,encodedVideo:L(e)}:{size:W(e)??"Not captured",resolvedInputDimensions:{width:E(e,"width"),height:E(e,"height")}};return(0,_.jsxs)("article",{"data-testid":"gallery-inspect-view",className:"border border-modiff-border bg-modiff-surface",children:[(0,_.jsx)(ee,{output:e,maxHeight:460}),(0,_.jsxs)("div",{className:"p-2",children:[(0,_.jsx)("h2",{className:"text-sm font-bold text-modiff-text",children:Q(e)}),(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:[new Date(e.createdAt).toLocaleString()," | Run ",e.runId||"untracked"," | Task"," ",e.taskId||"untracked"]}),(0,_.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Repo: ",e.repo," | Node: ",e.nodeId,":",e.fieldKey]}),(0,_.jsx)("p",{className:"mt-2 text-sm text-modiff-text",children:e.prompt||"No prompt recorded"}),(0,_.jsx)("p",{className:"mt-2 text-xs text-modiff-subtle-text","data-testid":"resolved-inputs-status",children:e.resolvedExecutionInputs?"Resolved node inputs captured by the backend. Connected values take precedence over saved field fallbacks. These are call arguments, not inferred library defaults.":"Legacy form/graph settings only: resolved node inputs were not captured for this output."}),(0,_.jsx)("pre",{className:"mt-2 max-h-80 overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 font-mono text-xs text-modiff-subtle-text",children:JSON.stringify({seed:E(e,"seed"),...t,steps:E(e,"steps"),guidanceScale:E(e,"guidanceScale"),resolvedExecutionInputs:e.resolvedExecutionInputs,templateLockHash:e.templateLockHash,promptSettingsHash:e.promptSettingsHash,exactTemplateCompatible:e.exactTemplateCompatible,mediaHash:e.mediaHash,mediaCollectionHash:e.mediaCollectionHash,mediaItems:e.mediaItems,variationGroupId:e.variationGroupId,variationLabel:e.variationLabel,provenance:e.provenance,sourceOutputId:e.sourceOutputId,referenceImages:e.referenceImages,sourceVideo:e.formSnapshot.sourceVideo,maskVideo:e.formSnapshot.maskVideo,controlVideo:e.formSnapshot.controlVideo,sourceAudio:e.formSnapshot.sourceAudio,referenceAudio:e.formSnapshot.referenceAudio,audioDuration:e.formSnapshot.audioDuration,numFrames:E(e,"numFrames"),fps:E(e,"fps"),backendImagePath:e.backendImagePath,backendMediaPath:e.backendMediaPath},null,2)})]})]})}function de({left:e,right:t}){let a=[["Prompt",e.prompt||"No prompt",t.prompt||"No prompt"],["Seed",String(E(e,"seed")),String(E(t,"seed"))],["Model",e.modelLabel,t.modelLabel],["Steps",String(E(e,"steps")),String(E(t,"steps"))],["Guidance",String(E(e,"guidanceScale")),String(E(t,"guidanceScale"))],["Size",`${E(e,"width")}x${E(e,"height")}`,`${E(t,"width")}x${E(t,"height")}`],["Template",e.templateLabel||"Manual",t.templateLabel||"Manual"],["Source",e.sourceOutputId||e.referenceImages.join(", ")||"None",t.sourceOutputId||t.referenceImages.join(", ")||"None"]];return(0,_.jsxs)("article",{className:"border border-modiff-border bg-modiff-surface p-2",children:[(0,_.jsx)("h3",{className:"mb-2 text-sm font-bold text-modiff-text",children:"Settings diff"}),(0,_.jsx)("div",{className:"grid gap-1",children:a.map(([e,t,a])=>(0,_.jsxs)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2 text-xs sm:grid-cols-[90px_1fr_1fr]",children:[(0,_.jsx)("span",{className:t===a?"font-semibold text-modiff-subtle-text":"font-semibold text-hf-orange",children:e}),(0,_.jsx)("span",{className:"min-w-0 break-words text-modiff-subtle-text",children:t}),(0,_.jsx)("span",{className:"min-w-0 break-words text-modiff-subtle-text",children:a})]},e))})]})}function ne({output:e}){return(0,_.jsxs)("article",{className:"border border-modiff-border bg-modiff-surface",children:[(0,_.jsx)(ee,{output:e,aspectRatio:"1 / 1"}),(0,_.jsxs)("div",{className:"p-2",children:[(0,_.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:Q(e)}),e.variationGroupId&&(0,_.jsxs)("p",{className:"text-xs text-hf-orange",children:[e.variationLabel||"Sweep variant"," | ",e.variationGroupId]}),(0,_.jsx)("p",{className:"max-h-16 overflow-hidden text-sm text-modiff-text",children:e.prompt})]})]})}function ce({output:e,onClick:t}){return(0,_.jsxs)(A,{tone:"ghost",align:"left",size:"compact",className:"h-auto border border-transparent px-2 py-1 text-xs text-modiff-subtle-text hover:border-modiff-border",onClick:t,children:[e.variationGroupId?"Sweep":e.parentId?"Branch":"Root"," |"," ",e.variationLabel||e.modelLabel," | ",new Date(e.createdAt).toLocaleString()," |"," ",e.prompt||e.id]})}function me(){let e=$(e=>e.galleryLibraryOpen),t=$(e=>e.setGalleryLibraryOpen);return(0,_.jsx)(O,{open:e,onClose:()=>t(!1),title:(0,_.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-2",children:[(0,_.jsx)(a,{size:17,className:"text-hf-yellow"}),(0,_.jsx)("span",{className:"truncate",children:"Output Gallery"})]}),panelClassName:"max-w-[1180px]",bodyClassName:"max-h-[76vh] p-0",children:(0,_.jsx)(te,{modalView:!0})})}export{me as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$ as t,Ft as a,P as s,Pt as i,Rn as r,Ut as o,Vt as l,Wt as d,Y as n,cr as c,dr as m,pn as p,rt as u,st as x,un as f,ut as h,z as g}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ai as b,An as j,Ca as v,G as k,K as y,Ln as w,Ni as N,Oi as S,Po as $,Sa as C,U as I,Va as D,W as L,Yn as z,an as H,ar as T,ba as O,cn as R,er as G,gr as P,in as A,mn as F,na as M,oa as V,on as E,un as q,wa as B,xa as W,yt as U}from"./studio-templates.js?v=ca6b74e6a02eedb3";var _=e(m(),1),J=c();function K(e){L(`modiff-${e.modelType}-${e.id}-workflow.json`,I(e))}async function Y(e){await k(`modiff-${e.modelType}-${e.id}-workflow.png`,e.url,I(e))}function Q(e){let t=e.templateLabel?` | ${e.templateLabel}`:"",a=e.mediaItems?.find(e=>e.durationSeconds)?.durationSeconds??(e.resolvedExecutionInputs?void 0:e.formSnapshot.audioDuration),s=W(e),i=v(e,"seed"),r=X(e)?" | "+(a?`${a.toFixed(1)} sec`:"audio"):Z(e)?` | ${V(e)}`:` | ${s||"image"}`;return`${e.modelLabel}${t} | ${D[e.mode]}${r} | ${void 0===i?"Seed not captured":`Seed ${i}`}`}function X(e){return"audio"===e.displayType||/\.(wav|mp3|flac|ogg|m4a|aac)(\?.*)?$/i.test(e.url)}function Z(e){return"video"===e.displayType||/\.(mp4|webm|mov|mkv|m4v)(\?.*)?$/i.test(e.url)}function ee({output:e,aspectRatio:t,maxHeight:a,onImageClick:s}){return X(e)?(0,J.jsx)("div",{className:w("grid min-h-24 w-full place-items-center border border-modiff-border bg-modiff-surface p-3","1 / 1"===t&&"aspect-square"),children:(0,J.jsx)("audio",{src:e.url,controls:!0,className:"w-full"})}):Z(e)?(0,J.jsx)("div",{className:w("border border-transparent bg-modiff-surface","1 / 1"===t&&"aspect-square"),children:(0,J.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",className:w("block h-full w-full bg-modiff-media-backdrop object-contain",!!a&&"max-h-[460px]")})}):e.mediaItems&&e.mediaItems.length>1&&"image_collection"===e.displayType?(0,J.jsx)("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(96px,1fr))] gap-1 bg-modiff-surface",children:e.mediaItems.slice(0,12).map(i=>(0,J.jsx)(j,{src:i.url,alt:i.label||`${e.id} item ${i.index+1}`,onClick:s,aspectRatio:t??"1 / 1",maxHeight:a,bordered:!1},`${i.index}-${i.url}`))}):(0,J.jsx)(j,{src:e.url,alt:e.prompt||e.id,onClick:s,aspectRatio:t,maxHeight:a,bordered:!1})}function te({modalView:e=!1}){let[a,c]=(0,_.useState)("generated"),[m,j]=(0,_.useState)("all"),[v,k]=(0,_.useState)("grid"),[I,D]=(0,_.useState)([]),L=(0,_.useRef)(null),H=N(e=>e.outputs),O=N(e=>e.importedAssets),R=N(e=>e.galleryBackendStatus),M=N(e=>e.galleryBackendError),V=N(e=>e.fetchBackendOutputs),E=N(e=>e.toggleFavoriteOutput),q=N(e=>e.deleteOutput),W=N(e=>e.deleteImportedAsset),Q=N(e=>e.useOutputAsReference),te=N(e=>e.useImportedAssetAsReference),ae=N(e=>e.restoreWorkflowFromOutput),me=N(e=>e.createWorkflowTab),pe=B(e=>e.setRightPanelOpen),ue=B(e=>e.setRightPanelTab),xe=B(e=>e.setGalleryLibraryOpen),fe=B(e=>e.setLightboxOpener),he=B(e=>e.setMediaExportOpener),ge=z(e=>e.sid),be=z(e=>e.isConnected),je=(0,_.useMemo)(()=>{let e=new Map;return H.forEach(t=>e.set(C(t),t.modelLabel)),Array.from(e.entries())},[H]),ve=(0,_.useMemo)(()=>"favorites"===m?H.filter(e=>e.favorite):"all"===m?H:H.filter(e=>`model:${C(e)}`===m),[m,H]),ke=(0,_.useMemo)(()=>{let e=I.map(e=>ve.find(t=>t.id===e)).filter(e=>!!e);return e.length>0?e:ve.slice(0,2)},[ve,I]),ye=ke[0]??ve[0],we=ke[0],Ne=ke[1],Se=(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(F,{ref:L,"aria-label":"Import workflow package",accept:"application/json,.json,image/png,.png",className:"sr-only","data-testid":"gallery-import-workflow-input",onChange:e=>{let t=e.currentTarget.files?.[0];e.currentTarget.value="",(async e=>{if(e)try{let t=await y(e);if(!t)throw Error("No MoDiff workflow metadata was found in that file.");me(t.title,t.snapshot,"import",t.sourceLabel),ue("studio"),xe(!1),$("Workflow package imported",{variant:"success",autoHideDuration:2200}),window.setTimeout(()=>P({sid:ge,isConnected:be,includeStudio:!0,showDialog:!0}),0)}catch(e){$(String(e),{variant:"error",autoHideDuration:6e3})}})(t)}}),(0,J.jsx)(re,{title:"Import workflow package","data-testid":"gallery-import-workflow",onClick:()=>L.current?.click(),children:(0,J.jsx)(s,{size:15})})]}),$e="idle"===R?"Backend history":"syncing"===R?"Syncing history":"loading"===R?"Loading history":"History offline",Ce="generated"===a&&0===H.length&&O.length>0?"imported":a;return 0===H.length&&0===O.length?(0,J.jsxs)("section",{className:w("p-3",e&&"min-h-[520px]"),"data-testid":"gallery-panel",children:[(0,J.jsxs)("div",{className:"mb-1 flex items-center gap-2",children:[(0,J.jsx)("h2",{className:"text-sm font-bold text-modiff-text",children:"Gallery"}),(0,J.jsx)(ie,{active:"error"!==R,error:"error"===R,"data-testid":"gallery-backend-status",children:$e}),(0,J.jsx)(re,{title:"Refresh history","data-testid":"gallery-refresh-history",onClick:()=>{V()},children:(0,J.jsx)(u,{size:15})}),Se]}),(0,J.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Generated and imported media appear here."}),M&&(0,J.jsx)("p",{className:"mt-1 text-xs text-modiff-red",children:M})]}):(0,J.jsxs)("section",{className:w("p-3",e&&"min-h-[520px]"),"data-testid":"gallery-panel",children:[(0,J.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,J.jsx)(ie,{active:"error"!==R,error:"error"===R,"data-testid":"gallery-backend-status",children:$e}),(0,J.jsx)(re,{title:"Refresh history","data-testid":"gallery-refresh-history",onClick:()=>{V()},children:(0,J.jsx)(u,{size:15})}),Se,(0,J.jsxs)(ie,{active:"generated"===Ce,onClick:()=>c("generated"),"data-testid":"gallery-kind-generated",children:["Generated ",H.length]}),(0,J.jsxs)(ie,{active:"imported"===Ce,onClick:()=>c("imported"),"data-testid":"gallery-kind-imported",children:["Imported ",O.length]}),"generated"===Ce?(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)(ie,{active:"all"===m,onClick:()=>j("all"),"data-testid":"gallery-filter-all",children:"All"}),(0,J.jsx)(ie,{active:"favorites"===m,onClick:()=>j("favorites"),"data-testid":"gallery-filter-favorites",children:"Favorites"}),je.map(([e,t])=>(0,J.jsx)(ie,{active:m===`model:${e}`,onClick:()=>j(`model:${e}`),"data-testid":`gallery-filter-${e}`,children:t},e))]}):null]}),"generated"===Ce?(0,J.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,J.jsx)(ie,{active:"grid"===v,onClick:()=>k("grid"),"data-testid":"gallery-view-grid",icon:(0,J.jsx)(o,{size:14}),children:"Grid"}),(0,J.jsx)(ie,{active:"inspect"===v,onClick:()=>k("inspect"),"data-testid":"gallery-view-inspect",icon:(0,J.jsx)(i,{size:14}),children:"Inspect"}),(0,J.jsx)(ie,{active:"compare"===v,onClick:()=>k("compare"),"data-testid":"gallery-view-compare",icon:(0,J.jsx)(r,{size:14}),children:"Compare"}),(0,J.jsx)(ie,{active:"lineage"===v,onClick:()=>k("lineage"),"data-testid":"gallery-view-lineage",icon:(0,J.jsx)(d,{size:14}),children:"Lineage"})]}):null,M&&(0,J.jsx)("p",{className:"mb-2 text-xs text-modiff-red",children:M}),"imported"===Ce?(0,J.jsx)(se,{assets:O,onDelete:W,onDownload:e=>{if("unknown"===e.displayType){let t=document.createElement("a");return t.href=e.url,t.download=e.name,t.rel="noopener noreferrer",document.body.append(t),t.click(),void t.remove()}he({source:e.url,filename:e.name,kind:e.displayType,defaultFormat:"audio"===e.displayType?"wav":"video"===e.displayType?"mp4":"png",title:`Download ${e.displayType}`})},onUse:e=>{te(e),ue("studio"),xe(!1)}}):0===ve.length?(0,J.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No gallery items match this filter."}):"inspect"===v&&ye?(0,J.jsx)(le,{output:ye}):"compare"===v?(0,J.jsxs)("div",{"data-testid":"gallery-compare-view",className:"grid gap-2",children:[(0,J.jsx)("div",{className:"grid gap-2 sm:grid-cols-2",children:ke.slice(0,2).map(e=>(0,J.jsx)(ne,{output:e},`compare-${e.id}`))}),we&&Ne&&(0,J.jsx)(de,{left:we,right:Ne})]}):"lineage"===v?(0,J.jsx)("div",{"data-testid":"gallery-lineage-view",className:"grid gap-2",children:H.slice(0,24).map(e=>(0,J.jsx)(ce,{output:e,onClick:()=>{D([e.id]),k("inspect")}},`lineage-full-${e.id}`))}):(0,J.jsx)("div",{className:"grid gap-2",children:ve.map((e,a)=>{let s=ve[a+1],i=I.includes(e.id);return(0,J.jsxs)("article",{"data-testid":`gallery-output-${a}`,className:w("border bg-modiff-surface",i?"border-hf-yellow":"border-modiff-border"),children:[(0,J.jsx)(ee,{output:e,maxHeight:420,onImageClick:()=>{D([e.id]),k("inspect")}}),(0,J.jsxs)("div",{className:"p-2",children:[(0,J.jsx)(oe,{output:e}),(0,J.jsx)("p",{className:"mt-1 max-h-10 overflow-hidden text-sm text-modiff-text",children:e.prompt||"No prompt recorded"}),(0,J.jsxs)("div",{className:"mt-2 flex flex-wrap gap-1",children:[(0,J.jsx)(re,{title:X(e)?"Inspect audio":Z(e)?"Inspect video":"Open full size","data-testid":`gallery-open-${a}`,onClick:()=>{Z(e)||X(e)?(D([e.id]),k("inspect")):fe(U([e.url]))},children:(0,J.jsx)(n,{size:15})}),(0,J.jsx)(re,{title:"Compare with previous visible item",disabled:!s||Z(e)||X(e)||!!s&&(Z(s)||X(s)),"data-testid":`gallery-compare-${a}`,onClick:()=>s&&fe(U([s.url,e.url],1)),children:(0,J.jsx)(n,{size:15})}),(0,J.jsx)(A,{className:"h-7 px-2 text-xs",tone:i?"primary":"secondary",onClick:()=>(e=>{D(t=>t.includes(e.id)?t.filter(t=>t!==e.id):[e.id,...t].slice(0,2))})(e),children:"Select"}),(0,J.jsx)(re,{title:"Favorite","data-testid":`gallery-favorite-${a}`,onClick:()=>E(e.id),children:(0,J.jsx)(l,{size:15,className:e.favorite?"fill-hf-yellow text-hf-yellow":void 0})}),(0,J.jsx)(re,{title:X(e)?"Download audio":Z(e)?"Download video":"Download image","data-testid":`gallery-download-image-${a}`,onClick:()=>{let t=X(e)?"audio":Z(e)?"video":"image";he({source:e.url,filename:`modiff-${e.modelType}-${e.id}${"audio"===t?".wav":"video"===t?".mp4":".png"}`,kind:t,defaultFormat:"audio"===t?"wav":"video"===t?"mp4":"png",title:`Download ${t}`})},children:(0,J.jsx)(f,{size:15})}),(0,J.jsx)(re,{title:"Download metadata package","data-testid":`gallery-download-package-${a}`,onClick:()=>K(e),children:(0,J.jsx)(f,{size:15})}),!Z(e)&&!X(e)&&(0,J.jsx)(re,{title:"Download PNG package","data-testid":`gallery-download-png-package-${a}`,onClick:()=>{Y(e).then(()=>$("PNG package exported",{variant:"success",autoHideDuration:1800})).catch(e=>$(String(e),{variant:"error",autoHideDuration:6e3}))},children:(0,J.jsx)(f,{size:15})}),(0,J.jsx)(re,{title:"Restore workflow","data-testid":`gallery-restore-${a}`,onClick:()=>(e=>{ae(e),ue("studio"),xe(!1),$("Workflow restored from gallery item",{variant:"success",autoHideDuration:2200})})(e),children:(0,J.jsx)(t,{size:15})}),(0,J.jsx)(re,{title:"Rerun this workflow","data-testid":`gallery-rerun-${a}`,onClick:()=>{(async e=>{if(!ge||!be)return void $("Connect to the MoDiff server before rerunning.",{variant:"error",autoHideDuration:4e3});ae(e);let t=S();try{if(!await G(t))return;await T({sid:ge,studioContext:{},workflowContext:t}),xe(!1),pe(!0),ue("queue")}catch(e){if(b(e))return;$(String(e),{variant:"error",autoHideDuration:7e3})}})(e)},children:(0,J.jsx)(x,{size:15})}),(0,J.jsx)(re,{title:"Send to edit","data-testid":`gallery-send-edit-${a}`,onClick:()=>{Q(e),ue("studio"),xe(!1)},children:(0,J.jsx)(h,{size:15})}),(0,J.jsx)(re,{title:"Copy metadata","data-testid":`gallery-copy-metadata-${a}`,onClick:()=>function(e){navigator.clipboard.writeText(JSON.stringify(e,null,2)),$("Metadata copied",{variant:"success",autoHideDuration:1800})}(e),children:(0,J.jsx)(p,{size:15})}),(0,J.jsx)(re,{title:"Delete record","data-testid":`gallery-delete-${a}`,onClick:()=>q(e.id),children:(0,J.jsx)(g,{size:15})})]})]})]},e.id)})}),"generated"===Ce?(0,J.jsxs)("div",{className:"mt-4",children:[(0,J.jsx)("h2",{className:"mb-2 text-sm font-bold text-modiff-text",children:"Version tree"}),(0,J.jsx)("div",{className:"grid gap-1",children:H.slice(0,12).map(e=>(0,J.jsx)(ce,{output:e,onClick:()=>{Z(e)||X(e)?(D([e.id]),k("inspect")):fe(U([e.url]))}},`lineage-${e.id}`))})]}):null]})}function ae({asset:e}){return"audio"===e.displayType?(0,J.jsx)("div",{className:"grid min-h-24 w-full place-items-center border border-modiff-border bg-modiff-surface p-3",children:(0,J.jsx)("audio",{src:e.url,controls:!0,className:"w-full"})}):"video"===e.displayType?(0,J.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",className:"block aspect-video w-full border border-modiff-border bg-modiff-media-backdrop object-contain"}):(0,J.jsx)(j,{src:e.url,alt:e.name,aspectRatio:"1 / 1",maxHeight:320,bordered:!1})}function se({assets:e,onDelete:t,onDownload:a,onUse:s}){return 0===e.length?(0,J.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-xs text-modiff-subtle-text",children:"No imported media yet."}):(0,J.jsx)("div",{className:"grid gap-2 sm:grid-cols-2 xl:grid-cols-3","data-testid":"gallery-imported-grid",children:e.map((e,i)=>(0,J.jsxs)("article",{className:"overflow-hidden border border-modiff-border bg-modiff-surface","data-testid":`gallery-imported-${i}`,children:[(0,J.jsx)(ae,{asset:e}),(0,J.jsxs)("div",{className:"flex items-center justify-between gap-2 p-2",children:[(0,J.jsxs)("div",{className:"min-w-0",children:[(0,J.jsx)("p",{className:"truncate text-sm font-semibold text-modiff-text",children:e.name}),(0,J.jsxs)("p",{className:"flex min-w-0 items-center gap-1 text-xs text-modiff-subtle-text",children:[(0,J.jsx)("span",{children:e.displayType}),(0,J.jsx)(ie,{active:"backend"===e.storage,"data-testid":`gallery-imported-storage-${i}`,title:"backend"===e.storage?e.backendPath??"Stored through backend":"Stored in this browser",children:"backend"===e.storage?"Backend":"Local"})]})]}),(0,J.jsxs)("div",{className:"flex shrink-0 gap-1",children:[(0,J.jsx)(re,{title:"Use as input","data-testid":`gallery-imported-use-${i}`,onClick:()=>s(e),children:(0,J.jsx)(h,{size:15})}),(0,J.jsx)(re,{title:"Download asset","data-testid":`gallery-imported-download-${i}`,onClick:()=>a(e),children:(0,J.jsx)(f,{size:15})}),(0,J.jsx)(re,{title:"Remove imported asset","data-testid":`gallery-imported-delete-${i}`,onClick:()=>t(e.id),children:(0,J.jsx)(g,{size:15})})]})]})]},e.id))})}function ie({active:e,children:t,error:a=!1,icon:s,onClick:i,...r}){let o="inline-flex items-center gap-1 rounded-modiff-compact px-2 text-xs font-semibold";return i?(0,J.jsxs)(q,{active:e,tone:a?"error":"default",className:w(o,"min-h-7"),onClick:i,...r,children:[s,t]}):(0,J.jsxs)(R,{className:w(o,"min-h-6"),tone:a?"error":e?"success":"default",...r,children:[s,t]})}function re({children:e,className:t,title:a,...s}){return(0,J.jsx)(E,{label:a,size:"compact",className:w("text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",t),...s,children:e})}function oe({output:e}){return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:Q(e)}),(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:[new Date(e.createdAt).toLocaleString()," | Run ",e.runId||"untracked"," | Task"," ",e.taskId||"untracked"]}),e.backendImagePath&&(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Stored: ",e.backendImagePath]}),e.backendMediaPath&&(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Stored: ",e.backendMediaPath]}),e.mediaItems&&e.mediaItems.length>1&&(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Media items: ",e.mediaItems.length," | Hash: ",e.mediaCollectionHash||e.mediaHash||"pending"]}),e.variationGroupId&&(0,J.jsxs)("p",{className:"break-all text-xs text-hf-orange",children:["Sweep: ",e.variationLabel||"Variant"," | ",e.variationGroupId]}),(e.sourceOutputId||e.referenceImages.length>0)&&(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Source: ",e.sourceOutputId||e.referenceImages.join(", ")]})]})}function le({output:e}){let t=Z(e)?{requestedSize:`${e.formSnapshot.width}x${e.formSnapshot.height}`,requestedNumFrames:e.formSnapshot.numFrames,requestedFps:e.formSnapshot.fps,resolvedSize:e.resolvedExecutionInputs?`${O(e,"width")}x${O(e,"height")}`:void 0,encodedVideo:M(e)}:{size:W(e)??"Not captured",resolvedInputDimensions:{width:O(e,"width"),height:O(e,"height")}};return(0,J.jsxs)("article",{"data-testid":"gallery-inspect-view",className:"border border-modiff-border bg-modiff-surface",children:[(0,J.jsx)(ee,{output:e,maxHeight:460}),(0,J.jsxs)("div",{className:"p-2",children:[(0,J.jsx)("h2",{className:"text-sm font-bold text-modiff-text",children:Q(e)}),(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:[new Date(e.createdAt).toLocaleString()," | Run ",e.runId||"untracked"," | Task"," ",e.taskId||"untracked"]}),(0,J.jsxs)("p",{className:"break-all text-xs text-modiff-subtle-text",children:["Repo: ",e.repo," | Node: ",e.nodeId,":",e.fieldKey]}),(0,J.jsx)("p",{className:"mt-2 text-sm text-modiff-text",children:e.prompt||"No prompt recorded"}),(0,J.jsx)("p",{className:"mt-2 text-xs text-modiff-subtle-text","data-testid":"resolved-inputs-status",children:e.resolvedExecutionInputs?"Resolved node inputs captured by the backend. Connected values take precedence over saved field fallbacks. These are call arguments, not inferred library defaults.":"Legacy form/graph settings only: resolved node inputs were not captured for this output."}),(0,J.jsx)("pre",{className:"mt-2 max-h-80 overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 font-mono text-xs text-modiff-subtle-text",children:JSON.stringify({seed:O(e,"seed"),...t,steps:O(e,"steps"),guidanceScale:O(e,"guidanceScale"),resolvedExecutionInputs:e.resolvedExecutionInputs,templateLockHash:e.templateLockHash,promptSettingsHash:e.promptSettingsHash,exactTemplateCompatible:e.exactTemplateCompatible,mediaHash:e.mediaHash,mediaCollectionHash:e.mediaCollectionHash,mediaItems:e.mediaItems,variationGroupId:e.variationGroupId,variationLabel:e.variationLabel,provenance:e.provenance,sourceOutputId:e.sourceOutputId,referenceImages:e.referenceImages,sourceVideo:e.formSnapshot.sourceVideo,maskVideo:e.formSnapshot.maskVideo,controlVideo:e.formSnapshot.controlVideo,sourceAudio:e.formSnapshot.sourceAudio,referenceAudio:e.formSnapshot.referenceAudio,audioDuration:e.formSnapshot.audioDuration,numFrames:O(e,"numFrames"),fps:O(e,"fps"),backendImagePath:e.backendImagePath,backendMediaPath:e.backendMediaPath},null,2)})]})]})}function de({left:e,right:t}){let a=[["Prompt",e.prompt||"No prompt",t.prompt||"No prompt"],["Seed",String(O(e,"seed")),String(O(t,"seed"))],["Model",e.modelLabel,t.modelLabel],["Steps",String(O(e,"steps")),String(O(t,"steps"))],["Guidance",String(O(e,"guidanceScale")),String(O(t,"guidanceScale"))],["Size",`${O(e,"width")}x${O(e,"height")}`,`${O(t,"width")}x${O(t,"height")}`],["Template",e.templateLabel||"Manual",t.templateLabel||"Manual"],["Source",e.sourceOutputId||e.referenceImages.join(", ")||"None",t.sourceOutputId||t.referenceImages.join(", ")||"None"]];return(0,J.jsxs)("article",{className:"border border-modiff-border bg-modiff-surface p-2",children:[(0,J.jsx)("h3",{className:"mb-2 text-sm font-bold text-modiff-text",children:"Settings diff"}),(0,J.jsx)("div",{className:"grid gap-1",children:a.map(([e,t,a])=>(0,J.jsxs)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2 text-xs sm:grid-cols-[90px_1fr_1fr]",children:[(0,J.jsx)("span",{className:t===a?"font-semibold text-modiff-subtle-text":"font-semibold text-hf-orange",children:e}),(0,J.jsx)("span",{className:"min-w-0 break-words text-modiff-subtle-text",children:t}),(0,J.jsx)("span",{className:"min-w-0 break-words text-modiff-subtle-text",children:a})]},e))})]})}function ne({output:e}){return(0,J.jsxs)("article",{className:"border border-modiff-border bg-modiff-surface",children:[(0,J.jsx)(ee,{output:e,aspectRatio:"1 / 1"}),(0,J.jsxs)("div",{className:"p-2",children:[(0,J.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:Q(e)}),e.variationGroupId&&(0,J.jsxs)("p",{className:"text-xs text-hf-orange",children:[e.variationLabel||"Sweep variant"," | ",e.variationGroupId]}),(0,J.jsx)("p",{className:"max-h-16 overflow-hidden text-sm text-modiff-text",children:e.prompt})]})]})}function ce({output:e,onClick:t}){return(0,J.jsxs)(A,{tone:"ghost",align:"left",size:"compact",className:"h-auto border border-transparent px-2 py-1 text-xs text-modiff-subtle-text hover:border-modiff-border",onClick:t,children:[e.variationGroupId?"Sweep":e.parentId?"Branch":"Root"," |"," ",e.variationLabel||e.modelLabel," | ",new Date(e.createdAt).toLocaleString()," |"," ",e.prompt||e.id]})}function me(){let e=B(e=>e.galleryLibraryOpen),t=B(e=>e.setGalleryLibraryOpen);return(0,J.jsx)(H,{open:e,onClose:()=>t(!1),title:(0,J.jsxs)("span",{className:"inline-flex min-w-0 items-center gap-2",children:[(0,J.jsx)(a,{size:17,className:"text-hf-yellow"}),(0,J.jsx)("span",{className:"truncate",children:"Output Gallery"})]}),panelClassName:"max-w-[1180px]",bodyClassName:"max-h-[76vh] p-0",children:(0,J.jsx)(te,{modalView:!0})})}export{me as default}; \ No newline at end of file diff --git a/web/assets/GraphList.js b/web/assets/GraphList.js index cc1a610..5c57ee2 100644 --- a/web/assets/GraphList.js +++ b/web/assets/GraphList.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$ as t,Dn as a,Et as r,Jt as s,On as i,Xt as l,cr as o,dr as n,in as d,ln as c,pn as f,un as m,ut as u,z as p}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{At as h,Ci as x,Eo as w,Ft as v,It as y,Ki as b,Mo as g,Mt as j,Nt as k,Oo as N,Ot as S,Pt as C,Qn as A,Sa as D,To as T,Tt as $,Xn as z,Yn as L,Zn as E,an as M,bn as R,ji as W,mn as O,oc as q,rn as H,wo as K,yn as _}from"./studio-templates.js?v=cc046c26d6fe7aa4";var B=e(n(),1),I=o(),U=(0,B.lazy)(()=>x(()=>import(`./DeveloperWorkflowLauncher.js?v=cc046c26d6fe7aa4`),[])),F=T();function P(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function V(e,t){if(!P(e)||"boolean"!=typeof e.isDir||"string"!=typeof e.path||"string"!=typeof e.name)throw Error(`Workflow entry ${t+1} is invalid.`);if(void 0!==e.children&&!Array.isArray(e.children))throw Error(`Workflow entry ${t+1} has invalid children.`);return{isDir:e.isDir,path:e.path,name:e.name,children:e.children?.map(V),modelType:"string"==typeof e.modelType?e.modelType:void 0,mode:"string"==typeof e.mode?e.mode:void 0,mediaKind:"string"==typeof e.mediaKind?e.mediaKind:void 0,supportTier:"string"==typeof e.supportTier?e.supportTier:void 0,qualificationStatus:"string"==typeof e.qualificationStatus?e.qualificationStatus:void 0,requiredArtifacts:Array.isArray(e.requiredArtifacts)?e.requiredArtifacts.filter(e=>"string"==typeof e):void 0}}function J(e){return P(e)&&"string"==typeof e.id?{id:e.id,title:"string"==typeof e.title?e.title:"Workflow",createdAt:"number"==typeof e.createdAt?e.createdAt:Date.now(),updatedAt:"number"==typeof e.updatedAt?e.updatedAt:Date.now(),dirty:!1,intent:"draft"===e.intent?"draft":"saved",source:"string"==typeof e.source?e.source:"manual",sourceLabel:"string"==typeof e.sourceLabel?e.sourceLabel:void 0,backendRevision:"number"==typeof e.revision?e.revision:0}:null}function X(e){if(!Array.isArray(e))throw Error("The workflow list response must be an array.");return e.map(V)}function Z(e){return e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"")}function Q(){let e=D(e=>e.workflowLibraryView),o=D(e=>e.setWorkflowLibraryView),[n,x]=(0,B.useState)(!1),[T,V]=(0,B.useState)([]),[Q,Y]=(0,B.useState)([]),[G,ee]=(0,B.useState)(new Set),[te,ae]=(0,B.useState)(""),[re,se]=(0,B.useState)(0),[ie,le]=(0,B.useState)("all"),[oe,ne]=(0,B.useState)("all"),[de,ce]=(0,B.useState)("all"),[fe,me]=(0,B.useState)("all"),[ue,pe]=(0,B.useState)("all"),he=D(e=>e.edgeType),xe=D(e=>e.setRightPanelOpen),we=D(e=>e.setRightPanelTab),ve=D(e=>e.setAlertOpener),ye=W(e=>e.createWorkflowTab),be=W(e=>e.workflowTabs),ge=W(e=>e.activeWorkflowTabId),je=W(e=>e.switchWorkflowTab),ke=W(e=>e.renameWorkflowTab),Ne=W(e=>e.mergeBackendWorkflow),[Se,Ce]=(0,B.useState)(null),[Ae,De]=(0,B.useState)(""),Te=(0,B.useCallback)(async()=>{let e=F.begin("graphs");x(!0);try{let t=await N(`${q.serverAddress}/listgraphs`,{signal:e.signal,parse:X});e.isLatest()&&V(t)}catch(t){e.isLatest()&&console.error("Error fetching graphs:",t)}finally{e.isLatest()&&x(!1),e.finish()}},[]),$e=(0,B.useCallback)(async()=>{try{let e=await N(`${q.serverAddress}/workflows?view=summary`),t=P(e)&&Array.isArray(e.workflows)?e.workflows:[];Y(t.map(J).filter(e=>!!e))}catch(e){}},[]);(0,B.useEffect)(()=>{Te(),$e()},[Te,$e]);let ze=T,Le=(0,B.useMemo)(()=>(e=>{let t=[],a=e=>{e.isDir?e.children&&e.children.forEach(a):t.push(e)};return e.forEach(a),t})(ze),[ze]),Ee=(0,B.useMemo)(()=>({media:[...new Set(Le.map(e=>e.mediaKind).filter(Boolean))],models:[...new Set(Le.map(e=>e.modelType).filter(Boolean))],modes:[...new Set(Le.map(e=>e.mode).filter(Boolean))]}),[Le]),Me=te||"all"!==ie||"all"!==oe||"all"!==de||"all"!==fe||"all"!==ue,Re=(0,B.useMemo)(()=>{let e=new Map(Q.map(e=>[e.id,e]));return be.forEach(t=>e.set(t.id,t)),[...e.values()].sort((e,t)=>t.updatedAt-e.updatedAt)},[Q,be]),We=Re.filter(t=>("drafts"===e?"draft"===t.intent:"draft"!==t.intent)&&t.title.toLowerCase().includes(te.trim().toLowerCase())),Oe=Math.max(0,Math.ceil(We.length/50)-1),qe=Math.min(re,Oe),He=50*qe,Ke=We.slice(He,He+50),_e=(0,B.useMemo)(()=>Me?Le.filter(e=>e.name.toLowerCase().includes(te.toLowerCase())&&("all"===ie||e.mediaKind===ie)&&("all"===oe||e.modelType===oe)&&("all"===de||e.mode===de)&&("all"===fe||e.supportTier===fe)&&("all"===ue||e.qualificationStatus===ue)):ze,[Le,Me,ie,de,oe,ue,te,fe,ze]),Be=(0,B.useCallback)(async e=>{if(!e.isDir)try{let t=`${q.serverAddress}/file?file=${encodeURIComponent(e.path)}&t=${Date.now()}`,a=await N(t,{parse:e=>{if(!P(e))throw Error("The workflow file is not a JSON object.");if(e.error)throw new K(String(e.error),{kind:"application",url:t,payload:e});return e}});ye(e.name||"Imported graph",b(a,he,W.getState().form),"import",e.path),xe(!0),we("studio"),g("Workflow opened as a new tab",{variant:"success",autoHideDuration:2200})}catch(e){g(w(e,"Could not open the workflow."),{variant:"error",autoHideDuration:6e3})}},[ye,he,xe,we]),Ie=(0,B.useCallback)(async e=>{if(e.snapshot)return e;let t=L(await N(`${q.serverAddress}/workflows/${encodeURIComponent(e.id)}`));if(!t)throw Error(`MoDiff returned an invalid saved workflow for ${e.title}.`);return t},[]),Ue=(e,t=0)=>{if(e.isDir&&!Me){let a=G.has(e.path),r=e.children||[];return(0,I.jsxs)("div",{children:[(0,I.jsxs)(C,{"data-testid":`workflow-source-${Z(e.name)}`,onClick:()=>(e=>{ee(t=>{let a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})})(e.path),level:t,open:a,children:[a?(0,I.jsx)(l,{size:16,className:"shrink-0 text-hf-yellow"}):(0,I.jsx)(s,{size:16,className:"shrink-0 text-hf-yellow"}),(0,I.jsx)("span",{className:"min-w-0 truncate",children:e.name})]}),a?(0,I.jsx)(v,{level:t+1,children:r.map(e=>Ue(e,t+1))}):null]},e.path)}return e.isDir?null:(0,I.jsxs)(y,{"data-testid":`workflow-file-${Z(e.path)}`,level:Me?0:t,className:"group cursor-pointer hover:bg-modiff-surface-hover",onDoubleClick:()=>{Be(e)},title:"Double-click to open workflow as a new tab",children:[(0,I.jsx)(d,{size:15,className:"shrink-0 text-modiff-subtle-text group-hover:text-hf-yellow"}),(0,I.jsx)("span",{draggable:!0,className:"min-w-0 flex-1 cursor-grab truncate",onDragStart:t=>{t.dataTransfer.setData("text/plain",e.path),t.dataTransfer.effectAllowed="move"},children:e.name}),e.mediaKind?(0,I.jsx)("span",{className:"text-modiff-tiny rounded bg-modiff-surface-hover/50 px-1.5 py-0.5 uppercase text-modiff-subtle-text",children:e.mediaKind}):null,(0,I.jsx)(M,{size:"compact",className:"text-modiff-subtle-text opacity-0 group-hover:opacity-100 focus-visible:opacity-100",label:`Open ${e.name}`,onClick:()=>{Be(e)},children:(0,I.jsx)(d,{size:14})})]},e.path)};return(0,I.jsxs)("div",{className:"flex h-full min-w-0 flex-col overflow-hidden",children:[(0,I.jsx)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:(0,I.jsx)("div",{className:"flex items-start justify-between gap-3",children:(0,I.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,I.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:(0,I.jsx)(s,{size:18})}),(0,I.jsxs)("div",{className:"min-w-0",children:[(0,I.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:"Workflows"}),(0,I.jsx)("p",{className:"truncate text-xs text-modiff-subtle-text",children:"Saved and example graphs"})]})]})})}),(0,I.jsxs)("div",{className:"flex flex-wrap gap-2 p-2",children:[(0,I.jsx)(H,{"aria-pressed":"start"===e,onClick:()=>o("start"),children:"Start"}),(0,I.jsx)(H,{"aria-pressed":"examples"===e,onClick:()=>o("examples"),children:"Example workflows"}),(0,I.jsx)(H,{"aria-pressed":"saved"===e,onClick:()=>o("saved"),children:"My workflows"}),(0,I.jsx)(H,{"aria-pressed":"drafts"===e,onClick:()=>o("drafts"),children:"Recovery drafts"})]}),"start"===e?(0,I.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",children:(0,I.jsx)(B.Suspense,{fallback:(0,I.jsx)("p",{role:"status",children:"Loading tasks…"}),children:(0,I.jsx)(U,{embedded:!0})})}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{className:"flex items-center gap-2 p-2",children:[(0,I.jsx)(_,{"aria-label":"Search workflows",className:"min-w-0 flex-1",placeholder:"Search workflows",value:te,onChange:e=>{ae(e.currentTarget.value),se(0)},onClear:()=>{ae(""),se(0)}}),(0,I.jsx)(M,{label:"Reload workflows",disabled:n,className:"text-hf-yellow hover:text-hf-orange",onClick:()=>{Te(),$e(),ee(new Set),ae(""),se(0),le("all"),ne("all"),ce("all"),me("all"),pe("all")},children:n?(0,I.jsx)(r,{size:18,className:"animate-spin"}):(0,I.jsx)(t,{size:17})})]}),"examples"===e?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"grid shrink-0 grid-cols-2 gap-1 px-2 pb-2",children:[["Media",ie,le,Ee.media],["Model",oe,ne,Ee.models],["Mode",de,ce,Ee.modes],["Tier",fe,me,["supported","experimental"]],["Readiness",ue,pe,["graph-qualified","runtime-qualified","unqualified"]]].map(([e,t,a,r])=>(0,I.jsxs)("div",{className:"min-w-0 text-modiff-label uppercase text-modiff-subtle-text",children:[(0,I.jsx)("span",{children:String(e)}),(0,I.jsx)(R,{"aria-label":`Filter workflows by ${String(e).toLowerCase()}`,value:String(t),onValueChange:a,options:[{value:"all",label:"All"},...r.sort().map(e=>({value:e,label:e.replace(/_/g," ")}))],size:"compact",className:"mt-0.5 w-full normal-case"})]},String(e)))}),n?(0,I.jsx)("div",{className:"text-center text-sm text-modiff-subtle-text",children:"Loading..."}):(0,I.jsx)("div",{className:"min-h-0 flex-1 select-none overflow-y-auto overscroll-contain","data-testid":"workflow-list",children:_e.length>0?_e.map(e=>Ue(e,0)):0===We.length?(0,I.jsx)("div",{className:"m-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text",children:"No saved, imported, or example workflows found."}):null})]}):(0,I.jsxs)("section",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain px-2 pb-2","data-testid":"my-workflows",children:[(0,I.jsx)("h3",{className:"text-modiff-label mb-1 px-1 font-semibold uppercase text-modiff-subtle-text",children:"drafts"===e?"Recovery drafts — open and Save to keep in My workflows":"My workflows"}),Oe>0&&(0,I.jsxs)("div",{className:"mb-1 flex min-w-0 items-center justify-between gap-1 text-xs text-modiff-subtle-text",children:[(0,I.jsx)(M,{size:"compact",label:"Previous saved workflows",disabled:0===qe,onClick:()=>se(qe-1),children:(0,I.jsx)(i,{size:14})}),(0,I.jsxs)("span",{children:[He+1,"–",He+Ke.length," of ",We.length]}),(0,I.jsx)(M,{size:"compact",label:"Next saved workflows",disabled:qe===Oe,onClick:()=>se(qe+1),children:(0,I.jsx)(a,{size:14})})]}),(0,I.jsx)("div",{className:"grid gap-1",children:Ke.map(e=>(0,I.jsxs)("div",{className:"group flex min-h-8 min-w-0 items-center gap-1 overflow-hidden rounded-modiff-compact px-2 text-xs "+(e.id===ge?"bg-hf-yellow/10 text-hf-yellow":"text-modiff-text hover:bg-modiff-surface-hover/50"),"data-testid":`saved-workflow-${e.id}`,children:[(0,I.jsx)(d,{size:14,className:"shrink-0"}),Se===e.id?(0,I.jsx)(O,{autoFocus:!0,value:Ae,onChange:e=>De(e.target.value),onBlur:()=>{(async(e,t)=>{let a=t.trim();if(a&&a!==e.title){if(be.some(t=>t.id===e.id))return void ke(e.id,a);try{let t=await A({...await Ie(e),title:a,dirty:!0});Y(e=>e.map(e=>e.id===t.id?t:e))}catch(t){g(w(t,`Could not rename ${e.title}.`),{variant:"error",autoHideDuration:6e3})}}})(e,Ae),Ce(null)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur(),"Escape"===e.key&&Ce(null)},controlSize:"compact",className:"nodrag nowheel min-w-0 flex-1 border-hf-yellow"}):(0,I.jsxs)($,{type:"button",className:"min-h-7 min-w-0 flex-1 truncate text-left",onClick:()=>{(async e=>{try{let t=await Ie(e);E(t.id),be.some(e=>e.id===t.id)||Ne(t),je(t.id)}catch(t){g(w(t,`Could not open ${e.title}.`),{variant:"error",autoHideDuration:6e3})}})(e)},children:[e.dirty?"* ":"",e.title]}),(0,I.jsxs)(h,{className:"shrink-0",children:[(0,I.jsx)(k,{children:(0,I.jsx)(M,{size:"compact",label:`Actions for ${e.title}`,className:"text-modiff-subtle-text hover:text-hf-yellow",children:(0,I.jsx)(c,{size:14})})}),(0,I.jsxs)(j,{anchor:"bottom end",className:"min-w-40",children:[(0,I.jsx)(S,{icon:(0,I.jsx)(u,{size:13}),onClick:()=>{Ce(e.id),De(e.title)},children:"Rename"}),(0,I.jsx)(S,{icon:(0,I.jsx)(f,{size:13}),onClick:()=>{(async e=>{W.getState().saveActiveWorkflowTab(!0);let t=Re.find(t=>t.id===e);if(t)try{let e=await Ie(t);ye(`${e.title} copy`,e.snapshot,"manual",e.sourceLabel),g("Workflow duplicated",{variant:"success",autoHideDuration:2200})}catch(e){g(w(e,`Could not duplicate ${t.title}.`),{variant:"error",autoHideDuration:6e3})}})(e.id)},children:"Duplicate"}),(0,I.jsx)(S,{icon:(0,I.jsx)(m,{size:13}),onClick:()=>{(async e=>{W.getState().saveActiveWorkflowTab(!0);let t=Re.find(t=>t.id===e);if(t)try{let e=await Ie(t),a=new Blob([JSON.stringify(e.snapshot,null,2)],{type:"application/json"}),r=URL.createObjectURL(a),s=document.createElement("a");s.href=r,s.download=`${e.title.replace(/[^a-z0-9_-]+/gi,"-").replace(/^-|-$/g,"")||"workflow"}.json`,s.click(),URL.revokeObjectURL(r)}catch(e){g(w(e,`Could not export ${t.title}.`),{variant:"error",autoHideDuration:6e3})}})(e.id)},children:"Export"}),(0,I.jsx)(S,{tone:"danger",icon:(0,I.jsx)(p,{size:13}),onClick:()=>(e=>{let t=Re.find(t=>t.id===e);t&&ve({title:"Delete workflow?",message:`${t.title}${t.dirty?" has unsaved changes.":""} This removes it from My workflows.`,confirmText:"Delete",cancelText:"Cancel",onConfirm:()=>{z(e).then(()=>{Y(t=>t.filter(t=>t.id!==e)),g(`Deleted ${t.title}`,{variant:"success",autoHideDuration:2200})}).catch(e=>{g(w(e,`Could not delete ${t.title}.`),{variant:"error",autoHideDuration:6e3})}),ve(null)},onCancel:()=>ve(null)})})(e.id),children:"Delete"})]})]})]},e.id))})]})]})]})}export{Q as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$ as t,Dn as a,Et as r,Jt as s,On as i,Xt as l,cr as o,dr as n,in as d,ln as c,pn as f,un as m,ut as u,z as p}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$n as h,Ao as x,Do as w,Eo as v,Et as y,Ft as b,It as g,Ji as j,Lt as k,Ni as N,Nt as S,Oo as C,Po as A,Pt as D,Qn as T,Ti as $,Xn as z,Zn as L,bn as E,hn as M,in as R,jt as W,kt as q,lc as O,on as H,wa as K,xn as _}from"./studio-templates.js?v=ca6b74e6a02eedb3";var B=e(n(),1),I=o(),P=(0,B.lazy)(()=>$(()=>import(`./DeveloperWorkflowLauncher.js?v=ca6b74e6a02eedb3`),[])),U=w();function F(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function J(e,t){if(!F(e)||"boolean"!=typeof e.isDir||"string"!=typeof e.path||"string"!=typeof e.name)throw Error(`Workflow entry ${t+1} is invalid.`);if(void 0!==e.children&&!Array.isArray(e.children))throw Error(`Workflow entry ${t+1} has invalid children.`);return{isDir:e.isDir,path:e.path,name:e.name,children:e.children?.map(J),modelType:"string"==typeof e.modelType?e.modelType:void 0,mode:"string"==typeof e.mode?e.mode:void 0,mediaKind:"string"==typeof e.mediaKind?e.mediaKind:void 0,supportTier:"string"==typeof e.supportTier?e.supportTier:void 0,qualificationStatus:"string"==typeof e.qualificationStatus?e.qualificationStatus:void 0,requiredArtifacts:Array.isArray(e.requiredArtifacts)?e.requiredArtifacts.filter(e=>"string"==typeof e):void 0}}function V(e){return F(e)&&"string"==typeof e.id?{id:e.id,title:"string"==typeof e.title?e.title:"Workflow",createdAt:"number"==typeof e.createdAt?e.createdAt:Date.now(),updatedAt:"number"==typeof e.updatedAt?e.updatedAt:Date.now(),dirty:!1,intent:"draft"===e.intent?"draft":"saved",source:"string"==typeof e.source?e.source:"manual",sourceLabel:"string"==typeof e.sourceLabel?e.sourceLabel:void 0,backendRevision:"number"==typeof e.revision?e.revision:0}:null}function X(e){if(!Array.isArray(e))throw Error("The workflow list response must be an array.");return e.map(J)}function Z(e){return e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"")}function Q(){let e=K(e=>e.workflowLibraryView),o=K(e=>e.setWorkflowLibraryView),[n,w]=(0,B.useState)(!1),[$,J]=(0,B.useState)([]),[Q,G]=(0,B.useState)([]),[Y,ee]=(0,B.useState)(new Set),[te,ae]=(0,B.useState)(""),[re,se]=(0,B.useState)(0),[ie,le]=(0,B.useState)("all"),[oe,ne]=(0,B.useState)("all"),[de,ce]=(0,B.useState)("all"),[fe,me]=(0,B.useState)("all"),[ue,pe]=(0,B.useState)("all"),he=K(e=>e.edgeType),xe=K(e=>e.setRightPanelOpen),we=K(e=>e.setRightPanelTab),ve=K(e=>e.setAlertOpener),ye=N(e=>e.createWorkflowTab),be=N(e=>e.workflowTabs),ge=N(e=>e.activeWorkflowTabId),je=N(e=>e.switchWorkflowTab),ke=N(e=>e.renameWorkflowTab),Ne=N(e=>e.mergeBackendWorkflow),[Se,Ce]=(0,B.useState)(null),[Ae,De]=(0,B.useState)(""),Te=(0,B.useCallback)(async()=>{let e=U.begin("graphs");w(!0);try{let t=await x(`${O.serverAddress}/listgraphs`,{signal:e.signal,parse:X});e.isLatest()&&J(t)}catch(t){e.isLatest()&&console.error("Error fetching graphs:",t)}finally{e.isLatest()&&w(!1),e.finish()}},[]),$e=(0,B.useCallback)(async()=>{try{let e=await x(`${O.serverAddress}/workflows?view=summary`),t=F(e)&&Array.isArray(e.workflows)?e.workflows:[];G(t.map(V).filter(e=>!!e))}catch(e){}},[]);(0,B.useEffect)(()=>{Te(),$e()},[Te,$e]);let ze=$,Le=(0,B.useMemo)(()=>(e=>{let t=[],a=e=>{e.isDir?e.children&&e.children.forEach(a):t.push(e)};return e.forEach(a),t})(ze),[ze]),Ee=(0,B.useMemo)(()=>({media:[...new Set(Le.map(e=>e.mediaKind).filter(Boolean))],models:[...new Set(Le.map(e=>e.modelType).filter(Boolean))],modes:[...new Set(Le.map(e=>e.mode).filter(Boolean))]}),[Le]),Me=te||"all"!==ie||"all"!==oe||"all"!==de||"all"!==fe||"all"!==ue,Re=(0,B.useMemo)(()=>{let e=new Map(Q.map(e=>[e.id,e]));return be.forEach(t=>e.set(t.id,t)),[...e.values()].sort((e,t)=>t.updatedAt-e.updatedAt)},[Q,be]),We=Re.filter(t=>("drafts"===e?"draft"===t.intent:"draft"!==t.intent)&&t.title.toLowerCase().includes(te.trim().toLowerCase())),qe=Math.max(0,Math.ceil(We.length/50)-1),Oe=Math.min(re,qe),He=50*Oe,Ke=We.slice(He,He+50),_e=(0,B.useMemo)(()=>Me?Le.filter(e=>e.name.toLowerCase().includes(te.toLowerCase())&&("all"===ie||e.mediaKind===ie)&&("all"===oe||e.modelType===oe)&&("all"===de||e.mode===de)&&("all"===fe||e.supportTier===fe)&&("all"===ue||e.qualificationStatus===ue)):ze,[Le,Me,ie,de,oe,ue,te,fe,ze]),Be=(0,B.useCallback)(async e=>{if(!e.isDir)try{let t=`${O.serverAddress}/file?file=${encodeURIComponent(e.path)}&t=${Date.now()}`,a=await x(t,{parse:e=>{if(!F(e))throw Error("The workflow file is not a JSON object.");if(e.error)throw new v(String(e.error),{kind:"application",url:t,payload:e});return e}});ye(e.name||"Imported graph",j(a,he,N.getState().form),"import",e.path),xe(!0),we("studio"),A("Workflow opened as a new tab",{variant:"success",autoHideDuration:2200})}catch(e){A(C(e,"Could not open the workflow."),{variant:"error",autoHideDuration:6e3})}},[ye,he,xe,we]),Ie=(0,B.useCallback)(async e=>{if(e.snapshot)return e;let t=z(await x(`${O.serverAddress}/workflows/${encodeURIComponent(e.id)}`));if(!t)throw Error(`MoDiff returned an invalid saved workflow for ${e.title}.`);return t},[]),Pe=(e,t=0)=>{if(e.isDir&&!Me){let a=Y.has(e.path),r=e.children||[];return(0,I.jsxs)("div",{children:[(0,I.jsxs)(b,{"data-testid":`workflow-source-${Z(e.name)}`,onClick:()=>(e=>{ee(t=>{let a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})})(e.path),level:t,open:a,children:[a?(0,I.jsx)(l,{size:16,className:"shrink-0 text-hf-yellow"}):(0,I.jsx)(s,{size:16,className:"shrink-0 text-hf-yellow"}),(0,I.jsx)("span",{className:"min-w-0 truncate",children:e.name})]}),a?(0,I.jsx)(g,{level:t+1,children:r.map(e=>Pe(e,t+1))}):null]},e.path)}return e.isDir?null:(0,I.jsxs)(k,{"data-testid":`workflow-file-${Z(e.path)}`,level:Me?0:t,className:"group cursor-pointer hover:bg-modiff-surface-hover",onDoubleClick:()=>{Be(e)},title:"Double-click to open workflow as a new tab",children:[(0,I.jsx)(d,{size:15,className:"shrink-0 text-modiff-subtle-text group-hover:text-hf-yellow"}),(0,I.jsx)("span",{draggable:!0,className:"min-w-0 flex-1 cursor-grab truncate",onDragStart:t=>{t.dataTransfer.setData("text/plain",e.path),t.dataTransfer.effectAllowed="move"},children:e.name}),e.mediaKind?(0,I.jsx)("span",{className:"text-modiff-tiny rounded bg-modiff-surface-hover/50 px-1.5 py-0.5 uppercase text-modiff-subtle-text",children:e.mediaKind}):null,(0,I.jsx)(H,{size:"compact",className:"text-modiff-subtle-text opacity-0 group-hover:opacity-100 focus-visible:opacity-100",label:`Open ${e.name}`,onClick:()=>{Be(e)},children:(0,I.jsx)(d,{size:14})})]},e.path)};return(0,I.jsxs)("div",{className:"flex h-full min-w-0 flex-col overflow-hidden",children:[(0,I.jsx)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:(0,I.jsx)("div",{className:"flex items-start justify-between gap-3",children:(0,I.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,I.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:(0,I.jsx)(s,{size:18})}),(0,I.jsxs)("div",{className:"min-w-0",children:[(0,I.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:"Workflows"}),(0,I.jsx)("p",{className:"truncate text-xs text-modiff-subtle-text",children:"Saved and example graphs"})]})]})})}),(0,I.jsxs)("div",{className:"flex flex-wrap gap-2 p-2",children:[(0,I.jsx)(R,{"aria-pressed":"start"===e,onClick:()=>o("start"),children:"Start"}),(0,I.jsx)(R,{"aria-pressed":"examples"===e,onClick:()=>o("examples"),children:"Example workflows"}),(0,I.jsx)(R,{"aria-pressed":"saved"===e,onClick:()=>o("saved"),children:"My workflows"}),(0,I.jsx)(R,{"aria-pressed":"drafts"===e,onClick:()=>o("drafts"),children:"Recovery drafts"})]}),"start"===e?(0,I.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain",children:(0,I.jsx)(B.Suspense,{fallback:(0,I.jsx)("p",{role:"status",children:"Loading tasks…"}),children:(0,I.jsx)(P,{embedded:!0})})}):(0,I.jsxs)(I.Fragment,{children:[(0,I.jsxs)("div",{className:"flex items-center gap-2 p-2",children:[(0,I.jsx)(E,{"aria-label":"Search workflows",className:"min-w-0 flex-1",placeholder:"Search workflows",value:te,onChange:e=>{ae(e.currentTarget.value),se(0)},onClear:()=>{ae(""),se(0)}}),(0,I.jsx)(H,{label:"Reload workflows",disabled:n,className:"text-hf-yellow hover:text-hf-orange",onClick:()=>{Te(),$e(),ee(new Set),ae(""),se(0),le("all"),ne("all"),ce("all"),me("all"),pe("all")},children:n?(0,I.jsx)(r,{size:18,className:"animate-spin"}):(0,I.jsx)(t,{size:17})})]}),"examples"===e?(0,I.jsxs)(I.Fragment,{children:[(0,I.jsx)("div",{className:"grid shrink-0 grid-cols-2 gap-1 px-2 pb-2",children:[["Media",ie,le,Ee.media],["Model",oe,ne,Ee.models],["Mode",de,ce,Ee.modes],["Tier",fe,me,["supported","experimental"]],["Readiness",ue,pe,["graph-qualified","runtime-qualified","unqualified"]]].map(([e,t,a,r])=>(0,I.jsxs)("div",{className:"min-w-0 text-modiff-label uppercase text-modiff-subtle-text",children:[(0,I.jsx)("span",{children:String(e)}),(0,I.jsx)(_,{"aria-label":`Filter workflows by ${String(e).toLowerCase()}`,value:String(t),onValueChange:a,options:[{value:"all",label:"All"},...r.sort().map(e=>({value:e,label:e.replace(/_/g," ")}))],size:"compact",className:"mt-0.5 w-full normal-case"})]},String(e)))}),n?(0,I.jsx)("div",{className:"text-center text-sm text-modiff-subtle-text",children:"Loading..."}):(0,I.jsx)("div",{className:"min-h-0 flex-1 select-none overflow-y-auto overscroll-contain","data-testid":"workflow-list",children:_e.length>0?_e.map(e=>Pe(e,0)):0===We.length?(0,I.jsx)("div",{className:"m-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text",children:"No saved, imported, or example workflows found."}):null})]}):(0,I.jsxs)("section",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto overscroll-contain px-2 pb-2","data-testid":"my-workflows",children:[(0,I.jsx)("h3",{className:"text-modiff-label mb-1 px-1 font-semibold uppercase text-modiff-subtle-text",children:"drafts"===e?"Recovery drafts — open and Save to keep in My workflows":"My workflows"}),qe>0&&(0,I.jsxs)("div",{className:"mb-1 flex min-w-0 items-center justify-between gap-1 text-xs text-modiff-subtle-text",children:[(0,I.jsx)(H,{size:"compact",label:"Previous saved workflows",disabled:0===Oe,onClick:()=>se(Oe-1),children:(0,I.jsx)(i,{size:14})}),(0,I.jsxs)("span",{children:[He+1,"–",He+Ke.length," of ",We.length]}),(0,I.jsx)(H,{size:"compact",label:"Next saved workflows",disabled:Oe===qe,onClick:()=>se(Oe+1),children:(0,I.jsx)(a,{size:14})})]}),(0,I.jsx)("div",{className:"grid gap-1",children:Ke.map(e=>(0,I.jsxs)("div",{className:"group flex min-h-8 min-w-0 items-center gap-1 overflow-hidden rounded-modiff-compact px-2 text-xs "+(e.id===ge?"bg-hf-yellow/10 text-hf-yellow":"text-modiff-text hover:bg-modiff-surface-hover/50"),"data-testid":`saved-workflow-${e.id}`,children:[(0,I.jsx)(d,{size:14,className:"shrink-0"}),Se===e.id?(0,I.jsx)(M,{autoFocus:!0,value:Ae,onChange:e=>De(e.target.value),onBlur:()=>{(async(e,t)=>{let a=t.trim();if(a&&a!==e.title){if(be.some(t=>t.id===e.id))return void ke(e.id,a);try{let t=await h({...await Ie(e),title:a,dirty:!0});G(e=>e.map(e=>e.id===t.id?t:e))}catch(t){A(C(t,`Could not rename ${e.title}.`),{variant:"error",autoHideDuration:6e3})}}})(e,Ae),Ce(null)},onKeyDown:e=>{"Enter"===e.key&&e.currentTarget.blur(),"Escape"===e.key&&Ce(null)},controlSize:"compact",className:"nodrag nowheel min-w-0 flex-1 border-hf-yellow"}):(0,I.jsxs)(y,{type:"button",className:"min-h-7 min-w-0 flex-1 truncate text-left",onClick:()=>{(async e=>{try{let t=await Ie(e);T(t.id),be.some(e=>e.id===t.id)||Ne(t),je(t.id)}catch(t){A(C(t,`Could not open ${e.title}.`),{variant:"error",autoHideDuration:6e3})}})(e)},children:[e.dirty?"* ":"",e.title]}),(0,I.jsxs)(W,{className:"shrink-0",children:[(0,I.jsx)(D,{children:(0,I.jsx)(H,{size:"compact",label:`Actions for ${e.title}`,className:"text-modiff-subtle-text hover:text-hf-yellow",children:(0,I.jsx)(c,{size:14})})}),(0,I.jsxs)(S,{anchor:"bottom end",className:"min-w-40",children:[(0,I.jsx)(q,{icon:(0,I.jsx)(u,{size:13}),onClick:()=>{Ce(e.id),De(e.title)},children:"Rename"}),(0,I.jsx)(q,{icon:(0,I.jsx)(f,{size:13}),onClick:()=>{(async e=>{N.getState().saveActiveWorkflowTab(!0);let t=Re.find(t=>t.id===e);if(t)try{let e=await Ie(t);ye(`${e.title} copy`,e.snapshot,"manual",e.sourceLabel),A("Workflow duplicated",{variant:"success",autoHideDuration:2200})}catch(e){A(C(e,`Could not duplicate ${t.title}.`),{variant:"error",autoHideDuration:6e3})}})(e.id)},children:"Duplicate"}),(0,I.jsx)(q,{icon:(0,I.jsx)(m,{size:13}),onClick:()=>{(async e=>{N.getState().saveActiveWorkflowTab(!0);let t=Re.find(t=>t.id===e);if(t)try{let e=await Ie(t),a=new Blob([JSON.stringify(e.snapshot,null,2)],{type:"application/json"}),r=URL.createObjectURL(a),s=document.createElement("a");s.href=r,s.download=`${e.title.replace(/[^a-z0-9_-]+/gi,"-").replace(/^-|-$/g,"")||"workflow"}.json`,s.click(),URL.revokeObjectURL(r)}catch(e){A(C(e,`Could not export ${t.title}.`),{variant:"error",autoHideDuration:6e3})}})(e.id)},children:"Export"}),(0,I.jsx)(q,{tone:"danger",icon:(0,I.jsx)(p,{size:13}),onClick:()=>(e=>{let t=Re.find(t=>t.id===e);t&&ve({title:"Delete workflow?",message:`${t.title}${t.dirty?" has unsaved changes.":""} This removes it from My workflows.`,confirmText:"Delete",cancelText:"Cancel",onConfirm:()=>{L(e).then(()=>{G(t=>t.filter(t=>t.id!==e)),A(`Deleted ${t.title}`,{variant:"success",autoHideDuration:2200})}).catch(e=>{A(C(e,`Could not delete ${t.title}.`),{variant:"error",autoHideDuration:6e3})}),ve(null)},onCancel:()=>ve(null)})})(e.id),children:"Delete"})]})]})]},e.id))})]})]})]})}export{Q as default}; \ No newline at end of file diff --git a/web/assets/GraphNodeInputs.js b/web/assets/GraphNodeInputs.js index cb4406a..a75a805 100644 --- a/web/assets/GraphNodeInputs.js +++ b/web/assets/GraphNodeInputs.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,ct as t,dr as s,lt as n}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$o as d,Br as i,Bt as o,Ci as l,Cs as r,In as c,Vr as p,Zo as u,dn as m,ft as f,ii as b,ji as x,os as h,rc as g,xn as j,zt as I}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as k}from"./presetDiff.js?v=cc046c26d6fe7aa4";var v=e(s(),1),N=new Set(["ui_image","ui_video","ui_audio","ui_text","ui_imagecompare"]),w=new WeakMap,S=new WeakMap;function y(e){let a=e.data.blockInstanceV2??e.data.params,t=w.get(a);if(t)return t;let s=e.data.blockInstanceV2?u(e.data.blockInstanceV2):e.data.params,n=Object.fromEntries(Object.entries(s).filter(([e,a])=>{let t=a.isInput?"input":a.display||"";return"input"!==t&&"output"!==t&&!N.has(t)&&!a.hidden&&!["output","images","latents"].includes(e)}).map(([e,a])=>[e,{...a,fieldOptions:{...a.fieldOptions,suppressInitialFieldAction:!0}}]));return w.set(a,n),n}function V(e,a=[]){let t=e.flatMap(e=>Object.entries(y(e)).map(([a,t])=>({id:`graph:${e.id}:${a}`,kind:"graph-param",label:`${e.data.label||e.id} / ${t.label||a}`,nodeId:e.id,paramKey:a,node:e,param:t}))),s=new Set(a.filter(e=>!t.some(a=>a.id===e)));if(!s.size)return t;let n=new Set(e.map(({id:e})=>e));for(let a of e){let e=a.data.blockInstanceV2;if(!e||![...s].some(e=>e.startsWith(`graph:block-v2-node:${a.id.length}:${a.id}:`)))continue;let d=S.get(e);d||(d=h({...a,data:{...a.data,blockInstanceV2:{...e,presentation:{...e.presentation,expanded:!0,collapsedContainerNodeIds:[]}}}}).nodes,S.set(e,d)),t.push(...V(d.filter(({id:e})=>!n.has(e))).filter(({id:e})=>s.has(e)))}return t}function O(e,a){if(x.getState().activeWorkflowTabId!==e)return;let t=a.data.blockProjectionOwnerId,s=p.getState().nodes.find(({id:e})=>e===t)?.data.blockInstanceV2;if(!s||!t||!a.data.blockProjectionNodeId)return;let n=d(s),i=new Set,o=n.get(a.data.blockProjectionNodeId);for(;o;)i.add(o),o=n.get(o);p.getState().setBlockPresentationV2(t,{expanded:!0,collapsedContainerNodeIds:(s.presentation.collapsedContainerNodeIds??[]).filter(e=>!i.has(e))})}function $(e,a,t,s,n,d){if(x.getState().activeWorkflowTabId!==e)return;let o=p.getState(),l=o.nodes.find(({id:e})=>e===a);if(l){if(void 0!==d){let e=l.data.blockInstanceV2?u(l.data.blockInstanceV2):l.data.params;if(!Object.prototype.hasOwnProperty.call(e,d)||!Object.prototype.hasOwnProperty.call(e,t))return}else if(!y(l)[t])return;if(l.data.blockInstanceV2)return void((void 0===n||"value"===n)&&o.setBlockInstanceValueV2(a,t,s));void 0===d?o.setParamWithHistory(a,t,s,n):o.setParam(a,t,s,n),i(a,t,s,n)}}var _=a(),P=(0,v.lazy)(()=>l(()=>import(`./NodeInspectionDetails.js?v=cc046c26d6fe7aa4`),[])),C=(0,v.lazy)(()=>l(()=>import(`./OperationOwnerControls.js?v=cc046c26d6fe7aa4`),[])),M=(0,v.lazy)(()=>l(()=>import(`./GuidanceNodeControls.js?v=cc046c26d6fe7aa4`),[])),z=[{value:"parameters",label:"Parameters"},{value:"interface",label:"Interface"},{value:"implementation",label:"Implementation"},{value:"docs",label:"Docs"},{value:"run",label:"Run details"}];function B({node:e,children:a}){let[t,s]=(0,v.useState)("parameters"),n=(0,v.useId)();return(0,_.jsxs)("div",{className:"grid min-w-0 gap-3",children:[(0,_.jsx)(j,{"aria-label":"Node inspector sections",className:"flex-wrap",size:"dense",value:t,onValueChange:s,options:z.map(e=>({...e,id:`${n}-${e.value}`,controls:`${n}-panel`}))}),(0,_.jsx)("div",{role:"tabpanel",id:`${n}-panel`,"aria-labelledby":`${n}-${t}`,tabIndex:0,children:"parameters"===t?(0,_.jsxs)("div",{className:"grid gap-3",children:[e.data.blockInstanceV2||e.data.userBlockSnapshot||e.data.userBlockId||g(e.data.operationAuthoring?.operation)?(0,_.jsx)(v.Suspense,{fallback:(0,_.jsx)(I,{children:"Loading model controls…"}),children:(0,_.jsx)(C,{node:e})}):null,r(e.data.blockInstanceV2)?(0,_.jsx)(v.Suspense,{fallback:(0,_.jsx)(I,{children:"Loading guidance controls…"}),children:(0,_.jsx)(M,{instance:e.data.blockInstanceV2})}):a]}):(0,_.jsx)(v.Suspense,{fallback:(0,_.jsx)(I,{children:"Loading node details…"}),children:(0,_.jsx)(P,{node:e,section:t})})})]})}var E=new Map;function D({candidates:e,nodes:a,onTogglePin:s,pinnedIds:d,pinnedInputs:i,selectedNodes:l,workflowId:r,controlIdPrefix:p="studio-inspector"}){let[u,x]=(0,v.useState)({}),h=(0,v.useMemo)(()=>new Set(d),[d]),g=1===l.length?l[0]:null,j=(0,v.useMemo)(()=>{let e=new Map;if(i.forEach(a=>{if(!a.nodeId||!a.paramKey)return;let t=e.get(a.nodeId)??{node:a.node,params:{}};t.params[a.paramKey]=a.param,e.set(a.nodeId,t)}),g){let a=y(g);e.set(g.id,{node:g,params:a})}return[...g?[g.id]:[],...[...new Set([...a.map(e=>e.id),...e.keys()])].filter(e=>e!==g?.id)].flatMap(a=>{let t=e.get(a);return t?[t]:[]})},[a,i,g]),N=(0,v.useCallback)((e,a,t,s)=>{$(r,e,a,t,s)},[r]);return(0,_.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2","data-testid":l.length>0?"studio-custom-graph-inspector":"studio-pinned-graph-inputs",children:[(0,_.jsx)("div",{className:"flex items-center justify-between gap-2",children:(0,_.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:"Node controls"})}),l.length>1?(0,_.jsx)(I,{children:"One node at a time"}):null,j.length>0?j.map(({node:e,params:t},s)=>{let n=g?.id===e.id,d=`${r??"unscoped"}:${e.id}`,i=u[d]??E.get(d),l=n||(i??0===s),h=b(e.data),j=Object.keys(t).length,v=a.some(({id:a})=>a===e.id)?j>0?(0,_.jsx)("div",{className:"grid min-w-0 grid-cols-1 gap-3 [&>[data-key]]:m-0 [&>[data-key]]:min-w-0",children:(0,_.jsx)(f,{nodeId:e.id,controlIdPrefix:p,params:t,updateStore:(a,t,s)=>N(e.id,a,t,s),updateFieldActionStore:(a,t,s,n)=>$(r,e.id,t,s,n,a),module:e.data.blockInstanceV2?e.data.blockInstanceV2.definitionSnapshot.source.library??e.data.blockInstanceV2.definitionSnapshot.source.provider??"MoDiff":e.data.module,action:e.data.blockInstanceV2?"BlockV2":e.data.action,mode:"controls",hidePreviews:!0,executionStatus:e.data.executionStatus,progressMessage:e.data.progressMessage,uiStateMessage:e.data.uiState?.validationMessage??e.data.uiState?.errorMessage})}):(0,_.jsx)(I,{tone:"secondary",children:"No editable params"}):(0,_.jsxs)("div",{className:"grid gap-2","data-testid":`studio-hidden-pinned-inputs-${e.id}`,children:[Object.entries(t).map(([e,a])=>(0,_.jsxs)("p",{className:"break-words text-xs text-modiff-subtle-text",children:[a.label||e,": ",k(a.value??a.default)]},e)),(0,_.jsx)(o,{tone:"secondary",onClick:()=>O(r,e),children:"Reveal in Block to edit"})]});return(0,_.jsx)(m,{"aria-label":`Node controls: ${h}`,className:c("overflow-hidden rounded-modiff-compact border bg-modiff-bg",n?"border-hf-yellow/60":"border-modiff-border"),"data-testid":`studio-node-disclosure-${e.id}`,defaultOpen:l,label:(0,_.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,_.jsx)("span",{className:"min-w-0 flex-1 truncate",title:h,children:h}),(0,_.jsx)("span",{className:"text-xs font-normal text-modiff-subtle-text",children:j})]}),onOpenChange:e=>{E.set(d,e),x(a=>a[d]===e?a:{...a,[d]:e})},panelClassName:"border-t border-modiff-border-subtle p-3",children:n?(0,_.jsx)(B,{node:e,children:v}):v},`${d}:${n?"selected":"idle"}`)}):(0,_.jsx)(I,{tone:"secondary",children:"No pinned inputs"}),e.length>0?(0,_.jsx)(m,{className:"border-t border-modiff-border pt-2",label:"Pin inputs",buttonClassName:"min-h-0 justify-start p-0 text-xs text-modiff-subtle-text hover:bg-transparent",panelClassName:"mt-2 grid gap-1",children:e.map(e=>(0,_.jsx)(o,{tone:"ghost",align:"left",fullWidth:!0,className:"min-h-8 px-2 text-xs",onClick:()=>s(e.id),icon:h.has(e.id)?(0,_.jsx)(n,{size:14,className:"text-hf-yellow"}):(0,_.jsx)(t,{size:14,className:"text-modiff-subtle-text"}),children:(0,_.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.label})},e.id))}):null]})}export{V as n,D as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,ct as t,dr as s,lt as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Bo as d,Bt as i,Es as o,Hr as l,Ln as r,Ni as c,Sn as p,Ti as u,Vr as m,Vt as f,ai as b,es as h,fn as x,ls as g,ns as j,oc as I,pt as k}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as N}from"./presetDiff.js?v=ca6b74e6a02eedb3";var v=e(s(),1),w=new Set(["ui_image","ui_video","ui_audio","ui_text","ui_imagecompare"]),S=new WeakMap,V=new WeakMap;function y(e){let a=e.data.blockInstanceV2??e.data.params,t=S.get(a);if(t)return t;let s=e.data.blockInstanceV2?h(e.data.blockInstanceV2):e.data.params,n=Object.fromEntries(Object.entries(s).filter(([e,a])=>{let t=a.isInput?"input":a.display||"";return("input"!==t||d(a))&&"output"!==t&&!w.has(t)&&!a.hidden&&!["output","images","latents"].includes(e)}).map(([e,a])=>[e,{...a,fieldOptions:{...a.fieldOptions,suppressInitialFieldAction:!0}}]));return S.set(a,n),n}function O(e,a=[]){let t=e.flatMap(e=>Object.entries(y(e)).map(([a,t])=>({id:`graph:${e.id}:${a}`,kind:"graph-param",label:`${e.data.label||e.id} / ${t.label||a}`,nodeId:e.id,paramKey:a,node:e,param:t}))),s=new Set(a.filter(e=>!t.some(a=>a.id===e)));if(!s.size)return t;let n=new Set(e.map(({id:e})=>e));for(let a of e){let e=a.data.blockInstanceV2;if(!e||![...s].some(e=>e.startsWith(`graph:block-v2-node:${a.id.length}:${a.id}:`)))continue;let d=V.get(e);d||(d=g({...a,data:{...a.data,blockInstanceV2:{...e,presentation:{...e.presentation,expanded:!0,collapsedContainerNodeIds:[]}}}}).nodes,V.set(e,d)),t.push(...O(d.filter(({id:e})=>!n.has(e))).filter(({id:e})=>s.has(e)))}return t}function _(e,a){if(c.getState().activeWorkflowTabId!==e)return;let t=a.data.blockProjectionOwnerId,s=l.getState().nodes.find(({id:e})=>e===t)?.data.blockInstanceV2;if(!s||!t||!a.data.blockProjectionNodeId)return;let n=j(s),d=new Set,i=n.get(a.data.blockProjectionNodeId);for(;i;)d.add(i),i=n.get(i);l.getState().setBlockPresentationV2(t,{expanded:!0,collapsedContainerNodeIds:(s.presentation.collapsedContainerNodeIds??[]).filter(e=>!d.has(e))})}function $(e,a,t,s,n,d){if(c.getState().activeWorkflowTabId!==e)return;let i=l.getState(),o=i.nodes.find(({id:e})=>e===a);if(o){if(void 0!==d){let e=o.data.blockInstanceV2?h(o.data.blockInstanceV2):o.data.params;if(!Object.prototype.hasOwnProperty.call(e,d)||!Object.prototype.hasOwnProperty.call(e,t))return}else if(!y(o)[t])return;if(o.data.blockInstanceV2)return void((void 0===n||"value"===n)&&i.setBlockInstanceValueV2(a,t,s));void 0===d?i.setParamWithHistory(a,t,s,n):i.setParam(a,t,s,n),m(a,t,s,n)}}var P=a(),M=(0,v.lazy)(()=>u(()=>import(`./NodeInspectionDetails.js?v=ca6b74e6a02eedb3`),[])),C=(0,v.lazy)(()=>u(()=>import(`./OperationOwnerControls.js?v=ca6b74e6a02eedb3`),[])),E=(0,v.lazy)(()=>u(()=>import(`./GuidanceNodeControls.js?v=ca6b74e6a02eedb3`),[])),B=[{value:"parameters",label:"Parameters"},{value:"interface",label:"Interface"},{value:"implementation",label:"Implementation"},{value:"docs",label:"Docs"},{value:"run",label:"Run details"}];function z({node:e,children:a}){let[t,s]=(0,v.useState)("parameters"),n=(0,v.useId)();return(0,P.jsxs)("div",{className:"grid min-w-0 gap-3",children:[(0,P.jsx)(p,{"aria-label":"Node inspector sections",className:"flex-wrap",size:"dense",value:t,onValueChange:s,options:B.map(e=>({...e,id:`${n}-${e.value}`,controls:`${n}-panel`}))}),(0,P.jsx)("div",{role:"tabpanel",id:`${n}-panel`,"aria-labelledby":`${n}-${t}`,tabIndex:0,children:"parameters"===t?(0,P.jsxs)("div",{className:"grid gap-3",children:[e.data.blockInstanceV2||e.data.userBlockSnapshot||e.data.userBlockId||I(e.data.operationAuthoring?.operation)?(0,P.jsx)(v.Suspense,{fallback:(0,P.jsx)(i,{children:"Loading model controls…"}),children:(0,P.jsx)(C,{node:e})}):null,o(e.data.blockInstanceV2)?(0,P.jsx)(v.Suspense,{fallback:(0,P.jsx)(i,{children:"Loading guidance controls…"}),children:(0,P.jsx)(E,{instance:e.data.blockInstanceV2})}):a]}):(0,P.jsx)(v.Suspense,{fallback:(0,P.jsx)(i,{children:"Loading node details…"}),children:(0,P.jsx)(M,{node:e,section:t})})})]})}var D=new Map;function L({candidates:e,nodes:a,onTogglePin:s,pinnedIds:d,pinnedInputs:o,selectedNodes:l,workflowId:c,controlIdPrefix:p="studio-inspector"}){let[u,m]=(0,v.useState)({}),h=(0,v.useMemo)(()=>new Set(d),[d]),g=1===l.length?l[0]:null,j=(0,v.useMemo)(()=>{let e=new Map;if(o.forEach(a=>{if(!a.nodeId||!a.paramKey)return;let t=e.get(a.nodeId)??{node:a.node,params:{}};t.params[a.paramKey]=a.param,e.set(a.nodeId,t)}),g){let a=y(g);e.set(g.id,{node:g,params:a})}return[...g?[g.id]:[],...[...new Set([...a.map(e=>e.id),...e.keys()])].filter(e=>e!==g?.id)].flatMap(a=>{let t=e.get(a);return t?[t]:[]})},[a,o,g]),I=(0,v.useCallback)((e,a,t,s)=>{$(c,e,a,t,s)},[c]);return(0,P.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2","data-testid":l.length>0?"studio-custom-graph-inspector":"studio-pinned-graph-inputs",children:[(0,P.jsx)("div",{className:"flex items-center justify-between gap-2",children:(0,P.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:"Node controls"})}),l.length>1?(0,P.jsx)(i,{children:"One node at a time"}):null,j.length>0?j.map(({node:e,params:t},s)=>{let n=g?.id===e.id,d=`${c??"unscoped"}:${e.id}`,o=u[d]??D.get(d),l=n||(o??0===s),h=b(e.data),j=Object.keys(t).length,v=a.some(({id:a})=>a===e.id)?j>0?(0,P.jsx)("div",{className:"grid min-w-0 grid-cols-1 gap-3 [&>[data-key]]:m-0 [&>[data-key]]:min-w-0",children:(0,P.jsx)(k,{nodeId:e.id,controlIdPrefix:p,params:t,updateStore:(a,t,s)=>I(e.id,a,t,s),updateFieldActionStore:(a,t,s,n)=>$(c,e.id,t,s,n,a),module:e.data.blockInstanceV2?e.data.blockInstanceV2.definitionSnapshot.source.library??e.data.blockInstanceV2.definitionSnapshot.source.provider??"MoDiff":e.data.module,action:e.data.blockInstanceV2?"BlockV2":e.data.action,mode:"controls",hidePreviews:!0,executionStatus:e.data.executionStatus,progressMessage:e.data.progressMessage,uiStateMessage:e.data.uiState?.validationMessage??e.data.uiState?.errorMessage})}):(0,P.jsx)(i,{tone:"secondary",children:"No editable params"}):(0,P.jsxs)("div",{className:"grid gap-2","data-testid":`studio-hidden-pinned-inputs-${e.id}`,children:[Object.entries(t).map(([e,a])=>(0,P.jsxs)("p",{className:"break-words text-xs text-modiff-subtle-text",children:[a.label||e,": ",N(a.value??a.default)]},e)),(0,P.jsx)(f,{tone:"secondary",onClick:()=>_(c,e),children:"Reveal in Block to edit"})]});return(0,P.jsx)(x,{"aria-label":`Node controls: ${h}`,className:r("overflow-hidden rounded-modiff-compact border bg-modiff-bg",n?"border-hf-yellow/60":"border-modiff-border"),"data-testid":`studio-node-disclosure-${e.id}`,defaultOpen:l,label:(0,P.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,P.jsx)("span",{className:"min-w-0 flex-1 truncate",title:h,children:h}),(0,P.jsx)("span",{className:"text-xs font-normal text-modiff-subtle-text",children:j})]}),onOpenChange:e=>{D.set(d,e),m(a=>a[d]===e?a:{...a,[d]:e})},panelClassName:"border-t border-modiff-border-subtle p-3",children:n?(0,P.jsx)(z,{node:e,children:v}):v},`${d}:${n?"selected":"idle"}`)}):(0,P.jsx)(i,{tone:"secondary",children:"No pinned inputs"}),e.length>0?(0,P.jsx)(x,{className:"border-t border-modiff-border pt-2",label:"Pin inputs",buttonClassName:"min-h-0 justify-start p-0 text-xs text-modiff-subtle-text hover:bg-transparent",panelClassName:"mt-2 grid gap-1",children:e.map(e=>(0,P.jsx)(f,{tone:"ghost",align:"left",fullWidth:!0,className:"min-h-8 px-2 text-xs",onClick:()=>s(e.id),icon:h.has(e.id)?(0,P.jsx)(n,{size:14,className:"text-hf-yellow"}):(0,P.jsx)(t,{size:14,className:"text-modiff-subtle-text"}),children:(0,P.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.label})},e.id))}):null]})}export{O as n,L as t}; \ No newline at end of file diff --git a/web/assets/GroupNode.js b/web/assets/GroupNode.js index c9cd3b8..f0e2d6e 100644 --- a/web/assets/GroupNode.js +++ b/web/assets/GroupNode.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Dn as a,Mn as o,cr as r,dr as t,kn as d}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ln as l,Pn as s,Vr as n,an as i}from"./studio-templates.js?v=cc046c26d6fe7aa4";var c=e(t(),1),f=r(),m=(0,c.memo)(e=>{let r=(0,c.useRef)(null);l(e.id,r);let t=!0===e.data.blockProjectionContainer,m=e.data.blockProjectionChildCount??0,p=!1!==e.data.blockProjectionContainerExpanded,x=n(e=>e.toggleBlockContainerExpandedV2);return(0,f.jsxs)("div",{ref:r,className:t?"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-hf-yellow/45 bg-hf-yellow/[0.025] shadow-inner":"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-modiff-border bg-modiff-surface/20 shadow-inner","data-testid":`group-node-${e.id}`,children:[(0,f.jsxs)("div",{className:"drag-handle flex h-11 items-center gap-2 border-b border-modiff-border/80 bg-modiff-panel/90 px-3 text-sm font-bold text-modiff-text",children:[(0,f.jsx)(o,{size:16,className:t?"text-hf-yellow":"text-modiff-subtle-text"}),(0,f.jsx)("span",{className:"truncate",children:e.data.label||"Group"}),t?(0,f.jsxs)("div",{className:"nodrag ml-auto flex shrink-0 items-center gap-1.5",children:[(0,f.jsxs)("span",{className:"rounded-modiff-compact border border-hf-yellow/30 px-1.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-hf-yellow",children:[m," ",1===m?"block":"blocks"]}),(0,f.jsx)(i,{label:`${p?"Collapse":"Expand"} ${e.data.label||"Modular Diffusers container"}`,size:"compact","data-testid":`toggle-modular-container-${e.id}`,onClick:()=>{let a=e.data.blockProjectionOwnerId,o=e.data.blockProjectionNodeId;a&&o&&x(a,o)},children:p?(0,f.jsx)(d,{size:14}):(0,f.jsx)(a,{size:14})})]}):null]}),e.data.description?(0,f.jsx)("span",{className:"pointer-events-none absolute left-3 top-12 max-w-[calc(100%-1.5rem)] truncate text-xs text-modiff-subtle-text/80",children:e.data.description}):null,!t||p?(0,f.jsx)(s,{}):null]})});m.displayName="GroupNode";export{m as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Dn as a,Mn as o,cr as r,dr as t,kn as d}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Fn as l,Hr as s,Rn as n,on as i}from"./studio-templates.js?v=ca6b74e6a02eedb3";var c=e(t(),1),f=r(),m=(0,c.memo)(e=>{let r=(0,c.useRef)(null);n(e.id,r);let t=!0===e.data.blockProjectionContainer,m=e.data.blockProjectionChildCount??0,p=!1!==e.data.blockProjectionContainerExpanded,x=s(e=>e.toggleBlockContainerExpandedV2);return(0,f.jsxs)("div",{ref:r,className:t?"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-hf-yellow/45 bg-hf-yellow/[0.025] shadow-inner":"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-modiff-border bg-modiff-surface/20 shadow-inner","data-testid":`group-node-${e.id}`,children:[(0,f.jsxs)("div",{className:"drag-handle flex h-11 items-center gap-2 border-b border-modiff-border/80 bg-modiff-panel/90 px-3 text-sm font-bold text-modiff-text",children:[(0,f.jsx)(o,{size:16,className:t?"text-hf-yellow":"text-modiff-subtle-text"}),(0,f.jsx)("span",{className:"truncate",children:e.data.label||"Group"}),t?(0,f.jsxs)("div",{className:"nodrag ml-auto flex shrink-0 items-center gap-1.5",children:[(0,f.jsxs)("span",{className:"rounded-modiff-compact border border-hf-yellow/30 px-1.5 py-0.5 text-xs font-semibold uppercase tracking-wide text-hf-yellow",children:[m," ",1===m?"block":"blocks"]}),(0,f.jsx)(i,{label:`${p?"Collapse":"Expand"} ${e.data.label||"Modular Diffusers container"}`,size:"compact","data-testid":`toggle-modular-container-${e.id}`,onClick:()=>{let a=e.data.blockProjectionOwnerId,o=e.data.blockProjectionNodeId;a&&o&&x(a,o)},children:p?(0,f.jsx)(d,{size:14}):(0,f.jsx)(a,{size:14})})]}):null]}),e.data.description?(0,f.jsx)("span",{className:"pointer-events-none absolute left-3 top-12 max-w-[calc(100%-1.5rem)] truncate text-xs text-modiff-subtle-text/80",children:e.data.description}):null,!t||p?(0,f.jsx)(l,{}):null]})});m.displayName="GroupNode";export{m as default}; \ No newline at end of file diff --git a/web/assets/GuidanceNodeControls.js b/web/assets/GuidanceNodeControls.js index a16a3d8..75270e5 100644 --- a/web/assets/GuidanceNodeControls.js +++ b/web/assets/GuidanceNodeControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,dr as t}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{ft as s}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{r,t as o}from"./guidanceNodeFields.js?v=cc046c26d6fe7aa4";var d=e(t(),1),n=a();function l({instance:e}){let a=(0,d.useMemo)(()=>o(e),[e]),[t,l]=(0,d.useState)(!1),[i,m]=(0,d.useState)(null);return(0,n.jsxs)("div",{className:"nodrag nowheel grid gap-2",children:[(0,n.jsx)(s,{nodeId:e.instanceId,params:Object.fromEntries(a.map(e=>[e.id,{...e.param,disabled:t||e.param.disabled}])),module:"MoDiff",action:"Guidance",mode:"controls",updateStore:(a,s,o)=>{t||o&&"value"!==o||(l(!0),m(null),r(e.instanceId,a,s).catch(e=>{m(e instanceof Error?e.message:"Could not update Guidance.")}).finally(()=>l(!1)))}}),t?(0,n.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Updating guidance controls…"}):null,i?(0,n.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:i}):null]})}export{l as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,dr as t}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{pt as s}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{r,t as o}from"./guidanceNodeFields.js?v=ca6b74e6a02eedb3";var d=e(t(),1),n=a();function l({instance:e}){let a=(0,d.useMemo)(()=>o(e),[e]),[t,l]=(0,d.useState)(!1),[i,m]=(0,d.useState)(null);return(0,n.jsxs)("div",{className:"nodrag nowheel grid gap-2",children:[(0,n.jsx)(s,{nodeId:e.instanceId,params:Object.fromEntries(a.map(e=>[e.id,{...e.param,disabled:t||e.param.disabled}])),module:"MoDiff",action:"Guidance",mode:"controls",updateStore:(a,s,o)=>{t||o&&"value"!==o||(l(!0),m(null),r(e.instanceId,a,s).catch(e=>{m(e instanceof Error?e.message:"Could not update Guidance.")}).finally(()=>l(!1)))}}),t?(0,n.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Updating guidance controls…"}):null,i?(0,n.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:i}):null]})}export{l as default}; \ No newline at end of file diff --git a/web/assets/HuggingFaceClusterNode.js b/web/assets/HuggingFaceClusterNode.js index f85bb19..f0cb59f 100644 --- a/web/assets/HuggingFaceClusterNode.js +++ b/web/assets/HuggingFaceClusterNode.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a,ht as i,nr as s,q as n,tr as r,wt as o,xt as l}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$r as d,H as c,In as u,Ln as g,Mo as f,Nn as h,Si as m,Vr as p,Xr as x,Yr as b,an as v,bn as w,cr as C,fn as S,ft as y,ji as k,or as j,sr as I,ti as E}from"./studio-templates.js?v=cc046c26d6fe7aa4";var F=e(a(),1),H=t(),N=(0,F.memo)(e=>{let t=(0,F.useRef)(null),a="root"===e.data.huggingFaceClusterRole,N=!!e.data.huggingFaceClusterInstance?.presentation.expanded,R=e.data.huggingFaceClusterInstance?.definition,M=x(e=>e.library?.definitions.find(e=>e.id===R?.id&&e.libraryRevision===R.libraryRevision&&e.contentHash===R.contentHash)),z=x(e=>e.loaded),T=x(e=>e.fetchLibrary),$=b(e=>e.snapshot),B=b(e=>e.loaded),L=b(e=>e.fetchSnapshot);(0,F.useEffect)(()=>{a&&!z&&T()},[T,a,z]),(0,F.useEffect)(()=>{a&&"diffusers"===M?.provider&&!B&&L()},[B,M?.provider,L,a]);let P="diffusers"===M?.provider?$?.pipelines.find(e=>e.pipelineClass===M.pipelineClass)?.contentHash:void 0,D=(0,F.useRef)(null);(0,F.useEffect)(()=>{if(!a||!M||!e.data.huggingFaceClusterInstance)return;let t=e.data.huggingFaceClusterInstance,i=[e.id,M.libraryRevision,M.contentHash,P??""].join("\0");if(D.current===i)return;D.current=i;let s=p.getState(),n=E({nodes:s.nodes,edges:s.edges},t.instanceId,M);p.setState({nodes:n.nodes,edges:n.edges}),p.getState().updateHandleConnectionStatus(),p.getState().updateSignalValues(n.edges)},[P,M,a,e.data.huggingFaceClusterInstance,e.id]);let _=(0,F.useMemo)(()=>M?.executionAdmissions.filter(e=>"admitted"===e.status&&"static_graph_contract_compatible"===e.claim&&"graph_qualified"===e.publication.readiness&&e.publication.insertable)??[],[M]),q=e.data.huggingFaceClusterInstance?.execution?.admissionId??"",A="transformers"===M?.provider||"Transformers Nodes"===e.data.category?"Transformers":"Diffusers",V=M?.suggestedInputs?.source,W=!(!M||!Object.keys(M.suggestedInputs?.values??{}).length),[O,X]=(0,F.useState)(!1),[Y,G]=(0,F.useState)("idle"),[J,U]=(0,F.useState)(null),K=(0,F.useRef)(null),Q=k(e=>e.workflowCanvasEpoch),Z=p(t=>t.nodes.some(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id)),ee=p(t=>t.nodes.filter(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id&&!t.hidden).map(e=>[e.id,e.position.x,e.position.y,e.measured?.width??e.width??0,e.measured?.height??e.height??0].join(":")).join("|")),te=!0===e.data.uiState?.clusterExecutionEdgesReady,ae=p(e=>e.toggleHuggingFaceClusterExpanded),ie=p(e=>e.setNodeSize),se=p(e=>e.setNodeUiState),ne=p(e=>e.beginHistoryTransaction),re=p(e=>e.commitHistoryTransaction),oe=r(),le=s(),de=g(e.id,t),ce=p(e=>e.setHuggingFaceClusterParameter),ue=p(e=>e.setHuggingFaceClusterExecution),ge=(0,F.useCallback)((t,i,s)=>{s&&"value"!==s||ce(a?e.id:e.data.huggingFaceClusterInstanceId??e.id,t,i)},[a,e.data.huggingFaceClusterInstanceId,e.id,ce]),fe=(0,F.useCallback)(()=>{ae(e.id),k.getState().saveActiveWorkflowTab(!0)},[e.id,ae]),he=(0,F.useCallback)(t=>{ue(e.id,t||null),k.getState().saveActiveWorkflowTab(!0)},[e.id,ue]);(0,F.useEffect)(()=>{N||(K.current=null,G("idle"),U(null))},[N]),(0,F.useEffect)(()=>{let t=e.data.huggingFaceClusterInstance;if(!a||!M||!t||Z)return void(Z&&(G("ready"),U(null)));let i=_.find(e=>e.id===q);if(!i)return G("error"),void U("Select a workflow mode before loading its graph.");let s=JSON.stringify({canvasEpoch:Q,definition:[M.id,M.libraryRevision,M.contentHash],admission:i.id,parameters:t.parameterOverrides,executionParameters:t.execution?.parameterOverrides,explicitSources:t.execution?.explicitParameterSources});if(K.current===s)return;K.current=s;let n=!0;G("loading"),U(null);let r=()=>m.getState().studioModelCapabilities.find(e=>e.modelType===M.pipelineClass)?.studioExecutionSpecs?.find(e=>e.id===i.studioExecutionSpec?.id&&e.contentHash===i.studioExecutionSpec.contentHash&&e.executionProfileId===i.studioExecutionSpec.executionProfileId),o=I(M,t,i);return Promise.resolve().then(async()=>{let e=await async function(e){return e()||(await m.getState().fetchStudioModelCapabilities(),e())}(r);if(!e)throw Error("The exact reviewed graph specification is unavailable.");return{spec:e,skeleton:await C({definition:M,instance:t,admission:i,executionSpec:e,nodesRegistry:m.getState().nodesRegistry,bindingValues:o,expanded:!0})}}).then(({spec:e,skeleton:a})=>j({definition:M,instance:t,admission:i,executionSpec:e,skeleton:a,bindingValues:o})).then(()=>{n&&(G("ready"),U(null))}).catch(e=>{n&&(G("error"),U(e instanceof Error?e.message:"Could not materialize the reviewed Block graph."))}),()=>{n=!1}},[M,_,N,Z,a,e.data.huggingFaceClusterInstance,q,Q]),(0,F.useEffect)(()=>{if(!N||!ee)return;let t=p.getState().nodes.filter(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id).map(e=>e.id),a=new Set,i=e=>{let t=window.requestAnimationFrame(()=>{a.delete(t),e()});a.add(t)},s=new Set(t),n=a=>{le([e.id,...t]),p.getState().edges.filter(e=>s.has(e.source)||s.has(e.target)).every(e=>{let t=!e.sourceHandle||!!document.querySelector(`[data-testid="node-handle-${e.source}-${e.sourceHandle}"]`),a=!e.targetHandle||!!document.querySelector(`[data-testid="node-handle-${e.target}-${e.targetHandle}"]`);return t&&a})?i(()=>se(e.id,{clusterExecutionEdgesReady:!0})):a<120&&i(()=>n(a+1))};te?le([e.id,...t]):i(()=>n(0));let r=window.setTimeout(()=>{p.setState(t=>{let a=d(t,e.id);return{...a===t?{}:{nodes:a.nodes},layoutRevision:t.layoutRevision+1}})},100);return()=>{a.forEach(e=>window.cancelAnimationFrame(e)),window.clearTimeout(r)}},[te,ee,N,e.id,se,le]);let me=(0,F.useCallback)(()=>{!M||!e.data.huggingFaceClusterInstance||!q||O||(X(!0),c(e.id).then(()=>{f("Created an editable Block copy for this workflow.",{variant:"success",autoHideDuration:2400})}).catch(e=>{f(e instanceof Error?e.message:"Could not create an editable Block copy.",{variant:"error",autoHideDuration:4200})}).finally(()=>X(!1)))},[M,O,e.data.huggingFaceClusterInstance,e.id,q]),pe=(0,F.useCallback)(a=>{if(N)return;a.preventDefault(),a.stopPropagation(),ne("Resize Block");let i=t.current?.clientWidth||e.width||360,s=t.current?.clientHeight||e.height||320,n=a.clientX,r=a.clientY,o=oe.getState().transform[2]||1,l=i,d=s,c=t=>{l=Math.min(720,Math.max(360,i+(t.clientX-n)/o)),d=Math.max(320,s+(t.clientY-r)/o),ie(e.id,Math.round(l),Math.round(d)),de()},u=()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",u),se(e.id,{clusterCollapsedWidth:Math.round(l),clusterCollapsedHeight:Math.round(d)}),re(),de()};document.addEventListener("mousemove",c),document.addEventListener("mouseup",u)},[ne,re,N,e.height,e.id,e.width,oe,de,ie,se]);return a?(0,H.jsxs)("div",{ref:t,className:u("relative flex h-full w-full min-w-[260px] flex-col overflow-visible rounded-modiff-panel border-2 border-hf-yellow/60 shadow-modiff-node",N?"bg-hf-yellow/[0.055]":"bg-modiff-surface"),"data-cluster-role":"root","data-testid":`hugging-face-cluster-${e.id}`,children:[(0,H.jsxs)("header",{className:u("drag-handle flex h-11 shrink-0 items-center gap-2 rounded-t-modiff-panel border-b border-hf-yellow/25 px-3 text-sm font-bold text-modiff-text",N?"bg-hf-yellow/10":"bg-modiff-bg"),children:[(0,H.jsx)(i,{size:16,className:"shrink-0 text-hf-yellow"}),(0,H.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.data.label}),N&&"loading"===Y?(0,H.jsx)("span",{className:"text-xs font-semibold text-modiff-subtle-text",children:"Loading graph…"}):null,N&&"error"===Y?(0,H.jsx)("span",{className:"max-w-40 truncate text-xs font-semibold text-modiff-red",title:J??void 0,children:"Graph unavailable"}):null,(0,H.jsx)(v,{className:"nodrag nowheel",size:"compact",label:"Customize as Block",title:q?"Make this workflow instance structurally editable while leaving the first-party Block unchanged.":"Select a reviewed workflow mode before customizing.",disabled:!M||!q||O,onClick:me,children:(0,H.jsx)(n,{size:15})}),(0,H.jsx)(v,{className:"nodrag nowheel",size:"compact",label:N?`Collapse ${A} Block`:`Expand ${A} Block`,title:M?void 0:"The exact reviewed library definition is unavailable.",disabled:!M,onClick:fe,"data-testid":`hugging-face-cluster-toggle-${e.id}`,children:N?(0,H.jsx)(l,{size:16}):(0,H.jsx)(o,{size:16})})]}),N?(0,H.jsx)("div",{className:"pointer-events-none min-h-0 flex-1","aria-hidden":"true",children:"error"===Y?(0,H.jsx)("p",{className:"pointer-events-auto m-4 max-w-md text-xs text-modiff-red",role:"status",children:J}):null}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)("div",{className:"nodrag nowheel min-h-24 flex-1 overflow-x-hidden overflow-y-auto bg-modiff-surface p-3",children:[_.length>1?(0,H.jsx)(S,{className:"mb-3",label:"Workflow",children:(0,H.jsx)(w,{value:q,onValueChange:he,options:_.map(e=>({value:e.id,label:e.studioMode.replace(/_/gu," ")})),placeholder:"Select a mode"})}):null,W&&V?(0,H.jsxs)("p",{className:"mb-3 rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg/60 px-2 py-1.5 text-modiff-label text-modiff-subtle-text","data-testid":`hugging-face-cluster-suggestion-source-${e.id}`,children:["Starter values:"," ",V.url?(0,H.jsx)("a",{className:"nodrag nowheel font-semibold text-hf-yellow hover:underline",href:V.url,target:"_blank",rel:"noreferrer",children:V.label}):(0,H.jsx)("span",{className:"font-semibold text-modiff-text",children:V.label})]}):null,(0,H.jsx)(y,{nodeId:e.id,params:e.data.params,updateStore:ge,module:M?.provider??"huggingface",action:"cluster",mode:"controls"})]}),(0,H.jsx)("div",{className:"shrink-0",children:(0,H.jsx)(y,{nodeId:e.id,params:e.data.params,updateStore:ge,module:M?.provider??"huggingface",action:"cluster",mode:"connectors"})})]}),N?null:(0,H.jsx)(h,{label:"Drag to resize Block",onMouseDown:pe})]}):null});N.displayName="HuggingFaceClusterNode";export{N as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a,ht as i,nr as n,q as s,tr as r,wt as o,xt as l}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{H as d,Hr as c,Ln as u,Ni as g,Pn as f,Po as h,Rn as m,Xr as p,Zr as x,cr as b,ei as v,lr as w,ni as C,on as S,pn as y,pt as k,sr as j,wi as I,xn as E}from"./studio-templates.js?v=ca6b74e6a02eedb3";var F=e(a(),1),H=t(),N=(0,F.memo)(e=>{let t=(0,F.useRef)(null),a="root"===e.data.huggingFaceClusterRole,N=!!e.data.huggingFaceClusterInstance?.presentation.expanded,R=e.data.huggingFaceClusterInstance?.definition,M=x(e=>e.library?.definitions.find(e=>e.id===R?.id&&e.libraryRevision===R.libraryRevision&&e.contentHash===R.contentHash)),z=x(e=>e.loaded),T=x(e=>e.fetchLibrary),B=p(e=>e.snapshot),P=p(e=>e.loaded),$=p(e=>e.fetchSnapshot);(0,F.useEffect)(()=>{a&&!z&&T()},[T,a,z]),(0,F.useEffect)(()=>{a&&"diffusers"===M?.provider&&!P&&$()},[P,M?.provider,$,a]);let L="diffusers"===M?.provider?B?.pipelines.find(e=>e.pipelineClass===M.pipelineClass)?.contentHash:void 0,D=(0,F.useRef)(null);(0,F.useEffect)(()=>{if(!a||!M||!e.data.huggingFaceClusterInstance)return;let t=e.data.huggingFaceClusterInstance,i=[e.id,M.libraryRevision,M.contentHash,L??""].join("\0");if(D.current===i)return;D.current=i;let n=c.getState(),s=C({nodes:n.nodes,edges:n.edges},t.instanceId,M);c.setState({nodes:s.nodes,edges:s.edges}),c.getState().updateHandleConnectionStatus(),c.getState().updateSignalValues(s.edges)},[L,M,a,e.data.huggingFaceClusterInstance,e.id]);let _=(0,F.useMemo)(()=>M?.executionAdmissions.filter(e=>"admitted"===e.status&&"static_graph_contract_compatible"===e.claim&&"graph_qualified"===e.publication.readiness&&e.publication.insertable)??[],[M]),q=e.data.huggingFaceClusterInstance?.execution?.admissionId??"",A="transformers"===M?.provider||"Transformers Nodes"===e.data.category?"Transformers":"Diffusers",W=M?.suggestedInputs?.source,O=!(!M||!Object.keys(M.suggestedInputs?.values??{}).length),[V,X]=(0,F.useState)(!1),[Y,G]=(0,F.useState)("idle"),[J,U]=(0,F.useState)(null),Z=(0,F.useRef)(null),K=g(e=>e.workflowCanvasEpoch),Q=c(t=>t.nodes.some(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id)),ee=c(t=>t.nodes.filter(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id&&!t.hidden).map(e=>[e.id,e.position.x,e.position.y,e.measured?.width??e.width??0,e.measured?.height??e.height??0].join(":")).join("|")),te=!0===e.data.uiState?.clusterExecutionEdgesReady,ae=c(e=>e.toggleHuggingFaceClusterExpanded),ie=c(e=>e.setNodeSize),ne=c(e=>e.setNodeUiState),se=c(e=>e.beginHistoryTransaction),re=c(e=>e.commitHistoryTransaction),oe=r(),le=n(),de=m(e.id,t),ce=c(e=>e.setHuggingFaceClusterParameter),ue=c(e=>e.setHuggingFaceClusterExecution),ge=(0,F.useCallback)((t,i,n)=>{n&&"value"!==n||ce(a?e.id:e.data.huggingFaceClusterInstanceId??e.id,t,i)},[a,e.data.huggingFaceClusterInstanceId,e.id,ce]),fe=(0,F.useCallback)(()=>{ae(e.id),g.getState().saveActiveWorkflowTab(!0)},[e.id,ae]),he=(0,F.useCallback)(t=>{ue(e.id,t||null),g.getState().saveActiveWorkflowTab(!0)},[e.id,ue]);(0,F.useEffect)(()=>{N||(Z.current=null,G("idle"),U(null))},[N]),(0,F.useEffect)(()=>{let t=e.data.huggingFaceClusterInstance;if(!a||!M||!t||Q)return void(Q&&(G("ready"),U(null)));let i=_.find(e=>e.id===q);if(!i)return G("error"),void U("Select a workflow mode before loading its graph.");let n=JSON.stringify({canvasEpoch:K,definition:[M.id,M.libraryRevision,M.contentHash],admission:i.id,parameters:t.parameterOverrides,executionParameters:t.execution?.parameterOverrides,explicitSources:t.execution?.explicitParameterSources});if(Z.current===n)return;Z.current=n;let s=!0;G("loading"),U(null);let r=()=>I.getState().studioModelCapabilities.find(e=>e.modelType===M.pipelineClass)?.studioExecutionSpecs?.find(e=>e.id===i.studioExecutionSpec?.id&&e.contentHash===i.studioExecutionSpec.contentHash&&e.executionProfileId===i.studioExecutionSpec.executionProfileId),o=b(M,t,i);return Promise.resolve().then(async()=>{let e=await async function(e){return e()||(await I.getState().fetchStudioModelCapabilities(),e())}(r);if(!e)throw Error("The exact reviewed graph specification is unavailable.");return{spec:e,skeleton:await w({definition:M,instance:t,admission:i,executionSpec:e,nodesRegistry:I.getState().nodesRegistry,bindingValues:o,expanded:!0})}}).then(({spec:e,skeleton:a})=>j({definition:M,instance:t,admission:i,executionSpec:e,skeleton:a,bindingValues:o})).then(()=>{s&&(G("ready"),U(null))}).catch(e=>{s&&(G("error"),U(e instanceof Error?e.message:"Could not materialize the reviewed Block graph."))}),()=>{s=!1}},[M,_,N,Q,a,e.data.huggingFaceClusterInstance,q,K]),(0,F.useEffect)(()=>{if(!N||!ee)return;let t=c.getState().nodes.filter(t=>"execution"===t.data.huggingFaceClusterRole&&t.data.huggingFaceClusterInstanceId===e.id).map(e=>e.id),a=new Set,i=e=>{let t=window.requestAnimationFrame(()=>{a.delete(t),e()});a.add(t)},n=new Set(t),s=a=>{le([e.id,...t]),c.getState().edges.filter(e=>n.has(e.source)||n.has(e.target)).every(e=>{let t=!e.sourceHandle||!!document.querySelector(`[data-testid="node-handle-${e.source}-${e.sourceHandle}"]`),a=!e.targetHandle||!!document.querySelector(`[data-testid="node-handle-${e.target}-${e.targetHandle}"]`);return t&&a})?i(()=>ne(e.id,{clusterExecutionEdgesReady:!0})):a<120&&i(()=>s(a+1))};te?le([e.id,...t]):i(()=>s(0));let r=window.setTimeout(()=>{c.setState(t=>{let a=v(t,e.id);return{...a===t?{}:{nodes:a.nodes},layoutRevision:t.layoutRevision+1}})},100);return()=>{a.forEach(e=>window.cancelAnimationFrame(e)),window.clearTimeout(r)}},[te,ee,N,e.id,ne,le]);let me=(0,F.useCallback)(()=>{!M||!e.data.huggingFaceClusterInstance||!q||V||(X(!0),d(e.id).then(()=>{h("Created an editable Block copy for this workflow.",{variant:"success",autoHideDuration:2400})}).catch(e=>{h(e instanceof Error?e.message:"Could not create an editable Block copy.",{variant:"error",autoHideDuration:4200})}).finally(()=>X(!1)))},[M,V,e.data.huggingFaceClusterInstance,e.id,q]),pe=(0,F.useCallback)(a=>{if(N)return;a.preventDefault(),a.stopPropagation(),se("Resize Block");let i=t.current?.clientWidth||e.width||360,n=t.current?.clientHeight||e.height||320,s=a.clientX,r=a.clientY,o=oe.getState().transform[2]||1,l=i,d=n,c=t=>{l=Math.min(720,Math.max(360,i+(t.clientX-s)/o)),d=Math.max(320,n+(t.clientY-r)/o),ie(e.id,Math.round(l),Math.round(d)),de()},u=()=>{document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",u),ne(e.id,{clusterCollapsedWidth:Math.round(l),clusterCollapsedHeight:Math.round(d)}),re(),de()};document.addEventListener("mousemove",c),document.addEventListener("mouseup",u)},[se,re,N,e.height,e.id,e.width,oe,de,ie,ne]);return a?(0,H.jsxs)("div",{ref:t,className:u("relative flex h-full w-full min-w-[260px] flex-col overflow-visible rounded-modiff-panel border-2 border-hf-yellow/60 shadow-modiff-node",N?"bg-hf-yellow/[0.055]":"bg-modiff-surface"),"data-cluster-role":"root","data-testid":`hugging-face-cluster-${e.id}`,children:[(0,H.jsxs)("header",{className:u("drag-handle flex h-11 shrink-0 items-center gap-2 rounded-t-modiff-panel border-b border-hf-yellow/25 px-3 text-sm font-bold text-modiff-text",N?"bg-hf-yellow/10":"bg-modiff-bg"),children:[(0,H.jsx)(i,{size:16,className:"shrink-0 text-hf-yellow"}),(0,H.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.data.label}),N&&"loading"===Y?(0,H.jsx)("span",{className:"text-xs font-semibold text-modiff-subtle-text",children:"Loading graph…"}):null,N&&"error"===Y?(0,H.jsx)("span",{className:"max-w-40 truncate text-xs font-semibold text-modiff-red",title:J??void 0,children:"Graph unavailable"}):null,(0,H.jsx)(S,{className:"nodrag nowheel",size:"compact",label:"Customize as Block",title:q?"Make this workflow instance structurally editable while leaving the first-party Block unchanged.":"Select a reviewed workflow mode before customizing.",disabled:!M||!q||V,onClick:me,children:(0,H.jsx)(s,{size:15})}),(0,H.jsx)(S,{className:"nodrag nowheel",size:"compact",label:N?`Collapse ${A} Block`:`Expand ${A} Block`,title:M?void 0:"The exact reviewed library definition is unavailable.",disabled:!M,onClick:fe,"data-testid":`hugging-face-cluster-toggle-${e.id}`,children:N?(0,H.jsx)(l,{size:16}):(0,H.jsx)(o,{size:16})})]}),N?(0,H.jsx)("div",{className:"pointer-events-none min-h-0 flex-1","aria-hidden":"true",children:"error"===Y?(0,H.jsx)("p",{className:"pointer-events-auto m-4 max-w-md text-xs text-modiff-red",role:"status",children:J}):null}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)("div",{className:"nodrag nowheel min-h-24 flex-1 overflow-x-hidden overflow-y-auto bg-modiff-surface p-3",children:[_.length>1?(0,H.jsx)(y,{className:"mb-3",label:"Workflow",children:(0,H.jsx)(E,{value:q,onValueChange:he,options:_.map(e=>({value:e.id,label:e.studioMode.replace(/_/gu," ")})),placeholder:"Select a mode"})}):null,O&&W?(0,H.jsxs)("p",{className:"mb-3 rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg/60 px-2 py-1.5 text-modiff-label text-modiff-subtle-text","data-testid":`hugging-face-cluster-suggestion-source-${e.id}`,children:["Starter values:"," ",W.url?(0,H.jsx)("a",{className:"nodrag nowheel font-semibold text-hf-yellow hover:underline",href:W.url,target:"_blank",rel:"noreferrer",children:W.label}):(0,H.jsx)("span",{className:"font-semibold text-modiff-text",children:W.label})]}):null,(0,H.jsx)(k,{nodeId:e.id,params:e.data.params,updateStore:ge,module:M?.provider??"huggingface",action:"cluster",mode:"controls"})]}),(0,H.jsx)("div",{className:"shrink-0",children:(0,H.jsx)(k,{nodeId:e.id,params:e.data.params,updateStore:ge,module:M?.provider??"huggingface",action:"cluster",mode:"connectors"})})]}),N?null:(0,H.jsx)(f,{label:"Drag to resize Block",onMouseDown:pe})]}):null});N.displayName="HuggingFaceClusterNode";export{N as default}; \ No newline at end of file diff --git a/web/assets/LeftLibraryPanels.js b/web/assets/LeftLibraryPanels.js index 63d96fa..96d43c6 100644 --- a/web/assets/LeftLibraryPanels.js +++ b/web/assets/LeftLibraryPanels.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{At as t,Et as s,Ht as a,It as l,K as i,Kt as n,Mn as r,P as d,V as o,cr as c,dr as m,kn as u,sn as f,vt as p}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ai as x,Cr as h,Fi as g,Ga as b,In as y,Ja as j,Jn as v,Li as N,Mo as w,Ns as k,Pi as C,Ra as I,S as $,Sa as T,Si as A,Sr as M,St as _,Vi as P,Vr as z,Zt as S,_o as L,co as O,ji as R,lo as D,oc as E,pa as K,pn as q,q as V,rn as W,rr as H,so as U,uo as B,xt as G}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{r as J,t as F}from"./templateBrowser.js?v=cc046c26d6fe7aa4";import{t as Z}from"./WorkflowArtifactRequirementRow.js?v=cc046c26d6fe7aa4";var Q=e(m(),1),X=c();function Y({action:e,actionPlacement:t="inline",children:s,icon:a,meta:l,title:i}){return(0,X.jsxs)("div",{className:"flex h-full flex-col",children:[(0,X.jsxs)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:[(0,X.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,X.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[(0,X.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:a}),(0,X.jsxs)("div",{className:"min-w-0",children:[(0,X.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:i}),(0,X.jsx)("p",{className:"truncate text-xs text-modiff-subtle-text",children:l})]})]}),"inline"===t?e:null]}),"stacked"===t&&e?(0,X.jsx)("div",{className:"mt-3 min-w-0",children:e}):null]}),(0,X.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:s})]})}function ee({children:e,className:t,onClick:s}){return s?(0,X.jsx)(W,{align:"left",className:y("h-auto min-h-0 w-full bg-modiff-surface p-3 text-sm font-normal",t),fullWidth:!0,onClick:s,tone:"secondary",children:e}):(0,X.jsx)("div",{className:y("w-full rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-left text-sm text-modiff-text",t),children:e})}function te({label:e,value:t}){return(0,X.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,X.jsx)("div",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,X.jsx)("div",{className:"mt-1 text-base font-bold text-modiff-text",children:t})]})}function se(e){return"default"===e?"neutral":e}function ae({children:e,disabled:t,onClick:s,progress:a,testId:l,title:i,tone:n}){return(0,X.jsx)(S,{action:"Installing"===("string"==typeof e?e:void 0)?"installing":s?"install":"success"===n?"ready":"warning"===n||"error"===n?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:t,label:e,onClick:s,progress:a,testId:l,title:i,tone:se(n)})}function le(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e;return String(t.id??t.repo_id??t.label??t.rel_path??t.path??JSON.stringify(e))}return String(e??"")}function ie(e){let t=le(e);return t.replace(/\\/g,"/").split("/").filter(Boolean).slice(-2).join("/")||t}var ne=["Image","Edit","Control","Video","Audio","Adapters","Components","Other"];function re(e){return"Audio"===e?"Audio":"Video"===e?"Video":"Control"===e?"Control":"Image Edit"===e?"Edit":"Utility"===e?"Adapters":"Image"===e?"Image":"Other"}function de(e){let t=le(e).toLowerCase();return t.includes("text_encoder")||t.includes("text encoder")||t.includes("vae")||t.includes("tokenizer")||t.includes("transformer")||t.includes("diffusion_model")||t.includes("clip")?"Components":t.includes("wan")||t.includes("video")?"Video":t.includes("ace")||t.includes("audio")?"Audio":t.includes("control")||t.includes("canny")||t.includes("depth")?"Control":t.includes("lora")||t.includes("adapter")?"Adapters":t.includes("edit")||t.includes("inpaint")||t.includes("fill")||t.includes("kontext")||t.includes("redux")?"Edit":t.includes("image")||t.includes("flux")||t.includes("z-image")||t.includes("qwen")?"Image":"Other"}var oe=["repo_id","model_id","repository_id","model","model_name","checkpoint","ckpt_name","path"];function ce(e){return String(e??"").replace(/\\/g,"/").toLowerCase()}function me(e,t,s){let a=function(e){let t=ce(le(e));return Object.values(I).find(e=>function(e,t){return[e.defaultRepo,e.alternateArtifact,e.label,e.displayName,e.family].some(e=>{let s=ce(e);return s.length>0&&(t.includes(s)||s.includes(t))})}(e,t))}(e),l=t.find(e=>e.modelType===a?.modelType)?.executionProfiles??[];if(l.length>0){let e=new Set;return l.map(e=>({key:`${e.loader_module}.${e.loader_action}`,identityKey:"ModelsLoader"===e.loader_action?"model_type":"pipeline_class",identity:"ModelsLoader"===e.loader_action?e.model_type:e.pipeline_class})).filter(t=>{let s=`${t.key}:${t.identityKey}:${t.identity}`;return!e.has(s)&&(e.add(s),!0)})}if(a&&s)return[];let i=a?re(a.surfaceCategory):de(e);return[{key:`modules.Diffusers${"Audio"===i?"Audio":"Video"===i?"Video":"Image"}.LoadPipeline`},{key:"modules.ModularDiffusers.ModelsLoader",...a?{identityKey:"model_type",identity:a.modelType}:{}}]}function ue(e,t){return t.find(t=>e.data.params[t])}function fe(e,t,s){e.data.params={...e.data.params,[t]:{...e.data.params[t],value:s}}}function pe(e,t){let s=new Map;return ne.forEach(e=>s.set(e,[])),e.forEach(e=>s.get(t(e))?.push(e)),ne.map(e=>[e,s.get(e)??[]]).filter(([,e])=>e.length>0)}function xe(e){return"audio"===e?(0,X.jsx)(p,{size:14}):"video"===e?(0,X.jsx)(o,{size:14}):(0,X.jsx)(l,{size:14})}function he(){let e=T(e=>e.setTemplateBrowserOpen),s=T(e=>e.openTemplateBrowser),a=K.filter(e=>"blocked"===e.difficulty||"blocked"===e.example?.status).length,l=K.length-a,i=new Map(F.map(e=>[e.id,"all"===e.id?l:K.filter(t=>J(t)===e.id&&"blocked"!==t.difficulty&&"blocked"!==t.example?.status).length])),n=F.filter(e=>"recommended"!==e.id&&("all"===e.id||(i.get(e.id)??0)>0));return(0,X.jsx)(Y,{title:"Templates",meta:`${l} usable, ${a} blocked`,icon:(0,X.jsx)(t,{size:18}),action:(0,X.jsx)(W,{className:"h-8 px-2 text-xs","data-testid":"left-open-template-browser",icon:(0,X.jsx)(t,{size:14}),onClick:()=>s("recommended"),tone:"primary",children:"Browse"}),children:(0,X.jsxs)("div",{className:"grid gap-2",children:[(0,X.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,X.jsx)(te,{label:"Templates",value:K.length}),(0,X.jsx)(te,{label:"Planning",value:a})]}),(0,X.jsxs)(ee,{className:"flex-col items-stretch gap-2",onClick:()=>e(!0),children:[(0,X.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[(0,X.jsx)(t,{size:16,className:"text-hf-yellow"}),"Template browser"]}),(0,X.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Search by task, model, inputs, media type, and backend requirement."})]}),(0,X.jsx)("div",{className:"grid gap-1",children:n.map(e=>(0,X.jsxs)(W,{align:"left",className:"min-h-9 justify-between bg-modiff-bg px-2 font-normal",fullWidth:!0,onClick:()=>s(e.id),tone:"secondary",children:[(0,X.jsx)("span",{className:"truncate",children:e.label}),(0,X.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:i.get(e.id)??0})]},e.id))})]})})}function ge(){let e=T(e=>e.setGalleryLibraryOpen),t=R(e=>e.outputs),a=R(e=>e.importedAssets),i=R(e=>e.addImportedAssets),r=R(e=>e.useImportedAssetAsReference),o=R(e=>e.activeWorkflowTabId),c=(0,Q.useRef)(null),m=h(e=>e.taskCount),[u,p]=(0,Q.useState)(!1),g=(0,Q.useMemo)(()=>x(t,o),[o,t]),b=g.filter(e=>"video"===e.displayType).length,y=g.filter(e=>"audio"===e.displayType).length,j=g.slice(0,9),v=a.slice(0,6);return(0,X.jsx)(Y,{title:"Assets",meta:`${g.length} generated, ${a.length} imported`,icon:(0,X.jsx)(n,{size:18}),actionPlacement:"stacked",action:(0,X.jsxs)("div",{className:"grid min-w-0 grid-cols-3 gap-1",children:[(0,X.jsx)(q,{ref:c,"aria-label":"Import assets",className:"hidden",multiple:!0,onChange:e=>{(async e=>{try{let t=await async function(e){return e?(await Promise.all(Array.from(e).map(async(e,t)=>{let s=function(e){return G(e,["image","video","audio"])??"unknown"}(e);if("unknown"===s)return null;let a=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${t}-${e.name}`;try{let l=await async function(e,t){let[s]=await H(e,function(e){return"audio"===e?"audio":"video"===e?"videos":"images"}(t));if(!s)throw Error("Imported asset upload did not return a file path.");return s}(e,s);return{id:a,kind:"imported",name:e.name,url:`${E.serverAddress}/file?file=${encodeURIComponent(l)}`,backendPath:l,displayType:s,mimeType:e.type,byteSize:e.size,createdAt:Date.now()-t,source:"upload",storage:"backend"}}catch(t){throw Error(`${e.name}: ${t instanceof Error?t.message:"The backend could not validate this media file."}`)}}))).filter(e=>null!==e):[]}(e);i(t)}catch(e){w(e instanceof Error?e.message:"The selected media could not be imported.",{variant:"error",autoHideDuration:6e3})}finally{c.current&&(c.current.value="")}})(e.currentTarget.files)},accept:_(["image","video","audio"])}),(0,X.jsx)(W,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-clean-temporary-media",disabled:u||m>0,icon:u?(0,X.jsx)(s,{size:14,className:"animate-spin"}):(0,X.jsx)(f,{size:14}),onClick:()=>{(async()=>{if(!(u||m>0)){p(!0);try{let e=await L();w(0===e.removed.length?"No unprotected temporary media to clean":`Removed ${e.removed.length} temporary media ${1===e.removed.length?"file":"files"}`,{variant:"success",autoHideDuration:3e3})}catch(e){w(String(e),{variant:"error",autoHideDuration:6e3})}finally{p(!1)}}})()},tone:"secondary",title:m>0?"Wait for the active generation to finish":"Remove unprotected temporary media",children:"Clean"}),(0,X.jsx)(W,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-import-assets",icon:(0,X.jsx)(d,{size:14}),onClick:()=>c.current?.click(),tone:"secondary",title:"Import local media. Assets are persisted through the backend when connected.",children:"Import"}),(0,X.jsx)(W,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-open-gallery-library",icon:(0,X.jsx)(n,{size:14}),onClick:()=>e(!0),tone:"primary",children:"Open"})]}),children:(0,X.jsxs)("div",{className:"grid gap-2",children:[(0,X.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,X.jsx)(te,{label:"Generated",value:g.length}),(0,X.jsx)(te,{label:"Imported",value:a.length}),(0,X.jsx)(te,{label:"Videos",value:b}),(0,X.jsx)(te,{label:"Audio",value:y})]}),(0,X.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,X.jsx)("span",{children:"Generated"}),(0,X.jsx)(ae,{tone:"default",children:g.length})]}),(0,X.jsx)("div",{className:"grid grid-cols-3 gap-1","data-testid":"left-gallery-thumbnails",children:0===j.length?(0,X.jsx)("div",{className:"col-span-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"No outputs yet."}):j.map((t,s)=>(0,X.jsx)(W,{"data-testid":`left-gallery-output-${s}`,title:`${t.modelLabel}${t.prompt?` | ${t.prompt}`:""}`,"aria-label":`Open gallery item from ${t.modelLabel}`,className:"aspect-square h-auto min-h-0 overflow-hidden bg-modiff-bg !p-0",onClick:()=>e(!0),tone:"secondary",children:"audio"===t.displayType||"video"===t.displayType?(0,X.jsx)("span",{className:"grid h-full w-full place-items-center text-hf-yellow",children:xe(t.displayType)}):(0,X.jsx)("img",{src:t.url,alt:"",className:"h-full w-full object-cover"})},t.id))}),(0,X.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,X.jsx)("span",{children:"Imported"}),(0,X.jsx)(ae,{tone:"default",children:a.length})]}),(0,X.jsx)("div",{className:"grid grid-cols-3 gap-1","data-testid":"left-imported-thumbnails",children:0===v.length?(0,X.jsx)(W,{align:"left",className:"col-span-3 h-auto min-h-0 border-dashed bg-modiff-bg p-3 text-xs text-modiff-subtle-text",fullWidth:!0,onClick:()=>c.current?.click(),tone:"secondary",title:"Import local media. Assets are persisted through the backend when connected.",children:"Import assets"}):v.map((e,t)=>(0,X.jsx)(W,{"data-testid":`left-imported-asset-${t}`,title:e.name,"aria-label":`Use imported asset ${e.name}`,className:"aspect-square h-auto min-h-0 overflow-hidden bg-modiff-bg !p-0",onClick:()=>r(e),tone:"secondary",children:"image"===e.displayType?(0,X.jsx)("img",{src:e.url,alt:"",className:"h-full w-full object-cover"}):(0,X.jsx)("span",{className:"grid h-full w-full place-items-center text-hf-yellow",children:xe(e.displayType)})},e.id))}),(0,X.jsx)(ee,{onClick:()=>e(!0),children:(0,X.jsxs)("div",{className:"flex items-center justify-between gap-2 font-semibold",children:[(0,X.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,X.jsx)(l,{size:16,className:"text-hf-yellow"}),(0,X.jsx)("span",{className:"truncate",children:"Open gallery"})]}),(0,X.jsx)(ae,{tone:"default",children:g.length})]})})]})})}function be(){let e=A(e=>e.hfCache),t=A(e=>e.localModels),s=A(e=>e.modelCacheDiagnostics),l=A(e=>e.hfDownloadProgress),n=A(e=>e.nodesRegistry),d=A(e=>e.studioModelCapabilities),o=A(e=>e.studioModelCapabilitiesAuthoritative),c=A(e=>e.installHfModel),m=A(e=>e.fetchRuntimeStatus),f=A(e=>e.fetchHfCache),p=A(e=>e.fetchLocalModels),x=A(e=>e.fetchModelCacheDiagnostics),h=T(e=>e.setModelManagerOpener),g=T(e=>e.setRightPanelOpen),N=T(e=>e.setRightPanelTab),_=R(e=>e.form),S=R(e=>e.activeTemplateId),L=R(e=>e.graphBinding),E=R(e=>e.sourceOutputId),K=R(e=>e.autoResourcePlans),q=R(e=>e.setAutoResourcePlans),H=v(e=>e.sid),U=z(e=>e.addNode),G=z(e=>e.viewport),J=z(e=>e.nodes.length),[F,ee]=(0,Q.useState)(new Set);(0,Q.useEffect)(()=>{m(),f(!1),p(!1),x(!1)},[f,p,x,m]);let te=!!(S||L||E),se=I[_.modelType],ae=(0,Q.useMemo)(()=>b({currentModelType:te?_.modelType:null,includeWorkflowOnly:!0}),[_.modelType,te]),ne=(0,Q.useMemo)(()=>ae.map(e=>j(e.modelType)),[ae]),ce=(0,Q.useMemo)(()=>ne.map(e=>C(e)),[ne]),xe=(0,Q.useMemo)(()=>function(e){let t=new Set;return e.filter(({item:e,source:s})=>{let a=`${s}:${le(e).toLowerCase()}`;return!t.has(a)&&(t.add(a),!0)})}([...e.map(e=>({source:"HF",item:e})),...t.map(e=>({source:"Local",item:e}))]),[e,t]),he=(0,Q.useMemo)(()=>pe(xe,({item:e})=>de(e)),[xe]),ge=(0,Q.useMemo)(()=>Object.values(l).filter(e=>D(e)||O(e)||B(e)).sort((e,t)=>(t.updated_at??t.completed_at??t.started_at??0)-(e.updated_at??e.completed_at??e.started_at??0)),[l]),be=(0,Q.useMemo)(()=>ae.filter(a=>!k(a,e,t,s).runnable),[e,t,s,ae]),je=(0,Q.useMemo)(()=>pe(be,e=>re(e.surfaceCategory)),[be]),ve=he,Ne=te&&se?M({form:_,autoResourcePlan:K[C(_)],hfCache:e,localModels:t,modelCacheDiagnostics:s,includePipeline:!1}):[];(0,Q.useEffect)(()=>{if(0===ne.length)return;let e=!1;return P(ne,ce).then(t=>{if(e)return;let s={};t.forEach((e,t)=>{let a=e.planKey??ce[t];a&&(s[a]=e)}),q(s)}).catch(e=>{console.error(e)}),()=>{e=!0}},[q,ne,ce]);let we=()=>{g(!0),N("setup")},ke=(0,Q.useCallback)(e=>{ee(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),Ce=async e=>{try{await c(e.repo,H,{repair:e.repair,revision:e.revision,files:e.files})}catch(e){console.error(e)}},Ie=(0,Q.useCallback)((e,t)=>{let s=le(e),a=me(e,d,o),l=function(e,t){let s=e.zoom||1,a=t%6*36;return{x:(220-e.x+a)/s,y:(140-e.y+a)/s}}(G,J),i=a.map(e=>({candidate:e,node:V(e.key,n,l)})).find(({candidate:e,node:t})=>t&&(ue(t,oe)||ue(t,["model_type"]))&&(!e.identityKey||ue(t,[e.identityKey]))),r=i?.node;if(!r)return void w("No matching loader node is available yet.",{variant:"error",autoHideDuration:2800});let c=i.candidate.identityKey;c&&i.candidate.identity&&fe(r,c,i.candidate.identity);let m=ue(r,oe);m&&fe(r,m,function(e,t,s,a){let l=t.data.params[s],i=l?.value??l?.default;return"modelselect"===l?.display||i&&"object"==typeof i&&!Array.isArray(i)?{source:"Local"===e?"local":"hub",value:a}:a}(t,r,m,s)),U({...r,selected:!0}),w(`Added ${ie(e)} loader`,{variant:"success",autoHideDuration:1800})},[U,J,n,d,o,G]);return(0,X.jsx)(Y,{title:"Models",meta:`${xe.length} installed, ${be.length} available`,icon:(0,X.jsx)(r,{size:18}),action:(0,X.jsx)(W,{className:"h-8 px-2 text-xs","data-testid":"left-open-model-manager",icon:(0,X.jsx)(i,{size:14}),onClick:()=>h({nodeId:null,fieldKey:null}),tone:"primary",children:"Models"}),children:(0,X.jsxs)("div",{className:"grid gap-2",children:[ge.length>0?(0,X.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-downloads",children:[(0,X.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,X.jsx)("span",{children:"Downloads"}),(0,X.jsxs)("span",{children:[ge.filter(D).length," active"]})]}),ge.slice(0,3).map(e=>(0,X.jsx)($,{compact:!0,progress:e,showTechnicalDetails:!1,testId:`left-model-download-${e.repo_id}`},e.repo_id)),ge.length>3?(0,X.jsxs)(W,{tone:"ghost",onClick:()=>h({nodeId:null,fieldKey:null}),children:["View all ",ge.length," downloads"]}):null]}):null,te&&se?(0,X.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-current",children:[(0,X.jsx)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:(0,X.jsx)("span",{children:"Current"})}),(0,X.jsx)(ye,{autoPlan:K[C(_)],installProgress:l,onInstall:Ce,onOpenSetup:we,profile:se,status:k(se,e,t,s)}),Ne.map(e=>(0,X.jsx)(Z,{actionTestId:`left-install-requirement-${e.id}`,compact:!0,installProgress:l,onInstall:Ce,onUseLocal:()=>h({nodeId:null,fieldKey:null,focus:{repo:e.repo,requirementId:e.id,label:e.label,source:"workflow"}}),requirement:e,testId:`left-model-requirement-${e.id}`},e.id))]}):null,(0,X.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-installed",children:[(0,X.jsxs)("div",{className:"px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:["Installed (",xe.length,")"]}),0===xe.length||0===ve.length?(0,X.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"No visible model artifacts indexed yet."}):ve.map(([e,t])=>{let s=`installed:${e}`,l=F.has(s);return(0,X.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg",children:[(0,X.jsxs)(W,{align:"left",className:"min-h-9 justify-between rounded-none border-0 bg-transparent px-2",fullWidth:!0,tone:"ghost",onClick:()=>ke(s),children:[(0,X.jsx)("span",{className:"truncate",children:e}),(0,X.jsxs)("span",{className:"flex shrink-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[t.length,(0,X.jsx)(u,{size:15,className:y("transition-transform",l&&"rotate-180")})]})]}),l?(0,X.jsx)("div",{className:"grid gap-1 border-t border-modiff-border p-1",children:t.map(({item:e,source:t})=>(0,X.jsxs)(W,{align:"left",fullWidth:!0,title:le(e),onClick:()=>Ie(e,t),className:"min-h-10 justify-between bg-modiff-bg p-2 font-normal",tone:"secondary",children:[(0,X.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,X.jsx)(a,{size:15,className:"shrink-0 text-modiff-subtle-text"}),(0,X.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:ie(e)})]}),(0,X.jsx)("span",{className:"shrink-0 text-xs font-semibold text-modiff-subtle-text",children:t})]},`${t}-${le(e)}`))}):null]},e)})]}),be.length>0?(0,X.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-supported",children:[(0,X.jsxs)("div",{className:"px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:["Available (",be.length,")"]}),je.map(([a,i])=>{let n=`available:${a}`,r=F.has(n);return(0,X.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg",children:[(0,X.jsxs)(W,{align:"left",className:"min-h-9 justify-between rounded-none border-0 bg-transparent px-2",fullWidth:!0,onClick:()=>ke(n),tone:"ghost",children:[(0,X.jsx)("span",{className:"truncate",children:a}),(0,X.jsxs)("span",{className:"flex shrink-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[i.length,(0,X.jsx)(u,{size:15,className:y("transition-transform",r&&"rotate-180")})]})]}),r?(0,X.jsx)("div",{className:"grid gap-1 border-t border-modiff-border p-1",children:i.map(a=>{let i=C(j(a.modelType));return(0,X.jsx)(ye,{autoPlan:K[i],installProgress:l,onInstall:Ce,onOpenSetup:we,profile:a,status:k(a,e,t,s)},a.modelType)})}):null]},a)})]}):null]})})}function ye({autoPlan:e,installProgress:t,onInstall:s,onOpenSetup:a,profile:l,status:i}){let n=N(e)??{repo:l.defaultRepo,label:l.label,actionLabel:"Install"},r=t[n.repo],d=g(e),o="queued"===r?.status||"running"===r?.status||"downloading"===r?.status,c="unsuitable"!==d.state||i.runnable?"warning":"error",m=o?"Installing":n.actionLabel??"Install",u=n.reason||`Install ${n.repo}`;return(0,X.jsx)("div",{"data-testid":`left-model-${l.modelType}`,className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:(0,X.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,X.jsxs)(W,{align:"left",className:"h-auto min-h-0 min-w-0 flex-1 bg-transparent p-0 font-normal",tone:"ghost",title:`${l.defaultRepo} | ${d.summary} | ${d.detail}`,onClick:a,children:[(0,X.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text",children:l.label}),(0,X.jsx)("div",{className:"mt-0.5 truncate text-xs text-modiff-subtle-text",children:l.family})]}),!i.runnable&&(0,X.jsx)(ae,{tone:c,testId:`left-install-${l.modelType}`,title:u,disabled:o,progress:o?U(r):null,onClick:()=>{s(n)},children:m})]})})}export{ge as AssetsLibraryPanel,be as ModelsLibraryPanel,he as TemplateLibraryPanel}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{At as t,Et as s,Ht as a,It as l,K as i,Kt as n,Mn as r,P as d,V as o,cr as c,dr as m,kn as u,sn as f,vt as p}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ba as x,Cr as h,Ct as g,Hr as b,Ii as y,Is as j,Li as v,Ln as N,Mi as w,Ni as k,Po as C,Qt as I,S as $,St as T,Ui as A,Xa as M,Yn as _,do as P,fo as z,ha as L,in as S,ir as O,lc as D,lo as R,mn as E,q,qa as K,uo as H,wa as W,wi as U,wr as V,yo as B,zi as G}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{r as F,t as J}from"./templateBrowser.js?v=ca6b74e6a02eedb3";import{t as Q}from"./WorkflowArtifactRequirementRow.js?v=ca6b74e6a02eedb3";var X=e(m(),1),Y=c();function Z({action:e,actionPlacement:t="inline",children:s,icon:a,meta:l,title:i}){return(0,Y.jsxs)("div",{className:"flex h-full flex-col",children:[(0,Y.jsxs)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:[(0,Y.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,Y.jsxs)("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[(0,Y.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:a}),(0,Y.jsxs)("div",{className:"min-w-0",children:[(0,Y.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:i}),(0,Y.jsx)("p",{className:"truncate text-xs text-modiff-subtle-text",children:l})]})]}),"inline"===t?e:null]}),"stacked"===t&&e?(0,Y.jsx)("div",{className:"mt-3 min-w-0",children:e}):null]}),(0,Y.jsx)("div",{className:"min-h-0 flex-1 overflow-y-auto p-2",children:s})]})}function ee({children:e,className:t,onClick:s}){return s?(0,Y.jsx)(S,{align:"left",className:N("h-auto min-h-0 w-full bg-modiff-surface p-3 text-sm font-normal",t),fullWidth:!0,onClick:s,tone:"secondary",children:e}):(0,Y.jsx)("div",{className:N("w-full rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-left text-sm text-modiff-text",t),children:e})}function te({label:e,value:t}){return(0,Y.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,Y.jsx)("div",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,Y.jsx)("div",{className:"mt-1 text-base font-bold text-modiff-text",children:t})]})}function se(e){return"default"===e?"neutral":e}function ae({children:e,disabled:t,onClick:s,progress:a,testId:l,title:i,tone:n}){return(0,Y.jsx)(I,{action:"Installing"===("string"==typeof e?e:void 0)?"installing":s?"install":"success"===n?"ready":"warning"===n||"error"===n?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:t,label:e,onClick:s,progress:a,testId:l,title:i,tone:se(n)})}function le(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){let t=e;return String(t.id??t.repo_id??t.label??t.rel_path??t.path??JSON.stringify(e))}return String(e??"")}function ie(e){let t=le(e);return t.replace(/\\/g,"/").split("/").filter(Boolean).slice(-2).join("/")||t}var ne=["Image","Edit","Control","Video","Audio","Adapters","Components","Other"];function re(e){return"Audio"===e?"Audio":"Video"===e?"Video":"Control"===e?"Control":"Image Edit"===e?"Edit":"Utility"===e?"Adapters":"Image"===e?"Image":"Other"}function de(e){let t=le(e).toLowerCase();return t.includes("text_encoder")||t.includes("text encoder")||t.includes("vae")||t.includes("tokenizer")||t.includes("transformer")||t.includes("diffusion_model")||t.includes("clip")?"Components":t.includes("wan")||t.includes("video")?"Video":t.includes("ace")||t.includes("audio")?"Audio":t.includes("control")||t.includes("canny")||t.includes("depth")?"Control":t.includes("lora")||t.includes("adapter")?"Adapters":t.includes("edit")||t.includes("inpaint")||t.includes("fill")||t.includes("kontext")||t.includes("redux")?"Edit":t.includes("image")||t.includes("flux")||t.includes("z-image")||t.includes("qwen")?"Image":"Other"}var oe=["repo_id","model_id","repository_id","model","model_name","checkpoint","ckpt_name","path"];function ce(e){return String(e??"").replace(/\\/g,"/").toLowerCase()}function me(e,t,s){let a=function(e){let t=ce(le(e));return Object.values(x).find(e=>function(e,t){return[e.defaultRepo,e.alternateArtifact,e.label,e.displayName,e.family].some(e=>{let s=ce(e);return s.length>0&&(t.includes(s)||s.includes(t))})}(e,t))}(e),l=t.find(e=>e.modelType===a?.modelType)?.executionProfiles??[];if(l.length>0){let e=new Set;return l.map(e=>({key:`${e.loader_module}.${e.loader_action}`,identityKey:"ModelsLoader"===e.loader_action?"model_type":"pipeline_class",identity:"ModelsLoader"===e.loader_action?e.model_type:e.pipeline_class})).filter(t=>{let s=`${t.key}:${t.identityKey}:${t.identity}`;return!e.has(s)&&(e.add(s),!0)})}if(a&&s)return[];let i=a?re(a.surfaceCategory):de(e);return[{key:`modules.Diffusers${"Audio"===i?"Audio":"Video"===i?"Video":"Image"}.LoadPipeline`},{key:"modules.ModularDiffusers.ModelsLoader",...a?{identityKey:"model_type",identity:a.modelType}:{}}]}function ue(e,t){return t.find(t=>e.data.params[t])}function fe(e,t,s){e.data.params={...e.data.params,[t]:{...e.data.params[t],value:s}}}function pe(e,t){let s=new Map;return ne.forEach(e=>s.set(e,[])),e.forEach(e=>s.get(t(e))?.push(e)),ne.map(e=>[e,s.get(e)??[]]).filter(([,e])=>e.length>0)}function xe(e){return"audio"===e?(0,Y.jsx)(p,{size:14}):"video"===e?(0,Y.jsx)(o,{size:14}):(0,Y.jsx)(l,{size:14})}function he(){let e=W(e=>e.setTemplateBrowserOpen),s=W(e=>e.openTemplateBrowser),a=L.filter(e=>"blocked"===e.difficulty||"blocked"===e.example?.status).length,l=L.length-a,i=new Map(J.map(e=>[e.id,"all"===e.id?l:L.filter(t=>F(t)===e.id&&"blocked"!==t.difficulty&&"blocked"!==t.example?.status).length])),n=J.filter(e=>"recommended"!==e.id&&("all"===e.id||(i.get(e.id)??0)>0));return(0,Y.jsx)(Z,{title:"Templates",meta:`${l} usable, ${a} blocked`,icon:(0,Y.jsx)(t,{size:18}),action:(0,Y.jsx)(S,{className:"h-8 px-2 text-xs","data-testid":"left-open-template-browser",icon:(0,Y.jsx)(t,{size:14}),onClick:()=>s("recommended"),tone:"primary",children:"Browse"}),children:(0,Y.jsxs)("div",{className:"grid gap-2",children:[(0,Y.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Y.jsx)(te,{label:"Templates",value:L.length}),(0,Y.jsx)(te,{label:"Planning",value:a})]}),(0,Y.jsxs)(ee,{className:"flex-col items-stretch gap-2",onClick:()=>e(!0),children:[(0,Y.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[(0,Y.jsx)(t,{size:16,className:"text-hf-yellow"}),"Template browser"]}),(0,Y.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"Search by task, model, inputs, media type, and backend requirement."})]}),(0,Y.jsx)("div",{className:"grid gap-1",children:n.map(e=>(0,Y.jsxs)(S,{align:"left",className:"min-h-9 justify-between bg-modiff-bg px-2 font-normal",fullWidth:!0,onClick:()=>s(e.id),tone:"secondary",children:[(0,Y.jsx)("span",{className:"truncate",children:e.label}),(0,Y.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:i.get(e.id)??0})]},e.id))})]})})}function ge(){let e=W(e=>e.setGalleryLibraryOpen),t=k(e=>e.outputs),a=k(e=>e.importedAssets),i=k(e=>e.addImportedAssets),r=k(e=>e.useImportedAssetAsReference),o=k(e=>e.activeWorkflowTabId),c=(0,X.useRef)(null),m=V(e=>e.taskCount),[u,p]=(0,X.useState)(!1),x=(0,X.useMemo)(()=>w(t,o),[o,t]),h=x.filter(e=>"video"===e.displayType).length,b=x.filter(e=>"audio"===e.displayType).length,y=x.slice(0,9),j=a.slice(0,6);return(0,Y.jsx)(Z,{title:"Assets",meta:`${x.length} generated, ${a.length} imported`,icon:(0,Y.jsx)(n,{size:18}),actionPlacement:"stacked",action:(0,Y.jsxs)("div",{className:"grid min-w-0 grid-cols-3 gap-1",children:[(0,Y.jsx)(E,{ref:c,"aria-label":"Import assets",className:"hidden",multiple:!0,onChange:e=>{(async e=>{try{let t=await async function(e){return e?(await Promise.all(Array.from(e).map(async(e,t)=>{let s=function(e){return T(e,["image","video","audio"])??"unknown"}(e);if("unknown"===s)return null;let a=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now()}-${t}-${e.name}`;try{let l=await async function(e,t){let[s]=await O(e,function(e){return"audio"===e?"audio":"video"===e?"videos":"images"}(t));if(!s)throw Error("Imported asset upload did not return a file path.");return s}(e,s);return{id:a,kind:"imported",name:e.name,url:`${D.serverAddress}/file?file=${encodeURIComponent(l)}`,backendPath:l,displayType:s,mimeType:e.type,byteSize:e.size,createdAt:Date.now()-t,source:"upload",storage:"backend"}}catch(t){throw Error(`${e.name}: ${t instanceof Error?t.message:"The backend could not validate this media file."}`)}}))).filter(e=>null!==e):[]}(e);i(t)}catch(e){C(e instanceof Error?e.message:"The selected media could not be imported.",{variant:"error",autoHideDuration:6e3})}finally{c.current&&(c.current.value="")}})(e.currentTarget.files)},accept:g(["image","video","audio"])}),(0,Y.jsx)(S,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-clean-temporary-media",disabled:u||m>0,icon:u?(0,Y.jsx)(s,{size:14,className:"animate-spin"}):(0,Y.jsx)(f,{size:14}),onClick:()=>{(async()=>{if(!(u||m>0)){p(!0);try{let e=await B();C(0===e.removed.length?"No unprotected temporary media to clean":`Removed ${e.removed.length} temporary media ${1===e.removed.length?"file":"files"}`,{variant:"success",autoHideDuration:3e3})}catch(e){C(String(e),{variant:"error",autoHideDuration:6e3})}finally{p(!1)}}})()},tone:"secondary",title:m>0?"Wait for the active generation to finish":"Remove unprotected temporary media",children:"Clean"}),(0,Y.jsx)(S,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-import-assets",icon:(0,Y.jsx)(d,{size:14}),onClick:()=>c.current?.click(),tone:"secondary",title:"Import local media. Assets are persisted through the backend when connected.",children:"Import"}),(0,Y.jsx)(S,{className:"h-8 min-w-0 px-1.5 text-xs","data-testid":"left-open-gallery-library",icon:(0,Y.jsx)(n,{size:14}),onClick:()=>e(!0),tone:"primary",children:"Open"})]}),children:(0,Y.jsxs)("div",{className:"grid gap-2",children:[(0,Y.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Y.jsx)(te,{label:"Generated",value:x.length}),(0,Y.jsx)(te,{label:"Imported",value:a.length}),(0,Y.jsx)(te,{label:"Videos",value:h}),(0,Y.jsx)(te,{label:"Audio",value:b})]}),(0,Y.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,Y.jsx)("span",{children:"Generated"}),(0,Y.jsx)(ae,{tone:"default",children:x.length})]}),(0,Y.jsx)("div",{className:"grid grid-cols-3 gap-1","data-testid":"left-gallery-thumbnails",children:0===y.length?(0,Y.jsx)("div",{className:"col-span-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"No outputs yet."}):y.map((t,s)=>(0,Y.jsx)(S,{"data-testid":`left-gallery-output-${s}`,title:`${t.modelLabel}${t.prompt?` | ${t.prompt}`:""}`,"aria-label":`Open gallery item from ${t.modelLabel}`,className:"aspect-square h-auto min-h-0 overflow-hidden bg-modiff-bg !p-0",onClick:()=>e(!0),tone:"secondary",children:"audio"===t.displayType||"video"===t.displayType?(0,Y.jsx)("span",{className:"grid h-full w-full place-items-center text-hf-yellow",children:xe(t.displayType)}):(0,Y.jsx)("img",{src:t.url,alt:"",className:"h-full w-full object-cover"})},t.id))}),(0,Y.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,Y.jsx)("span",{children:"Imported"}),(0,Y.jsx)(ae,{tone:"default",children:a.length})]}),(0,Y.jsx)("div",{className:"grid grid-cols-3 gap-1","data-testid":"left-imported-thumbnails",children:0===j.length?(0,Y.jsx)(S,{align:"left",className:"col-span-3 h-auto min-h-0 border-dashed bg-modiff-bg p-3 text-xs text-modiff-subtle-text",fullWidth:!0,onClick:()=>c.current?.click(),tone:"secondary",title:"Import local media. Assets are persisted through the backend when connected.",children:"Import assets"}):j.map((e,t)=>(0,Y.jsx)(S,{"data-testid":`left-imported-asset-${t}`,title:e.name,"aria-label":`Use imported asset ${e.name}`,className:"aspect-square h-auto min-h-0 overflow-hidden bg-modiff-bg !p-0",onClick:()=>r(e),tone:"secondary",children:"image"===e.displayType?(0,Y.jsx)("img",{src:e.url,alt:"",className:"h-full w-full object-cover"}):(0,Y.jsx)("span",{className:"grid h-full w-full place-items-center text-hf-yellow",children:xe(e.displayType)})},e.id))}),(0,Y.jsx)(ee,{onClick:()=>e(!0),children:(0,Y.jsxs)("div",{className:"flex items-center justify-between gap-2 font-semibold",children:[(0,Y.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,Y.jsx)(l,{size:16,className:"text-hf-yellow"}),(0,Y.jsx)("span",{className:"truncate",children:"Open gallery"})]}),(0,Y.jsx)(ae,{tone:"default",children:x.length})]})})]})})}function be(){let e=U(e=>e.hfCache),t=U(e=>e.localModels),s=U(e=>e.modelCacheDiagnostics),l=U(e=>e.hfDownloadProgress),n=U(e=>e.nodesRegistry),d=U(e=>e.studioModelCapabilities),o=U(e=>e.studioModelCapabilitiesAuthoritative),c=U(e=>e.installHfModel),m=U(e=>e.fetchRuntimeStatus),f=U(e=>e.fetchHfCache),p=U(e=>e.fetchLocalModels),g=U(e=>e.fetchModelCacheDiagnostics),v=W(e=>e.setModelManagerOpener),w=W(e=>e.setRightPanelOpen),I=W(e=>e.setRightPanelTab),T=k(e=>e.form),L=k(e=>e.activeTemplateId),O=k(e=>e.graphBinding),D=k(e=>e.sourceOutputId),R=k(e=>e.autoResourcePlans),E=k(e=>e.setAutoResourcePlans),V=_(e=>e.sid),B=b(e=>e.addNode),G=b(e=>e.viewport),F=b(e=>e.nodes.length),[J,ee]=(0,X.useState)(new Set);(0,X.useEffect)(()=>{m(),f(!1),p(!1),g(!1)},[f,p,g,m]);let te=!!(L||O||D),se=x[T.modelType],ae=(0,X.useMemo)(()=>K({currentModelType:te?T.modelType:null,includeWorkflowOnly:!0}),[T.modelType,te]),ne=(0,X.useMemo)(()=>ae.map(e=>M(e.modelType)),[ae]),ce=(0,X.useMemo)(()=>ne.map(e=>y(e)),[ne]),xe=(0,X.useMemo)(()=>function(e){let t=new Set;return e.filter(({item:e,source:s})=>{let a=`${s}:${le(e).toLowerCase()}`;return!t.has(a)&&(t.add(a),!0)})}([...e.map(e=>({source:"HF",item:e})),...t.map(e=>({source:"Local",item:e}))]),[e,t]),he=(0,X.useMemo)(()=>pe(xe,({item:e})=>de(e)),[xe]),ge=(0,X.useMemo)(()=>Object.values(l).filter(e=>P(e)||H(e)||z(e)).sort((e,t)=>(t.updated_at??t.completed_at??t.started_at??0)-(e.updated_at??e.completed_at??e.started_at??0)),[l]),be=(0,X.useMemo)(()=>ae.filter(a=>!j(a,e,t,s).runnable),[e,t,s,ae]),je=(0,X.useMemo)(()=>pe(be,e=>re(e.surfaceCategory)),[be]),ve=he,Ne=te&&se?h({form:T,autoResourcePlan:R[y(T)],hfCache:e,localModels:t,modelCacheDiagnostics:s,includePipeline:!1}):[];(0,X.useEffect)(()=>{if(0===ne.length)return;let e=!1;return A(ne,ce).then(t=>{if(e)return;let s={};t.forEach((e,t)=>{let a=e.planKey??ce[t];a&&(s[a]=e)}),E(s)}).catch(e=>{console.error(e)}),()=>{e=!0}},[E,ne,ce]);let we=()=>{w(!0),I("setup")},ke=(0,X.useCallback)(e=>{ee(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},[]),Ce=async e=>{try{await c(e.repo,V,{repair:e.repair,revision:e.revision,files:e.files})}catch(e){console.error(e)}},Ie=(0,X.useCallback)((e,t)=>{let s=le(e),a=me(e,d,o),l=function(e,t){let s=e.zoom||1,a=t%6*36;return{x:(220-e.x+a)/s,y:(140-e.y+a)/s}}(G,F),i=a.map(e=>({candidate:e,node:q(e.key,n,l)})).find(({candidate:e,node:t})=>t&&(ue(t,oe)||ue(t,["model_type"]))&&(!e.identityKey||ue(t,[e.identityKey]))),r=i?.node;if(!r)return void C("No matching loader node is available yet.",{variant:"error",autoHideDuration:2800});let c=i.candidate.identityKey;c&&i.candidate.identity&&fe(r,c,i.candidate.identity);let m=ue(r,oe);m&&fe(r,m,function(e,t,s,a){let l=t.data.params[s],i=l?.value??l?.default;return"modelselect"===l?.display||i&&"object"==typeof i&&!Array.isArray(i)?{source:"Local"===e?"local":"hub",value:a}:a}(t,r,m,s)),B({...r,selected:!0}),C(`Added ${ie(e)} loader`,{variant:"success",autoHideDuration:1800})},[B,F,n,d,o,G]);return(0,Y.jsx)(Z,{title:"Models",meta:`${xe.length} installed, ${be.length} available`,icon:(0,Y.jsx)(r,{size:18}),action:(0,Y.jsx)(S,{className:"h-8 px-2 text-xs","data-testid":"left-open-model-manager",icon:(0,Y.jsx)(i,{size:14}),onClick:()=>v({nodeId:null,fieldKey:null}),tone:"primary",children:"Models"}),children:(0,Y.jsxs)("div",{className:"grid gap-2",children:[ge.length>0?(0,Y.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-downloads",children:[(0,Y.jsxs)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,Y.jsx)("span",{children:"Downloads"}),(0,Y.jsxs)("span",{children:[ge.filter(P).length," active"]})]}),ge.slice(0,3).map(e=>(0,Y.jsx)($,{compact:!0,progress:e,showTechnicalDetails:!1,testId:`left-model-download-${e.repo_id}`},e.repo_id)),ge.length>3?(0,Y.jsxs)(S,{tone:"ghost",onClick:()=>v({nodeId:null,fieldKey:null}),children:["View all ",ge.length," downloads"]}):null]}):null,te&&se?(0,Y.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-current",children:[(0,Y.jsx)("div",{className:"flex items-center justify-between gap-2 px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:(0,Y.jsx)("span",{children:"Current"})}),(0,Y.jsx)(ye,{autoPlan:R[y(T)],installProgress:l,onInstall:Ce,onOpenSetup:we,profile:se,status:j(se,e,t,s)}),Ne.map(e=>(0,Y.jsx)(Q,{actionTestId:`left-install-requirement-${e.id}`,compact:!0,installProgress:l,onInstall:Ce,onUseLocal:()=>v({nodeId:null,fieldKey:null,focus:{repo:e.repo,requirementId:e.id,label:e.label,source:"workflow"}}),requirement:e,testId:`left-model-requirement-${e.id}`},e.id))]}):null,(0,Y.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-installed",children:[(0,Y.jsxs)("div",{className:"px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:["Installed (",xe.length,")"]}),0===xe.length||0===ve.length?(0,Y.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"No visible model artifacts indexed yet."}):ve.map(([e,t])=>{let s=`installed:${e}`,l=J.has(s);return(0,Y.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg",children:[(0,Y.jsxs)(S,{align:"left",className:"min-h-9 justify-between rounded-none border-0 bg-transparent px-2",fullWidth:!0,tone:"ghost",onClick:()=>ke(s),children:[(0,Y.jsx)("span",{className:"truncate",children:e}),(0,Y.jsxs)("span",{className:"flex shrink-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[t.length,(0,Y.jsx)(u,{size:15,className:N("transition-transform",l&&"rotate-180")})]})]}),l?(0,Y.jsx)("div",{className:"grid gap-1 border-t border-modiff-border p-1",children:t.map(({item:e,source:t})=>(0,Y.jsxs)(S,{align:"left",fullWidth:!0,title:le(e),onClick:()=>Ie(e,t),className:"min-h-10 justify-between bg-modiff-bg p-2 font-normal",tone:"secondary",children:[(0,Y.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,Y.jsx)(a,{size:15,className:"shrink-0 text-modiff-subtle-text"}),(0,Y.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:ie(e)})]}),(0,Y.jsx)("span",{className:"shrink-0 text-xs font-semibold text-modiff-subtle-text",children:t})]},`${t}-${le(e)}`))}):null]},e)})]}),be.length>0?(0,Y.jsxs)("section",{className:"grid gap-1","data-testid":"left-model-supported",children:[(0,Y.jsxs)("div",{className:"px-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:["Available (",be.length,")"]}),je.map(([a,i])=>{let n=`available:${a}`,r=J.has(n);return(0,Y.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg",children:[(0,Y.jsxs)(S,{align:"left",className:"min-h-9 justify-between rounded-none border-0 bg-transparent px-2",fullWidth:!0,onClick:()=>ke(n),tone:"ghost",children:[(0,Y.jsx)("span",{className:"truncate",children:a}),(0,Y.jsxs)("span",{className:"flex shrink-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[i.length,(0,Y.jsx)(u,{size:15,className:N("transition-transform",r&&"rotate-180")})]})]}),r?(0,Y.jsx)("div",{className:"grid gap-1 border-t border-modiff-border p-1",children:i.map(a=>{let i=y(M(a.modelType));return(0,Y.jsx)(ye,{autoPlan:R[i],installProgress:l,onInstall:Ce,onOpenSetup:we,profile:a,status:j(a,e,t,s)},a.modelType)})}):null]},a)})]}):null]})})}function ye({autoPlan:e,installProgress:t,onInstall:s,onOpenSetup:a,profile:l,status:i}){let n=G(e)??{repo:l.defaultRepo,label:l.label,actionLabel:"Install"},r=t[n.repo],d=v(e),o="queued"===r?.status||"running"===r?.status||"downloading"===r?.status,c="unsuitable"!==d.state||i.runnable?"warning":"error",m=o?"Installing":n.actionLabel??"Install",u=n.reason||`Install ${n.repo}`;return(0,Y.jsx)("div",{"data-testid":`left-model-${l.modelType}`,className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:(0,Y.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,Y.jsxs)(S,{align:"left",className:"h-auto min-h-0 min-w-0 flex-1 bg-transparent p-0 font-normal",tone:"ghost",title:`${l.defaultRepo} | ${d.summary} | ${d.detail}`,onClick:a,children:[(0,Y.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text",children:l.label}),(0,Y.jsx)("div",{className:"mt-0.5 truncate text-xs text-modiff-subtle-text",children:l.family})]}),!i.runnable&&(0,Y.jsx)(ae,{tone:c,testId:`left-install-${l.modelType}`,title:u,disabled:o,progress:o?R(r):null,onClick:()=>{s(n)},children:m})]})})}export{ge as AssetsLibraryPanel,be as ModelsLibraryPanel,he as TemplateLibraryPanel}; \ No newline at end of file diff --git a/web/assets/LegacyOperationOwnerControls.js b/web/assets/LegacyOperationOwnerControls.js index 2d77ca8..f1f865d 100644 --- a/web/assets/LegacyOperationOwnerControls.js +++ b/web/assets/LegacyOperationOwnerControls.js @@ -1 +1 @@ -import{r}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as o,dr as e}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Vr as t}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n}from"./operationLegacyBlockChange.js?v=cc046c26d6fe7aa4";import{BlockOwnerChoices as s}from"./OperationOwnerControls.js?v=cc046c26d6fe7aa4";var a=r(e(),1),i=o();function d({nodeId:r}){let o=t(r=>r.nodes),e=t(r=>r.edges),d=(0,a.useMemo)(()=>{try{return{root:n({nodes:o,edges:e},r).root}}catch(r){return{error:r instanceof Error?r.message:String(r)}}},[o,e,r]);return d.root?(0,i.jsx)(s,{node:d.root,ownerBlockId:r,inline:!0}):(0,i.jsx)("p",{role:"alert",children:d.error})}export{d as default}; \ No newline at end of file +import{r}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as o,dr as e}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Hr as t}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n}from"./operationLegacyBlockChange.js?v=ca6b74e6a02eedb3";import{BlockOwnerChoices as s}from"./OperationOwnerControls.js?v=ca6b74e6a02eedb3";var a=r(e(),1),i=o();function d({nodeId:r}){let o=t(r=>r.nodes),e=t(r=>r.edges),d=(0,a.useMemo)(()=>{try{return{root:n({nodes:o,edges:e},r).root}}catch(r){return{error:r instanceof Error?r.message:String(r)}}},[o,e,r]);return d.root?(0,i.jsx)(s,{node:d.root,ownerBlockId:r,inline:!0}):(0,i.jsx)("p",{role:"alert",children:d.error})}export{d as default}; \ No newline at end of file diff --git a/web/assets/LegacyUserBlockNode.js b/web/assets/LegacyUserBlockNode.js index e0885fb..8b4e21f 100644 --- a/web/assets/LegacyUserBlockNode.js +++ b/web/assets/LegacyUserBlockNode.js @@ -1 +1 @@ -import{Ei as e,Ti as t,V as a,Vr as o,ji as r,li as i,mi as s,si as n}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{a as l}from"./block-composition-tools.js?v=cc046c26d6fe7aa4";function d(e){let t=o.getState(),a=new Set(t.nodes.filter(t=>t.id===e||t.data.userBlockInstanceId===e).map(e=>e.id));return JSON.stringify({nodes:t.nodes.filter(e=>a.has(e.id)).map(e=>[e.id,e.parentId,e.position,e.data.params,e.data.userBlockSnapshot]).sort(([e],[t])=>String(e).localeCompare(String(t))),edges:t.edges.filter(e=>a.has(e.source)||a.has(e.target)).map(e=>[e.id,e.source,e.sourceHandle,e.target,e.targetHandle]).sort(([e],[t])=>String(e).localeCompare(String(t)))})}async function c({instanceId:l,choice:c,workflowTitle:f,context:g=e()},p=e=>n.getState().saveBlock(e)){let m=s(o.getState(),l,n.getState().blocks);if(!m)throw Error("The current User Node definition could not be captured.");let u=d(l),h="new"===c?i(m,a(m.name,f)):m,w="workflow"===c?h:await p(h);if(t(g,{includeForm:!1}),d(l)!==u)throw Error("The User Node changed while its reusable definition was saving. Retry the operation.");let S=o.getState();if(!S.nodes.some(e=>e.id===l&&"block"===e.data.type))throw Error("The User Node instance is no longer available in this workflow.");return S.applyUserBlockDefinition(l,w),r.getState().saveActiveWorkflowTab(!0),w}export{l as default,c as t}; \ No newline at end of file +import{Di as e,Hr as t,Ni as a,Oi as o,V as r,ci as i,gi as s,ui as n}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{a as l}from"./block-composition-tools.js?v=ca6b74e6a02eedb3";function d(e){let a=t.getState(),o=new Set(a.nodes.filter(t=>t.id===e||t.data.userBlockInstanceId===e).map(e=>e.id));return JSON.stringify({nodes:a.nodes.filter(e=>o.has(e.id)).map(e=>[e.id,e.parentId,e.position,e.data.params,e.data.userBlockSnapshot]).sort(([e],[t])=>String(e).localeCompare(String(t))),edges:a.edges.filter(e=>o.has(e.source)||o.has(e.target)).map(e=>[e.id,e.source,e.sourceHandle,e.target,e.targetHandle]).sort(([e],[t])=>String(e).localeCompare(String(t)))})}async function c({instanceId:l,choice:c,workflowTitle:g,context:f=o()},p=e=>i.getState().saveBlock(e)){let u=s(t.getState(),l,i.getState().blocks);if(!u)throw Error("The current User Node definition could not be captured.");let h=d(l),m="new"===c?n(u,r(u.name,g)):u,w="workflow"===c?m:await p(m);if(e(f,{includeForm:!1}),d(l)!==h)throw Error("The User Node changed while its reusable definition was saving. Retry the operation.");let S=t.getState();if(!S.nodes.some(e=>e.id===l&&"block"===e.data.type))throw Error("The User Node instance is no longer available in this workflow.");return S.applyUserBlockDefinition(l,w),a.getState().saveActiveWorkflowTab(!0),w}export{l as default,c as t}; \ No newline at end of file diff --git a/web/assets/LightboxDialog.js b/web/assets/LightboxDialog.js index e772ad2..d5b52a3 100644 --- a/web/assets/LightboxDialog.js +++ b/web/assets/LightboxDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Dn as o,E as t,On as a,an as n,cr as r,dr as l,pn as i,un as s}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{An as d,In as f,Mo as m,Sa as c,an as u,ht as h,in as g,rn as p,wt as x}from"./studio-templates.js?v=cc046c26d6fe7aa4";var b=e(l(),1),w=r();function v({opener:e,onClose:r}){let l=c(e=>e.setMediaExportOpener),u=(0,b.useMemo)(()=>(e&&!Array.isArray(e.images)?[e.images]:e?.images||[]).filter(e=>""!==e&&null!=e),[e]),v=(0,b.useMemo)(()=>x({value:u,artifacts:e?.artifacts,dataType:e?.dataType??"url",mimeType:e?.mimeType||"image/webp"}),[e?.artifacts,e?.dataType,e?.mimeType,u]),k=e?Math.min(Math.max(e.currentIndex,0),Math.max(v.length-1,0)):0,[C,M]=(0,b.useState)(k),[E,L]=(0,b.useState)({}),[N,T]=(0,b.useState)(50),[$,D]=(0,b.useState)(!1),z=(0,b.useRef)(null);(0,b.useEffect)(()=>{M(k)},[k]),(0,b.useEffect)(()=>{let e=()=>D(!1);return window.addEventListener("mouseup",e),window.addEventListener("touchend",e),()=>{window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e)}},[]);let P=(0,b.useCallback)(e=>{let o=z.current?.getBoundingClientRect();if(!o?.width)return;let t=Math.max(0,Math.min(e-o.left,o.width));T(t/o.width*100)},[]);(0,b.useEffect)(()=>{if(!e)return;let o=e=>{"ArrowLeft"===e.key?(e.preventDefault(),M(e=>(e-1+v.length)%v.length)):"ArrowRight"===e.key&&(e.preventDefault(),M(e=>(e+1)%v.length))};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[v.length,r,e]);let I=e=>{e.currentTarget.src=h};if(!e||0===v.length)return null;let S=v[C]??v[0];return S?(0,w.jsx)(g,{open:!0,onClose:r,title:e.comparison?"A/B image comparison":v.length>1?`Image ${C+1} of ${v.length}`:"Image preview",panelClassName:"flex h-[96vh] max-h-none max-w-[96vw] flex-col bg-modiff-media-backdrop/85",bodyClassName:"!max-h-none min-h-0 flex-1 !p-0",children:(0,w.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,w.jsxs)("div",{className:"relative flex min-h-0 w-full flex-1 items-center justify-center overflow-hidden px-4 py-8",onMouseDown:e=>{e.target===e.currentTarget&&r()},children:[e.comparison?(0,w.jsx)(d,{ref:z,imageFrom:e.comparison.beforeUrl,imageTo:S.url,beforeLabel:e.comparison.beforeLabel,afterLabel:e.comparison.afterLabel,sliderPosition:N,onSliderPositionChange:T,onError:I,className:"max-h-full max-w-full border-[16px] border-modiff-bg bg-modiff-bg",onMouseDown:e=>{e.stopPropagation(),D(!0),P(e.clientX)},onMouseMove:e=>{$&&P(e.clientX)},onMouseUp:()=>D(!1),onTouchStart:e=>{e.stopPropagation(),D(!0),P(e.touches[0]?.clientX??0)},onTouchMove:e=>{$&&P(e.touches[0]?.clientX??0)},onTouchEnd:()=>D(!1)}):(0,w.jsx)("img",{src:S.url,alt:`Image ${C+1}`,className:"modiff-generated-image block max-h-full max-w-full border-[16px] border-modiff-bg bg-modiff-bg object-contain",onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onError:I,onLoad:e=>{let{naturalWidth:o,naturalHeight:t}=e.currentTarget;o&&t&&L(e=>({...e,[C]:`${o}x${t}`}))}}),(0,w.jsxs)("div",{className:"nodrag absolute right-4 top-4 flex gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 p-1 text-modiff-text shadow-modiff-panel",children:[(0,w.jsx)(j,{label:"Download image as…",onClick:()=>{l({source:S.url,filename:S.filename||"MoDiff-image.png",kind:"image",defaultFormat:"png",title:"Download image"})},children:(0,w.jsx)(s,{size:18})}),(0,w.jsx)(j,{label:"Copy image URL",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(S.url),m("Image URL copied",{variant:"success",autoHideDuration:1600})}catch{m("Could not copy image URL",{variant:"error",autoHideDuration:2400})}})()},children:(0,w.jsx)(i,{size:18})}),(0,w.jsx)(j,{label:"Open full size",onClick:()=>window.open(S.url,"_blank","noopener,noreferrer"),children:(0,w.jsx)(n,{size:18})}),(0,w.jsx)(j,{label:"Close preview",onClick:r,children:(0,w.jsx)(t,{size:20})})]}),v.length>1&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(y,{label:"Previous image",side:"left",onClick:()=>M(e=>(e-1+v.length)%v.length),children:(0,w.jsx)(a,{size:28})}),(0,w.jsx)(y,{label:"Next image",side:"right",onClick:()=>M(e=>(e+1)%v.length),children:(0,w.jsx)(o,{size:28})})]}),(0,w.jsxs)("div",{className:"pointer-events-none absolute bottom-4 left-1/2 -translate-x-1/2 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-3 py-1 text-sm font-semibold text-modiff-subtle-text shadow-modiff-panel",children:[v.length>1?`${C+1}/${v.length}`:"Image",E[C]?` | ${E[C]}`:""]})]}),v.length>1&&(0,w.jsx)("div",{className:"flex h-32 w-full flex-none items-center justify-center gap-2 overflow-x-auto overflow-y-hidden bg-modiff-panel/90 p-3",children:v.map((e,o)=>(0,w.jsx)(p,{tone:"ghost","aria-label":`Show image ${o+1}`,onClick:()=>M(o),className:f("h-full flex-none border-2 border-transparent p-0",C===o&&"border-hf-yellow"),children:(0,w.jsx)("img",{src:e.url,alt:`Image ${o+1}`,className:"modiff-generated-image block h-full w-auto object-contain",onError:I})},`${e.url}-${o}`))})]})}):null}function j({label:e,onClick:o,children:t}){return(0,w.jsx)(u,{label:e,size:"prominent",className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:e=>{e.stopPropagation(),o()},children:t})}function y({label:e,side:o,onClick:t,children:a}){return(0,w.jsx)(u,{label:e,size:"prominent",className:f("nodrag absolute top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/80 text-modiff-subtle-text shadow-modiff-panel hover:bg-modiff-surface-hover hover:text-hf-yellow","left"===o?"left-4":"right-4"),onClick:e=>{e.stopPropagation(),t()},children:a})}export{v as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Dn as o,E as t,On as a,an as n,cr as r,dr as l,pn as i,un as s}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ln as d,Po as f,Tt as m,an as c,gt as u,in as h,jn as g,on as p,wa as x}from"./studio-templates.js?v=ca6b74e6a02eedb3";var b=e(l(),1),w=r();function v({opener:e,onClose:r}){let l=x(e=>e.setMediaExportOpener),p=(0,b.useMemo)(()=>(e&&!Array.isArray(e.images)?[e.images]:e?.images||[]).filter(e=>""!==e&&null!=e),[e]),v=(0,b.useMemo)(()=>m({value:p,artifacts:e?.artifacts,dataType:e?.dataType??"url",mimeType:e?.mimeType||"image/webp"}),[e?.artifacts,e?.dataType,e?.mimeType,p]),k=e?Math.min(Math.max(e.currentIndex,0),Math.max(v.length-1,0)):0,[C,L]=(0,b.useState)(k),[M,E]=(0,b.useState)({}),[T,N]=(0,b.useState)(50),[$,D]=(0,b.useState)(!1),z=(0,b.useRef)(null);(0,b.useEffect)(()=>{L(k)},[k]),(0,b.useEffect)(()=>{let e=()=>D(!1);return window.addEventListener("mouseup",e),window.addEventListener("touchend",e),()=>{window.removeEventListener("mouseup",e),window.removeEventListener("touchend",e)}},[]);let P=(0,b.useCallback)(e=>{let o=z.current?.getBoundingClientRect();if(!o?.width)return;let t=Math.max(0,Math.min(e-o.left,o.width));N(t/o.width*100)},[]);(0,b.useEffect)(()=>{if(!e)return;let o=e=>{"ArrowLeft"===e.key?(e.preventDefault(),L(e=>(e-1+v.length)%v.length)):"ArrowRight"===e.key&&(e.preventDefault(),L(e=>(e+1)%v.length))};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[v.length,r,e]);let I=e=>{e.currentTarget.src=u};if(!e||0===v.length)return null;let S=v[C]??v[0];return S?(0,w.jsx)(c,{open:!0,onClose:r,title:e.comparison?"A/B image comparison":v.length>1?`Image ${C+1} of ${v.length}`:"Image preview",panelClassName:"flex h-[96vh] max-h-none max-w-[96vw] flex-col bg-modiff-media-backdrop/85",bodyClassName:"!max-h-none min-h-0 flex-1 !p-0",children:(0,w.jsxs)("div",{className:"flex h-full min-h-0 flex-col",children:[(0,w.jsxs)("div",{className:"relative flex min-h-0 w-full flex-1 items-center justify-center overflow-hidden px-4 py-8",onMouseDown:e=>{e.target===e.currentTarget&&r()},children:[e.comparison?(0,w.jsx)(g,{ref:z,imageFrom:e.comparison.beforeUrl,imageTo:S.url,beforeLabel:e.comparison.beforeLabel,afterLabel:e.comparison.afterLabel,sliderPosition:T,onSliderPositionChange:N,onError:I,className:"max-h-full max-w-full border-[16px] border-modiff-bg bg-modiff-bg",onMouseDown:e=>{e.stopPropagation(),D(!0),P(e.clientX)},onMouseMove:e=>{$&&P(e.clientX)},onMouseUp:()=>D(!1),onTouchStart:e=>{e.stopPropagation(),D(!0),P(e.touches[0]?.clientX??0)},onTouchMove:e=>{$&&P(e.touches[0]?.clientX??0)},onTouchEnd:()=>D(!1)}):(0,w.jsx)("img",{src:S.url,alt:`Image ${C+1}`,className:"modiff-generated-image block max-h-full max-w-full border-[16px] border-modiff-bg bg-modiff-bg object-contain",onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onError:I,onLoad:e=>{let{naturalWidth:o,naturalHeight:t}=e.currentTarget;o&&t&&E(e=>({...e,[C]:`${o}x${t}`}))}}),(0,w.jsxs)("div",{className:"nodrag absolute right-4 top-4 flex gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 p-1 text-modiff-text shadow-modiff-panel",children:[(0,w.jsx)(j,{label:"Download image as…",onClick:()=>{l({source:S.url,filename:S.filename||"MoDiff-image.png",kind:"image",defaultFormat:"png",title:"Download image"})},children:(0,w.jsx)(s,{size:18})}),(0,w.jsx)(j,{label:"Copy image URL",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(S.url),f("Image URL copied",{variant:"success",autoHideDuration:1600})}catch{f("Could not copy image URL",{variant:"error",autoHideDuration:2400})}})()},children:(0,w.jsx)(i,{size:18})}),(0,w.jsx)(j,{label:"Open full size",onClick:()=>window.open(S.url,"_blank","noopener,noreferrer"),children:(0,w.jsx)(n,{size:18})}),(0,w.jsx)(j,{label:"Close preview",onClick:r,children:(0,w.jsx)(t,{size:20})})]}),v.length>1&&(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(y,{label:"Previous image",side:"left",onClick:()=>L(e=>(e-1+v.length)%v.length),children:(0,w.jsx)(a,{size:28})}),(0,w.jsx)(y,{label:"Next image",side:"right",onClick:()=>L(e=>(e+1)%v.length),children:(0,w.jsx)(o,{size:28})})]}),(0,w.jsxs)("div",{className:"pointer-events-none absolute bottom-4 left-1/2 -translate-x-1/2 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-3 py-1 text-sm font-semibold text-modiff-subtle-text shadow-modiff-panel",children:[v.length>1?`${C+1}/${v.length}`:"Image",M[C]?` | ${M[C]}`:""]})]}),v.length>1&&(0,w.jsx)("div",{className:"flex h-32 w-full flex-none items-center justify-center gap-2 overflow-x-auto overflow-y-hidden bg-modiff-panel/90 p-3",children:v.map((e,o)=>(0,w.jsx)(h,{tone:"ghost","aria-label":`Show image ${o+1}`,onClick:()=>L(o),className:d("h-full flex-none border-2 border-transparent p-0",C===o&&"border-hf-yellow"),children:(0,w.jsx)("img",{src:e.url,alt:`Image ${o+1}`,className:"modiff-generated-image block h-full w-auto object-contain",onError:I})},`${e.url}-${o}`))})]})}):null}function j({label:e,onClick:o,children:t}){return(0,w.jsx)(p,{label:e,size:"prominent",className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:e=>{e.stopPropagation(),o()},children:t})}function y({label:e,side:o,onClick:t,children:a}){return(0,w.jsx)(p,{label:e,size:"prominent",className:d("nodrag absolute top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/80 text-modiff-subtle-text shadow-modiff-panel hover:bg-modiff-surface-hover hover:text-hf-yellow","left"===o?"left-4":"right-4"),onClick:e=>{e.stopPropagation(),t()},children:a})}export{v as default}; \ No newline at end of file diff --git a/web/assets/LoopNode.js b/web/assets/LoopNode.js index 78908cb..5c3e8d5 100644 --- a/web/assets/LoopNode.js +++ b/web/assets/LoopNode.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,dr as o,nt as t}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Pn as l,Vr as r,bn as s,cn as d,fn as n,hn as i}from"./studio-templates.js?v=cc046c26d6fe7aa4";var m=e(o(),1),c=a();function p(e,a){let o=Number(e);return Number.isFinite(o)?o:a}var f=(0,m.memo)(e=>{let a=r(e=>e.setParamWithHistory),o=r(e=>e.nodes).filter(a=>a.parentId===e.id),m=p(e.data.params.iterations?.value,2),f="collection"===e.data.params.iteration_mode?.value?"collection":"count",x=p(e.data.params.max_iterations?.value,100),u=!1!==e.data.params.carry?.value,b=!1!==e.data.params.collect?.value,h=!0===e.data.params.durable?.value,g=p(e.data.params.max_retries?.value,1),v=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopResult"===e.data.action),j=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopIndex"===e.data.action),N=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopItems"===e.data.action);return(0,c.jsxs)("div",{className:"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-hf-yellow/55 bg-hf-yellow/[0.035] shadow-inner",children:[(0,c.jsxs)("div",{className:"drag-handle flex h-11 items-center gap-2 border-b border-hf-yellow/25 bg-modiff-panel/90 px-3 text-sm font-bold text-modiff-text",children:[(0,c.jsx)(t,{size:16,className:"text-hf-yellow"}),(0,c.jsx)("span",{className:"truncate",children:e.data.label||"Loop"}),e.data.progressMessage?(0,c.jsx)("span",{className:"ml-auto truncate text-xs font-medium text-modiff-subtle-text",children:e.data.progressMessage}):null]}),(0,c.jsx)("div",{className:"nodrag nowheel absolute right-2 top-1.5 flex items-center gap-2 text-xs text-modiff-subtle-text",children:(0,c.jsxs)("div",{className:"flex items-center gap-1",children:[(0,c.jsx)(s,{"aria-label":"Loop repeat mode",value:f,onValueChange:o=>a(e.id,"iteration_mode",o),options:[{value:"count",label:"Count"},{value:"collection",label:"Items"}],size:"compact"}),(0,c.jsx)(i,{"aria-label":"Loop iterations",min:1,max:x,value:m,disabled:"collection"===f,onValueChange:o=>a(e.id,"iterations",o??1),controlSize:"compact",className:"nodrag w-16"})]})}),(0,c.jsxs)("div",{className:"nodrag nowheel absolute bottom-2 left-2 flex items-center gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-2 py-1 text-xs text-modiff-subtle-text",children:[(0,c.jsx)(d,{checked:u,label:"Carry",onCheckedChange:o=>a(e.id,"carry",o)}),(0,c.jsx)(d,{checked:b,label:"Collect",onCheckedChange:o=>a(e.id,"collect",o)}),(0,c.jsx)(d,{checked:h,label:"Resume",onCheckedChange:o=>a(e.id,"durable",o)}),(0,c.jsxs)("span",{children:["Limit ",x]}),(0,c.jsx)(n,{label:"Retries",layout:"inline",className:"gap-1",children:(0,c.jsx)(i,{"aria-label":"Loop retries",min:0,max:10,value:g,onValueChange:o=>a(e.id,"max_retries",o??1),controlSize:"compact",className:"nodrag w-12 px-1"})})]}),v?"collection"!==f||N?j||"count"!==f?null:(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-2 py-1 text-xs text-modiff-subtle-text",children:"Add Loop Index when the body needs a changing seed, item, or parameter."}):(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-hf-orange/40 bg-modiff-panel/90 px-2 py-1 text-xs text-hf-orange",children:"Add one Loop Items node and connect its collection."}):(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-hf-orange/40 bg-modiff-panel/90 px-2 py-1 text-xs text-hf-orange",children:"Add one Loop Result node and connect the value to return."}),(0,c.jsx)(l,{})]})});f.displayName="LoopNode";export{f as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,dr as o,nt as t}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Fn as l,Hr as r,gn as s,ln as d,pn as n,xn as i}from"./studio-templates.js?v=ca6b74e6a02eedb3";var m=e(o(),1),c=a();function p(e,a){let o=Number(e);return Number.isFinite(o)?o:a}var x=(0,m.memo)(e=>{let a=r(e=>e.setParamWithHistory),o=r(e=>e.nodes).filter(a=>a.parentId===e.id),m=p(e.data.params.iterations?.value,2),x="collection"===e.data.params.iteration_mode?.value?"collection":"count",f=p(e.data.params.max_iterations?.value,100),u=!1!==e.data.params.carry?.value,b=!1!==e.data.params.collect?.value,h=!0===e.data.params.durable?.value,g=p(e.data.params.max_retries?.value,1),v=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopResult"===e.data.action),j=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopIndex"===e.data.action),N=o.some(e=>"modules.WorkflowControl"===e.data.module&&"LoopItems"===e.data.action);return(0,c.jsxs)("div",{className:"relative h-full w-full rounded-modiff-panel border-2 border-dashed border-hf-yellow/55 bg-hf-yellow/[0.035] shadow-inner",children:[(0,c.jsxs)("div",{className:"drag-handle flex h-11 items-center gap-2 border-b border-hf-yellow/25 bg-modiff-panel/90 px-3 text-sm font-bold text-modiff-text",children:[(0,c.jsx)(t,{size:16,className:"text-hf-yellow"}),(0,c.jsx)("span",{className:"truncate",children:e.data.label||"Loop"}),e.data.progressMessage?(0,c.jsx)("span",{className:"ml-auto truncate text-xs font-medium text-modiff-subtle-text",children:e.data.progressMessage}):null]}),(0,c.jsx)("div",{className:"nodrag nowheel absolute right-2 top-1.5 flex items-center gap-2 text-xs text-modiff-subtle-text",children:(0,c.jsxs)("div",{className:"flex items-center gap-1",children:[(0,c.jsx)(i,{"aria-label":"Loop repeat mode",value:x,onValueChange:o=>a(e.id,"iteration_mode",o),options:[{value:"count",label:"Count"},{value:"collection",label:"Items"}],size:"compact"}),(0,c.jsx)(s,{"aria-label":"Loop iterations",min:1,max:f,value:m,disabled:"collection"===x,onValueChange:o=>a(e.id,"iterations",o??1),controlSize:"compact",className:"nodrag w-16"})]})}),(0,c.jsxs)("div",{className:"nodrag nowheel absolute bottom-2 left-2 flex items-center gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-2 py-1 text-xs text-modiff-subtle-text",children:[(0,c.jsx)(d,{checked:u,label:"Carry",onCheckedChange:o=>a(e.id,"carry",o)}),(0,c.jsx)(d,{checked:b,label:"Collect",onCheckedChange:o=>a(e.id,"collect",o)}),(0,c.jsx)(d,{checked:h,label:"Resume",onCheckedChange:o=>a(e.id,"durable",o)}),(0,c.jsxs)("span",{children:["Limit ",f]}),(0,c.jsx)(n,{label:"Retries",layout:"inline",className:"gap-1",children:(0,c.jsx)(s,{"aria-label":"Loop retries",min:0,max:10,value:g,onValueChange:o=>a(e.id,"max_retries",o??1),controlSize:"compact",className:"nodrag w-12 px-1"})})]}),v?"collection"!==x||N?j||"count"!==x?null:(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-modiff-border bg-modiff-panel/90 px-2 py-1 text-xs text-modiff-subtle-text",children:"Add Loop Index when the body needs a changing seed, item, or parameter."}):(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-hf-orange/40 bg-modiff-panel/90 px-2 py-1 text-xs text-hf-orange",children:"Add one Loop Items node and connect its collection."}):(0,c.jsx)("div",{className:"pointer-events-none absolute bottom-12 left-2 rounded-modiff-compact border border-hf-orange/40 bg-modiff-panel/90 px-2 py-1 text-xs text-hf-orange",children:"Add one Loop Result node and connect the value to return."}),(0,c.jsx)(l,{})]})});x.displayName="LoopNode";export{x as default}; \ No newline at end of file diff --git a/web/assets/MediaAttachmentControls.js b/web/assets/MediaAttachmentControls.js index f134878..ca3f3fd 100644 --- a/web/assets/MediaAttachmentControls.js +++ b/web/assets/MediaAttachmentControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ei as n,Eo as r,Fo as i,Jo as l,Po as o,Si as s,Ti as d,Vr as u,bn as p,dn as c,fn as m,rn as f}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as b,t as h}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{t as g}from"./operationStarterRequest.js?v=cc046c26d6fe7aa4";import"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{a as j,i as y,n as x,t as S}from"./mediaAttachment.js?v=cc046c26d6fe7aa4";var k=e(a(),1),v=t();function I({node:e,initialSource:t,onAttached:a,inline:I=!1}){let A=s(e=>e.operationContracts),C=s(e=>e.pipelineSupport),O=u(e=>e.nodes),[w,N]=(0,k.useState)(""),[P,E]=(0,k.useState)(t?JSON.stringify([t.nodeId,t.handleId]):""),[R,J]=(0,k.useState)(null),[M,T]=(0,k.useState)(!1),V=(0,k.useRef)(null);(0,k.useEffect)(()=>()=>V.current?.abort(),[]);let q=l(e),F=x(S(A,C),q?.operation.pipelineClass??""),$=F.find(e=>e.key===w)??F.find(e=>e.task===q?.operation.task)??F[0];if(!$||e.parentId&&!e.data.blockProjectionOwnerId)return null;let _=O.flatMap(e=>{let a={...i(e)};if(t?.nodeId===e.id){let n=o(e,t.handleId);n&&(a[t.handleId]=n)}return Object.entries(a).filter(([,e])=>"output"===e.display&&!e.hidden&&!e.disabled&&(Array.isArray(e.type)?e.type:[e.type]).includes($.kind)).map(([t,a])=>({value:JSON.stringify([e.id,t]),label:`${e.data.label} · ${a.label??t}`}))});return(0,v.jsxs)(c,{label:"Add image / audio input",collapsible:!t&&!I,panelClassName:"grid gap-2 py-2",children:[(0,v.jsx)(m,{label:"Use input for",children:(0,v.jsx)(p,{"aria-label":"Media input role",value:$.key,disabled:M,options:F.map(e=>({value:e.key,label:e.label})),onValueChange:e=>{N(e),J(null)}})}),(0,v.jsx)(m,{label:"Source",children:(0,v.jsx)(p,{"aria-label":"Media input source",value:_.some(e=>e.value===P)?P:"",disabled:M,options:[{value:"",label:"Add Load "+("image"===$.kind?"Image":"Audio")},..._],onValueChange:E})}),(0,v.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Reuses this model and adds only the required encoding stages. Existing prompts and custom branches are retained."}),(0,v.jsx)(f,{tone:"primary",disabled:M,onClick:()=>{!async function(){if(!$||V.current)return;let t=new AbortController;V.current=t;let i=n(),l=u.getState().toObject(),o=b(l);T(!0),J(null);try{if(P&&!_.some(e=>e.value===P))throw Error("The selected source is no longer compatible. Choose a source for this input role.");let n=e.data.params.execution_profile_id?.value,r=await g(q.operation.pipelineClass,$.task,A,t.signal,"string"==typeof n&&n?n:void 0);if(t.signal.aborted)return;d(i,{includeForm:!1});let u=P&&_.some(e=>e.value===P)?JSON.parse(P):null,p=u?{nodeId:u[0],handleId:u[1]}:void 0;h(e.data.blockProjectionOwnerId?y(l,e.data.blockProjectionOwnerId,e.data.blockProjectionNodeId,r,$,s.getState().nodesRegistry,p):j(l,e.id,r,$,s.getState().nodesRegistry,p),i,o,"Attach media input"),a?.()}catch(e){t.signal.aborted||J(r(e,"Could not attach this input."))}finally{V.current===t&&(V.current=null,T(!1))}}()},children:M?"Preparing input…":"Attach input"}),R?(0,v.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:R}):null]})}export{I as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Di as i,Hr as n,Io as r,Lo as l,Oi as o,Oo as s,Zo as d,fn as u,in as p,pn as c,wi as m,xn as f}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as h,t as b}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{t as g}from"./operationStarterRequest.js?v=ca6b74e6a02eedb3";import"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{a as j,i as y,n as x,t as I}from"./mediaAttachment.js?v=ca6b74e6a02eedb3";var S=e(a(),1),k=t();function v({node:e,initialSource:t,onAttached:a,inline:v=!1}){let A=m(e=>e.operationContracts),C=m(e=>e.pipelineSupport),O=n(e=>e.nodes),[w,N]=(0,S.useState)(""),[P,R]=(0,S.useState)(t?JSON.stringify([t.nodeId,t.handleId]):""),[E,J]=(0,S.useState)(null),[M,q]=(0,S.useState)(!1),L=(0,S.useRef)(null);(0,S.useEffect)(()=>()=>L.current?.abort(),[]);let T=d(e),V=x(I(A,C),T?.operation.pipelineClass??""),$=V.find(e=>e.key===w)??V.find(e=>e.task===T?.operation.task)??V[0];if(!$||e.parentId&&!e.data.blockProjectionOwnerId)return null;let _=O.flatMap(e=>{let a={...l(e)};if(t?.nodeId===e.id){let i=r(e,t.handleId);i&&(a[t.handleId]=i)}return Object.entries(a).filter(([,e])=>"output"===e.display&&!e.hidden&&!e.disabled&&(Array.isArray(e.type)?e.type:[e.type]).includes($.kind)).map(([t,a])=>({value:JSON.stringify([e.id,t]),label:`${e.data.label} · ${a.label??t}`}))});return(0,k.jsxs)(u,{label:"Add image / audio input",collapsible:!t&&!v,panelClassName:"grid gap-2 py-2",children:[(0,k.jsx)(c,{label:"Use input for",children:(0,k.jsx)(f,{"aria-label":"Media input role",value:$.key,disabled:M,options:V.map(e=>({value:e.key,label:e.label})),onValueChange:e=>{N(e),J(null)}})}),(0,k.jsx)(c,{label:"Source",children:(0,k.jsx)(f,{"aria-label":"Media input source",value:_.some(e=>e.value===P)?P:"",disabled:M,options:[{value:"",label:"Add Load "+("image"===$.kind?"Image":"Audio")},..._],onValueChange:R})}),(0,k.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Reuses this model and adds only the required encoding stages. Existing prompts and custom branches are retained."}),(0,k.jsx)(p,{tone:"primary",disabled:M,onClick:()=>{!async function(){if(!$||L.current)return;let t=new AbortController;L.current=t;let r=o(),l=n.getState().toObject(),d=h(l);q(!0),J(null);try{if(P&&!_.some(e=>e.value===P))throw Error("The selected source is no longer compatible. Choose a source for this input role.");let n=e.data.params.execution_profile_id?.value,o=await g(T.operation.pipelineClass,$.task,A,t.signal,"string"==typeof n&&n?n:void 0);if(t.signal.aborted)return;i(r,{includeForm:!1});let s=P&&_.some(e=>e.value===P)?JSON.parse(P):null,u=s?{nodeId:s[0],handleId:s[1]}:void 0;b(e.data.blockProjectionOwnerId?y(l,e.data.blockProjectionOwnerId,e.data.blockProjectionNodeId,o,$,m.getState().nodesRegistry,u):j(l,e.id,o,$,m.getState().nodesRegistry,u),r,d,"Attach media input"),a?.()}catch(e){t.signal.aborted||J(s(e,"Could not attach this input."))}finally{L.current===t&&(L.current=null,q(!1))}}()},children:M?"Preparing input…":"Attach input"}),E?(0,k.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:E}):null]})}export{v as t}; \ No newline at end of file diff --git a/web/assets/MediaAttachmentDialog.js b/web/assets/MediaAttachmentDialog.js index 41a8365..a768e7e 100644 --- a/web/assets/MediaAttachmentDialog.js +++ b/web/assets/MediaAttachmentDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{bn as s,fn as o,in as i}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as l}from"./MediaAttachmentControls.js?v=cc046c26d6fe7aa4";var n=e(a(),1),r=t();function d({owners:e,source:t,onClose:a}){let[d,u]=(0,n.useState)(e[0]?.id??""),h=e.find(e=>e.id===d);return(0,r.jsx)(i,{open:!0,title:"Attach media input",onClose:a,children:(0,r.jsxs)("div",{className:"grid gap-3",children:[(0,r.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"Choose how this workflow should use the input. Required stages are added to the existing graph."}),e.length>1?(0,r.jsx)(o,{label:"Operation",children:(0,r.jsx)(s,{"aria-label":"Media attachment operation",value:d,onValueChange:u,options:e.map(e=>({value:e.id,label:e.data.label||e.id}))})}):null,h?(0,r.jsx)(l,{node:h,initialSource:t,onAttached:a},h.id):null]})})}export{d as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{an as s,pn as o,xn as i}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as l}from"./MediaAttachmentControls.js?v=ca6b74e6a02eedb3";var n=e(a(),1),r=t();function d({owners:e,source:t,onClose:a}){let[d,u]=(0,n.useState)(e[0]?.id??""),h=e.find(e=>e.id===d);return(0,r.jsx)(s,{open:!0,title:"Attach media input",onClose:a,children:(0,r.jsxs)("div",{className:"grid gap-3",children:[(0,r.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"Choose how this workflow should use the input. Required stages are added to the existing graph."}),e.length>1?(0,r.jsx)(o,{label:"Operation",children:(0,r.jsx)(i,{"aria-label":"Media attachment operation",value:d,onValueChange:u,options:e.map(e=>({value:e.id,label:e.data.label||e.id}))})}):null,h?(0,r.jsx)(l,{node:h,initialSource:t,onAttached:a},h.id):null]})})}export{d as default}; \ No newline at end of file diff --git a/web/assets/MediaExportDialog.js b/web/assets/MediaExportDialog.js index 2d85848..d3b22f9 100644 --- a/web/assets/MediaExportDialog.js +++ b/web/assets/MediaExportDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,dr as t,un as r}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Do as i,Eo as l,Mo as o,Oo as n,Sa as s,bn as d,fn as u,in as p,oc as m,rn as f}from"./studio-templates.js?v=cc046c26d6fe7aa4";var c=e(t(),1),h=null;function v(e){return"object"==typeof e&&e&&!Array.isArray(e)?e:null}function g(e,a){let t=e[a];if("string"!=typeof t||!t.trim())throw Error(`MoDiff returned an invalid media capability ${a}.`);return t}function b(e){if("string"!=typeof e||!/^\.[A-Za-z0-9]{1,10}$/.test(e))throw Error("MoDiff returned an invalid media file extension.");return e.toLowerCase()}function x(e){let a=v(e);if(!a)throw Error("MoDiff returned an invalid media export format.");let t=g(a,"mimeType");if(!/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/.test(t))throw Error("MoDiff returned an invalid media MIME type.");let r=a.preset;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error("MoDiff returned an invalid media export preset.");let i=a.sampleRates;if(void 0!==i&&(!Array.isArray(i)||i.some(e=>"number"!=typeof e||!Number.isInteger(e)||e<=0)))throw Error("MoDiff returned invalid media sample rates.");for(let e of["supportsAlpha","hasAudio"])if(void 0!==a[e]&&"boolean"!=typeof a[e])throw Error(`MoDiff returned an invalid media capability ${e}.`);return{value:g(a,"value"),label:g(a,"label"),extension:b(a.extension),mimeType:t,preset:r,sampleRates:i,supportsAlpha:a.supportsAlpha,hasAudio:a.hasAudio}}function w(e){let a=v(e),t=a?v(a.media):null;if(!a||1!==a.version||!t)throw Error("MoDiff returned an unsupported media capability contract.");return{version:1,media:Object.fromEntries(["image","video","audio"].map(e=>{let a=v(t[e]);if(!a||!Array.isArray(a.importExtensions)||!Array.isArray(a.exportFormats))throw Error(`MoDiff returned invalid ${e} media capabilities.`);let r=a.importExtensions.map(b);if(new Set(r).size!==r.length)throw Error(`MoDiff returned duplicate ${e} import extensions.`);let i=a.exportFormats.map(x);if(new Set(i.map(e=>e.value)).size!==i.length)throw Error(`MoDiff returned duplicate ${e} export formats.`);return[e,{importExtensions:r,exportFormats:i}]}))}}function y(){return h||=n(`${m.serverAddress}/media/capabilities`,{parse:w,timeoutMs:1e4}).catch(e=>{throw h=null,e}),h}function j(e){try{return new URL(e,m.serverAddress)}catch{return null}}function S(e){let a=j(e);if(!a)return!1;let t=new URL(m.serverAddress);return a.origin===t.origin&&("/file"===a.pathname||"/stream"===a.pathname||a.pathname.startsWith("/cache/"))}function A(e,a,t,r){if("original"===r.format||!t){let t=`MoDiff-${a}`,r=e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||t,i=Array.from(r,e=>e.charCodeAt(0)<32?"-":e).join("").replace(/[<>:"/\\|?*]/g,"-").replace(/[. ]+$/,"").trim()||t,l=i.replace(/\.[A-Za-z0-9]{1,10}$/,"");return/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(l)?`_${i}`:i}let i="audio"===a&&r.sampleRate?`-${r.sampleRate,r.sampleRate/1e3}kHz`:"";return`${function(e,a){let t=`MoDiff-${a}`,r=e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||t,i=Array.from(r,e=>e.charCodeAt(0)<32?"-":e).join("").replace(/\.[A-Za-z0-9]{1,8}$/,"").replace(/[<>:"/\\|?*]/g,"-").trim()||t;return/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(i)?`_${i}`:i}(e,a)}${i}${t.extension}`}async function E(e,a,t,r,l){let o=function(e,a,t){if("original"===t.format)return e;let r=j(e);if(!r)throw Error("This output does not have a downloadable media URL.");let i=new URL(m.serverAddress);if(r.origin!==i.origin)throw Error("Converted downloads are available for MoDiff-managed media. Download this source as Original.");if("/stream"===r.pathname){let e=r.searchParams.get("file");if(!e)throw Error("This video source does not identify its backing file.");r.pathname="/file",r.search="",r.searchParams.set("file",e)}if("/file"!==r.pathname&&!r.pathname.startsWith("/cache/"))throw Error("Converted downloads are not available for this source. Download it as Original.");return function(e,a,t){e.searchParams.set("download_format",t.format),e.searchParams.set("media_kind",a),[["sample_rate",t.sampleRate],["channels",t.channels],["bit_depth",t.bitDepth],["bitrate",t.bitrate],["quality",t.quality],["compression",t.compression],["fps",t.fps],["width",t.width]].forEach(([a,t])=>{void 0!==t&&Number.isFinite(t)&&e.searchParams.set(a,String(t))})}(r,a,t),r.toString()}(e,t,l),n=A(a,t,r,l),s=null;try{let e=function(e,a){let t=window.showSaveFilePicker;return t?t.call(window,{suggestedName:e,types:a?.mimeType&&a.extension?[{description:`${a.label} file`,accept:{[a.mimeType]:[a.extension]}}]:void 0}):null}(n,r);s=e?await e:null}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return!1;s=null}let d=await i(o,{timeoutMs:36e5});if(s)return await async function(e,a){let t=await a.createWritable();await t.write(e),await t.close()}(d,s),!0;let u=URL.createObjectURL(d);try{let e=document.createElement("a");e.href=u,e.download=n,e.rel="noopener noreferrer",document.body.append(e),e.click(),e.remove()}finally{window.setTimeout(()=>URL.revokeObjectURL(u),1e3)}return!0}var $="modiff.media-export.v1";function D(e){try{let a=JSON.parse(localStorage.getItem($)||"{}");if(!a||"object"!=typeof a)return{};let t=a[e];return t&&"object"==typeof t?t:{}}catch{return{}}}function M(e,a){try{let t=JSON.parse(localStorage.getItem($)||"{}"),r=t&&"object"==typeof t?t:{};localStorage.setItem($,JSON.stringify({...r,[e]:a}))}catch{}}var k=a(),R={value:"original",label:"Original file",extension:"",mimeType:"application/octet-stream",preset:"Original"};function C(){let e=s(e=>e.mediaExportOpener),a=s(e=>e.setMediaExportOpener),[t,i]=(0,c.useState)(null),[n,m]=(0,c.useState)(!1),[h,v]=(0,c.useState)(""),[g,b]=(0,c.useState)("original"),[x,w]=(0,c.useState)(48e3),[j,$]=(0,c.useState)(16),[C,N]=(0,c.useState)(256),[O,z]=(0,c.useState)(90),[F,L]=(0,c.useState)(12),[P,I]=(0,c.useState)(640);(0,c.useEffect)(()=>{if(!e)return;let a=D(e.kind);b(a.format||e.defaultFormat||function(e){return"audio"===e?"wav":"image"===e?"png":"video"===e?"mp4":"original"}(e.kind)),w(e.defaultSampleRate||a.sampleRate||48e3),$(a.bitDepth||16),N(a.bitrate||256),z(a.quality||90),L(a.fps||12),I(a.width||640),v(""),i(null);let t=!0;return y().then(e=>{t&&i(e)}).catch(e=>{t&&v(l(e,"Media export options could not be loaded."))}),()=>{t=!1}},[e]);let T=(0,c.useMemo)(()=>e?[R,...t&&S(e.source)?t.media[e.kind].exportFormats:[]]:[],[t,e]),U=T.find(e=>e.value===g)??T.find(e=>"original"===e.value)??null;if((0,c.useEffect)(()=>{!t||0===T.length||T.some(e=>e.value===g)||b(T[0]?.value??"original")},[t,g,T]),(0,c.useEffect)(()=>{!U?.sampleRates?.length||U.sampleRates.includes(x)||w(U.sampleRates[0]??48e3)},[x,U]),!e)return null;let V={format:U?.value??"original",sampleRate:"audio"===e.kind&&"original"!==U?.value?x:void 0,bitDepth:"wav"===U?.value?j:void 0,bitrate:["mp3","m4a","aac","opus"].includes(U?.value??"")?C:void 0,quality:"image"===e.kind&&["jpeg","webp","avif"].includes(U?.value??"")?O:void 0,fps:"gif"===U?.value?F:void 0,width:"gif"===U?.value?P:void 0},_=A(e.filename,e.kind,U,V),Z=()=>{n||a(null)};return(0,k.jsx)(p,{open:!0,onClose:Z,title:e.title||`Download ${e.kind}`,description:"Download the original unchanged, or convert a copy using the available export formats.",dismissible:!n,testId:"media-export-dialog",panelClassName:"max-w-xl",footer:(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(f,{tone:"secondary",disabled:n,onClick:Z,children:"Cancel"}),(0,k.jsxs)(f,{tone:"primary",disabled:!U,loading:n,onClick:()=>{(async()=>{if(U&&!n){m(!0),v("");try{if(!await E(e.source,e.filename,e.kind,U,V))return;M(e.kind,V),a(null),o(`${U.label} download ready`,{variant:"success",autoHideDuration:1800})}catch(e){v(l(e,`Could not create the ${U.label} download.`))}finally{m(!1)}}})()},children:[(0,k.jsx)(r,{size:16}),n?"Preparing…":"Download"]})]}),children:(0,k.jsxs)("div",{className:"grid gap-4",children:[(0,k.jsx)(u,{label:"Format",children:(0,k.jsx)(d,{"aria-label":"Download format",value:U?.value??"",onValueChange:b,options:T.map(e=>({value:e.value,label:e.label,group:e.preset})),placeholder:t?"Select format":"Loading formats…",disabled:n||!t})}),"audio"===e.kind&&U?.sampleRates&&U.sampleRates.length>1?(0,k.jsx)(u,{label:"Sample rate",children:(0,k.jsx)(d,{"aria-label":"Audio sample rate",value:String(x),onValueChange:e=>w(Number(e)),options:U.sampleRates.map(e=>({value:String(e),label:e/1e3+" kHz"}))})}):null,"wav"===U?.value?(0,k.jsx)(u,{label:"Bit depth",children:(0,k.jsx)(d,{"aria-label":"WAV bit depth",value:String(j),onValueChange:e=>$(Number(e)),options:[{value:"16",label:"16-bit PCM"},{value:"24",label:"24-bit PCM"}]})}):null,["mp3","m4a","aac","opus"].includes(U?.value??"")?(0,k.jsx)(u,{label:"Bitrate",children:(0,k.jsx)(d,{"aria-label":"Audio bitrate",value:String(C),onValueChange:e=>N(Number(e)),options:[128,192,256,320].map(e=>({value:String(e),label:`${e} kbps`}))})}):null,"image"===e.kind&&["jpeg","webp","avif"].includes(U?.value??"")?(0,k.jsx)(u,{label:"Quality",children:(0,k.jsx)(d,{"aria-label":"Image export quality",value:String(O),onValueChange:e=>z(Number(e)),options:[{value:"100",label:"Maximum · 100"},{value:"90",label:"High · 90"},{value:"80",label:"Balanced · 80"},{value:"65",label:"Small · 65"}]})}):null,"gif"===U?.value?(0,k.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,k.jsx)(u,{label:"Frame rate",children:(0,k.jsx)(d,{"aria-label":"GIF frame rate",value:String(F),onValueChange:e=>L(Number(e)),options:[8,12,16,24].map(e=>({value:String(e),label:`${e} fps`}))})}),(0,k.jsx)(u,{label:"Width",children:(0,k.jsx)(d,{"aria-label":"GIF width",value:String(P),onValueChange:e=>I(Number(e)),options:[480,640,960,1280].map(e=>({value:String(e),label:`${e} px`}))})})]}):null,(0,k.jsx)("div",{className:"break-all rounded-modiff-compact border border-modiff-border bg-modiff-bg px-3 py-2 text-modiff-metadata text-modiff-subtle-text",children:_}),(0,k.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:n?"Preparing your download. The generated source asset is not changed.":t||h?"original"===U?.value?"Original file: no conversion or quality loss.":"A converted copy is downloaded; the source asset is kept.":"Loading conversion formats… Original download is available."}),h?(0,k.jsx)("div",{role:"alert",className:"rounded-modiff-compact border border-modiff-invalid bg-modiff-invalid/10 px-3 py-2 text-sm text-modiff-invalid",children:h}):null]})})}export{C as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,dr as t,un as r}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ao as i,Oo as l,Po as o,an as n,in as s,ko as d,lc as u,pn as p,wa as m,xn as f}from"./studio-templates.js?v=ca6b74e6a02eedb3";var c=e(t(),1),h=null;function v(e){return"object"==typeof e&&e&&!Array.isArray(e)?e:null}function g(e,a){let t=e[a];if("string"!=typeof t||!t.trim())throw Error(`MoDiff returned an invalid media capability ${a}.`);return t}function b(e){if("string"!=typeof e||!/^\.[A-Za-z0-9]{1,10}$/.test(e))throw Error("MoDiff returned an invalid media file extension.");return e.toLowerCase()}function x(e){let a=v(e);if(!a)throw Error("MoDiff returned an invalid media export format.");let t=g(a,"mimeType");if(!/^[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*\/[A-Za-z0-9][A-Za-z0-9!#$&^_.+-]*$/.test(t))throw Error("MoDiff returned an invalid media MIME type.");let r=a.preset;if(void 0!==r&&("string"!=typeof r||!r.trim()))throw Error("MoDiff returned an invalid media export preset.");let i=a.sampleRates;if(void 0!==i&&(!Array.isArray(i)||i.some(e=>"number"!=typeof e||!Number.isInteger(e)||e<=0)))throw Error("MoDiff returned invalid media sample rates.");for(let e of["supportsAlpha","hasAudio"])if(void 0!==a[e]&&"boolean"!=typeof a[e])throw Error(`MoDiff returned an invalid media capability ${e}.`);return{value:g(a,"value"),label:g(a,"label"),extension:b(a.extension),mimeType:t,preset:r,sampleRates:i,supportsAlpha:a.supportsAlpha,hasAudio:a.hasAudio}}function w(e){let a=v(e),t=a?v(a.media):null;if(!a||1!==a.version||!t)throw Error("MoDiff returned an unsupported media capability contract.");return{version:1,media:Object.fromEntries(["image","video","audio"].map(e=>{let a=v(t[e]);if(!a||!Array.isArray(a.importExtensions)||!Array.isArray(a.exportFormats))throw Error(`MoDiff returned invalid ${e} media capabilities.`);let r=a.importExtensions.map(b);if(new Set(r).size!==r.length)throw Error(`MoDiff returned duplicate ${e} import extensions.`);let i=a.exportFormats.map(x);if(new Set(i.map(e=>e.value)).size!==i.length)throw Error(`MoDiff returned duplicate ${e} export formats.`);return[e,{importExtensions:r,exportFormats:i}]}))}}function y(){return h||=i(`${u.serverAddress}/media/capabilities`,{parse:w,timeoutMs:1e4}).catch(e=>{throw h=null,e}),h}function j(e){try{return new URL(e,u.serverAddress)}catch{return null}}function A(e){let a=j(e);if(!a)return!1;let t=new URL(u.serverAddress);return a.origin===t.origin&&("/file"===a.pathname||"/stream"===a.pathname||a.pathname.startsWith("/cache/"))}function S(e,a,t){if("original"===t.format)return e;let r=j(e);if(!r)throw Error("This output does not have a downloadable media URL.");let i=new URL(u.serverAddress);if(r.origin!==i.origin)throw Error("Converted downloads are available for MoDiff-managed media. Download this source as Original.");if("/stream"===r.pathname){let e=r.searchParams.get("file");if(!e)throw Error("This video source does not identify its backing file.");r.pathname="/file",r.search="",r.searchParams.set("file",e)}if("/file"!==r.pathname&&!r.pathname.startsWith("/cache/"))throw Error("Converted downloads are not available for this source. Download it as Original.");return function(e,a,t){e.searchParams.set("download_format",t.format),e.searchParams.set("media_kind",a),[["sample_rate",t.sampleRate],["channels",t.channels],["bit_depth",t.bitDepth],["bitrate",t.bitrate],["quality",t.quality],["compression",t.compression],["fps",t.fps],["width",t.width]].forEach(([a,t])=>{void 0!==t&&Number.isFinite(t)&&e.searchParams.set(a,String(t))})}(r,a,t),r.toString()}function $(e,a,t,r){if("original"===r.format||!t){let t=`MoDiff-${a}`,r=e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||t,i=Array.from(r,e=>e.charCodeAt(0)<32?"-":e).join("").replace(/[<>:"/\\|?*]/g,"-").replace(/[. ]+$/,"").trim()||t,l=i.replace(/\.[A-Za-z0-9]{1,10}$/,"");return/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(l)?`_${i}`:i}let i="audio"===a&&r.sampleRate?`-${r.sampleRate,r.sampleRate/1e3}kHz`:"";return`${function(e,a){let t=`MoDiff-${a}`,r=e.replace(/\\/g,"/").split("/").filter(Boolean).pop()||t,i=Array.from(r,e=>e.charCodeAt(0)<32?"-":e).join("").replace(/\.[A-Za-z0-9]{1,8}$/,"").replace(/[<>:"/\\|?*]/g,"-").trim()||t;return/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(i)?`_${i}`:i}(e,a)}${i}${t.extension}`}async function E(e,a,t,r,i){let l=S(e,t,i),o=$(a,t,r,i),n=null;try{let e=function(e,a){let t=window.showSaveFilePicker;return t?t.call(window,{suggestedName:e,types:a?.mimeType&&a.extension?[{description:`${a.label} file`,accept:{[a.mimeType]:[a.extension]}}]:void 0}):null}(o,r);n=e?await e:null}catch(e){if(e instanceof DOMException&&"AbortError"===e.name)return!1;n=null}let s=await d(l,{timeoutMs:36e5});if(n)return await async function(e,a){let t=await a.createWritable();await t.write(e),await t.close()}(s,n),!0;let u=URL.createObjectURL(s);try{let e=document.createElement("a");e.href=u,e.download=o,e.rel="noopener noreferrer",document.body.append(e),e.click(),e.remove()}finally{window.setTimeout(()=>URL.revokeObjectURL(u),1e3)}return!0}var D="modiff.media-export.v1";function M(e){try{let a=JSON.parse(localStorage.getItem(D)||"{}");if(!a||"object"!=typeof a)return{};let t=a[e];return t&&"object"==typeof t?t:{}}catch{return{}}}function k(e,a){try{let t=JSON.parse(localStorage.getItem(D)||"{}"),r=t&&"object"==typeof t?t:{};localStorage.setItem(D,JSON.stringify({...r,[e]:a}))}catch{}}var R=a(),C={value:"original",label:"Original file",extension:"",mimeType:"application/octet-stream",preset:"Original"};function N(){let e=m(e=>e.mediaExportOpener),a=m(e=>e.setMediaExportOpener),[t,i]=(0,c.useState)(null),[d,u]=(0,c.useState)(!1),[h,v]=(0,c.useState)(""),[g,b]=(0,c.useState)("original"),[x,w]=(0,c.useState)(48e3),[j,S]=(0,c.useState)(16),[D,N]=(0,c.useState)(256),[O,z]=(0,c.useState)(90),[F,L]=(0,c.useState)(12),[P,I]=(0,c.useState)(640);(0,c.useEffect)(()=>{if(!e)return;let a=M(e.kind);b(a.format||e.defaultFormat||function(e){return"audio"===e?"wav":"image"===e?"png":"video"===e?"mp4":"original"}(e.kind)),w(e.defaultSampleRate||a.sampleRate||48e3),S(a.bitDepth||16),N(a.bitrate||256),z(a.quality||90),L(a.fps||12),I(a.width||640),v(""),i(null);let t=!0;return y().then(e=>{t&&i(e)}).catch(e=>{t&&v(l(e,"Media export options could not be loaded."))}),()=>{t=!1}},[e]);let T=(0,c.useMemo)(()=>e?[C,...t&&A(e.source)?t.media[e.kind].exportFormats:[]]:[],[t,e]),U=T.find(e=>e.value===g)??T.find(e=>"original"===e.value)??null;if((0,c.useEffect)(()=>{!t||0===T.length||T.some(e=>e.value===g)||b(T[0]?.value??"original")},[t,g,T]),(0,c.useEffect)(()=>{!U?.sampleRates?.length||U.sampleRates.includes(x)||w(U.sampleRates[0]??48e3)},[x,U]),!e)return null;let V={format:U?.value??"original",sampleRate:"audio"===e.kind&&"original"!==U?.value?x:void 0,bitDepth:"wav"===U?.value?j:void 0,bitrate:["mp3","m4a","aac","opus"].includes(U?.value??"")?D:void 0,quality:"image"===e.kind&&["jpeg","webp","avif"].includes(U?.value??"")?O:void 0,fps:"gif"===U?.value?F:void 0,width:"gif"===U?.value?P:void 0},_=$(e.filename,e.kind,U,V),Z=()=>{d||a(null)};return(0,R.jsx)(n,{open:!0,onClose:Z,title:e.title||`Download ${e.kind}`,description:"Download the original unchanged, or convert a copy using the available export formats.",dismissible:!d,testId:"media-export-dialog",panelClassName:"max-w-xl",footer:(0,R.jsxs)(R.Fragment,{children:[(0,R.jsx)(s,{tone:"secondary",disabled:d,onClick:Z,children:"Cancel"}),(0,R.jsxs)(s,{tone:"primary",disabled:!U,loading:d,onClick:()=>{(async()=>{if(U&&!d){u(!0),v("");try{if(!await E(e.source,e.filename,e.kind,U,V))return;k(e.kind,V),a(null),o(`${U.label} download ready`,{variant:"success",autoHideDuration:1800})}catch(e){v(l(e,`Could not create the ${U.label} download.`))}finally{u(!1)}}})()},children:[(0,R.jsx)(r,{size:16}),d?"Preparing…":"Download"]})]}),children:(0,R.jsxs)("div",{className:"grid gap-4",children:[(0,R.jsx)(p,{label:"Format",children:(0,R.jsx)(f,{"aria-label":"Download format",value:U?.value??"",onValueChange:b,options:T.map(e=>({value:e.value,label:e.label,group:e.preset})),placeholder:t?"Select format":"Loading formats…",disabled:d||!t})}),"audio"===e.kind&&U?.sampleRates&&U.sampleRates.length>1?(0,R.jsx)(p,{label:"Sample rate",children:(0,R.jsx)(f,{"aria-label":"Audio sample rate",value:String(x),onValueChange:e=>w(Number(e)),options:U.sampleRates.map(e=>({value:String(e),label:e/1e3+" kHz"}))})}):null,"wav"===U?.value?(0,R.jsx)(p,{label:"Bit depth",children:(0,R.jsx)(f,{"aria-label":"WAV bit depth",value:String(j),onValueChange:e=>S(Number(e)),options:[{value:"16",label:"16-bit PCM"},{value:"24",label:"24-bit PCM"}]})}):null,["mp3","m4a","aac","opus"].includes(U?.value??"")?(0,R.jsx)(p,{label:"Bitrate",children:(0,R.jsx)(f,{"aria-label":"Audio bitrate",value:String(D),onValueChange:e=>N(Number(e)),options:[128,192,256,320].map(e=>({value:String(e),label:`${e} kbps`}))})}):null,"image"===e.kind&&["jpeg","webp","avif"].includes(U?.value??"")?(0,R.jsx)(p,{label:"Quality",children:(0,R.jsx)(f,{"aria-label":"Image export quality",value:String(O),onValueChange:e=>z(Number(e)),options:[{value:"100",label:"Maximum · 100"},{value:"90",label:"High · 90"},{value:"80",label:"Balanced · 80"},{value:"65",label:"Small · 65"}]})}):null,"gif"===U?.value?(0,R.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,R.jsx)(p,{label:"Frame rate",children:(0,R.jsx)(f,{"aria-label":"GIF frame rate",value:String(F),onValueChange:e=>L(Number(e)),options:[8,12,16,24].map(e=>({value:String(e),label:`${e} fps`}))})}),(0,R.jsx)(p,{label:"Width",children:(0,R.jsx)(f,{"aria-label":"GIF width",value:String(P),onValueChange:e=>I(Number(e)),options:[480,640,960,1280].map(e=>({value:String(e),label:`${e} px`}))})})]}):null,(0,R.jsx)("div",{className:"break-all rounded-modiff-compact border border-modiff-border bg-modiff-bg px-3 py-2 text-modiff-metadata text-modiff-subtle-text",children:_}),(0,R.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:d?"Preparing your download. The generated source asset is not changed.":t||h?"original"===U?.value?"Original file: no conversion or quality loss.":"A converted copy is downloaded; the source asset is kept.":"Loading conversion formats… Original download is available."}),h?(0,R.jsx)("div",{role:"alert",className:"rounded-modiff-compact border border-modiff-invalid bg-modiff-invalid/10 px-3 py-2 text-sm text-modiff-invalid",children:h}):null]})})}export{N as default}; \ No newline at end of file diff --git a/web/assets/MediaViewerDialog.js b/web/assets/MediaViewerDialog.js index 7351755..c1e6db5 100644 --- a/web/assets/MediaViewerDialog.js +++ b/web/assets/MediaViewerDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Dn as t,E as l,O as o,On as r,an as a,cr as i,dr as n,pn as d,un as s}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Do as f,In as c,Mo as u,Sa as m,Tn as x,an as p,bt as h,gt as b,in as w,oc as v,rn as g,yt as j}from"./studio-templates.js?v=cc046c26d6fe7aa4";var k=e(n(),1),y=i();function N(e){let t={image:"png",video:"mp4",audio:"wav",text:"txt"}[e.kind];return e.downloadName?.split(/[\\/]/).pop()?.split("").filter(e=>{let t=e.codePointAt(0)??0;return t>31&&127!==t}).join("").trim()||`modiff-${e.kind}.${t}`}async function C(e){try{let t="text"===e.kind?new Blob([e.text??""],{type:"text/plain;charset=utf-8"}):await f(e.url??""),l=URL.createObjectURL(t);try{!function(e,t){let l=document.createElement("a");l.href=e,l.download=t,l.rel="noopener noreferrer",document.body.append(l),l.click(),l.remove()}(l,N(e))}finally{window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}}catch{u("Could not download output",{variant:"error",autoHideDuration:2400})}}function z({children:e,label:t,onClick:l}){return(0,y.jsx)(p,{label:t,size:"prominent",className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:l,children:e})}function O({item:e}){return"video"===e.kind&&e.url?(0,y.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",playsInline:!0,className:"block max-h-full max-w-full bg-modiff-media-backdrop object-contain","data-testid":"media-viewer-video"},e.url):"audio"===e.kind&&e.url?(0,y.jsxs)("div",{className:"flex w-[min(720px,90%)] flex-col items-center gap-5 rounded-modiff-compact border border-modiff-border bg-modiff-panel p-6 shadow-modiff-panel","data-testid":"media-viewer-audio",children:[(0,y.jsxs)("div",{className:"text-center",children:[(0,y.jsx)("div",{className:"text-base font-semibold text-modiff-text",children:e.label}),(0,y.jsx)("div",{className:"mt-1 text-xs text-modiff-subtle-text",children:"Previous audio render"})]}),(0,y.jsx)("audio",{src:e.url,controls:!0,className:"w-full"},e.url)]}):"text"===e.kind?(0,y.jsx)("pre",{className:"max-h-full w-[min(900px,92%)] overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-panel p-5 text-sm text-modiff-text shadow-modiff-panel","data-testid":"media-viewer-text",children:(0,y.jsx)("code",{children:e.text??""})}):e.url?(0,y.jsx)("img",{src:e.url,alt:e.label,className:"modiff-generated-image block max-h-full max-w-full border-[12px] border-modiff-bg bg-modiff-bg object-contain","data-testid":"media-viewer-image"}):null}function D({active:e,item:t,onClick:l}){return(0,y.jsx)(g,{tone:"ghost","aria-label":`Show ${t.label}`,"aria-pressed":e,onClick:l,className:c("h-20 w-28 flex-none overflow-hidden border-2 border-transparent p-0",e&&"border-hf-yellow"),children:"image"===t.kind&&t.url?(0,y.jsx)("img",{src:t.url,alt:"",className:"h-full w-full object-cover"}):"video"===t.kind&&t.url?(0,y.jsx)("video",{src:t.url,muted:!0,playsInline:!0,preload:"metadata",className:"h-full w-full object-cover"}):(0,y.jsx)("span",{className:"flex h-full w-full items-center justify-center bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:"text"===t.kind?(t.text??"").slice(0,48)||"Text":"Audio"})})}function $(){let e=m(e=>e.mediaViewerOpener),i=m(e=>e.setMediaViewerOpener),n=m(e=>e.setMediaExportOpener),f=(0,k.useMemo)(()=>j(e?.items??[],v.serverAddress),[e]),c=b(e?.currentIndex??0,f.length),[g,$]=(0,k.useState)(c),L=b(g,f.length),[E,R]=(0,k.useState)(!1);if((0,k.useEffect)(()=>{$(c)},[c,e]),(0,k.useEffect)(()=>{e&&0===f.length&&i(null)},[f.length,e,i]),(0,k.useEffect)(()=>{if(!e||f.length<2)return;let t=e=>{e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||h(e.target)||("ArrowLeft"===e.key?(e.preventDefault(),$(e=>(b(e,f.length)-1+f.length)%f.length)):"ArrowRight"===e.key&&(e.preventDefault(),$(e=>(b(e,f.length)+1)%f.length)))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[f.length,e]),!e||0===f.length)return null;let A=f[L]??f[0];if(!A)return null;let U=()=>i(null);return(0,y.jsx)(w,{open:!0,onClose:U,title:f.length>1?`${e.title} · ${L+1} of ${f.length}`:e.title,panelClassName:"flex h-[80vh] w-[82vw] max-h-[80vh] max-w-[82vw] flex-col bg-modiff-media-backdrop/95",bodyClassName:"!max-h-none min-h-0 flex-1 !p-0",children:(0,y.jsxs)("div",{className:"flex h-full min-h-0 flex-col","data-testid":"media-viewer-dialog",children:[(0,y.jsxs)("div",{className:"relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-6",children:[(0,y.jsx)(O,{item:A}),(0,y.jsxs)("div",{className:"nodrag absolute right-3 top-3 flex gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-panel/95 p-1 shadow-modiff-panel",children:[(0,y.jsx)(z,{label:`Download ${A.kind}`,onClick:()=>{"text"!==A.kind?A.url&&n({source:A.url,kind:A.kind,filename:N(A),title:`Download ${A.kind}`,defaultFormat:"audio"===A.kind?"wav":"video"===A.kind?"mp4":"png"}):C(A)},children:(0,y.jsx)(s,{size:18})}),(0,y.jsx)(z,{label:"Copy output",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(A.url??A.text??""),u(A.url?"Output URL copied":"Output text copied",{variant:"success",autoHideDuration:1600})}catch{u("Could not copy output",{variant:"error",autoHideDuration:2400})}})()},children:(0,y.jsx)(d,{size:18})}),A.url?(0,y.jsx)(z,{label:"Open output in new tab",onClick:()=>window.open(A.url,"_blank","noopener,noreferrer"),children:(0,y.jsx)(a,{size:18})}):null,e.workflow?(0,y.jsx)(p,{label:`Open workflow ${e.workflow.name}`,size:"prominent",disabled:E,"aria-busy":E,className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:()=>{(async()=>{if(e.workflow&&!E){R(!0);try{"workflow"===await x({...e.workflow,status:"completed",preferWorkflow:!0})?U():u(`Could not open ${e.workflow.name}.`,{variant:"error",autoHideDuration:4e3})}finally{R(!1)}}})()},children:(0,y.jsx)(o,{size:18})}):null,(0,y.jsx)(z,{label:"Close media viewer",onClick:U,children:(0,y.jsx)(l,{size:20})})]}),f.length>1?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(p,{label:"Previous output",size:"prominent",className:"absolute left-4 top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/90 text-modiff-subtle-text hover:text-hf-yellow",onClick:()=>$(e=>(b(e,f.length)-1+f.length)%f.length),children:(0,y.jsx)(r,{size:28})}),(0,y.jsx)(p,{label:"Next output",size:"prominent",className:"absolute right-4 top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/90 text-modiff-subtle-text hover:text-hf-yellow",onClick:()=>$(e=>(b(e,f.length)+1)%f.length),children:(0,y.jsx)(t,{size:28})})]}):null]}),f.length>1?(0,y.jsx)("div",{className:"flex h-24 flex-none items-center justify-center gap-2 overflow-x-auto border-t border-modiff-border bg-modiff-panel/95 p-2",children:f.map((e,t)=>(0,y.jsx)(D,{active:t===L,item:e,onClick:()=>$(t)},e.id))}):null]})})}export{$ as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Dn as t,E as l,O as o,On as r,an as a,cr as i,dr as n,pn as d,un as s}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{En as f,Ln as c,Po as u,_t as m,an as x,bt as p,in as h,ko as b,lc as w,on as v,wa as g,xt as k}from"./studio-templates.js?v=ca6b74e6a02eedb3";var j=e(n(),1),y=i();function N(e){let t={image:"png",video:"mp4",audio:"wav",text:"txt"}[e.kind];return e.downloadName?.split(/[\\/]/).pop()?.split("").filter(e=>{let t=e.codePointAt(0)??0;return t>31&&127!==t}).join("").trim()||`modiff-${e.kind}.${t}`}async function C(e){try{let t="text"===e.kind?new Blob([e.text??""],{type:"text/plain;charset=utf-8"}):await b(e.url??""),l=URL.createObjectURL(t);try{!function(e,t){let l=document.createElement("a");l.href=e,l.download=t,l.rel="noopener noreferrer",document.body.append(l),l.click(),l.remove()}(l,N(e))}finally{window.setTimeout(()=>URL.revokeObjectURL(l),1e3)}}catch{u("Could not download output",{variant:"error",autoHideDuration:2400})}}function z({children:e,label:t,onClick:l}){return(0,y.jsx)(v,{label:t,size:"prominent",className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:l,children:e})}function O({item:e}){return"video"===e.kind&&e.url?(0,y.jsx)("video",{src:e.url,controls:!0,controlsList:"nodownload noremoteplayback",playsInline:!0,className:"block max-h-full max-w-full bg-modiff-media-backdrop object-contain","data-testid":"media-viewer-video"},e.url):"audio"===e.kind&&e.url?(0,y.jsxs)("div",{className:"flex w-[min(720px,90%)] flex-col items-center gap-5 rounded-modiff-compact border border-modiff-border bg-modiff-panel p-6 shadow-modiff-panel","data-testid":"media-viewer-audio",children:[(0,y.jsxs)("div",{className:"text-center",children:[(0,y.jsx)("div",{className:"text-base font-semibold text-modiff-text",children:e.label}),(0,y.jsx)("div",{className:"mt-1 text-xs text-modiff-subtle-text",children:"Previous audio render"})]}),(0,y.jsx)("audio",{src:e.url,controls:!0,className:"w-full"},e.url)]}):"text"===e.kind?(0,y.jsx)("pre",{className:"max-h-full w-[min(900px,92%)] overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-panel p-5 text-sm text-modiff-text shadow-modiff-panel","data-testid":"media-viewer-text",children:(0,y.jsx)("code",{children:e.text??""})}):e.url?(0,y.jsx)("img",{src:e.url,alt:e.label,className:"modiff-generated-image block max-h-full max-w-full border-[12px] border-modiff-bg bg-modiff-bg object-contain","data-testid":"media-viewer-image"}):null}function L({active:e,item:t,onClick:l}){return(0,y.jsx)(h,{tone:"ghost","aria-label":`Show ${t.label}`,"aria-pressed":e,onClick:l,className:c("h-20 w-28 flex-none overflow-hidden border-2 border-transparent p-0",e&&"border-hf-yellow"),children:"image"===t.kind&&t.url?(0,y.jsx)("img",{src:t.url,alt:"",className:"h-full w-full object-cover"}):"video"===t.kind&&t.url?(0,y.jsx)("video",{src:t.url,muted:!0,playsInline:!0,preload:"metadata",className:"h-full w-full object-cover"}):(0,y.jsx)("span",{className:"flex h-full w-full items-center justify-center bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:"text"===t.kind?(t.text??"").slice(0,48)||"Text":"Audio"})})}function $(){let e=g(e=>e.mediaViewerOpener),i=g(e=>e.setMediaViewerOpener),n=g(e=>e.setMediaExportOpener),c=(0,j.useMemo)(()=>p(e?.items??[],w.serverAddress),[e]),h=m(e?.currentIndex??0,c.length),[b,$]=(0,j.useState)(h),D=m(b,c.length),[E,R]=(0,j.useState)(!1);if((0,j.useEffect)(()=>{$(h)},[h,e]),(0,j.useEffect)(()=>{e&&0===c.length&&i(null)},[c.length,e,i]),(0,j.useEffect)(()=>{if(!e||c.length<2)return;let t=e=>{e.defaultPrevented||e.altKey||e.ctrlKey||e.metaKey||k(e.target)||("ArrowLeft"===e.key?(e.preventDefault(),$(e=>(m(e,c.length)-1+c.length)%c.length)):"ArrowRight"===e.key&&(e.preventDefault(),$(e=>(m(e,c.length)+1)%c.length)))};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[c.length,e]),!e||0===c.length)return null;let A=c[D]??c[0];if(!A)return null;let P=()=>i(null);return(0,y.jsx)(x,{open:!0,onClose:P,title:c.length>1?`${e.title} · ${D+1} of ${c.length}`:e.title,panelClassName:"flex h-[80vh] w-[82vw] max-h-[80vh] max-w-[82vw] flex-col bg-modiff-media-backdrop/95",bodyClassName:"!max-h-none min-h-0 flex-1 !p-0",children:(0,y.jsxs)("div",{className:"flex h-full min-h-0 flex-col","data-testid":"media-viewer-dialog",children:[(0,y.jsxs)("div",{className:"relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-6",children:[(0,y.jsx)(O,{item:A}),(0,y.jsxs)("div",{className:"nodrag absolute right-3 top-3 flex gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-panel/95 p-1 shadow-modiff-panel",children:[(0,y.jsx)(z,{label:`Download ${A.kind}`,onClick:()=>{"text"!==A.kind?A.url&&n({source:A.url,kind:A.kind,filename:N(A),title:`Download ${A.kind}`,defaultFormat:"audio"===A.kind?"wav":"video"===A.kind?"mp4":"png"}):C(A)},children:(0,y.jsx)(s,{size:18})}),(0,y.jsx)(z,{label:"Copy output",onClick:()=>{(async()=>{try{await navigator.clipboard.writeText(A.url??A.text??""),u(A.url?"Output URL copied":"Output text copied",{variant:"success",autoHideDuration:1600})}catch{u("Could not copy output",{variant:"error",autoHideDuration:2400})}})()},children:(0,y.jsx)(d,{size:18})}),A.url?(0,y.jsx)(z,{label:"Open output in new tab",onClick:()=>window.open(A.url,"_blank","noopener,noreferrer"),children:(0,y.jsx)(a,{size:18})}):null,e.workflow?(0,y.jsx)(v,{label:`Open workflow ${e.workflow.name}`,size:"prominent",disabled:E,"aria-busy":E,className:"text-modiff-subtle-text hover:bg-modiff-surface-hover hover:text-hf-yellow",onClick:()=>{(async()=>{if(e.workflow&&!E){R(!0);try{"workflow"===await f({...e.workflow,status:"completed",preferWorkflow:!0})?P():u(`Could not open ${e.workflow.name}.`,{variant:"error",autoHideDuration:4e3})}finally{R(!1)}}})()},children:(0,y.jsx)(o,{size:18})}):null,(0,y.jsx)(z,{label:"Close media viewer",onClick:P,children:(0,y.jsx)(l,{size:20})})]}),c.length>1?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(v,{label:"Previous output",size:"prominent",className:"absolute left-4 top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/90 text-modiff-subtle-text hover:text-hf-yellow",onClick:()=>$(e=>(m(e,c.length)-1+c.length)%c.length),children:(0,y.jsx)(r,{size:28})}),(0,y.jsx)(v,{label:"Next output",size:"prominent",className:"absolute right-4 top-1/2 size-12 -translate-y-1/2 border border-modiff-border bg-modiff-panel/90 text-modiff-subtle-text hover:text-hf-yellow",onClick:()=>$(e=>(m(e,c.length)+1)%c.length),children:(0,y.jsx)(t,{size:28})})]}):null]}),c.length>1?(0,y.jsx)("div",{className:"flex h-24 flex-none items-center justify-center gap-2 overflow-x-auto border-t border-modiff-border bg-modiff-panel/95 p-2",children:c.map((e,t)=>(0,y.jsx)(L,{active:t===D,item:e,onClick:()=>$(t)},e.id))}):null]})})}export{$ as default}; \ No newline at end of file diff --git a/web/assets/ModelManagerDialog.js b/web/assets/ModelManagerDialog.js index 4d4548d..4d6b958 100644 --- a/web/assets/ModelManagerDialog.js +++ b/web/assets/ModelManagerDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{En as a,Et as t,Ht as s,K as l,Nt as n,at as i,cr as o,dn as r,dr as d,kn as c,pn as m,rt as u,un as f,z as p}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ci as x,Eo as h,Fi as g,Ga as b,Ii as j,In as v,Jn as y,Li as w,Mo as N,Ms as C,Ns as k,Oo as $,Pi as _,Ps as S,S as T,Sa as R,Si as H,Sr as I,To as D,Vi as F,Vr as M,Wa as z,Wi as E,Za as A,Zt as L,an as P,bo as O,co as q,d as B,dn as V,gn as W,go as U,in as J,io as G,ji as K,l as Z,lo as Q,no as X,oc as Y,oo as ee,qa as ae,rn as te,so as se,uo as le,vo as ne,xn as ie,xo as oe,yn as re}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as de}from"./WorkflowArtifactRequirementRow.js?v=cc046c26d6fe7aa4";import{n as ce,t as me}from"./TemplateUsageTermsDialog.js?v=cc046c26d6fe7aa4";var ue=o();function fe({children:e,tone:a="muted"}){return(0,ue.jsx)("p",{className:v("break-words text-xs leading-5","muted"===a&&"text-modiff-subtle-text","success"===a&&"text-modiff-green","warning"===a&&"text-hf-orange","error"===a&&"text-modiff-red"),children:e})}var pe=e(d(),1),xe=D(),he=[{value:"all",label:"All models"},{value:"installed",label:"Installed"},{value:"supported",label:"Supported"},{value:"downloads",label:"Downloads"}],ge=(0,pe.lazy)(()=>x(()=>import(`./CustomExtensionsPanel.js?v=cc046c26d6fe7aa4`),[]));function be(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function je(e){if(!Array.isArray(e))throw Error("The Hugging Face cache response must be an array.");return e.map((e,a)=>{if(!be(e)||"string"!=typeof e.id||!Array.isArray(e.revisions))throw Error(`Hugging Face cache entry ${a+1} is invalid.`);if(e.revisions.some(e=>!be(e)||"string"!=typeof e.hash))throw Error(`Hugging Face cache entry ${a+1} has an invalid revision.`);return e})}var ve=["Image","Edit","Control","Video","Audio","Adapters","Components","Other"];function ye(e){return"default"===e?"neutral":e}function we({children:e,disabled:a,onClick:t,progress:s,testId:l,title:n,tone:i}){let o="string"==typeof e?e:void 0;return(0,ue.jsx)(L,{action:"Installing"===o?"installing":"Retry"===o?"retry":t?"install":"success"===i?"ready":"warning"===i||"error"===i?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:a,label:e,onClick:t,progress:s,testId:l,title:n,tone:ye(i)})}function Ne(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){let a=e;return String(a.id??a.repo_id??a.label??a.rel_path??a.path??JSON.stringify(e))}return String(e??"")}function Ce(e){let a=Ne(e);return a.replace(/\\/g,"/").split("/").filter(Boolean).slice(-2).join("/")||a}function ke(e){return!!(e&&"object"==typeof e&&"id"in e&&"revisions"in e)}function $e(e,a){let t=new Map;return ve.forEach(e=>t.set(e,[])),e.forEach(e=>t.get(a(e))?.push(e)),ve.map(e=>[e,t.get(e)??[]]).filter(([,e])=>e.length>0)}function _e(e){let a=X(e);return"spandrel"===a?"Spandrel":G(e)?"diffusers_accelerated"===a?"Accelerated":"Diffusers":"Legacy"}function Se(e){if(0===e)return"0 B";let a=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**a).toFixed(2)} ${["B","KB","MB","GB","TB"][a]}`}function Te(e){let a=Ne(e),t=a.split("/"),s=t.pop()||a,l=t.join("/");return(0,ue.jsxs)(ue.Fragment,{children:[l?(0,ue.jsx)("span",{className:"text-modiff-subtle-text",children:l}):null,l?"/":null,(0,ue.jsx)("strong",{children:s})]})}function Re({children:e,count:a,testId:t,title:s}){return(0,ue.jsxs)("section",{className:"grid gap-2","data-testid":t,children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,ue.jsx)("span",{children:s}),(0,ue.jsx)(we,{tone:"default",children:a})]}),e]})}function He({activeInstallCount:e,autoPlan:a,expertMode:t,form:s,focused:l,hfTokenConfigured:n,installProgress:i,onConfigureHfToken:o,onInstall:r,profile:d,status:c}){let m=w(a,s),u=t?S(d,c):null,f=m&&u&&m.repo===u.repo?{...m,repair:u.repair,revision:u.revision,files:u.files}:m??u,p=f?.repo??d.defaultRepo,x=i[p],h=Q(x),b=q(x),y=b&&("huggingface_access_required"===x?.error_code||"access"===ee(x)),N=y||!n&&B(p),C=E(c.runnable,a,s),k=g(a,s),$=C?"Ready":f?.actionLabel??j(a,s),_=!C&&("Not suitable locally"===$||"Will not work on this machine"===$||"unsuitable"===k.state),T=C?"success":_?"error":"warning",R=y?"Review access":N?"Add HF token":C?"Ready":h?"Installing":b?"Retry":function(e){return"This should work"===e?"Estimated":"Community option"===e?"Community":"Not suitable locally"===e||"Will not work on this machine"===e?"Blocked":"Repair required"===e?"Repair":"Failed here before"===e?"Failed":"Expert only"===e?"Custom memory":"Needs setup"===e||"Install model"===e||"Install Auto artifact"===e?"Install":e}(f?.actionLabel??$),H=N?y&&x?.error?x.error:"This gated Hugging Face repository needs an accepted license and a configured read token.":C?c.reason:b&&x?.error?x.error:f?.reason??k.detail,I=!N&&!C&&f&&!h&&e<2,D=d.artifactSelections?.length?d.artifactLabel:null,F=D??d.label,M=D?d.defaultRepo:null;return(0,ue.jsx)("article",{className:v("rounded-modiff-compact border bg-modiff-bg p-2",l?"border-hf-yellow/80":"border-modiff-border"),"data-testid":`model-manager-supported-${d.modelType}`,"data-model-repo":d.defaultRepo,"data-model-manager-focused":l?"true":void 0,children:(0,ue.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,ue.jsxs)("div",{className:"min-w-0",children:[(0,ue.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text","data-testid":"model-manager-artifact-label",children:F}),M?(0,ue.jsx)("div",{className:"mt-0.5 truncate text-xs text-modiff-subtle-text",title:d.defaultRepo,children:M}):null,(0,ue.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,ue.jsx)(we,{tone:"default",children:d.surfaceCategory??d.family}),(0,ue.jsx)(we,{tone:"default",children:_e(d)}),"workflowOnly"===d.catalogVisibility?(0,ue.jsx)(we,{tone:"warning",children:"Legacy"}):null,f?.repair?(0,ue.jsx)(we,{tone:"warning",children:"Repair"}):null]})]}),(0,ue.jsx)(we,{disabled:h||!N&&!C&&!I,onClick:N?()=>o(p):I?()=>{f&&r(f,f.repair)}:void 0,progress:h?se(x):null,testId:`model-manager-install-${d.modelType}`,title:`${p} | ${H}`,tone:T,children:R})]})})}function Ie({opener:e,onClose:o}){let{setAlertOpener:d}=R(),x=y(e=>e.sid),g=H(e=>e.hfCache),j=H(e=>e.localModels),v=H(e=>e.modelCacheDiagnostics),S=H(e=>e.runtimeStatus),D=H(e=>e.nodesRegistry),E=H(e=>e.studioModelCapabilities),L=H(e=>e.studioModelCapabilitiesAuthoritative),B=H(e=>e.refreshModelIndexes),G=H(e=>e.fetchRegistry),X=H(e=>e.installHfModel),ee=H(e=>e.hfDownloadProgress),se=H(e=>e.reconcileHfDownloadProgress),be=H(e=>e.fetchCustomModules),ve=M(e=>e.nodes),ye=M(e=>e.setNodeUiState),_e=K(e=>e.form),Ie=K(e=>e.activeTemplateId),De=K(e=>e.graphBinding),Fe=K(e=>e.sourceOutputId),Me=K(e=>e.autoResourcePlans),ze=K(e=>e.setAutoResourcePlans),[Ee,Ae]=(0,pe.useState)(!1),Le=(0,pe.useRef)(0),[Pe,Oe]=(0,pe.useState)([]),[qe,Be]=(0,pe.useState)([]),[Ve,We]=(0,pe.useState)(""),[Ue,Je]=(0,pe.useState)("all"),Ge=(0,pe.useRef)(null),Ke=e=>{Je(e),Ge.current?.closest("[data-dialog-scroll-body]")?.scrollTo(0,0)},[Ze,Qe]=(0,pe.useState)(!1),[Xe,Ye]=(0,pe.useState)(null),[ea,aa]=(0,pe.useState)(""),[ta,sa]=(0,pe.useState)(!1),[la,na]=(0,pe.useState)(null),ia=ce(),oa=e?.focus,ra=Object.values(ee).filter(Q).length,da=Object.entries(ee).filter(([e,a])=>(Q(a)||q(a)||le(a))&&e.toLowerCase().includes(Ve.trim().toLowerCase())),ca=ve.filter(e=>{if("group"===e.data.type||"loop"===e.data.type)return!1;let a=`${e.data.module}.${e.data.action}`;return!D[a]}),ma=(0,pe.useMemo)(()=>function(e){let a=new Set;return e.filter(({item:e,source:t})=>{let s=`${t}:${Ne(e).toLowerCase()}`;return!a.has(s)&&(a.add(s),!0)})}([...Pe.map(e=>({source:"HF",item:e})),...j.map(e=>({source:"Local",item:e}))].filter(({item:e})=>{let a=Ve.trim().toLowerCase();return!a||Ne(e).toLowerCase().includes(a)})),[Ve,Pe,j]),ua=(0,pe.useMemo)(()=>$e(ma,({item:e})=>function(e){let a=Ne(e).toLowerCase();return a.includes("text_encoder")||a.includes("text encoder")||a.includes("vae")||a.includes("tokenizer")||a.includes("transformer")||a.includes("diffusion_model")||a.includes("clip")?"Components":a.includes("wan")||a.includes("video")?"Video":a.includes("ace")||a.includes("audio")?"Audio":a.includes("control")||a.includes("canny")||a.includes("depth")?"Control":a.includes("lora")||a.includes("adapter")?"Adapters":a.includes("edit")||a.includes("inpaint")||a.includes("fill")||a.includes("kontext")||a.includes("redux")?"Edit":a.includes("image")||a.includes("flux")||a.includes("z-image")||a.includes("qwen")?"Image":"Other"}(e)),[ma]),fa=(0,pe.useMemo)(()=>ua,[!0,ua]),pa=(0,pe.useMemo)(()=>b({currentModelType:oa?.modelType??_e.modelType,includeWorkflowOnly:!0}).flatMap(e=>{if(!L)return[e];let a=E.find(a=>a.modelType===e.modelType);return a?z({...e,defaultRepo:a.defaultRepo??e.defaultRepo,artifactLabel:a.artifactLabel??e.artifactLabel,executionStatus:a.executionStatus??e.executionStatus,revisionCandidates:a.revisionCandidates??e.revisionCandidates,downloadFiles:a.downloadFiles??e.downloadFiles,artifactSelections:a.artifactSelections??e.artifactSelections,optionalRuntimeRequirement:a.optionalRuntimeRequirement??e.optionalRuntimeRequirement}):[e]}).sort((e,a)=>{if(oa?.modelType===e.modelType)return-1;if(oa?.modelType===a.modelType)return 1;if(oa?.repo===e.defaultRepo)return-1;if(oa?.repo===a.defaultRepo)return 1;let t=String(e.label??e.modelType??e.defaultRepo??""),s=String(a.label??a.modelType??a.defaultRepo??"");return t.localeCompare(s)}),[!0,oa?.modelType,oa?.repo,_e.modelType,E,L]),xa=(0,pe.useMemo)(()=>{let e=Ve.trim().toLowerCase();return pa.filter(a=>`${a.label} ${a.defaultRepo} ${a.family} ${a.surfaceCategory??""}`.toLowerCase().includes(e))},[pa,Ve]),ha=(0,pe.useMemo)(()=>pa.map(e=>ae(A(e),e.modelType)),[pa]),ga=(0,pe.useMemo)(()=>ha.map(_),[ha]),ba=(0,pe.useMemo)(()=>$e(xa,e=>function(e){return"Audio"===e?"Audio":"Video"===e?"Video":"Control"===e?"Control":"Image Edit"===e?"Edit":"Utility"===e?"Adapters":"Image"===e?"Image":"Other"}(e.surfaceCategory)),[xa]);(0,pe.useEffect)(()=>{if(!oa)return;let e=window.setTimeout(()=>{document.querySelector('[data-model-manager-focused="true"]')?.scrollIntoView({behavior:"smooth",block:"center"})},80);return()=>window.clearTimeout(e)},[oa,xa.length]);let ja=oa?.label??xa.find(e=>e.modelType===oa?.modelType||e.defaultRepo===oa?.repo)?.label??oa?.repo,va=_(_e),ya=!!(oa||Ie||De||Fe),wa=(0,pe.useMemo)(()=>ya?I({autoResourcePlan:Me[va],form:_e,hfCache:g,includePipeline:!1,localModels:j,modelCacheDiagnostics:v}):[],[Me,g,ya,j,v,_e,va]),Na=(0,pe.useCallback)(()=>{Le.current+=1,Ae(!0)},[]),Ca=(0,pe.useCallback)(()=>{Le.current=Math.max(0,Le.current-1),0===Le.current&&Ae(!1)},[]),ka=(0,pe.useCallback)(async()=>{let e=xe.begin("fullCache");Na();try{let a=await $(`${Y.serverAddress}/hf_cache`,{signal:e.signal,timeoutMs:12e4,parse:je});e.isLatest()&&Oe(a)}catch(a){e.isLatest()&&console.error("Error fetching Hugging Face models:",a)}finally{e.finish(),Ca()}},[Na,Ca]),$a=(0,pe.useCallback)(async()=>{let e=await F(ha,ga),a={};e.forEach((e,t)=>{let s=e.planKey??ga[t];s&&(a[s]=e)}),ze(a)},[ze,ha,ga]),_a=e=>{let a="string"==typeof e.workflowId?` (${e.workflowId})`:"";switch(e.code){case"graph_execution_active":return"a graph is running";case"graph_execution_queued":return"a graph is queued";case"model_download_active":return"a model download is active";case"template_gallery_install_active":return"the Template Gallery is installing";case"canonical_dependency_open":return`template evidence is not turnover-complete${a}`;case"saved_workflow_dependency":return`a saved workflow still uses the model${a}`;case"recent_incomplete_download":return"an incomplete file is newer than one hour";default:return e.code.split("_").join(" ")}},Sa=async(e,a)=>{Na();try{let t=await O(e),s=!1;if(!t.canDelete){let a=new Set(["canonical_dependency_open","saved_workflow_dependency"]);if(!(t.blockers.length>0&&t.blockers.every(e=>a.has(e.code)))){let e=t.blockers.slice(0,4).map(_a).join("; ");return void N(`Deletion blocked: ${e||"the revision is not turnover-safe"}.`,{variant:"error",autoHideDuration:Math.max(7e3,70*e.length)})}if(t=await O(e,!0),s=!0,!t.canDelete){let e=t.blockers.slice(0,4).map(_a).join("; ");return void N(`Local eviction blocked: ${e||"the cache state changed"}.`,{variant:"error",autoHideDuration:Math.max(7e3,70*e.length)})}}let l=t.targets.map(e=>`${e.repoId}@${e.revision}${e.sizeBytes?` (${Se(e.sizeBytes)})`:""}`).join(", "),n=t.canonicalDependencies.length,i=t.savedWorkflowDependencies.length;d({title:s?"Free local model storage?":"Confirm safe model deletion",message:s?`Evict the local copy of ${a}? Exact cache target: ${l}. ${n} canonical definition${1===n?"":"s"} and ${i} saved workflow${1===i?"":"s"} will be kept, but they must download this exact model revision before they can run again.`:`Delete ${a}? Exact cache target: ${l}. ${n} canonical workflow ${1===n?"dependency":"dependencies"} verified turnover-complete. This action cannot be undone without downloading the model again.`,confirmText:s?"Evict local copy":"Delete exact revision",cancelText:"Cancel",onConfirm:()=>{d(null),(async(e,a,t=!1)=>{Na();try{await ne(e,a,t),await ka()}catch(e){console.error("Error deleting Hugging Face model:",e);let a=h(e,"Error deleting Hugging Face model.");N(a,{variant:"error",autoHideDuration:80*a.length})}finally{Ca()}})(e,t.planHash,s)},onCancel:()=>d(null)})}catch(e){let a=h(e,"Could not inspect model dependencies before deletion.");N(a,{variant:"error",autoHideDuration:80*a.length})}finally{Ca()}},Ta=async(e,a=!1)=>{let t="string"==typeof e?{repo:e,label:e,repair:a}:e;ia.request("install",Z(t.repo,t.revision),()=>(async(e,a=!1)=>{let t="string"==typeof e?{repo:e,label:e,repair:a}:e;try{await X(t.repo,x,{repair:t.repair,revision:t.revision,files:t.files}),await Promise.all([ka(),B(!0)]),await $a()}catch(e){console.error(e)}})(t,t.repair))},Ra=()=>{o(),Be([]),We(""),Je("all"),Qe(!1),aa(""),na(null),Oe([])};return(0,pe.useEffect)(()=>{ka(),$a(),be()},[!0,be,ka,$a]),(0,pe.useEffect)(()=>{if(!e||0===ra)return;let a=!1,t=async()=>{try{await se()}catch(e){}};t();let s=window.setInterval(()=>{t()},2e3);return()=>{a=!0,window.clearInterval(s)}},[ra,e,se]),(0,ue.jsxs)(ue.Fragment,{children:[(0,ue.jsxs)(J,{open:!!e,onClose:Ra,title:(0,ue.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,ue.jsx)(r,{size:17,className:"shrink-0 text-hf-yellow"}),(0,ue.jsx)("span",{className:"truncate",children:"Models"})]}),description:"Manage local artifacts and install models from Hugging Face Hub.",panelClassName:"max-w-4xl",bodyClassName:"!p-0",testId:"model-manager-dialog",toolbar:(0,ue.jsxs)("div",{className:"grid gap-3 p-3","data-testid":"model-manager-toolbar",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(re,{"aria-label":"Filter models and artifacts",className:"min-w-0 flex-1 basis-56",controlSize:"normal",placeholder:"Search by model, repository or family",value:Ve,onChange:e=>We(e.target.value),onClear:()=>We("")}),(0,ue.jsx)(te,{icon:(0,ue.jsx)(n,{size:14}),"aria-expanded":Ze,"aria-controls":"model-manager-token-editor",onClick:()=>{Qe(e=>!e),aa(""),na(null)},children:S?.config?.hf_token_configured?"HF token ready":"Add HF token"}),(0,ue.jsx)(te,{loading:Ee,icon:(0,ue.jsx)(u,{size:14}),onClick:()=>{(async(e=!0)=>{Na();try{await Promise.all([ka(),B(e)]),await $a(),await be(),N("Models refreshed",{variant:"success",autoHideDuration:1800})}catch(e){N(h(e,"Could not refresh model health."),{variant:"error",autoHideDuration:6e3})}finally{Ca()}})(!0)},children:"Refresh"})]}),(0,ue.jsx)(ie,{"aria-label":"Model inventory sections",size:"dense",className:"flex-wrap",value:Ue,onValueChange:Ke,options:he.map(e=>({...e,label:"downloads"===e.value&&ra>0?`Downloads (${ra})`:e.label,id:`model-inventory-tab-${e.value}`,controls:`model-inventory-panel-${e.value}`}))})]}),footer:(0,ue.jsxs)(ue.Fragment,{children:[(0,ue.jsx)("span",{className:"mr-auto flex items-center text-xs text-modiff-subtle-text",role:"status","aria-live":"polite",children:Ee?"Refreshing model inventory…":`${ma.length} installed · ${xa.length} supported${Ve?" matches":""}`}),(0,ue.jsx)(te,{"data-testid":"model-manager-close",onClick:Ra,children:"Close"})]}),children:[Ze?(0,ue.jsxs)("div",{id:"model-manager-token-editor",className:"m-3 grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,ue.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Hugging Face access"}),(0,ue.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["Accept the"," ",(0,ue.jsx)("a",{className:"text-hf-yellow underline underline-offset-2",href:Xe?`https://huggingface.co/${Xe}`:"https://huggingface.co/models",target:"_blank",rel:"noreferrer",children:"repository terms"}),", create a"," ",(0,ue.jsx)("a",{className:"text-hf-yellow underline underline-offset-2",href:"https://huggingface.co/settings/tokens",target:"_blank",rel:"noreferrer",children:"read token"}),", then paste it below. The token is validated and stored on the backend; it is never returned to the browser."]}),(0,ue.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ue.jsx)(W,{"aria-label":"Hugging Face access token",autoFocus:!0,autoComplete:"off",value:ea,onChange:e=>aa(e.target.value),placeholder:"hf_...",disabled:ta,className:"min-w-0 flex-1 basis-56"}),(0,ue.jsx)(te,{tone:"primary",disabled:ta||!ea.trim(),loading:ta,icon:(0,ue.jsx)(n,{size:14}),onClick:()=>{(async()=>{let e=ea.trim();if(e){sa(!0),na(null);try{await $(`${Y.serverAddress}/hf_token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),timeoutMs:3e4}),aa(""),Qe(!1),await B(!0),N("Hugging Face token saved. Retry the model download.",{variant:"success",autoHideDuration:3500})}catch(e){na(h(e,"Could not validate the Hugging Face token."))}finally{sa(!1)}}else na("Paste a Hugging Face read token first.")})()},children:"Save token"}),(0,ue.jsx)(te,{disabled:ta,onClick:()=>{Qe(!1),aa(""),na(null)},children:"Cancel"})]}),la?(0,ue.jsx)(fe,{tone:"warning",children:la}):null]}):null,he.filter(e=>e.value!==Ue).map(e=>(0,ue.jsx)("div",{id:`model-inventory-panel-${e.value}`,role:"tabpanel","aria-labelledby":`model-inventory-tab-${e.value}`,hidden:!0},e.value)),(0,ue.jsxs)("div",{ref:Ge,className:"p-3",id:`model-inventory-panel-${Ue}`,role:"tabpanel","aria-labelledby":`model-inventory-tab-${Ue}`,children:[ja?(0,ue.jsxs)("div",{className:"mb-3 flex flex-wrap items-center gap-2 rounded-modiff-compact border border-hf-yellow/70 bg-hf-yellow/10 p-2","data-testid":"model-manager-focus",children:[(0,ue.jsx)(we,{tone:"warning",children:"Focused"}),(0,ue.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:ja})]}):null,("all"===Ue||"downloads"===Ue)&&da.length>0?(0,ue.jsxs)("section",{className:"mb-3 grid gap-2","data-testid":"model-manager-downloads",children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,ue.jsx)("span",{children:"Downloads"}),(0,ue.jsxs)(we,{tone:ra>0?"warning":"default",children:[ra," active"]})]}),da.map(([e,a])=>(0,ue.jsx)(T,{repoId:e,progress:a,compact:!1,testId:`model-manager-download-${e}`},e))]}):null,"downloads"===Ue&&0===da.length?(0,ue.jsxs)("div",{className:"grid justify-items-start gap-2 p-3 text-sm text-modiff-subtle-text",children:[(0,ue.jsx)(f,{size:22,"aria-hidden":"true"}),(0,ue.jsx)("p",{children:Ve?"No downloads match this search.":"No downloads to show. Choose a model in Supported to install it."}),Ve?(0,ue.jsx)(te,{onClick:()=>We(""),children:"Clear search"}):(0,ue.jsx)(te,{onClick:()=>Ke("supported"),children:"Browse supported models"})]}):null,(0,ue.jsxs)("div",{className:"grid gap-4",children:["all"===Ue&&ya&&wa.length>0?(0,ue.jsx)(Re,{count:wa.length,testId:"model-manager-requirements",title:"Current workflow",children:(0,ue.jsx)("div",{className:"grid gap-1",children:wa.map(e=>(0,ue.jsx)(de,{activeInstallCount:ra,actionTestId:`model-manager-install-requirement-${e.id}`,compact:!1,installProgress:ee,onInstall:e=>Ta(e),onUseLocal:()=>We(e.repo.split("/").pop()??e.repo),requirement:e,testId:`model-manager-requirement-${e.id}`},e.id))})}):null,"all"===Ue||"installed"===Ue?(0,ue.jsx)(Re,{count:ma.length,testId:"model-manager-installed",title:"Installed",children:0===fa.length?(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:[Ve?"No installed models match this search.":Ee?"Reading the model inventory…":"No visible model artifacts indexed yet.",Ve?(0,ue.jsx)(te,{className:"mt-2",onClick:()=>We(""),children:"Clear search"}):null]}):fa.map(([e,a])=>(0,ue.jsxs)("div",{className:"grid gap-1",children:[(0,ue.jsx)("div",{className:"px-1 text-xs font-semibold text-modiff-subtle-text",children:e}),a.map(({item:e,source:a})=>(0,ue.jsxs)("article",{className:"flex min-h-10 items-center justify-between gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",title:Ne(e),children:[(0,ue.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,ue.jsx)(s,{size:15,className:"shrink-0 text-hf-yellow"}),(0,ue.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:Ce(e)})]}),(0,ue.jsxs)("div",{className:"flex flex-none items-center gap-1",children:[ke(e)?(0,ue.jsx)(we,{tone:"default",title:Se(e.size),children:Se(e.size)}):null,(0,ue.jsx)(we,{tone:"success",children:a})]})]},`${a}-${Ne(e)}`))]},e))}):null,"all"===Ue||"supported"===Ue?(0,ue.jsx)(Re,{count:xa.length,testId:"model-manager-supported",title:"Supported",children:0===ba.length?(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:["No supported models match the current filter.",Ve?(0,ue.jsx)(te,{className:"mt-2",onClick:()=>We(""),children:"Clear search"}):null]}):ba.map(([e,a])=>(0,ue.jsxs)("div",{className:"grid gap-1",children:[(0,ue.jsx)("div",{className:"px-1 text-xs font-semibold text-modiff-subtle-text",children:e}),a.map(e=>{let a=ae(A(e),e.modelType),t=_(a),s=Me[t],l=w(s);return(0,ue.jsx)(He,{activeInstallCount:ra,autoPlan:s,expertMode:!0,form:a,focused:oa?.modelType===e.modelType||oa?.repo===e.defaultRepo||oa?.repo===l?.repo,installProgress:ee,hfTokenConfigured:!!S?.config?.hf_token_configured,onConfigureHfToken:e=>{Ye(e),Qe(!0)},onInstall:Ta,profile:e,status:k(e,g,j,v)},`${e.modelType}:${e.defaultRepo}`)})]},e))}):null,"all"===Ue?(0,ue.jsxs)(V,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-panel p-3","data-testid":"model-manager-diagnostics",label:(0,ue.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,ue.jsxs)("span",{className:"flex items-center gap-2",children:[(0,ue.jsx)(l,{size:15,className:"text-hf-yellow"}),"Diagnostics"]}),(0,ue.jsx)(we,{tone:"default",children:"Developer"})]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-4",children:[(0,ue.jsx)("section",{className:"grid gap-2",children:(0,ue.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ue.jsx)(te,{className:"h-8 px-2 text-xs",icon:(0,ue.jsx)(u,{size:14}),onClick:()=>{G()},children:"Update registry"}),(0,ue.jsx)(te,{className:"h-8 px-2 text-xs",icon:(0,ue.jsx)(m,{size:14}),onClick:()=>{let e={schemaVersion:1,capturedAt:(new Date).toISOString(),runtimeStatus:S,modelCacheDiagnostics:v,hfCache:g,localModels:j,workflow:{nodeCount:ve.length,missingNodes:ca.map(e=>({id:e.id,label:e.data.label,module:e.data.module,action:e.data.action,key:`${e.data.module}.${e.data.action}`,disabled:!!e.data.uiState?.disabled}))}};navigator.clipboard.writeText(JSON.stringify(e,null,2)),N("Environment snapshot copied",{variant:"success",autoHideDuration:1800})},children:"Copy snapshot"})]})}),v?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Scanned folders"}),v.locations.map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.exists?!1===e.runnable?"warning":"success":"error",children:e.exists?!1===e.runnable?"Not runnable":"Indexed":"Missing"}),(0,ue.jsxs)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:[e.label,": ",e.path||"default"]})]}),(0,ue.jsxs)(fe,{tone:!1===e.runnable?"warning":e.exists?"muted":"error",children:[e.repo_count??e.file_count??0," item(s),"," ",e.compatible_hf_repo_count??0," compatible HF repo(s),"," ",e.external_package_count??0," external package(s)",e.reason?` | ${e.reason}`:""]})]},`${e.label}-${e.path}`))]}):null,(v?.external_model_packages?.length??0)>0?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"External packages"}),v?.external_model_packages?.slice(0,8).map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.runnable?"success":"warning",children:e.runnable?"Compatible":"Needs link"}),(0,ue.jsx)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:e.label})]}),(0,ue.jsxs)(fe,{tone:e.runnable?"success":"warning",children:[e.format," | ",Se(e.model_file_bytes??0)," | ",e.path," | ",e.reason]})]},`${e.source}-${e.path}`))]}):null,(v?.hf_compatible_external_repos?.length??0)>0?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"HF-compatible external repos"}),v?.hf_compatible_external_repos?.slice(0,8).map(e=>{let a=C(e.repo_id,g,j,v);return(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:a.runnable?"success":"warning",children:a.runnable?"Runnable":"Link needed"}),(0,ue.jsx)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:e.repo_id})]}),(0,ue.jsxs)(fe,{tone:a.runnable?"success":"warning",children:[e.path," | ",e.reason]})]},`${e.source}-${e.path}`)})]}):null,(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Workflow node definitions"}),0===ca.length?(0,ue.jsx)(fe,{tone:"success",children:"Every current graph node has a matching backend registry definition."}):ca.slice(0,8).map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-red/70 bg-modiff-red/10 p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.data.uiState?.disabled?"warning":"error",children:e.data.uiState?.disabled?"Disabled":"Missing"}),(0,ue.jsx)("span",{className:"min-w-0 flex-1 break-all text-xs font-semibold text-modiff-subtle-text",children:e.data.label||e.id})]}),(0,ue.jsxs)(fe,{tone:e.data.uiState?.disabled?"warning":"error",children:[e.data.module,".",e.data.action]}),(0,ue.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[(0,ue.jsx)(te,{tone:"secondary",icon:(0,ue.jsx)(i,{size:14}),onClick:()=>((e,a)=>{ye(e,{disabled:a,validationSeverity:a?"warning":void 0,validationMessage:a?"Disabled nodes are skipped during run export.":void 0}),N(a?"Node disabled for run export":"Node enabled for run export",{variant:"success",autoHideDuration:1800})})(e.id,!e.data.uiState?.disabled),children:e.data.uiState?.disabled?"Enable":"Disable"}),(0,ue.jsx)(te,{tone:"secondary",icon:(0,ue.jsx)(m,{size:14}),onClick:()=>((e,a)=>{navigator.clipboard.writeText(`${e}\n${a}`),N("Missing node key copied",{variant:"success",autoHideDuration:1600})})(e.id,`${e.data.module}.${e.data.action}`),children:"Copy key"})]})]},e.id))]}),(0,ue.jsx)(pe.Suspense,{fallback:null,children:(0,ue.jsx)(ge,{})}),(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Raw Hugging Face cache"}),(0,ue.jsx)(te,{tone:"secondary",size:"compact",icon:Ee?(0,ue.jsx)(t,{size:13,className:"animate-spin"}):(0,ue.jsx)(p,{size:13}),disabled:Ee,onClick:()=>{(async()=>{Na();try{let e=await oe();if(!e.canCleanup){let a=e.blockers.slice(0,4).map(_a).join("; ");return void N(0!==e.eligibleFileCount||a?`Cleanup blocked: ${a||"no stale files are eligible"}.`:"No stale incomplete Hugging Face files are eligible for cleanup.",{variant:"default",autoHideDuration:6e3})}d({title:"Clean stale partial downloads?",message:`Remove ${e.eligibleFileCount} inactive .incomplete file(s) and reclaim ${Se(e.eligibleBytes)}? Only regular blob files older than one hour are included; installed snapshots and model revisions are not removed.`,confirmText:"Clean exact files",cancelText:"Cancel",onConfirm:()=>{d(null),(async e=>{Na();try{let a=await U(e),t="number"==typeof a.removedFileCount?a.removedFileCount:0,s="number"==typeof a.removedBytes?a.removedBytes:0;await ka(),N(`Removed ${t} stale partial file(s), reclaiming ${Se(s)}.`,{variant:"success",autoHideDuration:5e3})}catch(e){N(h(e,"Could not clean stale Hugging Face downloads."),{variant:"error",autoHideDuration:7e3})}finally{Ca()}})(e.planHash)},onCancel:()=>d(null)})}catch(e){N(h(e,"Could not inspect stale Hugging Face downloads."),{variant:"error",autoHideDuration:7e3})}finally{Ca()}})()},children:"Clean partial files"})]}),(0,ue.jsx)(fe,{tone:"muted",children:"Removes only hash-planned inactive .incomplete blobs older than one hour; installed revisions remain."}),0!==Pe.length||Ee?Pe.map(e=>{if(!ke(e)){let a=Ne(e);return(0,ue.jsx)("article",{className:"border-b border-modiff-border py-3 last:border-b-0",children:(0,ue.jsx)("div",{className:"flex items-start gap-3",children:(0,ue.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,ue.jsx)("h4",{className:"truncate text-sm font-semibold text-modiff-text",children:Te(a)}),(0,ue.jsx)("div",{className:"mt-1 flex flex-wrap gap-1",children:(0,ue.jsx)(we,{tone:"default",children:"Indexed"})})]})})},a)}let t=qe.includes(e.id);return(0,ue.jsxs)("article",{className:"border-b border-modiff-border py-3 last:border-b-0",children:[(0,ue.jsxs)("div",{className:"flex items-start gap-3",children:[(0,ue.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,ue.jsx)("h4",{className:"truncate text-sm font-semibold text-modiff-text",children:Te(e.id)}),(0,ue.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,ue.jsx)(we,{tone:"default",children:Se(e.size)}),(0,ue.jsx)(we,{tone:"default",children:new Date(1e3*e.last_accessed).toLocaleDateString()}),e.class_names.slice(0,5).map(e=>(0,ue.jsx)(we,{tone:"default",children:e},e))]}),(0,ue.jsx)(te,{tone:"ghost",size:"compact",className:"mt-2 px-2 text-xs",onClick:()=>(e=>{Be(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])})(e.id),icon:t?(0,ue.jsx)(a,{size:14}):(0,ue.jsx)(c,{size:14}),children:"Revisions"})]}),(0,ue.jsx)(P,{label:`Delete ${e.id}`,disabled:Ee,className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{Sa(e.revisions.map(e=>e.hash).join(","),`${e.id} model`)},children:(0,ue.jsx)(p,{size:15})})]}),t?(0,ue.jsx)("div",{className:"mt-2 space-y-1 pl-4",children:e.revisions.map(a=>(0,ue.jsxs)("div",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[(0,ue.jsxs)("div",{className:"min-w-0 flex-1 break-words",children:[(0,ue.jsx)("strong",{className:"text-modiff-text",children:a.hash.slice(0,8)})," |"," ",new Date(1e3*a.last_modified).toLocaleString()," |"," ",Se(a.size)]}),(0,ue.jsx)(P,{label:`Delete revision ${a.hash.slice(0,8)}`,disabled:Ee,size:"compact",className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{Sa(a.hash,`${a.hash.slice(0,8)} revision of ${e.id}`)},children:(0,ue.jsx)(p,{size:13})})]},a.hash))}):null]},e.id)}):(0,ue.jsx)(fe,{tone:"muted",children:Ve?"No cache entries match the current filter.":"The local cache is empty."})]})]}):null]})]})]}),(0,ue.jsx)(me,{open:!!ia.pending,policies:ia.pending?.policies??[],action:ia.pending?.action??"install",onCancel:ia.cancel,onConfirm:ia.confirm})]})}export{Ie as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{En as a,Et as t,Ht as s,K as l,Nt as n,at as i,cr as o,dn as r,dr as d,kn as c,pn as m,rt as u,un as f,z as p}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$a as x,Ao as h,Co as g,Cr as b,Do as j,Fs as v,Hr as y,Ii as w,Is as N,Ka as C,Ki as k,Li as $,Ln as _,Ls as S,Ni as T,Oo as R,Po as H,Qt as I,Ri as D,S as F,Sn as M,So as z,Ti as E,Ui as A,Ya as L,Yn as P,_n as O,an as q,bn as B,bo as V,co as U,d as W,do as K,fn as J,fo as G,in as Y,io as Q,l as X,lc as Z,lo as ee,on as ae,oo as te,qa as se,uo as le,vo as ne,wa as ie,wi as oe,zi as re}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as de}from"./WorkflowArtifactRequirementRow.js?v=ca6b74e6a02eedb3";import{n as ce,t as me}from"./TemplateUsageTermsDialog.js?v=ca6b74e6a02eedb3";var ue=o();function fe({children:e,tone:a="muted"}){return(0,ue.jsx)("p",{className:_("break-words text-xs leading-5","muted"===a&&"text-modiff-subtle-text","success"===a&&"text-modiff-green","warning"===a&&"text-hf-orange","error"===a&&"text-modiff-red"),children:e})}var pe=e(d(),1),xe=j(),he=[{value:"all",label:"All models"},{value:"installed",label:"Installed"},{value:"supported",label:"Supported"},{value:"downloads",label:"Downloads"}],ge=(0,pe.lazy)(()=>E(()=>import(`./CustomExtensionsPanel.js?v=ca6b74e6a02eedb3`),[]));function be(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function je(e){if(!Array.isArray(e))throw Error("The Hugging Face cache response must be an array.");return e.map((e,a)=>{if(!be(e)||"string"!=typeof e.id||!Array.isArray(e.revisions))throw Error(`Hugging Face cache entry ${a+1} is invalid.`);if(e.revisions.some(e=>!be(e)||"string"!=typeof e.hash))throw Error(`Hugging Face cache entry ${a+1} has an invalid revision.`);return e})}var ve=["Image","Edit","Control","Video","Audio","Adapters","Components","Other"];function ye(e){return"default"===e?"neutral":e}function we({children:e,disabled:a,onClick:t,progress:s,testId:l,title:n,tone:i}){let o="string"==typeof e?e:void 0;return(0,ue.jsx)(I,{action:"Installing"===o?"installing":"Retry"===o?"retry":t?"install":"success"===i?"ready":"warning"===i||"error"===i?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:a,label:e,onClick:t,progress:s,testId:l,title:n,tone:ye(i)})}function Ne(e){if("string"==typeof e)return e;if(e&&"object"==typeof e){let a=e;return String(a.id??a.repo_id??a.label??a.rel_path??a.path??JSON.stringify(e))}return String(e??"")}function Ce(e){let a=Ne(e);return a.replace(/\\/g,"/").split("/").filter(Boolean).slice(-2).join("/")||a}function ke(e){return!!(e&&"object"==typeof e&&"id"in e&&"revisions"in e)}function $e(e,a){let t=new Map;return ve.forEach(e=>t.set(e,[])),e.forEach(e=>t.get(a(e))?.push(e)),ve.map(e=>[e,t.get(e)??[]]).filter(([,e])=>e.length>0)}function _e(e){let a=Q(e);return"spandrel"===a?"Spandrel":te(e)?"diffusers_accelerated"===a?"Accelerated":"Diffusers":"Legacy"}function Se(e){if(0===e)return"0 B";let a=Math.floor(Math.log(e)/Math.log(1024));return`${(e/1024**a).toFixed(2)} ${["B","KB","MB","GB","TB"][a]}`}function Te(e){let a=Ne(e),t=a.split("/"),s=t.pop()||a,l=t.join("/");return(0,ue.jsxs)(ue.Fragment,{children:[l?(0,ue.jsx)("span",{className:"text-modiff-subtle-text",children:l}):null,l?"/":null,(0,ue.jsx)("strong",{children:s})]})}function Re({children:e,count:a,testId:t,title:s}){return(0,ue.jsxs)("section",{className:"grid gap-2","data-testid":t,children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,ue.jsx)("span",{children:s}),(0,ue.jsx)(we,{tone:"default",children:a})]}),e]})}function He({activeInstallCount:e,autoPlan:a,expertMode:t,form:s,focused:l,hfTokenConfigured:n,installProgress:i,onConfigureHfToken:o,onInstall:r,profile:d,status:c}){let m=re(a,s),u=t?S(d,c):null,f=m&&u&&m.repo===u.repo?{...m,repair:u.repair,revision:u.revision,files:u.files}:m??u,p=f?.repo??d.defaultRepo,x=i[p],h=K(x),g=le(x),b=g&&("huggingface_access_required"===x?.error_code||"access"===U(x)),j=b||!n&&W(p),v=k(c.runnable,a,s),y=$(a,s),w=v?"Ready":f?.actionLabel??D(a,s),N=!v&&("Not suitable locally"===w||"Will not work on this machine"===w||"unsuitable"===y.state),C=v?"success":N?"error":"warning",T=b?"Review access":j?"Add HF token":v?"Ready":h?"Installing":g?"Retry":function(e){return"This should work"===e?"Estimated":"Community option"===e?"Community":"Not suitable locally"===e||"Will not work on this machine"===e?"Blocked":"Repair required"===e?"Repair":"Failed here before"===e?"Failed":"Expert only"===e?"Custom memory":"Needs setup"===e||"Install model"===e||"Install Auto artifact"===e?"Install":e}(f?.actionLabel??w),R=j?b&&x?.error?x.error:"This gated Hugging Face repository needs an accepted license and a configured read token.":v?c.reason:g&&x?.error?x.error:f?.reason??y.detail,H=!j&&!v&&f&&!h&&e<2,I=d.artifactSelections?.length?d.artifactLabel:null,F=I??d.label,M=I?d.defaultRepo:null;return(0,ue.jsx)("article",{className:_("rounded-modiff-compact border bg-modiff-bg p-2",l?"border-hf-yellow/80":"border-modiff-border"),"data-testid":`model-manager-supported-${d.modelType}`,"data-model-repo":d.defaultRepo,"data-model-manager-focused":l?"true":void 0,children:(0,ue.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,ue.jsxs)("div",{className:"min-w-0",children:[(0,ue.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text","data-testid":"model-manager-artifact-label",children:F}),M?(0,ue.jsx)("div",{className:"mt-0.5 truncate text-xs text-modiff-subtle-text",title:d.defaultRepo,children:M}):null,(0,ue.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,ue.jsx)(we,{tone:"default",children:d.surfaceCategory??d.family}),(0,ue.jsx)(we,{tone:"default",children:_e(d)}),"workflowOnly"===d.catalogVisibility?(0,ue.jsx)(we,{tone:"warning",children:"Legacy"}):null,f?.repair?(0,ue.jsx)(we,{tone:"warning",children:"Repair"}):null]})]}),(0,ue.jsx)(we,{disabled:h||!j&&!v&&!H,onClick:j?()=>o(p):H?()=>{f&&r(f,f.repair)}:void 0,progress:h?ee(x):null,testId:`model-manager-install-${d.modelType}`,title:`${p} | ${R}`,tone:C,children:T})]})})}function Ie({opener:e,onClose:o}){let{setAlertOpener:d}=ie(),j=P(e=>e.sid),k=oe(e=>e.hfCache),$=oe(e=>e.localModels),_=oe(e=>e.modelCacheDiagnostics),S=oe(e=>e.runtimeStatus),I=oe(e=>e.nodesRegistry),D=oe(e=>e.studioModelCapabilities),E=oe(e=>e.studioModelCapabilitiesAuthoritative),U=oe(e=>e.refreshModelIndexes),W=oe(e=>e.fetchRegistry),Q=oe(e=>e.installHfModel),ee=oe(e=>e.hfDownloadProgress),te=oe(e=>e.reconcileHfDownloadProgress),be=oe(e=>e.fetchCustomModules),ve=y(e=>e.nodes),ye=y(e=>e.setNodeUiState),_e=T(e=>e.form),Ie=T(e=>e.activeTemplateId),De=T(e=>e.graphBinding),Fe=T(e=>e.sourceOutputId),Me=T(e=>e.autoResourcePlans),ze=T(e=>e.setAutoResourcePlans),[Ee,Ae]=(0,pe.useState)(!1),Le=(0,pe.useRef)(0),[Pe,Oe]=(0,pe.useState)([]),[qe,Be]=(0,pe.useState)([]),[Ve,Ue]=(0,pe.useState)(""),[We,Ke]=(0,pe.useState)("all"),Je=(0,pe.useRef)(null),Ge=e=>{Ke(e),Je.current?.closest("[data-dialog-scroll-body]")?.scrollTo(0,0)},[Ye,Qe]=(0,pe.useState)(!1),[Xe,Ze]=(0,pe.useState)(null),[ea,aa]=(0,pe.useState)(""),[ta,sa]=(0,pe.useState)(!1),[la,na]=(0,pe.useState)(null),ia=ce(),oa=e?.focus,ra=Object.values(ee).filter(K).length,da=Object.entries(ee).filter(([e,a])=>(K(a)||le(a)||G(a))&&e.toLowerCase().includes(Ve.trim().toLowerCase())),ca=ve.filter(e=>{if("group"===e.data.type||"loop"===e.data.type)return!1;let a=`${e.data.module}.${e.data.action}`;return!I[a]}),ma=(0,pe.useMemo)(()=>function(e){let a=new Set;return e.filter(({item:e,source:t})=>{let s=`${t}:${Ne(e).toLowerCase()}`;return!a.has(s)&&(a.add(s),!0)})}([...Pe.map(e=>({source:"HF",item:e})),...$.map(e=>({source:"Local",item:e}))].filter(({item:e})=>{let a=Ve.trim().toLowerCase();return!a||Ne(e).toLowerCase().includes(a)})),[Ve,Pe,$]),ua=(0,pe.useMemo)(()=>$e(ma,({item:e})=>function(e){let a=Ne(e).toLowerCase();return a.includes("text_encoder")||a.includes("text encoder")||a.includes("vae")||a.includes("tokenizer")||a.includes("transformer")||a.includes("diffusion_model")||a.includes("clip")?"Components":a.includes("wan")||a.includes("video")?"Video":a.includes("ace")||a.includes("audio")?"Audio":a.includes("control")||a.includes("canny")||a.includes("depth")?"Control":a.includes("lora")||a.includes("adapter")?"Adapters":a.includes("edit")||a.includes("inpaint")||a.includes("fill")||a.includes("kontext")||a.includes("redux")?"Edit":a.includes("image")||a.includes("flux")||a.includes("z-image")||a.includes("qwen")?"Image":"Other"}(e)),[ma]),fa=(0,pe.useMemo)(()=>ua,[!0,ua]),pa=(0,pe.useMemo)(()=>se({currentModelType:oa?.modelType??_e.modelType,includeWorkflowOnly:!0}).flatMap(e=>{if(!E)return[e];let a=D.find(a=>a.modelType===e.modelType);return a?C({...e,defaultRepo:a.defaultRepo??e.defaultRepo,artifactLabel:a.artifactLabel??e.artifactLabel,executionStatus:a.executionStatus??e.executionStatus,revisionCandidates:a.revisionCandidates??e.revisionCandidates,downloadFiles:a.downloadFiles??e.downloadFiles,artifactSelections:a.artifactSelections??e.artifactSelections,optionalRuntimeRequirement:a.optionalRuntimeRequirement??e.optionalRuntimeRequirement}):[e]}).sort((e,a)=>{if(oa?.modelType===e.modelType)return-1;if(oa?.modelType===a.modelType)return 1;if(oa?.repo===e.defaultRepo)return-1;if(oa?.repo===a.defaultRepo)return 1;let t=String(e.label??e.modelType??e.defaultRepo??""),s=String(a.label??a.modelType??a.defaultRepo??"");return t.localeCompare(s)}),[!0,oa?.modelType,oa?.repo,_e.modelType,D,E]),xa=(0,pe.useMemo)(()=>{let e=Ve.trim().toLowerCase();return pa.filter(a=>`${a.label} ${a.defaultRepo} ${a.family} ${a.surfaceCategory??""}`.toLowerCase().includes(e))},[pa,Ve]),ha=(0,pe.useMemo)(()=>pa.map(e=>L(x(e),e.modelType)),[pa]),ga=(0,pe.useMemo)(()=>ha.map(w),[ha]),ba=(0,pe.useMemo)(()=>$e(xa,e=>function(e){return"Audio"===e?"Audio":"Video"===e?"Video":"Control"===e?"Control":"Image Edit"===e?"Edit":"Utility"===e?"Adapters":"Image"===e?"Image":"Other"}(e.surfaceCategory)),[xa]);(0,pe.useEffect)(()=>{if(!oa)return;let e=window.setTimeout(()=>{document.querySelector('[data-model-manager-focused="true"]')?.scrollIntoView({behavior:"smooth",block:"center"})},80);return()=>window.clearTimeout(e)},[oa,xa.length]);let ja=oa?.label??xa.find(e=>e.modelType===oa?.modelType||e.defaultRepo===oa?.repo)?.label??oa?.repo,va=w(_e),ya=!!(oa||Ie||De||Fe),wa=(0,pe.useMemo)(()=>ya?b({autoResourcePlan:Me[va],form:_e,hfCache:k,includePipeline:!1,localModels:$,modelCacheDiagnostics:_}):[],[Me,k,ya,$,_,_e,va]),Na=(0,pe.useCallback)(()=>{Le.current+=1,Ae(!0)},[]),Ca=(0,pe.useCallback)(()=>{Le.current=Math.max(0,Le.current-1),0===Le.current&&Ae(!1)},[]),ka=(0,pe.useCallback)(async()=>{let e=xe.begin("fullCache");Na();try{let a=await h(`${Z.serverAddress}/hf_cache`,{signal:e.signal,timeoutMs:12e4,parse:je});e.isLatest()&&Oe(a)}catch(a){e.isLatest()&&console.error("Error fetching Hugging Face models:",a)}finally{e.finish(),Ca()}},[Na,Ca]),$a=(0,pe.useCallback)(async()=>{let e=await A(ha,ga),a={};e.forEach((e,t)=>{let s=e.planKey??ga[t];s&&(a[s]=e)}),ze(a)},[ze,ha,ga]),_a=e=>{let a="string"==typeof e.workflowId?` (${e.workflowId})`:"";switch(e.code){case"graph_execution_active":return"a graph is running";case"graph_execution_queued":return"a graph is queued";case"model_download_active":return"a model download is active";case"template_gallery_install_active":return"the Template Gallery is installing";case"canonical_dependency_open":return`template evidence is not turnover-complete${a}`;case"saved_workflow_dependency":return`a saved workflow still uses the model${a}`;case"recent_incomplete_download":return"an incomplete file is newer than one hour";default:return e.code.split("_").join(" ")}},Sa=async(e,a)=>{Na();try{let t=await z(e),s=!1;if(!t.canDelete){let a=new Set(["canonical_dependency_open","saved_workflow_dependency"]);if(!(t.blockers.length>0&&t.blockers.every(e=>a.has(e.code)))){let e=t.blockers.slice(0,4).map(_a).join("; ");return void H(`Deletion blocked: ${e||"the revision is not turnover-safe"}.`,{variant:"error",autoHideDuration:Math.max(7e3,70*e.length)})}if(t=await z(e,!0),s=!0,!t.canDelete){let e=t.blockers.slice(0,4).map(_a).join("; ");return void H(`Local eviction blocked: ${e||"the cache state changed"}.`,{variant:"error",autoHideDuration:Math.max(7e3,70*e.length)})}}let l=t.targets.map(e=>`${e.repoId}@${e.revision}${e.sizeBytes?` (${Se(e.sizeBytes)})`:""}`).join(", "),n=t.canonicalDependencies.length,i=t.savedWorkflowDependencies.length;d({title:s?"Free local model storage?":"Confirm safe model deletion",message:s?`Evict the local copy of ${a}? Exact cache target: ${l}. ${n} canonical definition${1===n?"":"s"} and ${i} saved workflow${1===i?"":"s"} will be kept, but they must download this exact model revision before they can run again.`:`Delete ${a}? Exact cache target: ${l}. ${n} canonical workflow ${1===n?"dependency":"dependencies"} verified turnover-complete. This action cannot be undone without downloading the model again.`,confirmText:s?"Evict local copy":"Delete exact revision",cancelText:"Cancel",onConfirm:()=>{d(null),(async(e,a,t=!1)=>{Na();try{await V(e,a,t),await ka()}catch(e){console.error("Error deleting Hugging Face model:",e);let a=R(e,"Error deleting Hugging Face model.");H(a,{variant:"error",autoHideDuration:80*a.length})}finally{Ca()}})(e,t.planHash,s)},onCancel:()=>d(null)})}catch(e){let a=R(e,"Could not inspect model dependencies before deletion.");H(a,{variant:"error",autoHideDuration:80*a.length})}finally{Ca()}},Ta=async(e,a=!1)=>{let t="string"==typeof e?{repo:e,label:e,repair:a}:e;ia.request("install",X(t.repo,t.revision),()=>(async(e,a=!1)=>{let t="string"==typeof e?{repo:e,label:e,repair:a}:e;try{await Q(t.repo,j,{repair:t.repair,revision:t.revision,files:t.files}),await Promise.all([ka(),U(!0)]),await $a()}catch(e){console.error(e)}})(t,t.repair))},Ra=()=>{o(),Be([]),Ue(""),Ke("all"),Qe(!1),aa(""),na(null),Oe([])};return(0,pe.useEffect)(()=>{ka(),$a(),be()},[!0,be,ka,$a]),(0,pe.useEffect)(()=>{if(!e||0===ra)return;let a=!1,t=async()=>{try{await te()}catch(e){}};t();let s=window.setInterval(()=>{t()},2e3);return()=>{a=!0,window.clearInterval(s)}},[ra,e,te]),(0,ue.jsxs)(ue.Fragment,{children:[(0,ue.jsxs)(q,{open:!!e,onClose:Ra,title:(0,ue.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,ue.jsx)(r,{size:17,className:"shrink-0 text-hf-yellow"}),(0,ue.jsx)("span",{className:"truncate",children:"Models"})]}),description:"Manage local artifacts and install models from Hugging Face Hub.",panelClassName:"max-w-4xl",bodyClassName:"!p-0",testId:"model-manager-dialog",toolbar:(0,ue.jsxs)("div",{className:"grid gap-3 p-3","data-testid":"model-manager-toolbar",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(B,{"aria-label":"Filter models and artifacts",className:"min-w-0 flex-1 basis-56",controlSize:"normal",placeholder:"Search by model, repository or family",value:Ve,onChange:e=>Ue(e.target.value),onClear:()=>Ue("")}),(0,ue.jsx)(Y,{icon:(0,ue.jsx)(n,{size:14}),"aria-expanded":Ye,"aria-controls":"model-manager-token-editor",onClick:()=>{Qe(e=>!e),aa(""),na(null)},children:S?.config?.hf_token_configured?"HF token ready":"Add HF token"}),(0,ue.jsx)(Y,{loading:Ee,icon:(0,ue.jsx)(u,{size:14}),onClick:()=>{(async(e=!0)=>{Na();try{await Promise.all([ka(),U(e)]),await $a(),await be(),H("Models refreshed",{variant:"success",autoHideDuration:1800})}catch(e){H(R(e,"Could not refresh model health."),{variant:"error",autoHideDuration:6e3})}finally{Ca()}})(!0)},children:"Refresh"})]}),(0,ue.jsx)(M,{"aria-label":"Model inventory sections",size:"dense",className:"flex-wrap",value:We,onValueChange:Ge,options:he.map(e=>({...e,label:"downloads"===e.value&&ra>0?`Downloads (${ra})`:e.label,id:`model-inventory-tab-${e.value}`,controls:`model-inventory-panel-${e.value}`}))})]}),footer:(0,ue.jsxs)(ue.Fragment,{children:[(0,ue.jsx)("span",{className:"mr-auto flex items-center text-xs text-modiff-subtle-text",role:"status","aria-live":"polite",children:Ee?"Refreshing model inventory…":`${ma.length} installed · ${xa.length} supported${Ve?" matches":""}`}),(0,ue.jsx)(Y,{"data-testid":"model-manager-close",onClick:Ra,children:"Close"})]}),children:[Ye?(0,ue.jsxs)("div",{id:"model-manager-token-editor",className:"m-3 grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,ue.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Hugging Face access"}),(0,ue.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["Accept the"," ",(0,ue.jsx)("a",{className:"text-hf-yellow underline underline-offset-2",href:Xe?`https://huggingface.co/${Xe}`:"https://huggingface.co/models",target:"_blank",rel:"noreferrer",children:"repository terms"}),", create a"," ",(0,ue.jsx)("a",{className:"text-hf-yellow underline underline-offset-2",href:"https://huggingface.co/settings/tokens",target:"_blank",rel:"noreferrer",children:"read token"}),", then paste it below. The token is validated and stored on the backend; it is never returned to the browser."]}),(0,ue.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ue.jsx)(O,{"aria-label":"Hugging Face access token",autoFocus:!0,autoComplete:"off",value:ea,onChange:e=>aa(e.target.value),placeholder:"hf_...",disabled:ta,className:"min-w-0 flex-1 basis-56"}),(0,ue.jsx)(Y,{tone:"primary",disabled:ta||!ea.trim(),loading:ta,icon:(0,ue.jsx)(n,{size:14}),onClick:()=>{(async()=>{let e=ea.trim();if(e){sa(!0),na(null);try{await h(`${Z.serverAddress}/hf_token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e}),timeoutMs:3e4}),aa(""),Qe(!1),await U(!0),H("Hugging Face token saved. Retry the model download.",{variant:"success",autoHideDuration:3500})}catch(e){na(R(e,"Could not validate the Hugging Face token."))}finally{sa(!1)}}else na("Paste a Hugging Face read token first.")})()},children:"Save token"}),(0,ue.jsx)(Y,{disabled:ta,onClick:()=>{Qe(!1),aa(""),na(null)},children:"Cancel"})]}),la?(0,ue.jsx)(fe,{tone:"warning",children:la}):null]}):null,he.filter(e=>e.value!==We).map(e=>(0,ue.jsx)("div",{id:`model-inventory-panel-${e.value}`,role:"tabpanel","aria-labelledby":`model-inventory-tab-${e.value}`,hidden:!0},e.value)),(0,ue.jsxs)("div",{ref:Je,className:"p-3",id:`model-inventory-panel-${We}`,role:"tabpanel","aria-labelledby":`model-inventory-tab-${We}`,children:[ja?(0,ue.jsxs)("div",{className:"mb-3 flex flex-wrap items-center gap-2 rounded-modiff-compact border border-hf-yellow/70 bg-hf-yellow/10 p-2","data-testid":"model-manager-focus",children:[(0,ue.jsx)(we,{tone:"warning",children:"Focused"}),(0,ue.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:ja})]}):null,("all"===We||"downloads"===We)&&da.length>0?(0,ue.jsxs)("section",{className:"mb-3 grid gap-2","data-testid":"model-manager-downloads",children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2 text-xs font-semibold uppercase text-modiff-subtle-text",children:[(0,ue.jsx)("span",{children:"Downloads"}),(0,ue.jsxs)(we,{tone:ra>0?"warning":"default",children:[ra," active"]})]}),da.map(([e,a])=>(0,ue.jsx)(F,{repoId:e,progress:a,compact:!1,testId:`model-manager-download-${e}`},e))]}):null,"downloads"===We&&0===da.length?(0,ue.jsxs)("div",{className:"grid justify-items-start gap-2 p-3 text-sm text-modiff-subtle-text",children:[(0,ue.jsx)(f,{size:22,"aria-hidden":"true"}),(0,ue.jsx)("p",{children:Ve?"No downloads match this search.":"No downloads to show. Choose a model in Supported to install it."}),Ve?(0,ue.jsx)(Y,{onClick:()=>Ue(""),children:"Clear search"}):(0,ue.jsx)(Y,{onClick:()=>Ge("supported"),children:"Browse supported models"})]}):null,(0,ue.jsxs)("div",{className:"grid gap-4",children:["all"===We&&ya&&wa.length>0?(0,ue.jsx)(Re,{count:wa.length,testId:"model-manager-requirements",title:"Current workflow",children:(0,ue.jsx)("div",{className:"grid gap-1",children:wa.map(e=>(0,ue.jsx)(de,{activeInstallCount:ra,actionTestId:`model-manager-install-requirement-${e.id}`,compact:!1,installProgress:ee,onInstall:e=>Ta(e),onUseLocal:()=>Ue(e.repo.split("/").pop()??e.repo),requirement:e,testId:`model-manager-requirement-${e.id}`},e.id))})}):null,"all"===We||"installed"===We?(0,ue.jsx)(Re,{count:ma.length,testId:"model-manager-installed",title:"Installed",children:0===fa.length?(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:[Ve?"No installed models match this search.":Ee?"Reading the model inventory…":"No visible model artifacts indexed yet.",Ve?(0,ue.jsx)(Y,{className:"mt-2",onClick:()=>Ue(""),children:"Clear search"}):null]}):fa.map(([e,a])=>(0,ue.jsxs)("div",{className:"grid gap-1",children:[(0,ue.jsx)("div",{className:"px-1 text-xs font-semibold text-modiff-subtle-text",children:e}),a.map(({item:e,source:a})=>(0,ue.jsxs)("article",{className:"flex min-h-10 items-center justify-between gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",title:Ne(e),children:[(0,ue.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,ue.jsx)(s,{size:15,className:"shrink-0 text-hf-yellow"}),(0,ue.jsx)("span",{className:"min-w-0 truncate text-sm font-semibold text-modiff-text",children:Ce(e)})]}),(0,ue.jsxs)("div",{className:"flex flex-none items-center gap-1",children:[ke(e)?(0,ue.jsx)(we,{tone:"default",title:Se(e.size),children:Se(e.size)}):null,(0,ue.jsx)(we,{tone:"success",children:a})]})]},`${a}-${Ne(e)}`))]},e))}):null,"all"===We||"supported"===We?(0,ue.jsx)(Re,{count:xa.length,testId:"model-manager-supported",title:"Supported",children:0===ba.length?(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:["No supported models match the current filter.",Ve?(0,ue.jsx)(Y,{className:"mt-2",onClick:()=>Ue(""),children:"Clear search"}):null]}):ba.map(([e,a])=>(0,ue.jsxs)("div",{className:"grid gap-1",children:[(0,ue.jsx)("div",{className:"px-1 text-xs font-semibold text-modiff-subtle-text",children:e}),a.map(e=>{let a=L(x(e),e.modelType),t=w(a),s=Me[t],l=re(s);return(0,ue.jsx)(He,{activeInstallCount:ra,autoPlan:s,expertMode:!0,form:a,focused:oa?.modelType===e.modelType||oa?.repo===e.defaultRepo||oa?.repo===l?.repo,installProgress:ee,hfTokenConfigured:!!S?.config?.hf_token_configured,onConfigureHfToken:e=>{Ze(e),Qe(!0)},onInstall:Ta,profile:e,status:N(e,k,$,_)},`${e.modelType}:${e.defaultRepo}`)})]},e))}):null,"all"===We?(0,ue.jsxs)(J,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-panel p-3","data-testid":"model-manager-diagnostics",label:(0,ue.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,ue.jsxs)("span",{className:"flex items-center gap-2",children:[(0,ue.jsx)(l,{size:15,className:"text-hf-yellow"}),"Diagnostics"]}),(0,ue.jsx)(we,{tone:"default",children:"Developer"})]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-4",children:[(0,ue.jsx)("section",{className:"grid gap-2",children:(0,ue.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,ue.jsx)(Y,{className:"h-8 px-2 text-xs",icon:(0,ue.jsx)(u,{size:14}),onClick:()=>{W()},children:"Update registry"}),(0,ue.jsx)(Y,{className:"h-8 px-2 text-xs",icon:(0,ue.jsx)(m,{size:14}),onClick:()=>{let e={schemaVersion:1,capturedAt:(new Date).toISOString(),runtimeStatus:S,modelCacheDiagnostics:_,hfCache:k,localModels:$,workflow:{nodeCount:ve.length,missingNodes:ca.map(e=>({id:e.id,label:e.data.label,module:e.data.module,action:e.data.action,key:`${e.data.module}.${e.data.action}`,disabled:!!e.data.uiState?.disabled}))}};navigator.clipboard.writeText(JSON.stringify(e,null,2)),H("Environment snapshot copied",{variant:"success",autoHideDuration:1800})},children:"Copy snapshot"})]})}),_?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Scanned folders"}),_.locations.map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.exists?!1===e.runnable?"warning":"success":"error",children:e.exists?!1===e.runnable?"Not runnable":"Indexed":"Missing"}),(0,ue.jsxs)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:[e.label,": ",e.path||"default"]})]}),(0,ue.jsxs)(fe,{tone:!1===e.runnable?"warning":e.exists?"muted":"error",children:[e.repo_count??e.file_count??0," item(s),"," ",e.compatible_hf_repo_count??0," compatible HF repo(s),"," ",e.external_package_count??0," external package(s)",e.reason?` | ${e.reason}`:""]})]},`${e.label}-${e.path}`))]}):null,(_?.external_model_packages?.length??0)>0?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"External packages"}),_?.external_model_packages?.slice(0,8).map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.runnable?"success":"warning",children:e.runnable?"Compatible":"Needs link"}),(0,ue.jsx)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:e.label})]}),(0,ue.jsxs)(fe,{tone:e.runnable?"success":"warning",children:[e.format," | ",Se(e.model_file_bytes??0)," | ",e.path," | ",e.reason]})]},`${e.source}-${e.path}`))]}):null,(_?.hf_compatible_external_repos?.length??0)>0?(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"HF-compatible external repos"}),_?.hf_compatible_external_repos?.slice(0,8).map(e=>{let a=v(e.repo_id,k,$,_);return(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:a.runnable?"success":"warning",children:a.runnable?"Runnable":"Link needed"}),(0,ue.jsx)("span",{className:"min-w-0 break-all text-xs font-semibold text-modiff-subtle-text",children:e.repo_id})]}),(0,ue.jsxs)(fe,{tone:a.runnable?"success":"warning",children:[e.path," | ",e.reason]})]},`${e.source}-${e.path}`)})]}):null,(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Workflow node definitions"}),0===ca.length?(0,ue.jsx)(fe,{tone:"success",children:"Every current graph node has a matching backend registry definition."}):ca.slice(0,8).map(e=>(0,ue.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-red/70 bg-modiff-red/10 p-2",children:[(0,ue.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,ue.jsx)(we,{tone:e.data.uiState?.disabled?"warning":"error",children:e.data.uiState?.disabled?"Disabled":"Missing"}),(0,ue.jsx)("span",{className:"min-w-0 flex-1 break-all text-xs font-semibold text-modiff-subtle-text",children:e.data.label||e.id})]}),(0,ue.jsxs)(fe,{tone:e.data.uiState?.disabled?"warning":"error",children:[e.data.module,".",e.data.action]}),(0,ue.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[(0,ue.jsx)(Y,{tone:"secondary",icon:(0,ue.jsx)(i,{size:14}),onClick:()=>((e,a)=>{ye(e,{disabled:a,validationSeverity:a?"warning":void 0,validationMessage:a?"Disabled nodes are skipped during run export.":void 0}),H(a?"Node disabled for run export":"Node enabled for run export",{variant:"success",autoHideDuration:1800})})(e.id,!e.data.uiState?.disabled),children:e.data.uiState?.disabled?"Enable":"Disable"}),(0,ue.jsx)(Y,{tone:"secondary",icon:(0,ue.jsx)(m,{size:14}),onClick:()=>((e,a)=>{navigator.clipboard.writeText(`${e}\n${a}`),H("Missing node key copied",{variant:"success",autoHideDuration:1600})})(e.id,`${e.data.module}.${e.data.action}`),children:"Copy key"})]})]},e.id))]}),(0,ue.jsx)(pe.Suspense,{fallback:null,children:(0,ue.jsx)(ge,{})}),(0,ue.jsxs)("section",{className:"grid gap-1",children:[(0,ue.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,ue.jsx)("h3",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:"Raw Hugging Face cache"}),(0,ue.jsx)(Y,{tone:"secondary",size:"compact",icon:Ee?(0,ue.jsx)(t,{size:13,className:"animate-spin"}):(0,ue.jsx)(p,{size:13}),disabled:Ee,onClick:()=>{(async()=>{Na();try{let e=await g();if(!e.canCleanup){let a=e.blockers.slice(0,4).map(_a).join("; ");return void H(0!==e.eligibleFileCount||a?`Cleanup blocked: ${a||"no stale files are eligible"}.`:"No stale incomplete Hugging Face files are eligible for cleanup.",{variant:"default",autoHideDuration:6e3})}d({title:"Clean stale partial downloads?",message:`Remove ${e.eligibleFileCount} inactive .incomplete file(s) and reclaim ${Se(e.eligibleBytes)}? Only regular blob files older than one hour are included; installed snapshots and model revisions are not removed.`,confirmText:"Clean exact files",cancelText:"Cancel",onConfirm:()=>{d(null),(async e=>{Na();try{let a=await ne(e),t="number"==typeof a.removedFileCount?a.removedFileCount:0,s="number"==typeof a.removedBytes?a.removedBytes:0;await ka(),H(`Removed ${t} stale partial file(s), reclaiming ${Se(s)}.`,{variant:"success",autoHideDuration:5e3})}catch(e){H(R(e,"Could not clean stale Hugging Face downloads."),{variant:"error",autoHideDuration:7e3})}finally{Ca()}})(e.planHash)},onCancel:()=>d(null)})}catch(e){H(R(e,"Could not inspect stale Hugging Face downloads."),{variant:"error",autoHideDuration:7e3})}finally{Ca()}})()},children:"Clean partial files"})]}),(0,ue.jsx)(fe,{tone:"muted",children:"Removes only hash-planned inactive .incomplete blobs older than one hour; installed revisions remain."}),0!==Pe.length||Ee?Pe.map(e=>{if(!ke(e)){let a=Ne(e);return(0,ue.jsx)("article",{className:"border-b border-modiff-border py-3 last:border-b-0",children:(0,ue.jsx)("div",{className:"flex items-start gap-3",children:(0,ue.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,ue.jsx)("h4",{className:"truncate text-sm font-semibold text-modiff-text",children:Te(a)}),(0,ue.jsx)("div",{className:"mt-1 flex flex-wrap gap-1",children:(0,ue.jsx)(we,{tone:"default",children:"Indexed"})})]})})},a)}let t=qe.includes(e.id);return(0,ue.jsxs)("article",{className:"border-b border-modiff-border py-3 last:border-b-0",children:[(0,ue.jsxs)("div",{className:"flex items-start gap-3",children:[(0,ue.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,ue.jsx)("h4",{className:"truncate text-sm font-semibold text-modiff-text",children:Te(e.id)}),(0,ue.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,ue.jsx)(we,{tone:"default",children:Se(e.size)}),(0,ue.jsx)(we,{tone:"default",children:new Date(1e3*e.last_accessed).toLocaleDateString()}),e.class_names.slice(0,5).map(e=>(0,ue.jsx)(we,{tone:"default",children:e},e))]}),(0,ue.jsx)(Y,{tone:"ghost",size:"compact",className:"mt-2 px-2 text-xs",onClick:()=>(e=>{Be(a=>a.includes(e)?a.filter(a=>a!==e):[...a,e])})(e.id),icon:t?(0,ue.jsx)(a,{size:14}):(0,ue.jsx)(c,{size:14}),children:"Revisions"})]}),(0,ue.jsx)(ae,{label:`Delete ${e.id}`,disabled:Ee,className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{Sa(e.revisions.map(e=>e.hash).join(","),`${e.id} model`)},children:(0,ue.jsx)(p,{size:15})})]}),t?(0,ue.jsx)("div",{className:"mt-2 space-y-1 pl-4",children:e.revisions.map(a=>(0,ue.jsxs)("div",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[(0,ue.jsxs)("div",{className:"min-w-0 flex-1 break-words",children:[(0,ue.jsx)("strong",{className:"text-modiff-text",children:a.hash.slice(0,8)})," |"," ",new Date(1e3*a.last_modified).toLocaleString()," |"," ",Se(a.size)]}),(0,ue.jsx)(ae,{label:`Delete revision ${a.hash.slice(0,8)}`,disabled:Ee,size:"compact",className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{Sa(a.hash,`${a.hash.slice(0,8)} revision of ${e.id}`)},children:(0,ue.jsx)(p,{size:13})})]},a.hash))}):null]},e.id)}):(0,ue.jsx)(fe,{tone:"muted",children:Ve?"No cache entries match the current filter.":"The local cache is empty."})]})]}):null]})]})]}),(0,ue.jsx)(me,{open:!!ia.pending,policies:ia.pending?.policies??[],action:ia.pending?.action??"install",onCancel:ia.cancel,onConfirm:ia.confirm})]})}export{Ie as default}; \ No newline at end of file diff --git a/web/assets/NodeDiscoveryFilters.js b/web/assets/NodeDiscoveryFilters.js index bfaf62a..edc8f29 100644 --- a/web/assets/NodeDiscoveryFilters.js +++ b/web/assets/NodeDiscoveryFilters.js @@ -1 +1 @@ -import{cr as e}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Q as a,cn as l}from"./studio-templates.js?v=cc046c26d6fe7aa4";var o=e();function n(){let e=a(e=>e.view),n=a(e=>e.setView),r="advanced"===e||"all"===e,s="experimental"===e||"all"===e;return(0,o.jsxs)("div",{className:"flex flex-wrap gap-x-4 gap-y-1 px-3 pb-2",role:"group","aria-label":"Node discovery options",children:[(0,o.jsx)(l,{label:"Show implementation nodes",checked:r,onCheckedChange:e=>n(e?s?"all":"advanced":s?"experimental":"common")}),(0,o.jsx)(l,{label:"Show experimental nodes",checked:s,onCheckedChange:e=>n(e?r?"all":"experimental":r?"advanced":"common")})]})}export{n as t}; \ No newline at end of file +import{cr as e}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Q as a,ln as l}from"./studio-templates.js?v=ca6b74e6a02eedb3";var o=e();function n(){let e=a(e=>e.view),n=a(e=>e.setView),r="advanced"===e||"all"===e,s="experimental"===e||"all"===e;return(0,o.jsxs)("div",{className:"flex flex-wrap gap-x-4 gap-y-1 px-3 pb-2",role:"group","aria-label":"Node discovery options",children:[(0,o.jsx)(l,{label:"Show implementation nodes",checked:r,onCheckedChange:e=>n(e?s?"all":"advanced":s?"experimental":"common")}),(0,o.jsx)(l,{label:"Show experimental nodes",checked:s,onCheckedChange:e=>n(e?r?"all":"experimental":r?"advanced":"common")})]})}export{n as t}; \ No newline at end of file diff --git a/web/assets/NodeInspectionDetails.js b/web/assets/NodeInspectionDetails.js index c25451d..cba0c8a 100644 --- a/web/assets/NodeInspectionDetails.js +++ b/web/assets/NodeInspectionDetails.js @@ -1 +1 @@ -import{cr as e}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$s as t,Cs as s,Fo as i,Io as a,Jo as n,Si as r,Ts as o,Vr as d,Xo as l}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as c}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{n as p}from"./presetDiff.js?v=cc046c26d6fe7aa4";var u=e();function h({node:e,section:h}){let x=d(e=>e.edges),m=d(t=>t.nodes.find(t=>t.id===e.data.blockProjectionOwnerId)),f=r(t=>t.customModules.find(t=>t.moduleKey===e.data.module)),j=n(e),g=e.data.blockInstanceV2,b=g?.definitionSnapshot.source,v=`${e.data.module}.${e.data.action}`,N=e.data.modularDiffusersCatalogNode??m?.data.blockInstanceV2?.effectiveGraph.nodes.find(t=>t.nodeId===e.data.blockProjectionNodeId)?.modularDiffusers;if("interface"===h){let t=g?l(g):{inputs:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"!==e.display&&("input"===e.display||e.isInput))),outputs:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"===e.display))};if(o(g)){let s=i(e);t.inputs=Object.fromEntries(Object.entries(s).filter(([,e])=>"output"!==e.display)),t.outputs=Object.fromEntries(Object.entries(s).filter(([,e])=>"output"===e.display))}return(0,u.jsxs)("div",{className:"grid gap-3 text-xs text-modiff-text",children:[g?(0,u.jsx)("p",{children:o(g)?"Sockets of this node. Its execution stages remain separate.":"Public sockets of this Block instance. Its internal graph remains unchanged."}):null,["inputs","outputs"].map(s=>(0,u.jsxs)("div",{className:"grid gap-2",children:[(0,u.jsx)("h3",{className:"font-semibold",children:"inputs"===s?"Inputs":"Outputs"}),Object.entries(t[s]).map(([t,i])=>{let n=x.filter(i=>"inputs"===s?i.target===e.id&&i.targetHandle===t:i.source===e.id&&i.sourceHandle===t);return(0,u.jsxs)("div",{className:"break-words",children:[(0,u.jsxs)("p",{children:[i.label||t," · ",Array.isArray(i.type)?i.type.join(" | "):i.type||"Any",i.required?" · Required":""]}),(0,u.jsxs)("p",{className:"text-modiff-subtle-text",children:["Socket: ",t]}),a(t)?(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Optional adaptation socket — connecting prepares the supported stage; unused sockets do not execute."}):null,n.length?n.map(e=>(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"inputs"===s?`From ${e.source}.${e.sourceHandle}`:`To ${e.target}.${e.targetHandle}`},e.id)):(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Not connected"})]},t)}),Object.keys(t[s]).length?null:(0,u.jsxs)("p",{children:["No declared ",s,"."]})]},s))]})}return"docs"===h?(0,u.jsxs)("div",{className:"grid gap-3 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{className:"whitespace-pre-wrap",children:g?.definitionSnapshot.description||e.data.description||"No description supplied by this node."}),g?(0,u.jsx)("p",{children:o(g)?`Use Separate ${s(g)?"guidance":"encoding"} stages to edit individual stages on the canvas.`:"Use Expand Block on the canvas to edit this composition. This does not edit the Python implementation."}):null,Object.entries(e.data.params).filter(([,e])=>e.description&&!e.hidden).map(([e,t])=>(0,u.jsxs)("div",{children:[(0,u.jsx)("h3",{className:"font-semibold",children:t.label||e}),(0,u.jsx)("p",{className:"whitespace-pre-wrap text-modiff-subtle-text",children:t.description})]},e)),g?.effectiveInterface.controls.filter(e=>e.help).map(e=>(0,u.jsxs)("div",{children:[(0,u.jsx)("h3",{className:"font-semibold",children:e.label}),(0,u.jsx)("p",{className:"whitespace-pre-wrap text-modiff-subtle-text",children:e.help})]},e.controlId))]}):"run"===h?(0,u.jsxs)("div",{className:"grid gap-2 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{children:e.data.executionStatus?`Status: ${e.data.executionStatus}`:"No execution recorded for this node."}),(0,u.jsx)("p",{children:e.data.isCached?"Cached outputs reported.":"No cached outputs reported."}),(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Reuse on the next run still requires matching execution inputs."}),e.data.activeTaskId?(0,u.jsxs)("p",{children:["Task: ",e.data.activeTaskId]}):null,e.data.executionPhase?(0,u.jsxs)("p",{children:["Phase: ",e.data.executionPhase]}):null,e.data.progressMessage?(0,u.jsx)("p",{children:e.data.progressMessage}):null,e.data.uiState?.validationMessage?(0,u.jsxs)("p",{children:["Validation: ",e.data.uiState.validationMessage]}):null,e.data.uiState?.errorMessage?(0,u.jsxs)("p",{children:["Error: ",e.data.uiState.errorMessage]}):null,(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"These are the node's current diagnostics. Previous runs remain in history."})]}):(0,u.jsxs)("div",{className:"grid gap-3 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{children:v}),(0,u.jsxs)("p",{className:"text-modiff-subtle-text",children:["Canvas node: ",e.id]}),j?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:[j.operation.pipelineClass," · ",j.operation.task]}),(0,u.jsx)("p",{children:j.operation.blockName??("loader"===j.operation.decomposition?"Model loader":"integrated"===j.operation.decomposition?"Model operation":"pipeline"===j.operation.decomposition?"Whole pipeline call":"Execution stage")}),(0,u.jsx)("dl",{className:"grid gap-2",children:Object.entries(j.defaults).map(([s,i])=>{let a=x.find(t=>t.target===e.id&&t.targetHandle===s);return(0,u.jsxs)("div",{children:[(0,u.jsxs)("dt",{children:[s," —"," ",a?`Connected from ${a.source}.${a.sourceHandle}; saved fallback`:t(i,c(e.data.params[s]))?"Selected contract default":"User override"]}),(0,u.jsx)("dd",{className:"text-modiff-subtle-text",children:p(c(e.data.params[s]))})]},s)})}),j.retained.length?(0,u.jsxs)("div",{children:[(0,u.jsx)("p",{children:"Retained settings — excluded from execution:"}),(0,u.jsx)("ul",{className:"list-inside list-disc",children:j.retained.map((e,t)=>(0,u.jsxs)("li",{children:[e.pipeline," / ",e.field,": ",p(e.value),". ",e.reason]},t))})]}):null]}):null,g&&b?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Editable graph composition · ",g.effectiveGraph.nodes.length," internal nodes ·"," ",g.effectiveGraph.edges.length," internal connections"]}),(0,u.jsxs)("p",{children:["Definition: ",g.definitionSnapshot.definitionId]}),(0,u.jsxs)("p",{children:["Revision: ",g.definitionSnapshot.contentHash]}),(0,u.jsxs)("p",{children:["Source: ",b.kind," ",b.library," ",b.pipelineClass]}),b.repository?(0,u.jsxs)("p",{children:["Repository: ",b.repository," · ",b.repositoryRevision??"Revision not supplied"]}):null,b.libraryRevision?(0,u.jsxs)("p",{children:["Library revision: ",b.libraryRevision]}):null,(0,u.jsxs)("p",{children:["Customization: ",g.customization.state.replace(/_/gu," ")]})]}):null,N?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Pinned upstream implementation: ",N.blockClass??N.blocksClass]}),(0,u.jsxs)("p",{children:[N.pipelineClass," · ",N.workflowId]}),(0,u.jsxs)("p",{children:["Library revision: ",N.libraryRevision]}),N.placementPath?.length?(0,u.jsxs)("p",{children:["Placement: ",N.placementPath.join(" / ")]}):null,N.blockContractHash?(0,u.jsxs)("p",{children:["Contract: ",N.blockContractHash]}):null]}):null,f?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Custom Python implementation · ",f.name," · ",f.status]}),(0,u.jsxs)("p",{children:["Source: ",f.path]}),f.revision?(0,u.jsxs)("p",{children:["Revision: ",f.revision]}):null,(0,u.jsxs)("p",{children:["Inspected code: ",f.codeHash??"Not inspected"]}),f.diagnostic?(0,u.jsx)("p",{children:f.diagnostic}):null,(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Manage source and approvals in Custom nodes. Inspection grants no code permission."})]}):null,g||j||f||N?null:(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Registered node implementation. Its controls and sockets come from the backend contract."})]})}export{h as default}; \ No newline at end of file +import{cr as e}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$o as t,Es as s,Hr as i,Lo as a,Os as n,Ro as r,Zo as o,nc as d,wi as l}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as c}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{n as p}from"./presetDiff.js?v=ca6b74e6a02eedb3";var u=e();function h({node:e,section:h}){let x=i(e=>e.edges),m=i(t=>t.nodes.find(t=>t.id===e.data.blockProjectionOwnerId)),f=l(t=>t.customModules.find(t=>t.moduleKey===e.data.module)),j=o(e),g=e.data.blockInstanceV2,b=g?.definitionSnapshot.source,v=`${e.data.module}.${e.data.action}`,N=e.data.modularDiffusersCatalogNode??m?.data.blockInstanceV2?.effectiveGraph.nodes.find(t=>t.nodeId===e.data.blockProjectionNodeId)?.modularDiffusers;if("interface"===h){let s=g?t(g):{inputs:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"!==e.display&&("input"===e.display||e.isInput))),outputs:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"===e.display))};if(n(g)){let t=a(e);s.inputs=Object.fromEntries(Object.entries(t).filter(([,e])=>"output"!==e.display)),s.outputs=Object.fromEntries(Object.entries(t).filter(([,e])=>"output"===e.display))}return(0,u.jsxs)("div",{className:"grid gap-3 text-xs text-modiff-text",children:[g?(0,u.jsx)("p",{children:n(g)?"Sockets of this node. Its execution stages remain separate.":"Public sockets of this Block instance. Its internal graph remains unchanged."}):null,["inputs","outputs"].map(t=>(0,u.jsxs)("div",{className:"grid gap-2",children:[(0,u.jsx)("h3",{className:"font-semibold",children:"inputs"===t?"Inputs":"Outputs"}),Object.entries(s[t]).map(([s,i])=>{let a=x.filter(i=>"inputs"===t?i.target===e.id&&i.targetHandle===s:i.source===e.id&&i.sourceHandle===s);return(0,u.jsxs)("div",{className:"break-words",children:[(0,u.jsxs)("p",{children:[i.label||s," · ",Array.isArray(i.type)?i.type.join(" | "):i.type||"Any",i.required?" · Required":""]}),(0,u.jsxs)("p",{className:"text-modiff-subtle-text",children:["Socket: ",s]}),r(s)?(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Optional adaptation socket — connecting prepares the supported stage; unused sockets do not execute."}):null,a.length?a.map(e=>(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"inputs"===t?`From ${e.source}.${e.sourceHandle}`:`To ${e.target}.${e.targetHandle}`},e.id)):(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Not connected"})]},s)}),Object.keys(s[t]).length?null:(0,u.jsxs)("p",{children:["No declared ",t,"."]})]},t))]})}return"docs"===h?(0,u.jsxs)("div",{className:"grid gap-3 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{className:"whitespace-pre-wrap",children:g?.definitionSnapshot.description||e.data.description||"No description supplied by this node."}),g?(0,u.jsx)("p",{children:n(g)?`Use Separate ${s(g)?"guidance":"encoding"} stages to edit individual stages on the canvas.`:"Use Expand Block on the canvas to edit this composition. This does not edit the Python implementation."}):null,Object.entries(e.data.params).filter(([,e])=>e.description&&!e.hidden).map(([e,t])=>(0,u.jsxs)("div",{children:[(0,u.jsx)("h3",{className:"font-semibold",children:t.label||e}),(0,u.jsx)("p",{className:"whitespace-pre-wrap text-modiff-subtle-text",children:t.description})]},e)),g?.effectiveInterface.controls.filter(e=>e.help).map(e=>(0,u.jsxs)("div",{children:[(0,u.jsx)("h3",{className:"font-semibold",children:e.label}),(0,u.jsx)("p",{className:"whitespace-pre-wrap text-modiff-subtle-text",children:e.help})]},e.controlId))]}):"run"===h?(0,u.jsxs)("div",{className:"grid gap-2 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{children:e.data.executionStatus?`Status: ${e.data.executionStatus}`:"No execution recorded for this node."}),(0,u.jsx)("p",{children:e.data.isCached?"Cached outputs reported.":"No cached outputs reported."}),(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Reuse on the next run still requires matching execution inputs."}),e.data.activeTaskId?(0,u.jsxs)("p",{children:["Task: ",e.data.activeTaskId]}):null,e.data.executionPhase?(0,u.jsxs)("p",{children:["Phase: ",e.data.executionPhase]}):null,e.data.progressMessage?(0,u.jsx)("p",{children:e.data.progressMessage}):null,e.data.uiState?.validationMessage?(0,u.jsxs)("p",{children:["Validation: ",e.data.uiState.validationMessage]}):null,e.data.uiState?.errorMessage?(0,u.jsxs)("p",{children:["Error: ",e.data.uiState.errorMessage]}):null,(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"These are the node's current diagnostics. Previous runs remain in history."})]}):(0,u.jsxs)("div",{className:"grid gap-3 break-words text-xs text-modiff-text",children:[(0,u.jsx)("p",{children:v}),(0,u.jsxs)("p",{className:"text-modiff-subtle-text",children:["Canvas node: ",e.id]}),j?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:[j.operation.pipelineClass," · ",j.operation.task]}),(0,u.jsx)("p",{children:j.operation.blockName??("loader"===j.operation.decomposition?"Model loader":"integrated"===j.operation.decomposition?"Model operation":"pipeline"===j.operation.decomposition?"Whole pipeline call":"Execution stage")}),(0,u.jsx)("dl",{className:"grid gap-2",children:Object.entries(j.defaults).map(([t,s])=>{let i=x.find(s=>s.target===e.id&&s.targetHandle===t);return(0,u.jsxs)("div",{children:[(0,u.jsxs)("dt",{children:[t," —"," ",i?`Connected from ${i.source}.${i.sourceHandle}; saved fallback`:d(s,c(e.data.params[t]))?"Selected contract default":"User override"]}),(0,u.jsx)("dd",{className:"text-modiff-subtle-text",children:p(c(e.data.params[t]))})]},t)})}),j.retained.length?(0,u.jsxs)("div",{children:[(0,u.jsx)("p",{children:"Retained settings — excluded from execution:"}),(0,u.jsx)("ul",{className:"list-inside list-disc",children:j.retained.map((e,t)=>(0,u.jsxs)("li",{children:[e.pipeline," / ",e.field,": ",p(e.value),". ",e.reason]},t))})]}):null]}):null,g&&b?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Editable graph composition · ",g.effectiveGraph.nodes.length," internal nodes ·"," ",g.effectiveGraph.edges.length," internal connections"]}),(0,u.jsxs)("p",{children:["Definition: ",g.definitionSnapshot.definitionId]}),(0,u.jsxs)("p",{children:["Revision: ",g.definitionSnapshot.contentHash]}),(0,u.jsxs)("p",{children:["Source: ",b.kind," ",b.library," ",b.pipelineClass]}),b.repository?(0,u.jsxs)("p",{children:["Repository: ",b.repository," · ",b.repositoryRevision??"Revision not supplied"]}):null,b.libraryRevision?(0,u.jsxs)("p",{children:["Library revision: ",b.libraryRevision]}):null,(0,u.jsxs)("p",{children:["Customization: ",g.customization.state.replace(/_/gu," ")]})]}):null,N?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Pinned upstream implementation: ",N.blockClass??N.blocksClass]}),(0,u.jsxs)("p",{children:[N.pipelineClass," · ",N.workflowId]}),(0,u.jsxs)("p",{children:["Library revision: ",N.libraryRevision]}),N.placementPath?.length?(0,u.jsxs)("p",{children:["Placement: ",N.placementPath.join(" / ")]}):null,N.blockContractHash?(0,u.jsxs)("p",{children:["Contract: ",N.blockContractHash]}):null]}):null,f?(0,u.jsxs)(u.Fragment,{children:[(0,u.jsxs)("p",{children:["Custom Python implementation · ",f.name," · ",f.status]}),(0,u.jsxs)("p",{children:["Source: ",f.path]}),f.revision?(0,u.jsxs)("p",{children:["Revision: ",f.revision]}):null,(0,u.jsxs)("p",{children:["Inspected code: ",f.codeHash??"Not inspected"]}),f.diagnostic?(0,u.jsx)("p",{children:f.diagnostic}):null,(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Manage source and approvals in Custom nodes. Inspection grants no code permission."})]}):null,g||j||f||N?null:(0,u.jsx)("p",{className:"text-modiff-subtle-text",children:"Registered node implementation. Its controls and sockets come from the backend contract."})]})}export{h as default}; \ No newline at end of file diff --git a/web/assets/NodeInspectorDialog.js b/web/assets/NodeInspectorDialog.js index 43cf147..2a1ef8e 100644 --- a/web/assets/NodeInspectorDialog.js +++ b/web/assets/NodeInspectorDialog.js @@ -1 +1 @@ -import{n as o,r as s}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as e,dr as n}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ei as a,Ts as t,Vr as r,in as d,ji as i}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as l}from"./GraphNodeInputs.js?v=cc046c26d6fe7aa4";var c=o({default:()=>m}),p=s(n(),1),f=e();function m({nodeId:o,onClose:s}){let[e]=(0,p.useState)(a),n=r(s=>s.nodes.find(s=>s.id===o)),c=i(o=>o.activeWorkflowTabId),m=i(o=>o.workflowCanvasEpoch),u=!(!n?.selected||c!==e.workflowTabId||m!==e.canvasEpoch);return(0,p.useEffect)(()=>{u||s()},[u,s]),u&&n?(0,f.jsx)(d,{open:!0,title:n.data.blockInstanceV2&&!t(n.data.blockInstanceV2)?"Block inspector":"Node inspector",onClose:s,children:(0,f.jsx)(l,{nodes:[n],selectedNodes:[n],workflowId:c,candidates:[],pinnedInputs:[],pinnedIds:[],onTogglePin:()=>{},controlIdPrefix:"dialog-inspector"})}):null}export{c as n,m as t}; \ No newline at end of file +import{n as o,r as s}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as e,dr as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Hr as a,Ni as t,Oi as r,Os as d,an as i}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as l}from"./GraphNodeInputs.js?v=ca6b74e6a02eedb3";var c=o({default:()=>m}),p=s(n(),1),f=e();function m({nodeId:o,onClose:s}){let[e]=(0,p.useState)(r),n=a(s=>s.nodes.find(s=>s.id===o)),c=t(o=>o.activeWorkflowTabId),m=t(o=>o.workflowCanvasEpoch),u=!(!n?.selected||c!==e.workflowTabId||m!==e.canvasEpoch);return(0,p.useEffect)(()=>{u||s()},[u,s]),u&&n?(0,f.jsx)(i,{open:!0,title:n.data.blockInstanceV2&&!d(n.data.blockInstanceV2)?"Block inspector":"Node inspector",onClose:s,children:(0,f.jsx)(l,{nodes:[n],selectedNodes:[n],workflowId:c,candidates:[],pinnedInputs:[],pinnedIds:[],onTogglePin:()=>{},controlIdPrefix:"dialog-inspector"})}):null}export{c as n,m as t}; \ No newline at end of file diff --git a/web/assets/NodeList.js b/web/assets/NodeList.js index 627fd40..469106c 100644 --- a/web/assets/NodeList.js +++ b/web/assets/NodeList.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Ct as s,Et as t,I as a,It as n,L as r,Mn as i,N as l,Nn as o,Vn as d,Zt as c,cr as u,dr as m,hn as f,j as x,jt as p,kn as h,ot as g,qt as b,z as j}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$ as k,A as w,B as v,Ci as N,Cn as y,D as C,E as I,Eo as $,F as z,Ft as D,I as S,In as B,L as F,M,Mo as T,N as G,O as E,P as _,Pt as H,R as L,Sa as O,Si as A,T as R,Vr as U,Xr as P,Yr as q,Z as W,a as V,bn as Z,ci as K,i as X,in as Y,j as J,ji as Q,k as ee,n as se,ni as te,nt as ae,o as ne,q as re,r as ie,ri as le,rn as oe,si as de,yn as ce,z as ue}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as me}from"./NodeDiscoveryFilters.js?v=cc046c26d6fe7aa4";var fe=e(m(),1),xe=u();function pe({search:e,insert:s,manage:t}){let a=A(e=>e.customModules),n=A(e=>e.nodesRegistry),r=A(e=>e.fetchCustomModules),l=A(e=>e.customModuleError),[o,d]=(0,fe.useState)(!1);(0,fe.useEffect)(()=>{let e=!1,s=async()=>{if(!e&&"hidden"!==document.visibilityState){e=!0;try{await r()}finally{e=!1}}};s();let t=window.setInterval(()=>{s()},15e3);return window.addEventListener("focus",s),()=>{window.clearInterval(t),window.removeEventListener("focus",s)}},[r]);let c=e.trim().toLowerCase(),u=o||!!c,m=Object.entries(n).filter(([e,s])=>e.startsWith("custom.")&&a.some(s=>s.enabled&&e.startsWith(s.moduleKey+"."))&&(!c||`${s.label} ${e}`.toLowerCase().includes(c)));return(0,xe.jsxs)("section",{"data-testid":"node-group-custom-nodes",className:"mb-2 rounded-modiff-compact border border-modiff-border",children:[(0,xe.jsxs)(H,{"aria-expanded":u,open:u,onClick:()=>d(!o),className:"min-h-10 justify-between font-semibold",children:[(0,xe.jsxs)("span",{className:"flex items-center gap-2",children:[(0,xe.jsx)(i,{size:16,className:"text-hf-yellow"}),"Custom nodes"]}),(0,xe.jsxs)("span",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[m.length,(0,xe.jsx)(h,{size:14,className:B(u&&"rotate-180")})]})]}),u?(0,xe.jsxs)(D,{level:1,children:[m.map(([e,t])=>(0,xe.jsx)(H,{draggable:!0,level:1,onClick:()=>s(e),onDragStart:s=>{s.dataTransfer.setData("text/plain",e),s.dataTransfer.effectAllowed="move"},children:(0,xe.jsx)("span",{className:"min-w-0 break-words",children:t.label||t.action})},e)),a.filter(e=>!e.enabled&&(!c||e.name.toLowerCase().includes(c))).map(e=>(0,xe.jsxs)(H,{level:1,onClick:t,title:e.diagnostic??"Load this source in Manage nodes",children:[(0,xe.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name}),(0,xe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:"disabled"!==e.status||e.approvedHash?e.status:"Not loaded"})]},e.name)),a.length?null:(0,xe.jsx)("p",{className:"p-2 text-xs text-modiff-subtle-text",children:"No custom nodes yet. Add a node or drop a Python node onto the canvas."}),l?(0,xe.jsx)("p",{role:"status",className:"p-2 text-xs text-modiff-red",children:l}):null,(0,xe.jsx)(oe,{fullWidth:!0,tone:"ghost",onClick:t,children:"Manage nodes"})]}):null]})}function he({entries:e,search:s,openGroups:t,toggle:a,insert:n}){let r=new Map;for(let s of e){let e=s.groupPath.slice(1).join(" / ")||"Operations";r.set(e,[...r.get(e)??[],s])}return[...r].sort(([e],[s])=>e.localeCompare(s)).map(([e,r])=>{let l=`runtime:${r[0].groupPath[0]}:${e}`,o=!!s.trim()||t.includes(l);return(0,xe.jsxs)("div",{"data-testid":`node-subgroup-${l.replace(/[^a-zA-Z0-9]+/gu,"-")}`,children:[(0,xe.jsxs)(H,{level:1,"aria-expanded":o,open:o,onClick:()=>a(l),className:"min-h-9 justify-between font-medium",children:[(0,xe.jsx)("span",{className:"min-w-0 truncate",children:e}),(0,xe.jsxs)("span",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[r.length,(0,xe.jsx)(h,{size:14,className:B("transition-transform",o&&"rotate-180")})]})]}),o?(0,xe.jsx)(D,{level:2,children:[...r].sort((e,s)=>e.label.localeCompare(s.label)||e.key.localeCompare(s.key)).map(e=>(0,xe.jsxs)(H,{"data-testid":`node-row-${e.key.replace(/[^a-zA-Z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`,level:2,draggable:!0,onClick:()=>n(e.dragKey),onDragStart:s=>{s.dataTransfer.setData("text/plain",e.dragKey),s.dataTransfer.effectAllowed="move"},title:`${e.node.label||e.label} · ${e.key}${e.description?`\n${e.description}`:""}`,className:"cursor-grab hover:bg-modiff-surface-hover",children:["experimental"===e.visibility?(0,xe.jsx)(c,{size:14,className:"shrink-0 text-hf-yellow"}):(0,xe.jsx)(i,{size:14,className:"shrink-0 text-hf-yellow"}),(0,xe.jsx)("span",{className:"min-w-0 flex-1 break-words",children:e.label})]},e.key))}):null]},l)})}var ge=(0,fe.lazy)(()=>N(()=>import(`./CustomExtensionsDialog.js?v=cc046c26d6fe7aa4`),[])),be=(0,fe.lazy)(()=>N(()=>import(`./OperationCatalogPanel.js?v=cc046c26d6fe7aa4`),[]));function je(){let e=A(e=>e.nodesRegistry),s=A(e=>e.operationContracts),t=A(e=>e.pipelineSupport),a=U(e=>e.addNode),n=U(e=>e.viewport),r=U(e=>e.nodes.length),l=de(e=>e.blocks),o=de(e=>e.blockDefinitionsV2),d=de(e=>e.loaded),c=de(e=>e.fetchBlocks),u=de(e=>e.deleteBlock),m=P(e=>e.library),f=q(e=>e.snapshot),x=q(e=>e.loaded),p=q(e=>e.fetchSnapshot),h=Q(e=>e.form),b=Q(e=>e.activeWorkflowTabId),v=O(e=>e.setWorkflowFocusRequest),z=P(e=>e.loaded),D=P(e=>e.error),B=P(e=>e.fetchLibrary),[F,G]=(0,fe.useState)(""),[_,H]=(0,fe.useState)(null),[L,R]=(0,fe.useState)(null),[V,Z]=(0,fe.useState)(!1),[K,ae]=(0,fe.useState)("add"),[ie,ue]=(0,fe.useState)("local"),[he,je]=(0,fe.useState)(()=>new Set),{view:ve,pipeline:Ne,task:ye}=W(),Ce=(0,fe.useMemo)(()=>ne(e,s,t,ve,{pipeline:Ne,task:ye}),[ve,e,s,t,Ne,ye]);(0,fe.useEffect)(()=>{d||c()},[c,d]),(0,fe.useEffect)(()=>{z||B()},[B,z]),(0,fe.useEffect)(()=>{x||p()},[p,x]);let Ie=(0,fe.useMemo)(()=>m?te(m,f):[],[m,f]),$e=(0,fe.useMemo)(()=>le(Ie,F,ve),[Ie,F,ve]),ze=(0,fe.useMemo)(()=>le(Ie,"",ve).reduce((e,s)=>e+s.entries.length,0),[Ie,ve]),De=(0,fe.useMemo)(()=>se(Ce).filter(e=>X(e,ve)).length,[Ce,ve]),Se=(0,fe.useCallback)(e=>{k();let s=M(e,we(ke(n,r),U.getState().nodes,{width:420,height:480}));if(a(s),b){let e=Date.now();v({workflowTabId:b,nodeId:s.id,requestId:e,requestedAt:e})}},[b,a,r,v,n]),Be=(0,fe.useCallback)((s,t)=>{k();let i=re(s,t?{[s]:t}:e,ke(n,r));i?a({...i,selected:!0}):T(`Node ${s} is no longer available. Reload the node list and try again.`,{variant:"error",autoHideDuration:5e3})},[a,r,e,n]),Fe=(0,fe.useCallback)(async s=>{if(!m||!s.insertable||he.has(s.id))return;if("block"===s.kind){try{k(),a(E(s,m,f)?I(s,m,e,ke(n,r),f):C(s,m,e,ke(n,r),f))}catch(e){T($(e,"The Modular Diffusers block could not be added."),{variant:"error",autoHideDuration:7e3})}return}if("cluster"!==s.kind)return;let t=m.definitions.find(e=>e.id===s.id);if(!t)return void T("The exact reviewed Block definition is unavailable. Reload the catalog and try again.",{variant:"error",autoHideDuration:5e3});k();let i=we(ke(n,r),U.getState().nodes,{width:360,height:320});je(e=>new Set(e).add(s.id));let l=ee(s.label,i);try{let{createHuggingFaceClusterForGraph:e}=await N(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=cc046c26d6fe7aa4`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]),s=await e(t,i,h,{insert:!1});if(J(l,s),b){let e=Date.now();v({workflowTabId:b,nodeId:s.id,requestId:e,requestedAt:e})}}catch(e){T($(e,"The registered Block could not be added."),{variant:"error",autoHideDuration:1e4})}finally{w(l),je(e=>{let t=new Set(e);return t.delete(s.id),t})}},[b,a,he,m,f,r,e,v,h,n]);return(0,xe.jsxs)("div",{className:"flex h-full flex-col",children:[(0,xe.jsx)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:(0,xe.jsx)("div",{className:"flex items-start justify-between gap-3",children:(0,xe.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:(0,xe.jsx)(i,{size:18})}),(0,xe.jsxs)("div",{className:"min-w-0",children:[(0,xe.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:"Nodes"}),(0,xe.jsxs)("p",{className:"truncate text-xs text-modiff-subtle-text",children:[De," nodes · ",ze," catalog entries"]})]})]})})}),(0,xe.jsx)("div",{className:"p-2",children:(0,xe.jsx)(ce,{"aria-label":"Search nodes",placeholder:"Search nodes",value:F,onChange:e=>G(e.currentTarget.value),onClear:()=>G("")})}),(0,xe.jsx)(me,{}),(0,xe.jsx)("div",{className:"px-3 pb-2",children:(0,xe.jsx)(oe,{tone:"primary",fullWidth:!0,icon:(0,xe.jsx)(g,{size:16}),onClick:()=>{ae("add"),ue("local"),Z(!0)},children:"Add custom node"})}),V?(0,xe.jsx)(fe.Suspense,{fallback:null,children:(0,xe.jsx)(ge,{initialView:K,initialKind:ie,onClose:()=>Z(!1)})}):null,(0,xe.jsx)("p",{className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Nodes, task Blocks and Saved Blocks share this library. Choose a pipeline to add nodes with its declared inputs."}),(0,xe.jsxs)("div",{className:"min-h-0 flex-1 select-none overflow-y-auto p-1",children:[(0,xe.jsx)(pe,{search:F,insert:Be,manage:()=>{ae("manage"),Z(!0)}}),(0,xe.jsx)(fe.Suspense,{fallback:null,children:(0,xe.jsx)(be,{search:F,onInsert:Be})}),(0,xe.jsx)(Me,{nodes:Object.fromEntries(Object.entries(Ce).filter(([e])=>!e.startsWith("custom."))),search:F,view:ve,userBlocks:[...o,...l],huggingFaceSections:$e,huggingFaceLoading:!z,huggingFaceError:D,insertingHuggingFaceDefinitionIds:he,onRetryHuggingFaceLibrary:B,onInsertNode:Be,onInsertHuggingFaceCluster:Fe,onInsertUserBlock:Se,onImportHuggingFaceUserNode:()=>{ae("add"),ue("hub"),Z(!0)},onOpenUserBlockMenu:(e,s)=>H({block:e,anchor:s})})]}),(0,xe.jsx)(y,{open:!!_,onClose:()=>H(null),anchor:_?.anchor,ariaLabel:"Block actions",role:"menu",gap:0,panelClassName:"w-52 p-1",testId:"user-block-context-menu",children:(0,xe.jsx)(oe,{fullWidth:!0,align:"left",tone:"danger",icon:(0,xe.jsx)(j,{size:15}),onClick:()=>{R(_?.block??null),H(null)},children:"Delete from Saved Blocks"})}),(0,xe.jsx)(Y,{open:!!L,onClose:()=>R(null),title:"Delete block definition?",testId:"delete-user-block-dialog",panelClassName:"max-w-md",footer:(0,xe.jsxs)(xe.Fragment,{children:[(0,xe.jsx)(oe,{onClick:()=>R(null),children:"Cancel"}),(0,xe.jsx)(oe,{tone:"danger",onClick:()=>{L&&u(S(L)).then(()=>R(null)).catch(()=>{})},"data-testid":"confirm-delete-user-block",children:"Delete definition"})]}),children:(0,xe.jsx)("p",{className:"text-sm text-modiff-text",children:"Existing workflow instances keep their embedded snapshot and continue to work."})})]})}function ke(e,s){let t=e.zoom||1,a=s%6*36;return{x:(180-e.x+a)/t,y:(120-e.y+a)/t}}function we(e,s,t){let a=s.filter(e=>!e.parentId&&!e.hidden),n=e=>a.some(s=>{let a=s.measured?.width??s.width??320,n=s.measured?.height??s.height??220;return e.xs.position.x&&e.ys.position.y});for(let s=0;s<36;s+=1){let a=s%6,r=Math.floor(s/6),i={x:e.x+a*(t.width+32),y:e.y+r*(t.height+32)};if(!n(i))return i}return{x:Math.max(e.x,...a.map(e=>e.position.x+(e.measured?.width??e.width??320)+32)),y:e.y}}function ve(e){switch(e||="default",e.toLowerCase()){case"image":case"preview":return(0,xe.jsx)(n,{size:16});case"edit":case"editing":case"image_filter":return(0,xe.jsx)(b,{size:16});case"generate":case"generation":case"audio":case"sampler":return(0,xe.jsx)(d,{size:16});case"condition":case"conditioning":case"adapters":default:return(0,xe.jsx)(x,{size:16});case"export":case"upscaler":return(0,xe.jsx)(s,{size:16});case"video":case"embedding":return(0,xe.jsx)(p,{size:16});case"text":return(0,xe.jsx)(a,{size:16});case"primitive":return(0,xe.jsx)(o,{size:16});case"custom":return(0,xe.jsx)(l,{size:16});case"load":case"loader":case"loaders":return(0,xe.jsx)(r,{size:16})}}function Ne(e){return e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"")}function ye(e){return"reviewed_modiff_contract"===e?"Reviewed MoDiff contract":"reviewed_transformers_contract"===e?"Reviewed Transformers contract":"equivalent_standard_route"===e?"Equivalent standard route":"contract_only"===e?"Contract only":"Reviewed upstream metadata"}function Ce(e){let s=new Map;e.entries.forEach(t=>{let a=s;t.groupPath.forEach((s,n)=>{let r=t.groupPath.slice(0,n+1),i=`${e.id}:${r.join("/")}`,l=a.get(s)??{id:i,label:s,entries:[],children:new Map};a.set(s,l),a=l.children,n===t.groupPath.length-1&&l.entries.push(t)})});let t=e=>[...e.values()].sort((e,s)=>e.label.localeCompare(s.label)).map(e=>({id:e.id,label:e.label,entries:[...e.entries].sort((e,s)=>e.label.localeCompare(s.label)||e.id.localeCompare(s.id)),children:t(e.children)}));return t(s)}function Ie(e){return e.entries.length+e.children.reduce((e,s)=>e+Ie(s),0)}function $e({entry:e,insertingDefinitionIds:s,level:a,onInsertCluster:n}){let r=!!s?.has(e.id),i=(0,xe.jsxs)(xe.Fragment,{children:[(0,xe.jsx)("span",{className:"mt-0.5 grid size-4 shrink-0 self-start place-items-center text-hf-yellow",children:"cluster"===e.kind?(0,xe.jsx)(p,{size:15}):(0,xe.jsx)(o,{size:15})}),(0,xe.jsxs)("span",{className:"min-w-[min(100%,6rem)] flex-1",children:[(0,xe.jsx)("span",{className:"block break-words whitespace-normal","data-catalog-entry-label":!0,children:e.label}),(0,xe.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.detail})]}),(0,xe.jsxs)("span",{"data-catalog-entry-readiness":!0,className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:[r?(0,xe.jsx)(t,{size:12,className:"animate-spin","aria-hidden":"true"}):null,r?"Adding…":e.readinessLabel]})]}),l=e.insertable?"block"===e.kind?`${e.description} ${ye(e.integrationStatus)}. Add this exact pinned Modular Diffusers definition from ${e.modularBlockContexts?.length??1} compatible context${1===(e.modularBlockContexts?.length??1)?"":"s"} as an ordinary composable node.`:"graph_qualified"===e.readiness?`${e.description} ${ye(e.integrationStatus)}. Custom memory settings use your configured recipe; Automatic checks the exact runtime, installed artifacts, and available resources before submission.`:`${e.description} ${ye(e.integrationStatus)}. Insert the reviewed structural Block; execution remains unavailable until its exact graph, artifact, runtime, and resource admission completes.`:`${e.description} ${ye(e.integrationStatus)}. Catalog metadata only; insertion is unavailable until its exact graph compiler is admitted.`;return e.insertable?(0,xe.jsx)(H,{"aria-label":`${e.label}. ${e.readinessLabel}; insert ${"cluster"===e.kind?"Block":"Modular Diffusers block"}.`,className:"cursor-pointer flex-wrap gap-y-1 py-1 hover:bg-modiff-surface-hover","data-readiness":e.readiness,"data-testid":`hugging-face-node-row-${Ne(e.id)}`,"aria-busy":r||void 0,disabled:r,draggable:!r,level:a,onClick:()=>n(e),onDragStart:s=>{s.dataTransfer.setData("text/plain","cluster"===e.kind?`${v}${e.id}`:`${R}${e.id}`),s.dataTransfer.effectAllowed="move"},title:l,children:i}):(0,xe.jsx)("div",{"aria-disabled":"true","aria-label":`${e.label}. ${e.readinessLabel}; insertion unavailable.`,className:"flex min-h-10 min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-modiff-compact py-1 pl-2 pr-2 text-sm text-modiff-text","data-readiness":e.readiness,"data-testid":`hugging-face-node-row-${Ne(e.id)}`,role:"listitem",title:l,children:i})}function ze({activeGroupIds:e,forceOpen:s,insertingDefinitionIds:t,level:a,nodes:n,onInsertCluster:r,onToggleGroup:i}){return n.map(n=>{let l=`hugging-face:${n.id}`,o=s||e.includes(l);return(0,xe.jsxs)("div",{"data-testid":`node-subgroup-${Ne(n.id)}`,children:[(0,xe.jsxs)(H,{"aria-expanded":o,className:"min-h-9 justify-between font-medium",level:a,onClick:()=>i(l),open:o,children:[(0,xe.jsx)("span",{className:"min-w-0 truncate",children:n.label}),(0,xe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:Ie(n)}),(0,xe.jsx)(h,{size:14,className:B("text-modiff-subtle-text transition-transform",o&&"rotate-180")})]})]}),o?(0,xe.jsxs)(D,{level:a+1,children:[(0,xe.jsx)(ze,{activeGroupIds:e,forceOpen:s,insertingDefinitionIds:t,level:a+1,nodes:n.children,onInsertCluster:r,onToggleGroup:i}),n.entries.map(e=>(0,xe.jsx)($e,{entry:e,insertingDefinitionIds:t,level:a+1,onInsertCluster:r},e.id))]}):null]},n.id)})}function De({activeGroupIds:e,error:s,insertingDefinitionIds:t,loading:a,onToggleGroup:n,onRetry:r,onInsertCluster:l,searching:o,sections:d}){return a?(0,xe.jsx)("div",{"aria-live":"polite",className:"mb-1 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text","data-testid":"hugging-face-node-catalog-loading",role:"status",children:"Loading Hugging Face node catalog…"}):s?(0,xe.jsxs)("div",{className:"mb-1 grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text","data-testid":"hugging-face-node-catalog-error",role:"alert",children:[(0,xe.jsx)("span",{children:"Hugging Face node catalog unavailable. Runtime nodes and Saved Blocks are unaffected."}),(0,xe.jsx)(oe,{align:"left",className:"h-8 px-2 text-xs",onClick:()=>{r()},tone:"secondary",children:"Retry catalog"})]}):d.map(s=>{let a=`hugging-face:${s.id}`,r=o||e.includes(a);return(0,xe.jsxs)("div",{"data-testid":`node-group-${Ne(s.label)}`,className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",r&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,xe.jsxs)(H,{"aria-expanded":r,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>n(a),open:r,children:[(0,xe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:s.id.endsWith("_cluster_nodes")?(0,xe.jsx)(p,{size:15}):(0,xe.jsx)(i,{size:15})}),(0,xe.jsx)("span",{className:"min-w-0 truncate leading-none",children:s.label})]}),(0,xe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:s.entries.length}),(0,xe.jsx)(h,{size:16,className:B("text-modiff-subtle-text transition-transform",r&&"rotate-180")})]})]}),r?(0,xe.jsx)(D,{level:1,children:(0,xe.jsx)("div",{role:"list","aria-label":s.label,children:(0,xe.jsx)(ze,{activeGroupIds:e,forceOpen:o,insertingDefinitionIds:t,level:1,nodes:Ce(s),onInsertCluster:l,onToggleGroup:n})})}):null]},s.id)})}function Se(e,s){let t=new Map;e.forEach(e=>{let a=t,n=z(e,s);n.forEach((t,r)=>{let i=`user-nodes:${s}:${JSON.stringify(n.slice(0,r+1))}`,l=a.get(t)??{id:i,label:t,blocks:[],children:new Map};a.set(t,l),a=l.children,r===n.length-1&&l.blocks.push(e)})});let a=e=>[...e.values()].sort((e,s)=>e.label.localeCompare(s.label)).map(e=>({id:e.id,label:e.label,blocks:[...e.blocks].sort((e,s)=>F(e).localeCompare(F(s))||S(e).localeCompare(S(s))),children:a(e.children)}));return a(t)}function Be(e){return e.blocks.length+e.children.reduce((e,s)=>e+Be(s),0)}function Fe({activeGroupIds:e,blocks:s,forceOpen:t,level:a,onInsertUserBlock:n,onOpenUserBlockMenu:r,onToggleGroup:l}){return s.map(s=>{let o=`user-block:${s.id}`,d=t||e.includes(o);return(0,xe.jsxs)("div",{"data-testid":`user-node-subgroup-${Ne(s.id)}`,children:[(0,xe.jsxs)(H,{"aria-expanded":d,className:"min-h-9 justify-between font-medium",level:a,onClick:()=>l(o),open:d,children:[(0,xe.jsx)("span",{className:"min-w-0 truncate",children:s.label}),(0,xe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:Be(s)}),(0,xe.jsx)(h,{size:14,className:B("text-modiff-subtle-text transition-transform",d&&"rotate-180")})]})]}),d?(0,xe.jsxs)(D,{level:a+1,children:[(0,xe.jsx)(Fe,{activeGroupIds:e,blocks:s.children,forceOpen:t,level:a+1,onInsertUserBlock:n,onOpenUserBlockMenu:r,onToggleGroup:l}),s.blocks.map(e=>(0,xe.jsxs)(H,{"data-testid":`user-block-row-${Ne(S(e))}`,draggable:!0,level:a+1,title:`Add Block · ${S(e)} · ${L(e)}`,className:"cursor-grab",onClick:()=>n(e),onContextMenu:s=>{s.preventDefault(),r(e,{left:s.clientX,top:s.clientY})},onDragStart:s=>{s.dataTransfer.setData("text/plain",`${G(e)?ae:K}${S(e)}`),s.dataTransfer.effectAllowed="move"},children:[(0,xe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center self-start text-hf-yellow",children:(0,xe.jsx)(i,{size:15})}),(0,xe.jsxs)("span",{className:"min-w-0 flex-1 whitespace-normal break-words text-left",children:[(0,xe.jsx)("span",{className:"block",children:F(e)}),(0,xe.jsx)("span",{className:"block text-xs text-modiff-subtle-text",children:L(e)}),(0,xe.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:S(e)})]})]},S(e)))]}):null]},s.id)})}function Me({nodes:e,search:s,view:t,userBlocks:a,huggingFaceSections:n,huggingFaceLoading:r,huggingFaceError:l,insertingHuggingFaceDefinitionIds:o,onRetryHuggingFaceLibrary:d,onInsertNode:c,onInsertHuggingFaceCluster:u,onInsertUserBlock:m,onImportHuggingFaceUserNode:x,onOpenUserBlockMenu:p}){let{activeNodeGroups:g,setActiveNodeGroups:b}=O(),j=(0,fe.useMemo)(()=>se(e).filter(e=>X(e,t)).filter(e=>ie(e,s)).reduce((e,s)=>{let t=V(s);return e[t]||(e[t]=[]),e[t].push(s),e},{}),[e,s,t]),k=Object.entries(j).sort(([e],[s])=>e.localeCompare(s)),w=O(e=>e.userBlockGrouping),v=O(e=>e.setUserBlockGrouping),N=(0,fe.useMemo)(()=>ue(a).filter(e=>_(e,s)),[s,a]),y=g.includes("User Nodes")||!(!s.trim()||!N.length);return(0,xe.jsxs)(xe.Fragment,{children:[(0,xe.jsx)(De,{activeGroupIds:g,error:l,insertingDefinitionIds:o,loading:r,onToggleGroup:b,onRetry:d,onInsertCluster:u,searching:!!s.trim(),sections:n}),(0,xe.jsxs)("div",{"data-testid":"node-group-User-Nodes",className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",y&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,xe.jsxs)(H,{"aria-expanded":y,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>b("User Nodes"),open:y,children:[(0,xe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:(0,xe.jsx)(i,{size:15})}),(0,xe.jsx)("span",{className:"min-w-0 truncate leading-none",children:"Saved Blocks"})]}),(0,xe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:N.length}),(0,xe.jsx)(h,{size:16,className:B("text-modiff-subtle-text transition-transform",y&&"rotate-180")})]})]}),y?(0,xe.jsxs)(D,{level:1,children:[(0,xe.jsxs)("div",{className:"grid gap-1 px-2 py-2",children:[(0,xe.jsx)(Z,{"aria-label":"Group Saved Blocks by",value:w,options:[{value:"source",label:"By source and family"},{value:"workflow",label:"By saved workflow context"}],onValueChange:e=>v("workflow"===e?"workflow":"source")}),(0,xe.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Saved copies only. Updating replaces the library revision; open workflows keep their own copy."})]}),(0,xe.jsxs)(H,{"data-testid":"import-hugging-face-user-node",level:1,title:"Import an immutable Modular Diffusers block from Hugging Face Hub",onClick:x,children:[(0,xe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:(0,xe.jsx)(f,{size:15})}),(0,xe.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Import from Hugging Face Hub"})]}),(0,xe.jsx)(Fe,{activeGroupIds:g,blocks:Se(N,w),forceOpen:!!s.trim(),level:1,onInsertUserBlock:m,onOpenUserBlockMenu:p,onToggleGroup:b})]}):null]}),0===k.length&&0===N.length&&0===n.length?(0,xe.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text",children:"No nodes match this view."}):k.map(([e,t])=>{let a=!!s.trim()||g.includes(e);return(0,xe.jsxs)("div",{"data-testid":`node-group-${Ne(e)}`,className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",a&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,xe.jsxs)(H,{"aria-expanded":a,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>b(e),open:a,children:[(0,xe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:ve(e)}),(0,xe.jsx)("span",{className:"min-w-0 truncate leading-none",children:e})]}),(0,xe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,xe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:t.length}),(0,xe.jsx)(h,{size:16,className:B("text-modiff-subtle-text transition-transform",a&&"rotate-180")})]})]}),a?(0,xe.jsx)(D,{level:1,children:(0,xe.jsx)(he,{entries:t,search:s,openGroups:g,toggle:b,insert:c})}):null]},e)})]})}export{De as HuggingFaceNodeGroups,je as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Ct as s,Et as t,I as a,It as n,L as r,Mn as i,N as l,Nn as o,Vn as d,Zt as c,cr as u,dr as m,hn as f,j as x,jt as p,kn as g,ot as h,qt as b,z as j}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$ as k,A as v,B as w,D as N,E as y,F as C,Ft as I,Hr as $,I as z,It as D,L as S,Ln as B,M as F,N as M,Ni as T,O as G,Oo as _,P as E,Po as H,R as L,T as O,Ti as A,Xr as R,Z as U,Zr as P,a as q,an as W,bn as V,ci as Z,et as K,i as X,ii as J,in as Y,j as Q,k as ee,li as se,n as te,o as ae,q as ne,r as re,ri as ie,rt as le,wa as oe,wi as de,wn as ce,xn as ue,z as me}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as fe}from"./NodeDiscoveryFilters.js?v=ca6b74e6a02eedb3";var xe=e(m(),1),pe=u();function ge({search:e,insert:s,manage:t}){let a=de(e=>e.customModules),n=de(e=>e.nodesRegistry),r=de(e=>e.fetchCustomModules),l=de(e=>e.customModuleError),[o,d]=(0,xe.useState)(!1);(0,xe.useEffect)(()=>{let e=!1,s=async()=>{if(!e&&"hidden"!==document.visibilityState){e=!0;try{await r()}finally{e=!1}}};s();let t=window.setInterval(()=>{s()},15e3);return window.addEventListener("focus",s),()=>{window.clearInterval(t),window.removeEventListener("focus",s)}},[r]);let c=e.trim().toLowerCase(),u=o||!!c,m=Object.entries(n).filter(([e,s])=>e.startsWith("custom.")&&a.some(s=>s.enabled&&e.startsWith(s.moduleKey+"."))&&(!c||`${s.label} ${e}`.toLowerCase().includes(c)));return(0,pe.jsxs)("section",{"data-testid":"node-group-custom-nodes",className:"mb-2 rounded-modiff-compact border border-modiff-border",children:[(0,pe.jsxs)(I,{"aria-expanded":u,open:u,onClick:()=>d(!o),className:"min-h-10 justify-between font-semibold",children:[(0,pe.jsxs)("span",{className:"flex items-center gap-2",children:[(0,pe.jsx)(i,{size:16,className:"text-hf-yellow"}),"Custom nodes"]}),(0,pe.jsxs)("span",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[m.length,(0,pe.jsx)(g,{size:14,className:B(u&&"rotate-180")})]})]}),u?(0,pe.jsxs)(D,{level:1,children:[m.map(([e,t])=>(0,pe.jsx)(I,{draggable:!0,level:1,onClick:()=>s(e),onDragStart:s=>{s.dataTransfer.setData("text/plain",e),s.dataTransfer.effectAllowed="move"},children:(0,pe.jsx)("span",{className:"min-w-0 break-words",children:t.label||t.action})},e)),a.filter(e=>!e.enabled&&(!c||e.name.toLowerCase().includes(c))).map(e=>(0,pe.jsxs)(I,{level:1,onClick:t,title:e.diagnostic??"Load this source in Manage nodes",children:[(0,pe.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name}),(0,pe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:"disabled"!==e.status||e.approvedHash?e.status:"Not loaded"})]},e.name)),a.length?null:(0,pe.jsx)("p",{className:"p-2 text-xs text-modiff-subtle-text",children:"No custom nodes yet. Add a node or drop a Python node onto the canvas."}),l?(0,pe.jsx)("p",{role:"status",className:"p-2 text-xs text-modiff-red",children:l}):null,(0,pe.jsx)(Y,{fullWidth:!0,tone:"ghost",onClick:t,children:"Manage nodes"})]}):null]})}function he({entries:e,search:s,openGroups:t,toggle:a,insert:n}){let r=new Map;for(let s of e){let e=s.groupPath.slice(1).join(" / ")||"Operations";r.set(e,[...r.get(e)??[],s])}return[...r].sort(([e],[s])=>e.localeCompare(s)).map(([e,r])=>{let l=`runtime:${r[0].groupPath[0]}:${e}`,o=!!s.trim()||t.includes(l);return(0,pe.jsxs)("div",{"data-testid":`node-subgroup-${l.replace(/[^a-zA-Z0-9]+/gu,"-")}`,children:[(0,pe.jsxs)(I,{level:1,"aria-expanded":o,open:o,onClick:()=>a(l),className:"min-h-9 justify-between font-medium",children:[(0,pe.jsx)("span",{className:"min-w-0 truncate",children:e}),(0,pe.jsxs)("span",{className:"flex items-center gap-2 text-xs text-modiff-subtle-text",children:[r.length,(0,pe.jsx)(g,{size:14,className:B("transition-transform",o&&"rotate-180")})]})]}),o?(0,pe.jsx)(D,{level:2,children:[...r].sort((e,s)=>e.label.localeCompare(s.label)||e.key.localeCompare(s.key)).map(e=>(0,pe.jsxs)(I,{"data-testid":`node-row-${e.key.replace(/[^a-zA-Z0-9]+/gu,"-").replace(/^-|-$/gu,"")}`,level:2,draggable:!0,onClick:()=>n(e.dragKey),onDragStart:s=>{s.dataTransfer.setData("text/plain",e.dragKey),s.dataTransfer.effectAllowed="move"},title:`${e.node.label||e.label} · ${e.key}${e.description?`\n${e.description}`:""}`,className:"cursor-grab hover:bg-modiff-surface-hover",children:["experimental"===e.visibility?(0,pe.jsx)(c,{size:14,className:"shrink-0 text-hf-yellow"}):(0,pe.jsx)(i,{size:14,className:"shrink-0 text-hf-yellow"}),(0,pe.jsx)("span",{className:"min-w-0 flex-1 break-words",children:e.label})]},e.key))}):null]},l)})}var be=(0,xe.lazy)(()=>A(()=>import(`./CustomExtensionsDialog.js?v=ca6b74e6a02eedb3`),[])),je=(0,xe.lazy)(()=>A(()=>import(`./OperationCatalogPanel.js?v=ca6b74e6a02eedb3`),[]));function ke(){let e=de(e=>e.nodesRegistry),s=de(e=>e.operationContracts),t=de(e=>e.pipelineSupport),a=$(e=>e.addNode),n=$(e=>e.viewport),r=$(e=>e.nodes.length),l=Z(e=>e.blocks),o=Z(e=>e.blockDefinitionsV2),d=Z(e=>e.loaded),c=Z(e=>e.fetchBlocks),u=Z(e=>e.deleteBlock),m=P(e=>e.library),f=R(e=>e.snapshot),x=R(e=>e.loaded),p=R(e=>e.fetchSnapshot),g=T(e=>e.form),b=T(e=>e.activeWorkflowTabId),w=oe(e=>e.setWorkflowFocusRequest),C=P(e=>e.loaded),I=P(e=>e.error),D=P(e=>e.fetchLibrary),[S,B]=(0,xe.useState)(""),[M,E]=(0,xe.useState)(null),[L,O]=(0,xe.useState)(null),[q,se]=(0,xe.useState)(!1),[re,le]=(0,xe.useState)("add"),[ue,me]=(0,xe.useState)("local"),[he,ke]=(0,xe.useState)(()=>new Set),{view:we,pipeline:Ne,task:ye}=U(),Ce=(0,xe.useMemo)(()=>ae(e,s,t,we,{pipeline:Ne,task:ye}),[we,e,s,t,Ne,ye]);(0,xe.useEffect)(()=>{d||c()},[c,d]),(0,xe.useEffect)(()=>{C||D()},[D,C]),(0,xe.useEffect)(()=>{x||p()},[p,x]);let Ie=(0,xe.useMemo)(()=>m?ie(m,f):[],[m,f]),$e=(0,xe.useMemo)(()=>J(Ie,S,we),[Ie,S,we]),ze=(0,xe.useMemo)(()=>J(Ie,"",we).reduce((e,s)=>e+s.entries.length,0),[Ie,we]),De=(0,xe.useMemo)(()=>te(Ce).filter(e=>X(e,we)).length,[Ce,we]),Se=(0,xe.useCallback)(e=>{K();let s=F(e,k(ve(n,r),$.getState().nodes,{width:420,height:480}));if(a(s),b){let e=Date.now();w({workflowTabId:b,nodeId:s.id,requestId:e,requestedAt:e})}},[b,a,r,w,n]),Be=(0,xe.useCallback)((s,t)=>{K();let i=ne(s,t?{[s]:t}:e,ve(n,r));i?(i.position=k(i.position,$.getState().nodes,{width:360,height:420}),a({...i,selected:!0})):H(`Node ${s} is no longer available. Reload the node list and try again.`,{variant:"error",autoHideDuration:5e3})},[a,r,e,n]),Fe=(0,xe.useCallback)(async s=>{if(!m||!s.insertable||he.has(s.id))return;if("block"===s.kind){try{K(),a(G(s,m,f)?y(s,m,e,ve(n,r),f):N(s,m,e,ve(n,r),f))}catch(e){H(_(e,"The Modular Diffusers block could not be added."),{variant:"error",autoHideDuration:7e3})}return}if("cluster"!==s.kind)return;let t=m.definitions.find(e=>e.id===s.id);if(!t)return void H("The exact reviewed Block definition is unavailable. Reload the catalog and try again.",{variant:"error",autoHideDuration:5e3});K();let i=k(ve(n,r),$.getState().nodes,{width:360,height:320});ke(e=>new Set(e).add(s.id));let l=ee(s.label,i);try{let{createHuggingFaceClusterForGraph:e}=await A(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=ca6b74e6a02eedb3`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]),s=await e(t,i,g,{insert:!1});if(Q(l,s),b){let e=Date.now();w({workflowTabId:b,nodeId:s.id,requestId:e,requestedAt:e})}}catch(e){H(_(e,"The registered Block could not be added."),{variant:"error",autoHideDuration:1e4})}finally{v(l),ke(e=>{let t=new Set(e);return t.delete(s.id),t})}},[b,a,he,m,f,r,e,w,g,n]);return(0,pe.jsxs)("div",{className:"flex h-full flex-col",children:[(0,pe.jsx)("header",{className:"border-b border-modiff-border bg-modiff-surface px-3 py-3",children:(0,pe.jsx)("div",{className:"flex items-start justify-between gap-3",children:(0,pe.jsxs)("div",{className:"flex min-w-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact border border-modiff-border bg-modiff-bg text-hf-yellow",children:(0,pe.jsx)(i,{size:18})}),(0,pe.jsxs)("div",{className:"min-w-0",children:[(0,pe.jsx)("h2",{className:"truncate text-sm font-semibold text-modiff-text",children:"Nodes"}),(0,pe.jsxs)("p",{className:"truncate text-xs text-modiff-subtle-text",children:[De," nodes · ",ze," catalog entries"]})]})]})})}),(0,pe.jsx)("div",{className:"p-2",children:(0,pe.jsx)(V,{"aria-label":"Search nodes",placeholder:"Search nodes",value:S,onChange:e=>B(e.currentTarget.value),onClear:()=>B("")})}),(0,pe.jsx)(fe,{}),(0,pe.jsx)("div",{className:"px-3 pb-2",children:(0,pe.jsx)(Y,{tone:"primary",fullWidth:!0,icon:(0,pe.jsx)(h,{size:16}),onClick:()=>{le("add"),me("local"),se(!0)},children:"Add custom node"})}),q?(0,pe.jsx)(xe.Suspense,{fallback:null,children:(0,pe.jsx)(be,{initialView:re,initialKind:ue,onClose:()=>se(!1)})}):null,(0,pe.jsx)("p",{className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Nodes, task Blocks and Saved Blocks share this library. Choose a pipeline to add nodes with its declared inputs."}),(0,pe.jsxs)("div",{className:"min-h-0 flex-1 select-none overflow-y-auto p-1",children:[(0,pe.jsx)(ge,{search:S,insert:Be,manage:()=>{le("manage"),se(!0)}}),(0,pe.jsx)(xe.Suspense,{fallback:null,children:(0,pe.jsx)(je,{search:S,onInsert:Be})}),(0,pe.jsx)(Me,{nodes:Object.fromEntries(Object.entries(Ce).filter(([e])=>!e.startsWith("custom."))),search:S,view:we,userBlocks:[...o,...l],huggingFaceSections:$e,huggingFaceLoading:!C,huggingFaceError:I,insertingHuggingFaceDefinitionIds:he,onRetryHuggingFaceLibrary:D,onInsertNode:Be,onInsertHuggingFaceCluster:Fe,onInsertUserBlock:Se,onImportHuggingFaceUserNode:()=>{le("add"),me("hub"),se(!0)},onOpenUserBlockMenu:(e,s)=>E({block:e,anchor:s})})]}),(0,pe.jsx)(ce,{open:!!M,onClose:()=>E(null),anchor:M?.anchor,ariaLabel:"Block actions",role:"menu",gap:0,panelClassName:"w-52 p-1",testId:"user-block-context-menu",children:(0,pe.jsx)(Y,{fullWidth:!0,align:"left",tone:"danger",icon:(0,pe.jsx)(j,{size:15}),onClick:()=>{O(M?.block??null),E(null)},children:"Delete from Saved Blocks"})}),(0,pe.jsx)(W,{open:!!L,onClose:()=>O(null),title:"Delete block definition?",testId:"delete-user-block-dialog",panelClassName:"max-w-md",footer:(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(Y,{onClick:()=>O(null),children:"Cancel"}),(0,pe.jsx)(Y,{tone:"danger",onClick:()=>{L&&u(z(L)).then(()=>O(null)).catch(()=>{})},"data-testid":"confirm-delete-user-block",children:"Delete definition"})]}),children:(0,pe.jsx)("p",{className:"text-sm text-modiff-text",children:"Existing workflow instances keep their embedded snapshot and continue to work."})})]})}function ve(e,s){let t=e.zoom||1,a=s%6*36;return{x:(180-e.x+a)/t,y:(120-e.y+a)/t}}function we(e){switch(e||="default",e.toLowerCase()){case"image":case"preview":return(0,pe.jsx)(n,{size:16});case"edit":case"editing":case"image_filter":return(0,pe.jsx)(b,{size:16});case"generate":case"generation":case"audio":case"sampler":return(0,pe.jsx)(d,{size:16});case"condition":case"conditioning":case"adapters":default:return(0,pe.jsx)(x,{size:16});case"export":case"upscaler":return(0,pe.jsx)(s,{size:16});case"video":case"embedding":return(0,pe.jsx)(p,{size:16});case"text":return(0,pe.jsx)(a,{size:16});case"primitive":return(0,pe.jsx)(o,{size:16});case"custom":return(0,pe.jsx)(l,{size:16});case"load":case"loader":case"loaders":return(0,pe.jsx)(r,{size:16})}}function Ne(e){return e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-|-$/g,"")}function ye(e){return"reviewed_modiff_contract"===e?"Reviewed MoDiff contract":"reviewed_transformers_contract"===e?"Reviewed Transformers contract":"equivalent_standard_route"===e?"Equivalent standard route":"contract_only"===e?"Contract only":"Reviewed upstream metadata"}function Ce(e){let s=new Map;e.entries.forEach(t=>{let a=s;t.groupPath.forEach((s,n)=>{let r=t.groupPath.slice(0,n+1),i=`${e.id}:${r.join("/")}`,l=a.get(s)??{id:i,label:s,entries:[],children:new Map};a.set(s,l),a=l.children,n===t.groupPath.length-1&&l.entries.push(t)})});let t=e=>[...e.values()].sort((e,s)=>e.label.localeCompare(s.label)).map(e=>({id:e.id,label:e.label,entries:[...e.entries].sort((e,s)=>e.label.localeCompare(s.label)||e.id.localeCompare(s.id)),children:t(e.children)}));return t(s)}function Ie(e){return e.entries.length+e.children.reduce((e,s)=>e+Ie(s),0)}function $e({entry:e,insertingDefinitionIds:s,level:a,onInsertCluster:n}){let r=!!s?.has(e.id),i=(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)("span",{className:"mt-0.5 grid size-4 shrink-0 self-start place-items-center text-hf-yellow",children:"cluster"===e.kind?(0,pe.jsx)(p,{size:15}):(0,pe.jsx)(o,{size:15})}),(0,pe.jsxs)("span",{className:"min-w-[min(100%,6rem)] flex-1",children:[(0,pe.jsx)("span",{className:"block break-words whitespace-normal","data-catalog-entry-label":!0,children:e.label}),(0,pe.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.detail})]}),(0,pe.jsxs)("span",{"data-catalog-entry-readiness":!0,className:"ml-auto inline-flex shrink-0 items-center gap-1 whitespace-nowrap rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:[r?(0,pe.jsx)(t,{size:12,className:"animate-spin","aria-hidden":"true"}):null,r?"Adding…":e.readinessLabel]})]}),l=e.insertable?"block"===e.kind?`${e.description} ${ye(e.integrationStatus)}. Add this exact pinned Modular Diffusers definition from ${e.modularBlockContexts?.length??1} compatible context${1===(e.modularBlockContexts?.length??1)?"":"s"} as an ordinary composable node.`:"graph_qualified"===e.readiness?`${e.description} ${ye(e.integrationStatus)}. Custom memory settings use your configured recipe; Automatic checks the exact runtime, installed artifacts, and available resources before submission.`:`${e.description} ${ye(e.integrationStatus)}. Insert the reviewed structural Block; execution remains unavailable until its exact graph, artifact, runtime, and resource admission completes.`:`${e.description} ${ye(e.integrationStatus)}. Catalog metadata only; insertion is unavailable until its exact graph compiler is admitted.`;return e.insertable?(0,pe.jsx)(I,{"aria-label":`${e.label}. ${e.readinessLabel}; insert ${"cluster"===e.kind?"Block":"Modular Diffusers block"}.`,className:"cursor-pointer flex-wrap gap-y-1 py-1 hover:bg-modiff-surface-hover","data-readiness":e.readiness,"data-testid":`hugging-face-node-row-${Ne(e.id)}`,"aria-busy":r||void 0,disabled:r,draggable:!r,level:a,onClick:()=>n(e),onDragStart:s=>{s.dataTransfer.setData("text/plain","cluster"===e.kind?`${w}${e.id}`:`${O}${e.id}`),s.dataTransfer.effectAllowed="move"},title:l,children:i}):(0,pe.jsx)("div",{"aria-disabled":"true","aria-label":`${e.label}. ${e.readinessLabel}; insertion unavailable.`,className:"flex min-h-10 min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-modiff-compact py-1 pl-2 pr-2 text-sm text-modiff-text","data-readiness":e.readiness,"data-testid":`hugging-face-node-row-${Ne(e.id)}`,role:"listitem",title:l,children:i})}function ze({activeGroupIds:e,forceOpen:s,insertingDefinitionIds:t,level:a,nodes:n,onInsertCluster:r,onToggleGroup:i}){return n.map(n=>{let l=`hugging-face:${n.id}`,o=s||e.includes(l);return(0,pe.jsxs)("div",{"data-testid":`node-subgroup-${Ne(n.id)}`,children:[(0,pe.jsxs)(I,{"aria-expanded":o,className:"min-h-9 justify-between font-medium",level:a,onClick:()=>i(l),open:o,children:[(0,pe.jsx)("span",{className:"min-w-0 truncate",children:n.label}),(0,pe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:Ie(n)}),(0,pe.jsx)(g,{size:14,className:B("text-modiff-subtle-text transition-transform",o&&"rotate-180")})]})]}),o?(0,pe.jsxs)(D,{level:a+1,children:[(0,pe.jsx)(ze,{activeGroupIds:e,forceOpen:s,insertingDefinitionIds:t,level:a+1,nodes:n.children,onInsertCluster:r,onToggleGroup:i}),n.entries.map(e=>(0,pe.jsx)($e,{entry:e,insertingDefinitionIds:t,level:a+1,onInsertCluster:r},e.id))]}):null]},n.id)})}function De({activeGroupIds:e,error:s,insertingDefinitionIds:t,loading:a,onToggleGroup:n,onRetry:r,onInsertCluster:l,searching:o,sections:d}){return a?(0,pe.jsx)("div",{"aria-live":"polite",className:"mb-1 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text","data-testid":"hugging-face-node-catalog-loading",role:"status",children:"Loading Hugging Face node catalog…"}):s?(0,pe.jsxs)("div",{className:"mb-1 grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text","data-testid":"hugging-face-node-catalog-error",role:"alert",children:[(0,pe.jsx)("span",{children:"Hugging Face node catalog unavailable. Runtime nodes and Saved Blocks are unaffected."}),(0,pe.jsx)(Y,{align:"left",className:"h-8 px-2 text-xs",onClick:()=>{r()},tone:"secondary",children:"Retry catalog"})]}):d.map(s=>{let a=`hugging-face:${s.id}`,r=o||e.includes(a);return(0,pe.jsxs)("div",{"data-testid":`node-group-${Ne(s.label)}`,className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",r&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,pe.jsxs)(I,{"aria-expanded":r,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>n(a),open:r,children:[(0,pe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:s.id.endsWith("_cluster_nodes")?(0,pe.jsx)(p,{size:15}):(0,pe.jsx)(i,{size:15})}),(0,pe.jsx)("span",{className:"min-w-0 truncate leading-none",children:s.label})]}),(0,pe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:s.entries.length}),(0,pe.jsx)(g,{size:16,className:B("text-modiff-subtle-text transition-transform",r&&"rotate-180")})]})]}),r?(0,pe.jsx)(D,{level:1,children:(0,pe.jsx)("div",{role:"list","aria-label":s.label,children:(0,pe.jsx)(ze,{activeGroupIds:e,forceOpen:o,insertingDefinitionIds:t,level:1,nodes:Ce(s),onInsertCluster:l,onToggleGroup:n})})}):null]},s.id)})}function Se(e,s){let t=new Map;e.forEach(e=>{let a=t,n=C(e,s);n.forEach((t,r)=>{let i=`user-nodes:${s}:${JSON.stringify(n.slice(0,r+1))}`,l=a.get(t)??{id:i,label:t,blocks:[],children:new Map};a.set(t,l),a=l.children,r===n.length-1&&l.blocks.push(e)})});let a=e=>[...e.values()].sort((e,s)=>e.label.localeCompare(s.label)).map(e=>({id:e.id,label:e.label,blocks:[...e.blocks].sort((e,s)=>S(e).localeCompare(S(s))||z(e).localeCompare(z(s))),children:a(e.children)}));return a(t)}function Be(e){return e.blocks.length+e.children.reduce((e,s)=>e+Be(s),0)}function Fe({activeGroupIds:e,blocks:s,forceOpen:t,level:a,onInsertUserBlock:n,onOpenUserBlockMenu:r,onToggleGroup:l}){return s.map(s=>{let o=`user-block:${s.id}`,d=t||e.includes(o);return(0,pe.jsxs)("div",{"data-testid":`user-node-subgroup-${Ne(s.id)}`,children:[(0,pe.jsxs)(I,{"aria-expanded":d,className:"min-h-9 justify-between font-medium",level:a,onClick:()=>l(o),open:d,children:[(0,pe.jsx)("span",{className:"min-w-0 truncate",children:s.label}),(0,pe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:Be(s)}),(0,pe.jsx)(g,{size:14,className:B("text-modiff-subtle-text transition-transform",d&&"rotate-180")})]})]}),d?(0,pe.jsxs)(D,{level:a+1,children:[(0,pe.jsx)(Fe,{activeGroupIds:e,blocks:s.children,forceOpen:t,level:a+1,onInsertUserBlock:n,onOpenUserBlockMenu:r,onToggleGroup:l}),s.blocks.map(e=>(0,pe.jsxs)(I,{"data-testid":`user-block-row-${Ne(z(e))}`,draggable:!0,level:a+1,title:`Add Block · ${z(e)} · ${L(e)}`,className:"cursor-grab",onClick:()=>n(e),onContextMenu:s=>{s.preventDefault(),r(e,{left:s.clientX,top:s.clientY})},onDragStart:s=>{s.dataTransfer.setData("text/plain",`${M(e)?le:se}${z(e)}`),s.dataTransfer.effectAllowed="move"},children:[(0,pe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center self-start text-hf-yellow",children:(0,pe.jsx)(i,{size:15})}),(0,pe.jsxs)("span",{className:"min-w-0 flex-1 whitespace-normal break-words text-left",children:[(0,pe.jsx)("span",{className:"block",children:S(e)}),(0,pe.jsx)("span",{className:"block text-xs text-modiff-subtle-text",children:L(e)}),(0,pe.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:z(e)})]})]},z(e)))]}):null]},s.id)})}function Me({nodes:e,search:s,view:t,userBlocks:a,huggingFaceSections:n,huggingFaceLoading:r,huggingFaceError:l,insertingHuggingFaceDefinitionIds:o,onRetryHuggingFaceLibrary:d,onInsertNode:c,onInsertHuggingFaceCluster:u,onInsertUserBlock:m,onImportHuggingFaceUserNode:x,onOpenUserBlockMenu:p}){let{activeNodeGroups:h,setActiveNodeGroups:b}=oe(),j=(0,xe.useMemo)(()=>te(e).filter(e=>X(e,t)).filter(e=>re(e,s)).reduce((e,s)=>{let t=q(s);return e[t]||(e[t]=[]),e[t].push(s),e},{}),[e,s,t]),k=Object.entries(j).sort(([e],[s])=>e.localeCompare(s)),v=oe(e=>e.userBlockGrouping),w=oe(e=>e.setUserBlockGrouping),N=(0,xe.useMemo)(()=>me(a).filter(e=>E(e,s)),[s,a]),y=h.includes("User Nodes")||!(!s.trim()||!N.length);return(0,pe.jsxs)(pe.Fragment,{children:[(0,pe.jsx)(De,{activeGroupIds:h,error:l,insertingDefinitionIds:o,loading:r,onToggleGroup:b,onRetry:d,onInsertCluster:u,searching:!!s.trim(),sections:n}),(0,pe.jsxs)("div",{"data-testid":"node-group-User-Nodes",className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",y&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,pe.jsxs)(I,{"aria-expanded":y,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>b("User Nodes"),open:y,children:[(0,pe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:(0,pe.jsx)(i,{size:15})}),(0,pe.jsx)("span",{className:"min-w-0 truncate leading-none",children:"Saved Blocks"})]}),(0,pe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:N.length}),(0,pe.jsx)(g,{size:16,className:B("text-modiff-subtle-text transition-transform",y&&"rotate-180")})]})]}),y?(0,pe.jsxs)(D,{level:1,children:[(0,pe.jsxs)("div",{className:"grid gap-1 px-2 py-2",children:[(0,pe.jsx)(ue,{"aria-label":"Group Saved Blocks by",value:v,options:[{value:"source",label:"By source and family"},{value:"workflow",label:"By saved workflow context"}],onValueChange:e=>w("workflow"===e?"workflow":"source")}),(0,pe.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Saved copies only. Updating replaces the library revision; open workflows keep their own copy."})]}),(0,pe.jsxs)(I,{"data-testid":"import-hugging-face-user-node",level:1,title:"Import an immutable Modular Diffusers block from Hugging Face Hub",onClick:x,children:[(0,pe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:(0,pe.jsx)(f,{size:15})}),(0,pe.jsx)("span",{className:"min-w-0 flex-1 truncate",children:"Import from Hugging Face Hub"})]}),(0,pe.jsx)(Fe,{activeGroupIds:h,blocks:Se(N,v),forceOpen:!!s.trim(),level:1,onInsertUserBlock:m,onOpenUserBlockMenu:p,onToggleGroup:b})]}):null]}),0===k.length&&0===N.length&&0===n.length?(0,pe.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-sm text-modiff-subtle-text",children:"No nodes match this view."}):k.map(([e,t])=>{let a=!!s.trim()||h.includes(e);return(0,pe.jsxs)("div",{"data-testid":`node-group-${Ne(e)}`,className:B("mb-1 rounded-modiff-compact border border-transparent transition-colors",a&&"border-modiff-border bg-modiff-surface-hover/40"),children:[(0,pe.jsxs)(I,{"aria-expanded":a,className:"min-h-10 justify-between px-2 font-semibold",onClick:()=>b(e),open:a,children:[(0,pe.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"grid size-4 shrink-0 place-items-center text-hf-yellow",children:we(e)}),(0,pe.jsx)("span",{className:"min-w-0 truncate leading-none",children:e})]}),(0,pe.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,pe.jsx)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:t.length}),(0,pe.jsx)(g,{size:16,className:B("text-modiff-subtle-text transition-transform",a&&"rotate-180")})]})]}),a?(0,pe.jsx)(D,{level:1,children:(0,pe.jsx)(he,{entries:t,search:s,openGroups:h,toggle:b,insert:c})}):null]},e)})]})}export{De as HuggingFaceNodeGroups,ke as default}; \ No newline at end of file diff --git a/web/assets/NodeSearchDialog.js b/web/assets/NodeSearchDialog.js index baaa848..9fa3f1e 100644 --- a/web/assets/NodeSearchDialog.js +++ b/web/assets/NodeSearchDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ao as n,Ci as o,Cn as s,D as i,E as r,Ei as l,Eo as c,In as d,M as u,O as f,Oo as p,P as h,Q as m,Si as x,Ti as g,Tt as b,Xr as y,Yr as k,Z as v,cc as j,cn as C,ii as w,ji as N,ni as S,o as D,oa as I,oc as E,q as T,ri as M,si as A,yn as B}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as H}from"./huggingFaceCatalogAdmission.js?v=cc046c26d6fe7aa4";import{n as F}from"./operationCatalog.js?v=cc046c26d6fe7aa4";import{a as O}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{t as $}from"./NodeDiscoveryFilters.js?v=cc046c26d6fe7aa4";import{a as L,i as R,n as _,o as K,r as P,t as V}from"./nodeConnectionSearch.js?v=cc046c26d6fe7aa4";var G=e(a(),1);function W(){throw Error("Invalid registered Block interface index.")}function q(e){return("string"!=typeof e||!e||e.length>2048||/\p{Cc}/u.test(e))&&W(),e}function z(e){(!Array.isArray(e)||e.length>512)&&W();let t=e.map(e=>{(!I(e)||"portId,valueType"!==Object.keys(e).sort().join(","))&&W();let t=Array.isArray(e.valueType)?e.valueType.length&&e.valueType.length<=64?e.valueType.map(q):W():q(e.valueType);return{portId:q(e.portId),valueType:t}});return new Set(t.map(e=>e.portId)).size!==t.length&&W(),t}function Q(e){(!I(e)||"entries,error,schemaVersion"!==Object.keys(e).sort().join(",")||1!==e.schemaVersion||!1!==e.error||!Array.isArray(e.entries)||e.entries.length>2048)&&W();let t=e.entries.map(e=>{(!I(e)||"admissionId,catalogDefinitionContentHash,catalogDefinitionId,compiledDefinitionCanonicalSha256,compiledDefinitionContentHash,inputs,outputs"!==Object.keys(e).sort().join(","))&&W();let t={catalogDefinitionId:q(e.catalogDefinitionId),catalogDefinitionContentHash:q(e.catalogDefinitionContentHash),admissionId:q(e.admissionId),compiledDefinitionContentHash:q(e.compiledDefinitionContentHash),compiledDefinitionCanonicalSha256:q(e.compiledDefinitionCanonicalSha256),inputs:z(e.inputs),outputs:z(e.outputs)};return/^sha256:[a-f0-9]{64}$/u.test(t.compiledDefinitionCanonicalSha256)||W(),t});return new Set(t.map(e=>`${e.catalogDefinitionId}\0${e.admissionId}`)).size!==t.length&&W(),t}var U=null,X=j(e=>({entries:[],loaded:!1,error:null,fetch:()=>U||(U=(async()=>{try{e({entries:await p(`${E.serverAddress}/huggingface/registered-block-interfaces`,{parse:Q,timeoutMs:3e4}),loaded:!0,error:null})}catch(t){e({entries:[],loaded:!0,error:c(t,"Could not load Block interfaces.")})}})().finally(()=>{U=null}),U)}));function Y(e,t,a,o,s,r,l,c=!1){return M(e,o,s).flatMap(({entries:e})=>e).filter(e=>{if(!e.insertable||"component"===e.kind)return!1;if(!l)return!0;let o=null;if("cluster"===e.kind){let n=t.library.definitions.find(t=>t.id===e.id),s=n?H(n,t.form).route:null;s&&(o=function(e,t){let a=e.find(e=>e.catalogDefinitionId===t.definitionId&&e.admissionId===t.admissionId);if(!a||a.catalogDefinitionContentHash!==t.definitionContentHash||a.compiledDefinitionContentHash!==t.compiledDefinitionContentHash||a.compiledDefinitionCanonicalSha256!==t.compiledDefinitionCanonicalSha256)return null;let n={};for(let[e,t]of[["input",a.inputs],["output",a.outputs]])for(let a of t)n[`${e}:${a.portId}`]={display:e,type:a.valueType};return{type:"block",module:"",action:"",label:"",category:"",params:n}}(a,s))}else{if(f(e,t.library,t.snapshot))return!1;try{o=i(e,t.library,t.registry,{x:0,y:0},t.snapshot).data}catch{return!1}}return!(!o||!n(o,r,l,void 0,c))})}async function Z(e,t,a,n){if(n.aborted)throw new DOMException("Insertion cancelled.","AbortError");if(!e.insertable)throw Error("This catalog entry is not available for insertion.");if("block"===e.kind)return f(e,t.library,t.snapshot)?r(e,t.library,t.registry,a,t.snapshot):i(e,t.library,t.registry,a,t.snapshot);let s=t.library.definitions.find(t=>t.id===e.id);if("cluster"!==e.kind||!s)throw Error("The selected catalog Block is no longer available.");let{createHuggingFaceClusterForGraph:l}=await o(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=cc046c26d6fe7aa4`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]);return l(s,a,t.form,{insert:!1,signal:n})}var J=t(),ee=({anchorPosition:e,onClose:t,onSelect:a,nodes:o,dataType:i,handleType:r,origin:f})=>{let{pipeline:p,task:j,view:I,support:E}=v(),M=x(e=>e.operationContracts),H=x(e=>e.resolveOperation),W=N(e=>e.activeWorkflowTabId),q=N(e=>e.workflowCanvasEpoch),z=(0,G.useRef)(null),[Q,U]=(0,G.useState)(!1),[ee,te]=(0,G.useState)(null),[ae,ne]=(0,G.useState)(""),[oe,se]=(0,G.useState)(0),[ie,re]=(0,G.useState)(!0),[le,ce]=(0,G.useState)(!0),[de,ue]=(0,G.useState)(!1),fe=(0,G.useRef)(null),pe=A(e=>e.blocks),he=A(e=>e.blockDefinitionsV2),me=A(e=>e.loaded),xe=A(e=>e.fetchBlocks),ge=A(e=>e.error),be=(0,G.useMemo)(()=>L([...he,...pe]),[he,pe]),ye=y(e=>e.library),ke=y(e=>e.loaded),ve=y(e=>e.error),je=y(e=>e.fetchLibrary),Ce=k(e=>e.snapshot),we=k(e=>e.loaded),Ne=k(e=>e.error),Se=k(e=>e.fetchSnapshot),De=X(e=>e.entries),Ie=X(e=>e.loaded),Ee=X(e=>e.error),Te=X(e=>e.fetch),Me=N(e=>e.form),Ae=(0,G.useMemo)(()=>ye?{library:ye,snapshot:Ce,registry:o,form:Me}:null,[ye,Ce,o,Me]),Be=(0,G.useMemo)(()=>ye?S(ye,Ce):[],[ye,Ce]),He=(0,G.useMemo)(()=>Ae?Y(Be,Ae,De,ae,I,i,r,de):[],[Be,Ae,De,ae,I,i,r,de]);(0,G.useEffect)(()=>{ke||je()},[ke,je]),(0,G.useEffect)(()=>{we||Se()},[we,Se]),(0,G.useEffect)(()=>{r&&!Ie&&Te()},[r,Ie,Te]),(0,G.useEffect)(()=>{me||xe()},[me,xe]),(0,G.useEffect)(()=>{if(e){let e=setTimeout(()=>{fe.current&&fe.current.focus()},10);return()=>clearTimeout(e)}},[e]);let Fe=(0,G.useMemo)(()=>D(o,M,E,I,{pipeline:p,task:j}),[o,M,E,I,p,j]),Oe=(0,G.useMemo)(()=>R([..._(M,p,j,i,r,ae,o,f,de).map(e=>({key:`operation:${e.operationId}`,label:F(e),operation:e,node:o[e.nodeKey]})),...V(Fe,i,r,ae,I,f,de).map(([e,t])=>({key:e,node:t,label:w(t)})),...He.map(e=>({key:`catalog:${e.id}`,label:e.label,catalog:e})),...be.filter(({block:e,node:t})=>h(e,ae)&&(!r||n(t,i,r,f,de))).map(e=>({...e,label:e.node.label}))],i,r,f),[Fe,M,p,j,I,i,r,ae,be,o,He,f,de]),{builtInEntries:$e,customEntries:Le}=(0,G.useMemo)(()=>({builtInEntries:Oe.filter(e=>!e.node?.module.startsWith("custom.")),customEntries:Oe.filter(e=>e.node?.module.startsWith("custom."))}),[Oe]),Re=(0,G.useMemo)(()=>[...ie?$e:[],...le?Le:[]],[$e,ie,Le,le]);(0,G.useEffect)(()=>(z.current?.abort(),z.current=null,U(!1),te(null),()=>{z.current?.abort()}),[p,j,I,W,q,e]);let _e=Math.min(oe,Math.max(0,Re.length-1)),Ke=(0,G.useCallback)(()=>{z.current?.abort(),t(),setTimeout(()=>{ne(""),se(0)},0)},[t]),Pe=(0,G.useCallback)(async e=>{if(z.current)return;let t=new AbortController,n=l(),o=m.getState().selection;z.current=t,U(!0),te(null);try{let s;if(e.operation){let a=e.operation,n=O(P(await H(a,t.signal),a,i,r),a);s=e=>T(a.nodeKey,{[a.nodeKey]:n},e)}else if(e.catalog&&Ae){let a=e.catalog;s=async e=>{let n=await Z(a,Ae,e,t.signal);if(y.getState().library!==Ae.library)throw Error("The catalog changed. Select the Block again.");return n}}else if(e.block){let t=e.block;s=e=>u(t,e)}else{if(!e.node)return;{let t=e.node;s=a=>T(e.key,{[e.key]:t},a)}}if(t.signal.aborted||m.getState().selection!==o||(g(n,{includeForm:!1}),await a(s,t.signal,de),t.signal.aborted))return;Ke()}catch(e){t.signal.aborted||te(c(e,"Could not resolve the selected node."))}finally{z.current===t&&(z.current=null,U(!1))}},[H,a,Ke,i,r,Ae,de]),Ve=(0,G.useCallback)(e=>{switch(e.key){case"ArrowDown":e.preventDefault(),Re.length>0&&se(e=>(e+1)%Re.length);break;case"ArrowUp":e.preventDefault(),Re.length>0&&se(e=>(e-1+Re.length)%Re.length);break;case"Enter":Re[_e]&&Pe(Re[_e]);break;case"Escape":Ke()}},[Re,_e,Pe,Ke]);if(!e)return null;let Ge=(e,t)=>(0,J.jsxs)(b,{type:"button",id:`node-search-${t}`,role:"option","aria-selected":t===_e,disabled:Q,"aria-busy":Q||void 0,onClick:()=>{Pe(e)},className:d("block w-full px-3 py-2 text-left transition hover:bg-modiff-surface-hover",t===_e&&"bg-modiff-surface"),children:[(0,J.jsx)("div",{className:"truncate text-sm text-modiff-text",children:e.label}),e.block?(0,J.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["Saved Block · ",e.revision]}):null,e.catalog?(0,J.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["cluster"===e.catalog.kind?"Block":"Implementation"," · ",e.catalog.readinessLabel]}):null,e.operation?(0,J.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:[e.operation.pipelineClass," · ",e.operation.task?.replace(/_/gu," ")]}):null,e.node?.description?(0,J.jsx)("div",{className:"truncate text-xs text-modiff-subtle-text",children:e.node.description.substring(0,72)+(e.node.description.length>72?"...":"")}):null]},e.key),We=(e,t,a,n)=>(0,J.jsxs)(b,{type:"button","aria-expanded":a,onClick:n,className:"flex w-full shrink-0 items-center gap-2 border-b border-modiff-border px-3 py-2 text-left text-xs font-semibold text-modiff-text",children:[(0,J.jsx)("span",{"aria-hidden":"true",children:a?"▾":"▸"}),(0,J.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e}),(0,J.jsx)("span",{className:"text-modiff-subtle-text",children:t})]});return(0,J.jsxs)(s,{anchor:e,ariaLabel:"Search nodes",closeOnOutside:!1,gap:0,modal:!0,onClose:Ke,open:!0,panelClassName:"flex h-[min(512px,calc(100dvh-16px))] w-[368px] flex-col overflow-hidden border-4 border-modiff-bg bg-modiff-panel",placement:"bottom-start",children:[(0,J.jsx)("div",{className:"shrink-0 p-2",children:(0,J.jsx)(B,{ref:fe,"aria-label":"Search nodes","aria-activedescendant":Re[_e]?`node-search-${_e}`:void 0,autoFocus:!0,placeholder:"Search nodes and Blocks",value:ae,onChange:e=>{ne(e.currentTarget.value),se(0)},onClear:()=>{ne(""),se(0)},onKeyDown:e=>{Ve(e.nativeEvent)}})}),(0,J.jsx)($,{}),(0,J.jsx)(K,{inPopover:!0}),ee?(0,J.jsx)("p",{role:"alert",className:"px-3 pb-2 text-xs text-modiff-text",children:ee}):null,me?null:(0,J.jsx)("p",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Loading Saved Blocks…"}),ge?(0,J.jsxs)("div",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:["Saved Blocks could not be loaded.",(0,J.jsx)(b,{onClick:()=>{xe()},children:"Retry Saved Blocks"})]}):null,!ke||!we||r&&!Ie?(0,J.jsx)("p",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Loading catalog Blocks…"}):null,ve||Ne||r&&Ee?(0,J.jsxs)("div",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:["Some catalog Blocks or compatible ports could not be loaded.",(0,J.jsx)(b,{onClick:()=>{ve&&je(),Ne&&Se(),Ee&&Te()},children:"Retry catalog"})]}):null,r?(0,J.jsxs)("div",{className:"shrink-0 px-3 pb-2 text-xs text-modiff-subtle-text",children:[(0,J.jsx)(C,{checked:de,onCheckedChange:ue,label:"Show unverified matches (generic or missing types)"}),(0,J.jsx)("p",{children:"source"===r?"Nodes with matching input port types":"Nodes with matching output port types"}),(0,J.jsx)("p",{children:"Model, shape, and custom-code constraints are checked when declared and again at Run."})]}):null,(0,J.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",role:"listbox","aria-label":"Matching nodes",children:[(0,J.jsxs)("section",{className:d("flex min-h-0 flex-col",ie&&$e.length?"flex-1":"shrink-0"),children:[We("Built-in nodes and Blocks",$e.length,ie,()=>{re(e=>!e),se(0)}),ie?(0,J.jsx)("div",{className:d($e.length?"min-h-0 flex-1 overflow-auto":"shrink-0"),children:$e.length?$e.map((e,t)=>Ge(e,t)):(0,J.jsxs)("div",{className:"px-4 py-4 text-center",children:[(0,J.jsx)("div",{className:"text-sm font-semibold text-modiff-text",children:r?"No compatible nodes found":"No results found"}),(0,J.jsx)("div",{className:"text-xs text-modiff-subtle-text",children:r?"Try another search or start from a different port.":"Try a different search query"})]})}):null]}),(0,J.jsxs)("section",{className:d("flex min-h-0 flex-col",le&&Le.length?"flex-1":"shrink-0"),children:[We("Custom nodes",Le.length,le,()=>{ce(e=>!e),se(0)}),le?(0,J.jsx)("div",{className:d(Le.length?"min-h-0 flex-1 overflow-auto":"shrink-0"),children:Le.length?Le.map((e,t)=>Ge(e,(ie?$e.length:0)+t)):(0,J.jsx)("div",{className:"px-4 py-3 text-center text-xs text-modiff-subtle-text",children:"No matching enabled custom nodes"})}):null]})]})]})};export{ee as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ao as n,D as o,Di as s,E as i,Et as r,Ln as l,M as c,Mo as d,Ni as u,O as f,Oi as p,Oo as h,P as m,Q as x,Ti as g,Xr as b,Z as y,Zr as k,ai as v,bn as j,ca as C,ci as w,dc as N,ii as S,lc as D,ln as I,o as E,q as T,ri as M,wi as A,wn as B}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as H}from"./huggingFaceCatalogAdmission.js?v=ca6b74e6a02eedb3";import{n as F}from"./operationCatalog.js?v=ca6b74e6a02eedb3";import{a as O}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{t as $}from"./NodeDiscoveryFilters.js?v=ca6b74e6a02eedb3";import{a as L,i as R,n as _,o as K,r as P,t as V}from"./nodeConnectionSearch.js?v=ca6b74e6a02eedb3";var G=e(a(),1);function W(){throw Error("Invalid registered Block interface index.")}function q(e){return("string"!=typeof e||!e||e.length>2048||/\p{Cc}/u.test(e))&&W(),e}function z(e){(!Array.isArray(e)||e.length>512)&&W();let t=e.map(e=>{(!C(e)||"portId,valueType"!==Object.keys(e).sort().join(","))&&W();let t=Array.isArray(e.valueType)?e.valueType.length&&e.valueType.length<=64?e.valueType.map(q):W():q(e.valueType);return{portId:q(e.portId),valueType:t}});return new Set(t.map(e=>e.portId)).size!==t.length&&W(),t}function Z(e){(!C(e)||"entries,error,schemaVersion"!==Object.keys(e).sort().join(",")||1!==e.schemaVersion||!1!==e.error||!Array.isArray(e.entries)||e.entries.length>2048)&&W();let t=e.entries.map(e=>{(!C(e)||"admissionId,catalogDefinitionContentHash,catalogDefinitionId,compiledDefinitionCanonicalSha256,compiledDefinitionContentHash,inputs,outputs"!==Object.keys(e).sort().join(","))&&W();let t={catalogDefinitionId:q(e.catalogDefinitionId),catalogDefinitionContentHash:q(e.catalogDefinitionContentHash),admissionId:q(e.admissionId),compiledDefinitionContentHash:q(e.compiledDefinitionContentHash),compiledDefinitionCanonicalSha256:q(e.compiledDefinitionCanonicalSha256),inputs:z(e.inputs),outputs:z(e.outputs)};return/^sha256:[a-f0-9]{64}$/u.test(t.compiledDefinitionCanonicalSha256)||W(),t});return new Set(t.map(e=>`${e.catalogDefinitionId}\0${e.admissionId}`)).size!==t.length&&W(),t}var Q=null,U=N(e=>({entries:[],loaded:!1,error:null,fetch:()=>Q||(Q=(async()=>{try{e({entries:await n(`${D.serverAddress}/huggingface/registered-block-interfaces`,{parse:Z,timeoutMs:3e4}),loaded:!0,error:null})}catch(t){e({entries:[],loaded:!0,error:h(t,"Could not load Block interfaces.")})}})().finally(()=>{Q=null}),Q)}));function X(e,t,a,n,s,i,r,l=!1){return S(e,n,s).flatMap(({entries:e})=>e).filter(e=>{if(!e.insertable||"component"===e.kind)return!1;if(!r)return!0;let n=null;if("cluster"===e.kind){let o=t.library.definitions.find(t=>t.id===e.id),s=o?H(o,t.form).route:null;s&&(n=function(e,t){let a=e.find(e=>e.catalogDefinitionId===t.definitionId&&e.admissionId===t.admissionId);if(!a||a.catalogDefinitionContentHash!==t.definitionContentHash||a.compiledDefinitionContentHash!==t.compiledDefinitionContentHash||a.compiledDefinitionCanonicalSha256!==t.compiledDefinitionCanonicalSha256)return null;let n={};for(let[e,t]of[["input",a.inputs],["output",a.outputs]])for(let a of t)n[`${e}:${a.portId}`]={display:e,type:a.valueType};return{type:"block",module:"",action:"",label:"",category:"",params:n}}(a,s))}else{if(f(e,t.library,t.snapshot))return!1;try{n=o(e,t.library,t.registry,{x:0,y:0},t.snapshot).data}catch{return!1}}return!(!n||!d(n,i,r,void 0,l))})}async function J(e,t,a,n){if(n.aborted)throw new DOMException("Insertion cancelled.","AbortError");if(!e.insertable)throw Error("This catalog entry is not available for insertion.");if("block"===e.kind)return f(e,t.library,t.snapshot)?i(e,t.library,t.registry,a,t.snapshot):o(e,t.library,t.registry,a,t.snapshot);let s=t.library.definitions.find(t=>t.id===e.id);if("cluster"!==e.kind||!s)throw Error("The selected catalog Block is no longer available.");let{createHuggingFaceClusterForGraph:r}=await g(async()=>{let{createHuggingFaceClusterForGraph:e}=await import(`./huggingFaceClusterInsertion.js?v=ca6b74e6a02eedb3`).then(e=>e.n);return{createHuggingFaceClusterForGraph:e}},[]);return r(s,a,t.form,{insert:!1,signal:n})}var Y=t(),ee=({anchorPosition:e,onClose:t,onSelect:a,nodes:n,dataType:o,handleType:i,origin:f})=>{let{pipeline:g,task:C,view:N,support:S}=y(),D=A(e=>e.operationContracts),H=A(e=>e.resolveOperation),W=u(e=>e.activeWorkflowTabId),q=u(e=>e.workflowCanvasEpoch),z=(0,G.useRef)(null),[Z,Q]=(0,G.useState)(!1),[ee,te]=(0,G.useState)(null),[ae,ne]=(0,G.useState)(""),[oe,se]=(0,G.useState)(0),[ie,re]=(0,G.useState)(!0),[le,ce]=(0,G.useState)(!0),[de,ue]=(0,G.useState)(!1),fe=(0,G.useRef)(null),pe=w(e=>e.blocks),he=w(e=>e.blockDefinitionsV2),me=w(e=>e.loaded),xe=w(e=>e.fetchBlocks),ge=w(e=>e.error),be=(0,G.useMemo)(()=>L([...he,...pe]),[he,pe]),ye=k(e=>e.library),ke=k(e=>e.loaded),ve=k(e=>e.error),je=k(e=>e.fetchLibrary),Ce=b(e=>e.snapshot),we=b(e=>e.loaded),Ne=b(e=>e.error),Se=b(e=>e.fetchSnapshot),De=U(e=>e.entries),Ie=U(e=>e.loaded),Ee=U(e=>e.error),Te=U(e=>e.fetch),Me=u(e=>e.form),Ae=(0,G.useMemo)(()=>ye?{library:ye,snapshot:Ce,registry:n,form:Me}:null,[ye,Ce,n,Me]),Be=(0,G.useMemo)(()=>ye?M(ye,Ce):[],[ye,Ce]),He=(0,G.useMemo)(()=>Ae?X(Be,Ae,De,ae,N,o,i,de):[],[Be,Ae,De,ae,N,o,i,de]);(0,G.useEffect)(()=>{ke||je()},[ke,je]),(0,G.useEffect)(()=>{we||Se()},[we,Se]),(0,G.useEffect)(()=>{i&&!Ie&&Te()},[i,Ie,Te]),(0,G.useEffect)(()=>{me||xe()},[me,xe]),(0,G.useEffect)(()=>{if(e){let e=setTimeout(()=>{fe.current&&fe.current.focus()},10);return()=>clearTimeout(e)}},[e]);let Fe=(0,G.useMemo)(()=>E(n,D,S,N,{pipeline:g,task:C}),[n,D,S,N,g,C]),Oe=(0,G.useMemo)(()=>R([..._(D,g,C,o,i,ae,n,f,de).map(e=>({key:`operation:${e.operationId}`,label:F(e),operation:e,node:n[e.nodeKey]})),...V(Fe,o,i,ae,N,f,de).map(([e,t])=>({key:e,node:t,label:v(t)})),...He.map(e=>({key:`catalog:${e.id}`,label:e.label,catalog:e})),...be.filter(({block:e,node:t})=>m(e,ae)&&(!i||d(t,o,i,f,de))).map(e=>({...e,label:e.node.label}))],o,i,f),[Fe,D,g,C,N,o,i,ae,be,n,He,f,de]),{builtInEntries:$e,customEntries:Le}=(0,G.useMemo)(()=>({builtInEntries:Oe.filter(e=>!e.node?.module.startsWith("custom.")),customEntries:Oe.filter(e=>e.node?.module.startsWith("custom."))}),[Oe]),Re=(0,G.useMemo)(()=>[...ie?$e:[],...le?Le:[]],[$e,ie,Le,le]);(0,G.useEffect)(()=>(z.current?.abort(),z.current=null,Q(!1),te(null),()=>{z.current?.abort()}),[g,C,N,W,q,e]);let _e=Math.min(oe,Math.max(0,Re.length-1)),Ke=(0,G.useCallback)(()=>{z.current?.abort(),t(),setTimeout(()=>{ne(""),se(0)},0)},[t]),Pe=(0,G.useCallback)(async e=>{if(z.current)return;let t=new AbortController,n=p(),r=x.getState().selection;z.current=t,Q(!0),te(null);try{let l;if(e.operation){let a=e.operation,n=O(P(await H(a,t.signal),a,o,i),a);l=e=>T(a.nodeKey,{[a.nodeKey]:n},e)}else if(e.catalog&&Ae){let a=e.catalog;l=async e=>{let n=await J(a,Ae,e,t.signal);if(k.getState().library!==Ae.library)throw Error("The catalog changed. Select the Block again.");return n}}else if(e.block){let t=e.block;l=e=>c(t,e)}else{if(!e.node)return;{let t=e.node;l=a=>T(e.key,{[e.key]:t},a)}}if(t.signal.aborted||x.getState().selection!==r||(s(n,{includeForm:!1}),await a(l,t.signal,de),t.signal.aborted))return;Ke()}catch(e){t.signal.aborted||te(h(e,"Could not resolve the selected node."))}finally{z.current===t&&(z.current=null,Q(!1))}},[H,a,Ke,o,i,Ae,de]),Ve=(0,G.useCallback)(e=>{switch(e.key){case"ArrowDown":e.preventDefault(),Re.length>0&&se(e=>(e+1)%Re.length);break;case"ArrowUp":e.preventDefault(),Re.length>0&&se(e=>(e-1+Re.length)%Re.length);break;case"Enter":Re[_e]&&Pe(Re[_e]);break;case"Escape":Ke()}},[Re,_e,Pe,Ke]);if(!e)return null;let Ge=(e,t)=>(0,Y.jsxs)(r,{type:"button",id:`node-search-${t}`,role:"option","aria-selected":t===_e,disabled:Z,"aria-busy":Z||void 0,onClick:()=>{Pe(e)},className:l("block w-full px-3 py-2 text-left transition hover:bg-modiff-surface-hover",t===_e&&"bg-modiff-surface"),children:[(0,Y.jsx)("div",{className:"truncate text-sm text-modiff-text",children:e.label}),e.block?(0,Y.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["Saved Block · ",e.revision]}):null,e.catalog?(0,Y.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:["cluster"===e.catalog.kind?"Block":"Implementation"," · ",e.catalog.readinessLabel]}):null,e.operation?(0,Y.jsxs)("div",{className:"text-xs text-modiff-subtle-text",children:[e.operation.pipelineClass," · ",e.operation.task?.replace(/_/gu," ")]}):null,e.node?.description?(0,Y.jsx)("div",{className:"truncate text-xs text-modiff-subtle-text",children:e.node.description.substring(0,72)+(e.node.description.length>72?"...":"")}):null]},e.key),We=(e,t,a,n)=>(0,Y.jsxs)(r,{type:"button","aria-expanded":a,onClick:n,className:"flex w-full shrink-0 items-center gap-2 border-b border-modiff-border px-3 py-2 text-left text-xs font-semibold text-modiff-text",children:[(0,Y.jsx)("span",{"aria-hidden":"true",children:a?"▾":"▸"}),(0,Y.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e}),(0,Y.jsx)("span",{className:"text-modiff-subtle-text",children:t})]});return(0,Y.jsxs)(B,{anchor:e,ariaLabel:"Search nodes",closeOnOutside:!1,gap:0,modal:!0,onClose:Ke,open:!0,panelClassName:"flex h-[min(512px,calc(100dvh-16px))] w-[368px] flex-col overflow-hidden border-4 border-modiff-bg bg-modiff-panel",placement:"bottom-start",children:[(0,Y.jsx)("div",{className:"shrink-0 p-2",children:(0,Y.jsx)(j,{ref:fe,"aria-label":"Search nodes","aria-activedescendant":Re[_e]?`node-search-${_e}`:void 0,autoFocus:!0,placeholder:"Search nodes and Blocks",value:ae,onChange:e=>{ne(e.currentTarget.value),se(0)},onClear:()=>{ne(""),se(0)},onKeyDown:e=>{Ve(e.nativeEvent)}})}),(0,Y.jsx)($,{}),(0,Y.jsx)(K,{inPopover:!0}),ee?(0,Y.jsx)("p",{role:"alert",className:"px-3 pb-2 text-xs text-modiff-text",children:ee}):null,me?null:(0,Y.jsx)("p",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Loading Saved Blocks…"}),ge?(0,Y.jsxs)("div",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:["Saved Blocks could not be loaded.",(0,Y.jsx)(r,{onClick:()=>{xe()},children:"Retry Saved Blocks"})]}):null,!ke||!we||i&&!Ie?(0,Y.jsx)("p",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:"Loading catalog Blocks…"}):null,ve||Ne||i&&Ee?(0,Y.jsxs)("div",{role:"status",className:"px-3 pb-2 text-xs text-modiff-subtle-text",children:["Some catalog Blocks or compatible ports could not be loaded.",(0,Y.jsx)(r,{onClick:()=>{ve&&je(),Ne&&Se(),Ee&&Te()},children:"Retry catalog"})]}):null,i?(0,Y.jsxs)("div",{className:"shrink-0 px-3 pb-2 text-xs text-modiff-subtle-text",children:[(0,Y.jsx)(I,{checked:de,onCheckedChange:ue,label:"Show unverified matches (generic or missing types)"}),(0,Y.jsx)("p",{children:"source"===i?"Nodes with matching input port types":"Nodes with matching output port types"}),(0,Y.jsx)("p",{children:"Model, shape, and custom-code constraints are checked when declared and again at Run."})]}):null,(0,Y.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",role:"listbox","aria-label":"Matching nodes",children:[(0,Y.jsxs)("section",{className:l("flex min-h-0 flex-col",ie&&$e.length?"flex-1":"shrink-0"),children:[We("Built-in nodes and Blocks",$e.length,ie,()=>{re(e=>!e),se(0)}),ie?(0,Y.jsx)("div",{className:l($e.length?"min-h-0 flex-1 overflow-auto":"shrink-0"),children:$e.length?$e.map((e,t)=>Ge(e,t)):(0,Y.jsxs)("div",{className:"px-4 py-4 text-center",children:[(0,Y.jsx)("div",{className:"text-sm font-semibold text-modiff-text",children:i?"No compatible nodes found":"No results found"}),(0,Y.jsx)("div",{className:"text-xs text-modiff-subtle-text",children:i?"Try another search or start from a different port.":"Try a different search query"})]})}):null]}),(0,Y.jsxs)("section",{className:l("flex min-h-0 flex-col",le&&Le.length?"flex-1":"shrink-0"),children:[We("Custom nodes",Le.length,le,()=>{ce(e=>!e),se(0)}),le?(0,Y.jsx)("div",{className:l(Le.length?"min-h-0 flex-1 overflow-auto":"shrink-0"),children:Le.length?Le.map((e,t)=>Ge(e,(ie?$e.length:0)+t)):(0,Y.jsx)("div",{className:"px-4 py-3 text-center text-xs text-modiff-subtle-text",children:"No matching enabled custom nodes"})}):null]})]})]})};export{ee as default}; \ No newline at end of file diff --git a/web/assets/OperationCatalogPanel.js b/web/assets/OperationCatalogPanel.js index a909b91..091cc36 100644 --- a/web/assets/OperationCatalogPanel.js +++ b/web/assets/OperationCatalogPanel.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ei as o,Eo as s,Pt as n,Q as r,Si as i,Ti as l,X as d,Y as p,Z as c,ji as u}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as m}from"./operationCatalog.js?v=cc046c26d6fe7aa4";import{a as f}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{t as x}from"./OperationGraphControls.js?v=cc046c26d6fe7aa4";import{n as h,o as b}from"./nodeConnectionSearch.js?v=cc046c26d6fe7aa4";var g=e(a(),1),j=t();function v({search:e,onInsert:t}){let a=i(e=>e.operationContracts),v=i(e=>e.nodesRegistry),k=i(e=>e.resolveOperation),N=u(e=>e.activeWorkflowTabId),{pipeline:w,task:C,selected:S,support:y}=c(),E=u(e=>e.workflowCanvasEpoch),[D,R]=(0,g.useState)(!1),[I,T]=(0,g.useState)(null),$=(0,g.useRef)(null),A=(0,g.useMemo)(()=>S?h(a,w,S.task,void 0,void 0,e,v):[],[a,w,S,e,v]);return(0,g.useEffect)(()=>($.current?.abort(),$.current=null,R(!1),T(null),()=>{$.current?.abort()}),[w,C,N,E]),y.length?(0,j.jsxs)("section",{"aria-label":"Diffusers operations",className:"mb-2 border-b border-modiff-border pb-2",children:[(0,j.jsxs)("div",{className:"space-y-2 px-2 pb-2",children:[(0,j.jsx)(b,{}),S?(0,j.jsxs)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:["adapter"===S.execution?"Execution adapter available.":"declared"===S.execution?"Declared nodes; no execution adapter.":"No operation binding for this task."," ","pipeline"===S.decomposition?"Whole pipeline call.":"stages"===S.decomposition?"Editable nodes.":""," ","blocked"===S.dependencies?"Runtime setup required in Setup.":"ready"===S.dependencies?"Runtime available; Run still checks models and resources.":"Runtime support unverified."]}):null,I?(0,j.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:I}):null]}),S?.operationIds.length?(0,j.jsx)(x,{pipeline:w,task:S.task}):null,A.map(e=>(0,j.jsxs)(n,{level:0,draggable:!D,onDragStart:t=>{D?t.preventDefault():(t.dataTransfer.setData("text/plain",p(e)),t.dataTransfer.effectAllowed="move")},onDragEnd:d,disabled:D,"aria-busy":D||void 0,onClick:()=>{!async function(e){if($.current)return;let a=o(),n=r.getState().selection,i=new AbortController;$.current=i,R(!0),T(null);try{let o=await k(e,i.signal);if(i.signal.aborted||r.getState().selection!==n)return;l(a,{includeForm:!1}),t(`${o.module}.${o.action}`,f(o,e))}catch(e){i.signal.aborted||T(s(e,"Could not resolve the selected operation."))}finally{$.current===i&&($.current=null,R(!1))}}(e)},title:`Add ${m(e)} for ${e.pipelineClass}. ${"pipeline"===e.decomposition?"This operation calls the complete pipeline.":"Uses the existing node execution path."}`,children:[(0,j.jsx)("span",{className:"min-w-0 flex-1 break-words",children:m(e)}),(0,j.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:"pipeline"===e.decomposition?"Pipeline":"loader"===e.decomposition?"Load":"Node"})]},e.operationId)),S&&!A.length&&S.operationIds.length>0?(0,j.jsx)("p",{className:"px-2 text-xs text-modiff-subtle-text",children:"No operations match this search."}):null]}):null}export{v as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Di as o,Ft as s,Ni as n,Oi as r,Oo as i,Q as l,X as d,Y as p,Z as c,wi as u}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as m}from"./operationCatalog.js?v=ca6b74e6a02eedb3";import{a as f}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{t as x}from"./OperationGraphControls.js?v=ca6b74e6a02eedb3";import{n as h,o as b}from"./nodeConnectionSearch.js?v=ca6b74e6a02eedb3";var g=e(a(),1),j=t();function v({search:e,onInsert:t}){let a=u(e=>e.operationContracts),v=u(e=>e.nodesRegistry),k=u(e=>e.resolveOperation),N=n(e=>e.activeWorkflowTabId),{pipeline:w,task:C,selected:y,support:D}=c(),S=n(e=>e.workflowCanvasEpoch),[R,E]=(0,g.useState)(!1),[I,$]=(0,g.useState)(null),A=(0,g.useRef)(null),O=(0,g.useMemo)(()=>y?h(a,w,y.task,void 0,void 0,e,v):[],[a,w,y,e,v]);return(0,g.useEffect)(()=>(A.current?.abort(),A.current=null,E(!1),$(null),()=>{A.current?.abort()}),[w,C,N,S]),D.length?(0,j.jsxs)("section",{"aria-label":"Diffusers operations",className:"mb-2 border-b border-modiff-border pb-2",children:[(0,j.jsxs)("div",{className:"space-y-2 px-2 pb-2",children:[(0,j.jsx)(b,{}),y?(0,j.jsxs)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:["adapter"===y.execution?"Execution adapter available.":"declared"===y.execution?"Declared nodes; no execution adapter.":"No operation binding for this task."," ","pipeline"===y.decomposition?"Whole pipeline call.":"stages"===y.decomposition?"Editable nodes.":""," ","blocked"===y.dependencies?"Runtime setup required in Setup.":"ready"===y.dependencies?"Runtime available; Run still checks models and resources.":"Runtime support unverified."]}):null,I?(0,j.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:I}):null]}),y?.operationIds.length?(0,j.jsx)(x,{pipeline:w,task:y.task}):null,O.map(e=>(0,j.jsxs)(s,{level:0,draggable:!R,onDragStart:t=>{R?t.preventDefault():(t.dataTransfer.setData("text/plain",p(e)),t.dataTransfer.effectAllowed="move")},onDragEnd:d,disabled:R,"aria-busy":R||void 0,onClick:()=>{!async function(e){if(A.current)return;let a=r(),s=l.getState().selection,n=new AbortController;A.current=n,E(!0),$(null);try{let r=await k(e,n.signal);if(n.signal.aborted||l.getState().selection!==s)return;o(a,{includeForm:!1}),t(`${r.module}.${r.action}`,f(r,e))}catch(e){n.signal.aborted||$(i(e,"Could not resolve the selected operation."))}finally{A.current===n&&(A.current=null,E(!1))}}(e)},title:`Add ${m(e)} for ${e.pipelineClass}. ${"pipeline"===e.decomposition?"This operation calls the complete pipeline.":"Uses the existing node execution path."}`,children:[(0,j.jsx)("span",{className:"min-w-0 flex-1 break-words",children:m(e)}),(0,j.jsx)("span",{className:"text-xs text-modiff-subtle-text",children:"pipeline"===e.decomposition?"Pipeline":"loader"===e.decomposition?"Load":"Node"})]},e.operationId)),y&&!O.length&&y.operationIds.length>0?(0,j.jsx)("p",{className:"px-2 text-xs text-modiff-subtle-text",children:"No operations match this search."}):null]}):null}export{v as default}; \ No newline at end of file diff --git a/web/assets/OperationGraphControls.js b/web/assets/OperationGraphControls.js index c17ffb4..1d6dfcd 100644 --- a/web/assets/OperationGraphControls.js +++ b/web/assets/OperationGraphControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as r}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$ as n,Bo as a,Ci as s,Ei as l,Eo as i,Jo as o,Si as d,Ti as c,Vr as p,bn as u,dn as h,fn as g,in as m,ji as x,rc as j,rn as f}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as b}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{t as w}from"./operationStarterRequest.js?v=cc046c26d6fe7aa4";import{r as k,t as v}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{t as C}from"./NodeInspectorDialog.js?v=cc046c26d6fe7aa4";var I=e(r(),1),y=t();function S({pipeline:e,task:t,ownerId:r,blockId:S,executionProfileId:N}){let O=p(e=>e.nodes),E=x(e=>e.activeWorkflowTabId),B=x(e=>e.workflowCanvasEpoch),A=d(e=>e.operationContracts),[R,T]=(0,I.useState)(""),q=r??R,[P,_]=(0,I.useState)(!1),[$,F]=(0,I.useState)(null),[J,U]=(0,I.useState)(null),[D,M]=(0,I.useState)(!1),V=(0,I.useRef)(null),G=O.filter(e=>!e.parentId&&!e.data.blockProjectionOwnerId&&j(e.data.operationAuthoring?.operation)),L=O.find(e=>e.selected&&e.data.operationAuthoring),W=L?o(L):null;async function K(r){if(V.current)return;let n=new AbortController;V.current=n;let a=l(),o=p.getState().toObject(),d=JSON.stringify(o);_(!0),F(null);try{let l=await w(e,t,A,n.signal,N);if(n.signal.aborted)return;if(c(a,{includeForm:!1}),JSON.stringify(p.getState().toObject())!==d)throw Error("The graph changed. Request a fresh preview.");let i=r?S?(await s(async()=>{let{planOwnerBlockOperationChange:e}=await import(`./operationLegacyBlockChange.js?v=cc046c26d6fe7aa4`).then(e=>e.t);return{planOwnerBlockOperationChange:e}},[])).planOwnerBlockOperationChange(o,S,q,l,{replaceModel:!!N}):k(o,q,l,{replaceModel:!!N}):null;if(n.signal.aborted)return;if(c(a,{includeForm:!1}),JSON.stringify(p.getState().toObject())!==d)throw Error("The graph changed. Request a fresh preview.");U({starter:l,plan:i,context:a,signature:d})}catch(e){n.signal.aborted||F(i(e,"Could not prepare the graph."))}finally{V.current===n&&(V.current=null,_(!1))}}return(0,I.useEffect)(()=>(V.current?.abort(),V.current=null,_(!1),U(null),F(null),M(!1),()=>{V.current?.abort()}),[e,t,E,B,q,S,N]),(0,y.jsxs)("div",{className:"space-y-2 px-2 pb-2",children:[r?null:(0,y.jsx)(f,{disabled:P,onClick:()=>{K(!1)},children:"Preview connected starter"}),S||G.length?(0,y.jsxs)(y.Fragment,{children:[r?null:(0,y.jsx)(g,{label:"Graph to change",children:(0,y.jsx)(u,{"aria-label":"Operation graph to change",value:q,onValueChange:T,options:[{value:"",label:"Select a loader on this canvas"},...G.map(e=>({value:e.id,label:`${e.data.operationAuthoring.operation.pipelineClass} · ${e.id.slice(-6)}`}))]})}),(0,y.jsx)(f,{disabled:P||!S&&!G.some(e=>e.id===q),onClick:()=>{K(!0)},children:"Preview model / task change"})]}):null,!r&&W?(0,y.jsx)(f,{onClick:()=>M(!0),children:"Inspect selected node"}):null,P?(0,y.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Preparing ordinary nodes and connections…"}):null,$?(0,y.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:$}):null,J?(0,y.jsx)(m,{open:!0,title:J.plan?"Review model / task change":"Connected starter",onClose:()=>{U(null),F(null)},children:(0,y.jsxs)("div",{className:"space-y-3 text-sm",children:[(0,y.jsxs)("p",{children:[J.starter.pipelineClass," · ",J.starter.task.replace(/_/gu," ")]}),(0,y.jsx)("p",{children:J.starter.nodes.map(e=>e.node.label).join(" → ")}),(0,y.jsxs)("p",{children:[S?"The result updates the editable graph inside this Block.":"The result is an editable canvas graph."," ","Run checks model files, runtime support, required inputs and resources."]}),(0,y.jsx)("p",{children:"Connect the final result to a Preview, Save or Export node before running. Drag from its output to see compatible nodes."}),J.starter.sharedInputs.map((e,t)=>(0,y.jsxs)("p",{children:["Shared ",e.name,":"," ",e.members.map(e=>e.operationId.split(".")[1]?.replace(/_/gu," ")).join(", "),". Editing either control updates the group.","seed"===e.name?" Random mode draws one value per run.":""]},t)),J.starter.requiredInputs.length?(0,y.jsxs)("div",{children:[(0,y.jsx)("p",{children:"Provide or connect the required inputs:"}),(0,y.jsx)("ul",{className:"list-inside list-disc",children:J.starter.requiredInputs.map(e=>(0,y.jsxs)("li",{children:[e.operationId.split(".")[1]?.replace(/_/gu," ")," · ",e.field]},`${e.operationId}:${e.field}`))})]}):null,J.plan?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)("ul",{className:"list-inside list-disc",children:J.plan.changes.map((e,t)=>(0,y.jsx)("li",{children:e},t))}),J.plan.diagnostics.length?(0,y.jsxs)("div",{role:"status",children:[(0,y.jsx)("p",{children:"Review before applying:"}),(0,y.jsx)("ul",{className:"list-inside list-disc",children:J.plan.diagnostics.map((e,t)=>(0,y.jsx)("li",{children:e},t))})]}):null,(0,y.jsx)("p",{children:"Custom nodes are retained. Unsupported settings remain available in the inspector’s Implementation tab. Undo restores the entire change."})]}):null,(0,y.jsxs)(h,{label:"Inspect implementation",children:[(0,y.jsx)("p",{children:J.starter.workflowId?`Upstream workflow: ${J.starter.workflowId}`:"Whole pipeline adapter"}),(0,y.jsx)("ul",{className:"list-inside list-disc",children:J.starter.nodes.map(e=>(0,y.jsxs)("li",{children:[e.node.label,": ",e.operation.nodeKey,e.operation.blockName?` / ${e.operation.blockName}`:""]},e.operation.operationId))}),J.starter.upstreamBlocks.length?(0,y.jsx)("p",{className:"break-words",children:J.starter.upstreamBlocks.join(" → ")}):null,(0,y.jsx)("p",{children:"Inspection does not expand or convert saved Blocks. Use the existing Block composition inspector for structural editing."})]}),$?(0,y.jsx)("p",{role:"alert",children:$}):null,(0,y.jsxs)("div",{className:"flex gap-2",children:[(0,y.jsx)(f,{onClick:function(){if(J)try{c(J.context,{includeForm:!1});let e=p.getState();if(JSON.stringify(e.toObject())!==J.signature)throw Error("The graph changed after this preview. Close it and request a fresh preview.");if(J.plan)b(J.plan.graph,J.context,J.signature,"Change operation model or task");else{let t=e.nodes.length?Math.max(...e.nodes.map(e=>e.position.x+(e.measured?.width??e.width??360)))+100:80,r=a(v(J.starter,{x:t,y:120}));n(),b({nodes:[...e.nodes,...r.nodes],edges:[...e.edges,...r.edges]},l(),J.signature,"Add operation starter")}U(null)}catch(e){F(i(e,"Could not apply the graph change."))}},children:J.plan?"Apply graph change":"Add starter to canvas"}),(0,y.jsx)(f,{onClick:()=>{U(null),F(null)},children:"Cancel"})]})]})}):null,D&&L&&W?(0,y.jsx)(C,{nodeId:L.id,onClose:()=>M(!1)},L.id):null]})}export{S as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Di as r,Hr as a,Ni as s,Oi as l,Oo as i,Ti as o,Uo as d,Zo as c,an as p,et as u,fn as h,in as g,oc as m,pn as x,wi as j,xn as f}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as w}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{t as b}from"./operationStarterRequest.js?v=ca6b74e6a02eedb3";import{r as k,t as v}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{t as C}from"./NodeInspectorDialog.js?v=ca6b74e6a02eedb3";var I=e(n(),1),O=t();function y({pipeline:e,task:t,ownerId:n,blockId:y,executionProfileId:N}){let S=a(e=>e.nodes),A=s(e=>e.activeWorkflowTabId),B=s(e=>e.workflowCanvasEpoch),E=j(e=>e.operationContracts),[R,T]=(0,I.useState)(""),q=n??R,[P,_]=(0,I.useState)(!1),[$,F]=(0,I.useState)(null),[U,D]=(0,I.useState)(null),[J,M]=(0,I.useState)(!1),G=(0,I.useRef)(null),L=S.filter(e=>!e.parentId&&!e.data.blockProjectionOwnerId&&m(e.data.operationAuthoring?.operation)),V=S.find(e=>e.selected&&e.data.operationAuthoring),W=V?c(V):null;async function H(n){if(G.current)return;let s=new AbortController;G.current=s;let d=l(),c=a.getState().toObject(),p=JSON.stringify(c);_(!0),F(null);try{let l=await b(e,t,E,s.signal,N);if(s.signal.aborted)return;if(r(d,{includeForm:!1}),JSON.stringify(a.getState().toObject())!==p)throw Error("The graph changed. Request a fresh preview.");let i=n?y?(await o(async()=>{let{planOwnerBlockOperationChange:e}=await import(`./operationLegacyBlockChange.js?v=ca6b74e6a02eedb3`).then(e=>e.t);return{planOwnerBlockOperationChange:e}},[])).planOwnerBlockOperationChange(c,y,q,l,{replaceModel:!!N}):k(c,q,l,{replaceModel:!!N}):null;if(s.signal.aborted)return;if(r(d,{includeForm:!1}),JSON.stringify(a.getState().toObject())!==p)throw Error("The graph changed. Request a fresh preview.");D({starter:l,plan:i,context:d,signature:p})}catch(e){s.signal.aborted||F(i(e,"Could not prepare the graph."))}finally{G.current===s&&(G.current=null,_(!1))}}return(0,I.useEffect)(()=>(G.current?.abort(),G.current=null,_(!1),D(null),F(null),M(!1),()=>{G.current?.abort()}),[e,t,A,B,q,y,N]),(0,O.jsxs)("div",{className:"space-y-2 px-2 pb-2",children:[n?null:(0,O.jsx)(g,{disabled:P,onClick:()=>{H(!1)},children:"Preview connected starter"}),y||L.length?(0,O.jsxs)(O.Fragment,{children:[n?null:(0,O.jsx)(x,{label:"Graph to change",children:(0,O.jsx)(f,{"aria-label":"Operation graph to change",value:q,onValueChange:T,options:[{value:"",label:"Select a loader on this canvas"},...L.map(e=>({value:e.id,label:`${e.data.operationAuthoring.operation.pipelineClass} · ${e.id.slice(-6)}`}))]})}),(0,O.jsx)(g,{disabled:P||!y&&!L.some(e=>e.id===q),onClick:()=>{H(!0)},children:"Preview model / task change"})]}):null,!n&&W?(0,O.jsx)(g,{onClick:()=>M(!0),children:"Inspect selected node"}):null,P?(0,O.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Preparing ordinary nodes and connections…"}):null,$?(0,O.jsx)("p",{role:"alert",className:"text-xs text-modiff-text",children:$}):null,U?(0,O.jsx)(p,{open:!0,title:U.plan?"Review model / task change":"Connected starter",onClose:()=>{D(null),F(null)},children:(0,O.jsxs)("div",{className:"space-y-3 text-sm",children:[(0,O.jsxs)("p",{children:[U.starter.pipelineClass," · ",U.starter.task.replace(/_/gu," ")]}),(0,O.jsx)("p",{children:U.starter.nodes.map(e=>e.node.label).join(" → ")}),(0,O.jsxs)("p",{children:[y?"The result updates the editable graph inside this Block.":"The result is an editable canvas graph."," ","Run checks model files, runtime support, required inputs and resources."]}),(0,O.jsx)("p",{children:"Connect the final result to a Preview, Save or Export node before running. Drag from its output to see compatible nodes."}),U.starter.sharedInputs.map((e,t)=>(0,O.jsxs)("p",{children:["Shared ",e.name,":"," ",e.members.map(e=>e.operationId.split(".")[1]?.replace(/_/gu," ")).join(", "),". Editing either control updates the group.","seed"===e.name?" Random mode draws one value per run.":""]},t)),U.starter.requiredInputs.length?(0,O.jsxs)("div",{children:[(0,O.jsx)("p",{children:"Provide or connect the required inputs:"}),(0,O.jsx)("ul",{className:"list-inside list-disc",children:U.starter.requiredInputs.map(e=>(0,O.jsxs)("li",{children:[e.operationId.split(".")[1]?.replace(/_/gu," ")," · ",e.field]},`${e.operationId}:${e.field}`))})]}):null,U.plan?(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)("ul",{className:"list-inside list-disc",children:U.plan.changes.map((e,t)=>(0,O.jsx)("li",{children:e},t))}),U.plan.diagnostics.length?(0,O.jsxs)("div",{role:"status",children:[(0,O.jsx)("p",{children:"Review before applying:"}),(0,O.jsx)("ul",{className:"list-inside list-disc",children:U.plan.diagnostics.map((e,t)=>(0,O.jsx)("li",{children:e},t))})]}):null,(0,O.jsx)("p",{children:"Custom nodes are retained. Unsupported settings remain available in the inspector’s Implementation tab. Undo restores the entire change."})]}):null,(0,O.jsxs)(h,{label:"Inspect implementation",children:[(0,O.jsx)("p",{children:U.starter.workflowId?`Upstream workflow: ${U.starter.workflowId}`:"Whole pipeline adapter"}),(0,O.jsx)("ul",{className:"list-inside list-disc",children:U.starter.nodes.map(e=>(0,O.jsxs)("li",{children:[e.node.label,": ",e.operation.nodeKey,e.operation.blockName?` / ${e.operation.blockName}`:""]},e.operation.operationId))}),U.starter.upstreamBlocks.length?(0,O.jsx)("p",{className:"break-words",children:U.starter.upstreamBlocks.join(" → ")}):null,(0,O.jsx)("p",{children:"Inspection does not expand or convert saved Blocks. Use the existing Block composition inspector for structural editing."})]}),$?(0,O.jsx)("p",{role:"alert",children:$}):null,(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(g,{onClick:function(){if(U)try{r(U.context,{includeForm:!1});let e=a.getState();if(JSON.stringify(e.toObject())!==U.signature)throw Error("The graph changed after this preview. Close it and request a fresh preview.");if(U.plan)w(U.plan.graph,U.context,U.signature,"Change operation model or task");else{let t=e.nodes.length?Math.max(...e.nodes.map(e=>e.position.x+(e.measured?.width??e.width??360)))+100:80,n=d(v(U.starter,{x:t,y:120}));u(),w({nodes:[...e.nodes,...n.nodes],edges:[...e.edges,...n.edges]},l(),U.signature,"Add operation starter")}D(null)}catch(e){F(i(e,"Could not apply the graph change."))}},children:U.plan?"Apply graph change":"Add starter to canvas"}),(0,O.jsx)(g,{onClick:()=>{D(null),F(null)},children:"Cancel"})]})]})}):null,J&&V&&W?(0,O.jsx)(C,{nodeId:V.id,onClose:()=>M(!1)},V.id):null]})}export{y as t}; \ No newline at end of file diff --git a/web/assets/OperationModelField.js b/web/assets/OperationModelField.js index 37c2b6b..3b978d9 100644 --- a/web/assets/OperationModelField.js +++ b/web/assets/OperationModelField.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as o,dr as t}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Jo as n,es as a,jn as d,rc as r}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as l}from"./operationLegacyBlockChange.js?v=cc046c26d6fe7aa4";import i from"./OperationModelPicker.js?v=cc046c26d6fe7aa4";var s=e(t(),1);function c(e,o){let t=(e,o)=>["model_id","repo_id"].includes(o)&&!!n(e)?.operation.task&&r(n(e)?.operation);if(t(e,o))return e;if(!e.data.blockInstanceV2&&!e.data.userBlockSnapshot||e.data.userBlockSnapshot&&e.data.uiState?.blockExpanded)return null;try{let n=l({nodes:[e],edges:[]},e.id).root.data.blockInstanceV2;if(!n)return null;let d=n.effectiveInterface.controls.find(e=>e.controlId===o);if(!d||d.sealed||d.mirrorBindings?.length)return null;let r=a(n).nodes.find(e=>e.data.blockProjectionNodeId===d.binding.nodeId);return r&&t(r,d.binding.fieldId)?{...r,data:{...r.data,blockProjectionOwnerId:e.id}}:null}catch{return null}}var f=o();function u({root:e,field:o,value:t,fallback:n}){let a=(0,s.useMemo)(()=>c(e,o.fieldKey),[e,o.fieldKey]);return a?(0,f.jsx)(d,{dataKey:o.fieldKey,hidden:o.hidden,layoutStyle:o.style,className:"modiff-field",children:(0,f.jsx)(i,{node:a,value:t,disabled:o.disabled||o.isConnected})}):n}export{u as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as o,dr as t}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Mn as n,Zo as a,oc as d,rs as r}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as l}from"./operationLegacyBlockChange.js?v=ca6b74e6a02eedb3";import i from"./OperationModelPicker.js?v=ca6b74e6a02eedb3";var s=e(t(),1);function c(e,o){let t=(e,o)=>["model_id","repo_id"].includes(o)&&!!a(e)?.operation.task&&d(a(e)?.operation);if(t(e,o))return e;if(!e.data.blockInstanceV2&&!e.data.userBlockSnapshot||e.data.userBlockSnapshot&&e.data.uiState?.blockExpanded)return null;try{let n=l({nodes:[e],edges:[]},e.id).root.data.blockInstanceV2;if(!n)return null;let a=n.effectiveInterface.controls.find(e=>e.controlId===o);if(!a||a.sealed||a.mirrorBindings?.length)return null;let d=r(n).nodes.find(e=>e.data.blockProjectionNodeId===a.binding.nodeId);return d&&t(d,a.binding.fieldId)?{...d,data:{...d.data,blockProjectionOwnerId:e.id}}:null}catch{return null}}var f=o();function u({root:e,field:o,value:t,fallback:a}){let d=(0,s.useMemo)(()=>c(e,o.fieldKey),[e,o.fieldKey]);return d?(0,f.jsx)(n,{dataKey:o.fieldKey,hidden:o.hidden,layoutStyle:o.style,className:"modiff-field",children:(0,f.jsx)(i,{node:d,value:t,disabled:o.disabled||o.isConnected})}):a}export{u as default}; \ No newline at end of file diff --git a/web/assets/OperationModelPicker.js b/web/assets/OperationModelPicker.js index 840fa35..c2da872 100644 --- a/web/assets/OperationModelPicker.js +++ b/web/assets/OperationModelPicker.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as l,dr as t}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{As as s,Ci as a,Ei as n,Eo as o,Jo as i,Si as r,Ti as d,Vr as c,dn as p,in as m,ji as u,js as h,ks as f,rc as x,rn as b,yn as g}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as j,t as w}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{t as C}from"./operationStarterRequest.js?v=cc046c26d6fe7aa4";import{n as k}from"./taskModelPreferences.js?v=cc046c26d6fe7aa4";import{i as N,r as v}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";var y=e(t(),1),S=l();function O(e){let l=(e.repo||"").split("/");return e.label||l[l.length-1]||e.pipeline}function I({node:e,value:l,disabled:t}){let I=i(e),D=r(e=>e.pipelineSupport),R=r(e=>e.studioModelCapabilities),A=r(e=>e.workflowModelDescriptors),E=r(e=>e.hfCache),M=r(e=>e.localModels),P=r(e=>e.modelCacheDiagnostics),T=r(e=>e.operationContracts),L=u(e=>e.activeWorkflowTabId),[W,$]=(0,y.useState)(!1),[_,B]=(0,y.useState)(""),[q,F]=(0,y.useState)(!1),[V,U]=(0,y.useState)(!1),[G,J]=(0,y.useState)(null),[K,z]=(0,y.useState)(null),H=(0,y.useRef)(null),Q=(0,y.useMemo)(()=>s(D,R,E,M,P,A).filter(e=>e.task===I.operation.task&&e.repo&&e.profileId),[D,R,E,M,P,A,I.operation.task]),X=Q.find(e=>e.repo===l&&e.pipeline===I.operation.pipelineClass),Y=Q.filter(e=>(!q||e.cache?.runnable)&&`${e.label} ${e.repo}`.toLowerCase().includes(_.trim().toLowerCase()));function Z(){H.current?.abort(),H.current=null,U(!1),z(null),J(null),$(!1)}function ee(e){w(e.plan.graph,e.context,e.signature,e.restoreDefaults?"Restore model defaults":"Change model"),u.getState().saveActiveWorkflowTab(!0),!e.restoreDefaults&&e.choice.profileId&&k(e.choice.task,e.choice.profileId),Z()}async function le(l,t=!1){if(H.current)return;let s=new AbortController;H.current=s;let i=n(),r=c.getState().toObject(),p=j(r);U(!0),J(null),z(null);try{let n=await C(l.pipeline,l.task,T,s.signal,l.profileId);if(s.signal.aborted)return;d(i,{includeForm:!1});let o=e.data.blockProjectionOwnerId?null:await C(I.operation.pipelineClass,I.operation.task,T,s.signal);if(s.signal.aborted)return;let m=e.data.blockProjectionOwnerId?(await a(async()=>{let{planOwnerBlockOperationChange:e}=await import(`./operationLegacyBlockChange.js?v=cc046c26d6fe7aa4`).then(e=>e.t);return{planOwnerBlockOperationChange:e}},[])).planOwnerBlockOperationChange(r,e.data.blockProjectionOwnerId,e.data.blockProjectionNodeId??e.id,n,{replaceModel:!t,restoreDefaults:t}):!t&&o&&N(r,e.id,o,n)||v(r,e.id,n,{replaceModel:!t,restoreDefaults:t,baseline:o});if(s.signal.aborted)return;if(d(i,{includeForm:!1}),j(c.getState().toObject())!==p)throw Error("The workflow changed. Select the model again.");let u={plan:m,context:i,signature:p,choice:l,restoreDefaults:t};m.review.required?z(u):ee(u)}catch(e){s.signal.aborted||J(o(e,"Could not change this model."))}finally{H.current===s&&(H.current=null,U(!1))}}(0,y.useEffect)(()=>($(!1),()=>{H.current?.abort()}),[L,e.id]);let te=K?(0,S.jsxs)("section",{className:"w-full space-y-2","aria-label":"Review model selection","data-testid":"model-selection-review",children:[(0,S.jsxs)("div",{children:[(0,S.jsx)("p",{className:"font-semibold text-modiff-text",children:"Review selection"}),(0,S.jsxs)("p",{className:"text-sm text-modiff-subtle-text",children:["Apply ",O(K.choice)," to this workflow, or keep the current model."]})]}),K.plan.review.changes.length?(0,S.jsx)(p,{label:`What will change (${K.plan.review.changes.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,S.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.changes.map((e,l)=>(0,S.jsx)("li",{children:e},l))})}):null,K.plan.review.preserved.length?(0,S.jsx)(p,{label:`Values and connections kept (${K.plan.review.preserved.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,S.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.preserved.map((e,l)=>(0,S.jsx)("li",{children:e},l))})}):null,K.plan.review.attention.length?(0,S.jsx)(p,{label:`Needs attention (${K.plan.review.attention.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,S.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.attention.map((e,l)=>(0,S.jsx)("li",{children:e},l))})}):null,(0,S.jsxs)("div",{className:"flex flex-wrap justify-end gap-2",children:[(0,S.jsx)(b,{onClick:()=>z(null),children:"Keep current model"}),(0,S.jsx)(b,{tone:"primary",onClick:()=>{try{ee(K)}catch(e){J(o(e,"Could not apply the model change."))}},children:"Apply model change"})]})]}):void 0;return(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(b,{"aria-label":"Choose model",className:"w-full",align:"left",disabled:t,onClick:()=>$(!0),title:l,children:(0,S.jsx)("span",{className:"min-w-0 truncate",children:X?O(X):l||"Choose model"})}),X&&T.some(e=>e.pipelineClass===I.operation.pipelineClass&&e.task===I.operation.task&&!x(e))?(0,S.jsx)(b,{disabled:t||V,onClick:()=>{$(!0),le(X,!0)},title:"Reset unconnected prompts and generation controls; keep model, memory settings, media and custom nodes. Undo is available.",children:"Restore model defaults"}):null,W?(0,S.jsx)(m,{open:!0,onClose:Z,title:"Choose model for Load Models",panelClassName:"max-w-3xl",footer:te,children:(0,S.jsxs)("div",{className:"space-y-3",children:[(0,S.jsxs)("p",{className:"text-sm text-modiff-subtle-text",children:[h(I.operation.task??""),". Selecting a model updates its connected nodes. Nothing is downloaded or executed."]}),(0,S.jsx)(g,{"aria-label":"Search compatible models",placeholder:"Search by model or repository",value:_,onChange:e=>B(e.target.value),onClear:()=>B("")}),(0,S.jsxs)("div",{className:"flex gap-2",children:[(0,S.jsx)(b,{tone:q?"secondary":"primary",onClick:()=>F(!1),children:"All supported"}),(0,S.jsx)(b,{tone:q?"primary":"secondary",onClick:()=>F(!0),children:"Downloaded"})]}),G?(0,S.jsx)("p",{role:"alert",children:G}):null,V?(0,S.jsx)("p",{role:"status",children:"Updating model and node contracts…"}):null,(0,S.jsxs)("div",{className:"grid max-h-[min(24rem,50dvh)] gap-2 overflow-y-auto overscroll-contain pr-1","aria-label":"Compatible models",children:[f(Y,X?.id).map(({id:e,primary:l,routes:t})=>(0,S.jsxs)("div",{className:"overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-panel",children:[(0,S.jsxs)(b,{"aria-pressed":K?.choice.id===l.id||!K&&X?.id===l.id,className:"h-auto w-full rounded-none p-3",align:"left",disabled:V,onClick:()=>{le(l)},tone:K?.choice.id===l.id?"primary":"ghost",children:[(0,S.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,S.jsx)("span",{className:"block font-semibold",children:O(l)}),(0,S.jsx)("span",{className:"block break-all text-xs text-modiff-subtle-text",children:l.repo})]}),(0,S.jsxs)("span",{className:"ml-auto flex shrink-0 flex-col items-end gap-1 text-xs text-modiff-subtle-text",children:[l.cache?.runnable?(0,S.jsx)("span",{className:"rounded-modiff-compact bg-modiff-selected-surface px-2 py-1 text-hf-yellow",children:"Downloaded"}):null,(0,S.jsx)("span",{children:"stages"===l.support.decomposition?"Editable nodes":"Whole pipeline"}),"blocked"===l.support.dependencies?(0,S.jsx)("span",{children:"Runtime setup required"}):null]})]}),t.length>1?(0,S.jsx)(p,{label:(0,S.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,S.jsx)("span",{children:"Other implementations"}),(0,S.jsx)("span",{className:"text-modiff-subtle-text",children:t.length-1})]}),className:"border-t border-modiff-border",buttonClassName:"rounded-none px-3 py-2 text-xs",panelClassName:"grid gap-1 border-t border-modiff-border bg-modiff-bg/40 p-2",children:t.slice(1).map(e=>(0,S.jsxs)(b,{"aria-pressed":K?.choice.id===e.id,align:"left",className:"h-auto w-full justify-between px-2 py-2",disabled:V,onClick:()=>{le(e)},tone:K?.choice.id===e.id?"primary":"ghost",children:[(0,S.jsx)("span",{children:"stages"===e.support.decomposition?"Editable nodes":"Whole pipeline"}),(0,S.jsxs)("span",{className:"min-w-0 break-words text-xs text-modiff-subtle-text",children:[O(e)," · ",e.pipeline," · ",e.profileId]})]},e.id))}):null]},e)),Y.length?null:(0,S.jsx)("p",{role:"status",children:"No compatible models match these filters."})]})]})}):null]})}export{I as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as l,dr as t}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Di as s,Hr as a,Ms as n,Ni as o,Ns as i,Oi as r,Oo as d,Ps as c,Ti as p,Zo as m,an as u,bn as h,fn as f,in as x,oc as b,wi as g}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as j,t as w}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{t as C}from"./operationStarterRequest.js?v=ca6b74e6a02eedb3";import{n as k}from"./taskModelPreferences.js?v=ca6b74e6a02eedb3";import{i as N,r as v}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";var y=e(t(),1),O=l();function S(e){let l=(e.repo||"").split("/");return e.label||l[l.length-1]||e.pipeline}function D({node:e,value:l,disabled:t}){let D=m(e),I=g(e=>e.pipelineSupport),M=g(e=>e.studioModelCapabilities),R=g(e=>e.workflowModelDescriptors),A=g(e=>e.hfCache),P=g(e=>e.localModels),E=g(e=>e.modelCacheDiagnostics),T=g(e=>e.operationContracts),L=o(e=>e.activeWorkflowTabId),[W,$]=(0,y.useState)(!1),[_,B]=(0,y.useState)(""),[q,F]=(0,y.useState)(!1),[U,V]=(0,y.useState)(!1),[G,H]=(0,y.useState)(null),[K,Z]=(0,y.useState)(null),z=(0,y.useRef)(null),J=(0,y.useMemo)(()=>i(I,M,A,P,E,R).filter(e=>e.task===D.operation.task&&e.repo&&e.profileId),[I,M,A,P,E,R,D.operation.task]),Q=J.find(e=>e.repo===l&&e.pipeline===D.operation.pipelineClass),X=J.filter(e=>(!q||e.cache?.runnable)&&`${e.label} ${e.repo}`.toLowerCase().includes(_.trim().toLowerCase()));function Y(){z.current?.abort(),z.current=null,V(!1),Z(null),H(null),$(!1)}function ee(e){w(e.plan.graph,e.context,e.signature,e.restoreDefaults?"Restore model defaults":"Change model"),o.getState().saveActiveWorkflowTab(!0),!e.restoreDefaults&&e.choice.profileId&&k(e.choice.task,e.choice.profileId),Y()}async function le(l,t=!1){if(z.current)return;let n=new AbortController;z.current=n;let o=r(),i=a.getState().toObject(),c=j(i);V(!0),H(null),Z(null);try{let r=await C(l.pipeline,l.task,T,n.signal,l.profileId);if(n.signal.aborted)return;s(o,{includeForm:!1});let d=e.data.blockProjectionOwnerId?null:await C(D.operation.pipelineClass,D.operation.task,T,n.signal);if(n.signal.aborted)return;let m=e.data.blockProjectionOwnerId?(await p(async()=>{let{planOwnerBlockOperationChange:e}=await import(`./operationLegacyBlockChange.js?v=ca6b74e6a02eedb3`).then(e=>e.t);return{planOwnerBlockOperationChange:e}},[])).planOwnerBlockOperationChange(i,e.data.blockProjectionOwnerId,e.data.blockProjectionNodeId??e.id,r,{replaceModel:!t,restoreDefaults:t}):!t&&d&&N(i,e.id,d,r)||v(i,e.id,r,{replaceModel:!t,restoreDefaults:t,baseline:d});if(n.signal.aborted)return;if(s(o,{includeForm:!1}),j(a.getState().toObject())!==c)throw Error("The workflow changed. Select the model again.");let u={plan:m,context:o,signature:c,choice:l,restoreDefaults:t};m.review.required?Z(u):ee(u)}catch(e){n.signal.aborted||H(d(e,"Could not change this model."))}finally{z.current===n&&(z.current=null,V(!1))}}(0,y.useEffect)(()=>($(!1),()=>{z.current?.abort()}),[L,e.id]);let te=K?(0,O.jsxs)("section",{className:"w-full space-y-2","aria-label":"Review model selection","data-testid":"model-selection-review",children:[(0,O.jsxs)("div",{children:[(0,O.jsx)("p",{className:"font-semibold text-modiff-text",children:"Review selection"}),(0,O.jsxs)("p",{className:"text-sm text-modiff-subtle-text",children:["Apply ",S(K.choice)," to this workflow, or keep the current model."]})]}),K.plan.review.changes.length?(0,O.jsx)(f,{label:`What will change (${K.plan.review.changes.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,O.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.changes.map((e,l)=>(0,O.jsx)("li",{children:e},l))})}):null,K.plan.review.preserved.length?(0,O.jsx)(f,{label:`Values and connections kept (${K.plan.review.preserved.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,O.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.preserved.map((e,l)=>(0,O.jsx)("li",{children:e},l))})}):null,K.plan.review.attention.length?(0,O.jsx)(f,{label:`Needs attention (${K.plan.review.attention.length})`,buttonClassName:"px-0 py-1 text-sm",panelClassName:"pt-1",children:(0,O.jsx)("ul",{className:"list-inside list-disc text-sm text-modiff-subtle-text",children:K.plan.review.attention.map((e,l)=>(0,O.jsx)("li",{children:e},l))})}):null,(0,O.jsxs)("div",{className:"flex flex-wrap justify-end gap-2",children:[(0,O.jsx)(x,{onClick:()=>Z(null),children:"Keep current model"}),(0,O.jsx)(x,{tone:"primary",onClick:()=>{try{ee(K)}catch(e){H(d(e,"Could not apply the model change."))}},children:"Apply model change"})]})]}):void 0;return(0,O.jsxs)(O.Fragment,{children:[(0,O.jsx)(x,{"aria-label":"Choose model",className:"w-full",align:"left",disabled:t,onClick:()=>$(!0),title:l,children:(0,O.jsx)("span",{className:"min-w-0 truncate",children:Q?S(Q):l||"Choose model"})}),Q&&T.some(e=>e.pipelineClass===D.operation.pipelineClass&&e.task===D.operation.task&&!b(e))?(0,O.jsx)(x,{disabled:t||U,onClick:()=>{$(!0),le(Q,!0)},title:"Reset unconnected prompts and generation controls; keep model, memory settings, media and custom nodes. Undo is available.",children:"Restore model defaults"}):null,W?(0,O.jsx)(u,{open:!0,onClose:Y,title:"Choose model for Load Models",panelClassName:"max-w-3xl",footer:te,children:(0,O.jsxs)("div",{className:"space-y-3",children:[(0,O.jsxs)("p",{className:"text-sm text-modiff-subtle-text",children:[c(D.operation.task??""),". Selecting a model updates its connected nodes. Nothing is downloaded or executed."]}),(0,O.jsx)(h,{"aria-label":"Search compatible models",placeholder:"Search by model or repository",value:_,onChange:e=>B(e.target.value),onClear:()=>B("")}),(0,O.jsxs)("div",{className:"flex gap-2",children:[(0,O.jsx)(x,{tone:q?"secondary":"primary",onClick:()=>F(!1),children:"All supported"}),(0,O.jsx)(x,{tone:q?"primary":"secondary",onClick:()=>F(!0),children:"Downloaded"})]}),G?(0,O.jsx)("p",{role:"alert",children:G}):null,U?(0,O.jsx)("p",{role:"status",children:"Updating model and node contracts…"}):null,(0,O.jsxs)("div",{className:"grid max-h-[min(24rem,50dvh)] gap-2 overflow-y-auto overscroll-contain pr-1","aria-label":"Compatible models",children:[n(X,Q?.id).map(({id:e,primary:l,routes:t})=>(0,O.jsxs)("div",{className:"overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-panel",children:[(0,O.jsxs)(x,{"aria-pressed":K?.choice.id===l.id||!K&&Q?.id===l.id,className:"h-auto w-full rounded-none p-3",align:"left",disabled:U,onClick:()=>{le(l)},tone:K?.choice.id===l.id?"primary":"ghost",children:[(0,O.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,O.jsx)("span",{className:"block font-semibold",children:S(l)}),(0,O.jsx)("span",{className:"block break-all text-xs text-modiff-subtle-text",children:l.repo})]}),(0,O.jsxs)("span",{className:"ml-auto flex shrink-0 flex-col items-end gap-1 text-xs text-modiff-subtle-text",children:[l.cache?.runnable?(0,O.jsx)("span",{className:"rounded-modiff-compact bg-modiff-selected-surface px-2 py-1 text-hf-yellow",children:"Downloaded"}):null,(0,O.jsx)("span",{children:"stages"===l.support.decomposition?"Editable nodes":"Whole pipeline"}),"blocked"===l.support.dependencies?(0,O.jsx)("span",{children:"Runtime setup required"}):null]})]}),t.length>1?(0,O.jsx)(f,{label:(0,O.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,O.jsx)("span",{children:"Other implementations"}),(0,O.jsx)("span",{className:"text-modiff-subtle-text",children:t.length-1})]}),className:"border-t border-modiff-border",buttonClassName:"rounded-none px-3 py-2 text-xs",panelClassName:"grid gap-1 border-t border-modiff-border bg-modiff-bg/40 p-2",children:t.slice(1).map(e=>(0,O.jsxs)(x,{"aria-pressed":K?.choice.id===e.id,align:"left",className:"h-auto w-full justify-between px-2 py-2",disabled:U,onClick:()=>{le(e)},tone:K?.choice.id===e.id?"primary":"ghost",children:[(0,O.jsx)("span",{children:"stages"===e.support.decomposition?"Editable nodes":"Whole pipeline"}),(0,O.jsxs)("span",{className:"min-w-0 break-words text-xs text-modiff-subtle-text",children:[S(e)," · ",e.pipeline," · ",e.profileId]})]},e.id))}):null]},e)),X.length?null:(0,O.jsx)("p",{role:"status",children:"No compatible models match these filters."})]})]})}):null]})}export{D as default}; \ No newline at end of file diff --git a/web/assets/OperationOwnerControls.js b/web/assets/OperationOwnerControls.js index 6f26632..079e329 100644 --- a/web/assets/OperationOwnerControls.js +++ b/web/assets/OperationOwnerControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as a,dr as l}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{As as o,Ci as s,Go as n,Jo as t,Si as i,Ts as r,bn as d,dn as p,es as c,fn as u,rc as k}from"./studio-templates.js?v=cc046c26d6fe7aa4";import"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{t as j}from"./OperationGraphControls.js?v=cc046c26d6fe7aa4";var b=e(l(),1),f=a(),h=(0,b.lazy)(()=>s(()=>import(`./VisualStageControls.js?v=cc046c26d6fe7aa4`),[])),m=(0,b.lazy)(()=>s(()=>import(`./OperationModelPicker.js?v=cc046c26d6fe7aa4`),[])),x=(0,b.lazy)(()=>s(()=>import(`./LegacyOperationOwnerControls.js?v=cc046c26d6fe7aa4`),[])),I=(0,b.lazy)(()=>s(()=>import(`./BlockModelTaskControls.js?v=cc046c26d6fe7aa4`),[]));function g({node:e}){if(r(e.data.blockInstanceV2))return null;if(n(e))return(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:e})});if(e.data.blockInstanceV2)return(0,f.jsx)(C,{node:e});if(e.data.userBlockSnapshot||e.data.userBlockId)return(0,f.jsx)(p,{label:"Change model / task",panelClassName:"grid gap-2 py-2",children:(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model/task controls…"}),children:(0,f.jsx)(x,{nodeId:e.id})})});let a=t(e);return a&&a.operation.pipelineClass&&a.operation.task&&k(a.operation)&&(!e.parentId||e.data.blockProjectionOwnerId)?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:e})}),(0,f.jsx)(v,{ownerId:e.data.blockProjectionNodeId??e.id,blockId:e.data.blockProjectionOwnerId,pipelineClass:a.operation.pipelineClass,currentTask:a.operation.task},`${e.id}:${a.operation.pipelineClass}:${a.operation.task}`)]}):null}function C({node:e,ownerBlockId:a=e.id,inline:l=!1}){let o=c(e.data.blockInstanceV2).nodes.filter(e=>k(t(e)?.operation)),[s,n]=(0,b.useState)(""),i=o.find(e=>e.data.blockProjectionNodeId===s)??o[0],r=i?t(i):null;return i&&r?.operation.pipelineClass&&r.operation.task?(0,f.jsxs)("div",{className:"grid gap-2",children:[o.length>1?(0,f.jsx)(u,{label:"Loader to change",children:(0,f.jsx)(d,{"aria-label":"Block loader to change",value:i.data.blockProjectionNodeId,onValueChange:n,options:o.map(e=>({value:e.data.blockProjectionNodeId,label:`${e.data.label} · ${e.data.operationAuthoring.operation.pipelineClass} · ${e.data.blockProjectionNodeId}`}))})}):null,(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model choices…"}),children:(0,f.jsx)(m,{node:{...i,data:{...i.data,blockProjectionOwnerId:a}},value:(()=>{let e=i.data.params.repo_id?.value??i.data.params.model_id?.value;return"string"==typeof e?e:e&&"object"==typeof e&&"value"in e?String(e.value??""):""})()})}),(0,f.jsx)(v,{ownerId:i.data.blockProjectionNodeId,blockId:a,inline:l,pipelineClass:r.operation.pipelineClass,currentTask:r.operation.task},`${i.id}:${r.operation.pipelineClass}:${r.operation.task}`),(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:{...i,data:{...i.data,blockProjectionOwnerId:a}}})})]}):e.data.blockInstanceV2.effectiveGraph.nodes.some(e=>e.modularDiffusers)||"diffusers.definition-switch:v1"===e.data.blockInstanceV2.routeSelection?.routeSetId?(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model/task controls…"}),children:(0,f.jsx)(I,{node:e})}):null}function v({ownerId:e,blockId:a,pipelineClass:l,currentTask:s,inline:n=!1}){let t=i(e=>e.pipelineSupport),r=i(e=>e.studioModelCapabilities),c=i(e=>e.workflowModelDescriptors),[k,h]=(0,b.useState)(l),[m,x]=(0,b.useState)(s),[I,g]=(0,b.useState)(""),C=t.filter(e=>e.tasks.some(e=>e.operationIds.length)),v=C.find(e=>e.pipelineClass===k),_=v?.tasks.filter(e=>e.operationIds.length)??[],w=_.find(e=>e.task===m),S=o(v&&w?[{...v,tasks:[w]}]:[],r,[],[],null,c).flatMap(e=>e.profileId?[{value:e.profileId,label:`${e.label} · ${e.repo}`}]:[]);return(0,f.jsxs)(p,{label:"Change model / task",collapsible:!n,panelClassName:"grid gap-2 py-2",children:[(0,f.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Review changes to this node and its connected nodes. Model files and resources are checked when you run."}),(0,f.jsx)(u,{label:"Pipeline",children:(0,f.jsx)(d,{"aria-label":"Replacement pipeline",value:k,onValueChange:e=>{let a=C.find(a=>a.pipelineClass===e)?.tasks.filter(e=>e.operationIds.length);h(e),g(""),x(a?.find(e=>e.task===m)?.task??a?.[0]?.task??"")},options:C.map(e=>({value:e.pipelineClass,label:e.pipelineClass}))})}),(0,f.jsx)(u,{label:"Task",children:(0,f.jsx)(d,{"aria-label":"Replacement task",value:w?.task??"",onValueChange:e=>{x(e),g("")},options:_.map(e=>({value:e.task,label:e.task.replace(/_/gu," ")}))})}),S.length?(0,f.jsx)(u,{label:"Model",children:(0,f.jsx)(d,{"aria-label":"Replacement model",value:I,onValueChange:g,options:[{value:"",label:"Keep compatible model selection"},...S]})}):null,w?(0,f.jsx)(j,{pipeline:k,task:w.task,ownerId:e,blockId:a,executionProfileId:S.some(e=>e.value===I)?I:void 0}):(0,f.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Select an available pipeline and task to preview a change."})]})}export{C as BlockOwnerChoices,g as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as a,dr as l}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Jo as o,Ns as s,Os as n,Ti as t,Zo as i,fn as r,oc as d,pn as p,rs as c,wi as u,xn as k}from"./studio-templates.js?v=ca6b74e6a02eedb3";import"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{t as j}from"./OperationGraphControls.js?v=ca6b74e6a02eedb3";var b=e(l(),1),f=a(),h=(0,b.lazy)(()=>t(()=>import(`./VisualStageControls.js?v=ca6b74e6a02eedb3`),[])),m=(0,b.lazy)(()=>t(()=>import(`./OperationModelPicker.js?v=ca6b74e6a02eedb3`),[])),x=(0,b.lazy)(()=>t(()=>import(`./LegacyOperationOwnerControls.js?v=ca6b74e6a02eedb3`),[])),I=(0,b.lazy)(()=>t(()=>import(`./BlockModelTaskControls.js?v=ca6b74e6a02eedb3`),[]));function g({node:e}){if(n(e.data.blockInstanceV2))return null;if(o(e))return(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:e})});if(e.data.blockInstanceV2)return(0,f.jsx)(C,{node:e});if(e.data.userBlockSnapshot||e.data.userBlockId)return(0,f.jsx)(r,{label:"Change model / task",panelClassName:"grid gap-2 py-2",children:(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model/task controls…"}),children:(0,f.jsx)(x,{nodeId:e.id})})});let a=i(e);return a&&a.operation.pipelineClass&&a.operation.task&&d(a.operation)&&(!e.parentId||e.data.blockProjectionOwnerId)?(0,f.jsxs)(f.Fragment,{children:[(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:e})}),(0,f.jsx)(v,{ownerId:e.data.blockProjectionNodeId??e.id,blockId:e.data.blockProjectionOwnerId,pipelineClass:a.operation.pipelineClass,currentTask:a.operation.task},`${e.id}:${a.operation.pipelineClass}:${a.operation.task}`)]}):null}function C({node:e,ownerBlockId:a=e.id,inline:l=!1}){let o=c(e.data.blockInstanceV2).nodes.filter(e=>d(i(e)?.operation)),[s,n]=(0,b.useState)(""),t=o.find(e=>e.data.blockProjectionNodeId===s)??o[0],r=t?i(t):null;return t&&r?.operation.pipelineClass&&r.operation.task?(0,f.jsxs)("div",{className:"grid gap-2",children:[o.length>1?(0,f.jsx)(p,{label:"Loader to change",children:(0,f.jsx)(k,{"aria-label":"Block loader to change",value:t.data.blockProjectionNodeId,onValueChange:n,options:o.map(e=>({value:e.data.blockProjectionNodeId,label:`${e.data.label} · ${e.data.operationAuthoring.operation.pipelineClass} · ${e.data.blockProjectionNodeId}`}))})}):null,(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model choices…"}),children:(0,f.jsx)(m,{node:{...t,data:{...t.data,blockProjectionOwnerId:a}},value:(()=>{let e=t.data.params.repo_id?.value??t.data.params.model_id?.value;return"string"==typeof e?e:e&&"object"==typeof e&&"value"in e?String(e.value??""):""})()})}),(0,f.jsx)(v,{ownerId:t.data.blockProjectionNodeId,blockId:a,inline:l,pipelineClass:r.operation.pipelineClass,currentTask:r.operation.task},`${t.id}:${r.operation.pipelineClass}:${r.operation.task}`),(0,f.jsx)(b.Suspense,{fallback:null,children:(0,f.jsx)(h,{node:{...t,data:{...t.data,blockProjectionOwnerId:a}}})})]}):e.data.blockInstanceV2.effectiveGraph.nodes.some(e=>e.modularDiffusers)||"diffusers.definition-switch:v1"===e.data.blockInstanceV2.routeSelection?.routeSetId?(0,f.jsx)(b.Suspense,{fallback:(0,f.jsx)("p",{role:"status",children:"Loading model/task controls…"}),children:(0,f.jsx)(I,{node:e})}):null}function v({ownerId:e,blockId:a,pipelineClass:l,currentTask:o,inline:n=!1}){let t=u(e=>e.pipelineSupport),i=u(e=>e.studioModelCapabilities),d=u(e=>e.workflowModelDescriptors),[c,h]=(0,b.useState)(l),[m,x]=(0,b.useState)(o),[I,g]=(0,b.useState)(""),C=t.filter(e=>e.tasks.some(e=>e.operationIds.length)),v=C.find(e=>e.pipelineClass===c),_=v?.tasks.filter(e=>e.operationIds.length)??[],w=_.find(e=>e.task===m),P=s(v&&w?[{...v,tasks:[w]}]:[],i,[],[],null,d).flatMap(e=>e.profileId?[{value:e.profileId,label:`${e.label} · ${e.repo}`}]:[]);return(0,f.jsxs)(r,{label:"Change model / task",collapsible:!n,panelClassName:"grid gap-2 py-2",children:[(0,f.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Review changes to this node and its connected nodes. Model files and resources are checked when you run."}),(0,f.jsx)(p,{label:"Pipeline",children:(0,f.jsx)(k,{"aria-label":"Replacement pipeline",value:c,onValueChange:e=>{let a=C.find(a=>a.pipelineClass===e)?.tasks.filter(e=>e.operationIds.length);h(e),g(""),x(a?.find(e=>e.task===m)?.task??a?.[0]?.task??"")},options:C.map(e=>({value:e.pipelineClass,label:e.pipelineClass}))})}),(0,f.jsx)(p,{label:"Task",children:(0,f.jsx)(k,{"aria-label":"Replacement task",value:w?.task??"",onValueChange:e=>{x(e),g("")},options:_.map(e=>({value:e.task,label:e.task.replace(/_/gu," ")}))})}),P.length?(0,f.jsx)(p,{label:"Model",children:(0,f.jsx)(k,{"aria-label":"Replacement model",value:I,onValueChange:g,options:[{value:"",label:"Keep compatible model selection"},...P]})}):null,w?(0,f.jsx)(j,{pipeline:c,task:w.task,ownerId:e,blockId:a,executionProfileId:P.some(e=>e.value===I)?I:void 0}):(0,f.jsx)("p",{role:"status",className:"text-xs text-modiff-subtle-text",children:"Select an available pipeline and task to preview a change."})]})}export{C as BlockOwnerChoices,g as default}; \ No newline at end of file diff --git a/web/assets/PreviewHistoryStripContent.js b/web/assets/PreviewHistoryStripContent.js index ce14c5c..c87845e 100644 --- a/web/assets/PreviewHistoryStripContent.js +++ b/web/assets/PreviewHistoryStripContent.js @@ -1 +1 @@ -import{$ as e,Bt as t,_n as i,cr as a,en as l,ln as o,pn as s,un as d,yt as r}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{At as n,Et as m,Mo as f,Mt as c,Nt as u,Ot as x,Sa as p,Tt as b,ji as h,wt as v,xa as y,ya as g}from"./studio-templates.js?v=cc046c26d6fe7aa4";var w=a();function j(e){return e.mediaItems?.[0]?.url??e.url}function N(e){return e.mediaItems?.[0]?.displayType??e.displayType??"unknown"}function I(e){let t=N(e);if("image"===t)return g(e)??"Image";if("video"===t){let t=y(e,"numFrames");return void 0===t?"Video":`${t} frames`}return"audio"===t?"Audio":"text"===t?"Text":"Output"}function $(e){return"string"==typeof e.value?e.value:JSON.stringify(e.value,null,2)}async function T(e){try{await navigator.clipboard.writeText(e),f("Output URL copied",{variant:"success",autoHideDuration:1600})}catch{f("Could not copy output URL",{variant:"error",autoHideDuration:2400})}}function k({history:a,audioDownloadSampleRate:f}){let y=h(e=>e.restoreWorkflowFromOutput),g=p(e=>e.setLightboxOpener),k=p(e=>e.setMediaViewerOpener),O=p(e=>e.setMediaExportOpener),R=p(e=>e.setRightPanelOpen),L=p(e=>e.setRightPanelTab);return(0,w.jsxs)("div",{className:"nodrag mb-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg/80 p-2",children:[(0,w.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-2 text-xs text-modiff-subtle-text",children:[(0,w.jsxs)("span",{className:"inline-flex items-center gap-1 font-semibold text-modiff-text",children:[(0,w.jsx)(t,{size:13}),"Previous"]}),(0,w.jsx)(b,{type:"button",className:"min-h-7 px-1 text-modiff-subtle-text transition hover:text-hf-yellow",onClick:()=>{R(!0),L("gallery")},children:"Gallery"})]}),(0,w.jsx)("div",{className:"flex gap-2 overflow-x-auto pb-1",children:a.map(t=>{let a=N(t),p=j(t);return(0,w.jsxs)("div",{className:"group/history relative min-w-[96px] max-w-[120px] overflow-hidden rounded-modiff-compact border border-modiff-border bg-modiff-panel",children:[(0,w.jsx)(b,{type:"button",className:"block h-16 w-full overflow-hidden border-2 border-transparent text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-modiff-focus",onClick:()=>(e=>{let t=N(e);if("image"===t||"image_collection"===e.displayType){let t=v({value:e.mediaItems?.map(e=>e.url)??[e.url],artifacts:e.mediaItems?.map(t=>({url:t.url,nodeId:e.nodeId,fieldKey:e.fieldKey,index:t.index,mimeType:t.contentType,filename:t.backendPath?.split("/").pop(),width:t.width,height:t.height})),dataType:"url",mimeType:"image/webp",nodeId:e.nodeId,fieldKey:e.fieldKey});return void g({images:t.map(e=>e.url),artifacts:t,currentIndex:0,dataType:"url",mimeType:t[0]?.mimeType??"image/webp"})}if("text"!==t&&"text"!==e.displayType){if("video"===t||"audio"===t){let i=e.mediaItems&&e.mediaItems.length>0?e.mediaItems:[{index:0,url:j(e),displayType:t}];return void k({title:"video"===t?"Previous video render":"Previous audio render",currentIndex:0,items:i.filter(e=>e.url).map((a,l)=>({id:`${e.id}:${a.index??l}`,kind:t,label:a.label||`${I(e)} ${i.length>1?l+1:""}`.trim(),url:a.url,downloadName:a.backendPath?.split("/").pop()??`modiff-${e.nodeId}-${e.fieldKey}-${l+1}.${"video"===t?"mp4":"wav"}`}))})}}else k({title:"Previous text render",currentIndex:0,items:[{id:e.id,kind:"text",label:I(e),text:$(e),downloadName:`modiff-${e.nodeId}-${e.fieldKey}.txt`}]})})(t),title:`${I(t)} from ${new Date(t.createdAt).toLocaleTimeString()}`,children:"image"===a?(0,w.jsx)("img",{src:p,alt:I(t),className:"h-full w-full object-cover modiff-generated-image"}):"video"===a?(0,w.jsx)("video",{src:p,muted:!0,playsInline:!0,preload:"metadata","aria-label":I(t),className:"pointer-events-none h-full w-full object-cover"}):"audio"===a?(0,w.jsxs)("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:[(0,w.jsx)(r,{size:20,className:"text-hf-yellow"}),I(t)]}):"text"===a?(0,w.jsxs)("span",{className:"flex h-full w-full items-start gap-1 overflow-hidden bg-modiff-surface p-2 text-left text-xs text-modiff-subtle-text",children:[(0,w.jsx)(l,{size:14,className:"mt-0.5 shrink-0 text-hf-yellow"}),(0,w.jsx)("span",{className:"line-clamp-3",children:$(t)})]}):(0,w.jsx)("span",{className:"flex h-full w-full items-center justify-center bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:I(t)})}),(0,w.jsxs)("div",{className:"text-modiff-label flex items-center gap-1 border-t border-modiff-border px-1 py-1 text-modiff-subtle-text",children:[(0,w.jsx)(i,{size:11}),(0,w.jsx)("span",{className:"min-w-0 flex-1 truncate",children:new Date(t.createdAt).toLocaleTimeString()})]}),(0,w.jsx)("div",{className:"absolute right-1 top-1",children:(0,w.jsxs)(n,{children:[(0,w.jsx)(u,{children:(0,w.jsx)(m,{label:"Output actions",className:"border border-modiff-border bg-modiff-panel/90 hover:bg-modiff-surface hover:text-hf-yellow",children:(0,w.jsx)(o,{size:14})})}),(0,w.jsxs)(c,{layer:"graph",anchor:"bottom end",className:"min-w-44",children:[(0,w.jsx)(x,{icon:(0,w.jsx)(d,{size:14}),onClick:()=>{"text"!==a?("video"===a||"audio"===a||"image"===a)&&O({source:p,kind:a,filename:t.mediaItems?.[0]?.backendPath?.split("/").pop()??`modiff-${t.nodeId}-${t.fieldKey}-${t.createdAt}.${"audio"===a?"wav":"video"===a?"mp4":"webp"}`,title:`Download ${a}`,defaultFormat:"audio"===a?"wav":"video"===a?"mp4":"png",defaultSampleRate:"audio"===a?f:void 0}):function(e){let t=URL.createObjectURL(new Blob([$(e)],{type:"text/plain;charset=utf-8"})),i=document.createElement("a");i.href=t,i.download=`modiff-${e.nodeId}-${e.fieldKey}.txt`,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3)}(t)},disabled:"unknown"===a,children:"Download…"}),(0,w.jsx)(x,{icon:(0,w.jsx)(s,{size:14}),onClick:()=>{T(p)},children:"Copy URL"}),(0,w.jsx)(x,{icon:(0,w.jsx)(e,{size:14}),onClick:()=>y(t),children:"Restore settings"})]})]})})]},t.id)})})]})}export{k as default}; \ No newline at end of file +import{$ as e,Bt as t,_n as i,cr as a,en as l,ln as o,pn as s,un as d,yt as r}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ca as n,Dt as m,Et as f,Ni as c,Nt as u,Po as x,Pt as p,Tt as b,jt as h,kt as v,wa as y,xa as g}from"./studio-templates.js?v=ca6b74e6a02eedb3";var w=a();function j(e){return e.mediaItems?.[0]?.url??e.url}function N(e){return e.mediaItems?.[0]?.displayType??e.displayType??"unknown"}function I(e){let t=N(e);if("image"===t)return g(e)??"Image";if("video"===t){let t=n(e,"numFrames");return void 0===t?"Video":`${t} frames`}return"audio"===t?"Audio":"text"===t?"Text":"Output"}function $(e){return"string"==typeof e.value?e.value:JSON.stringify(e.value,null,2)}async function k(e){try{await navigator.clipboard.writeText(e),x("Output URL copied",{variant:"success",autoHideDuration:1600})}catch{x("Could not copy output URL",{variant:"error",autoHideDuration:2400})}}function T({history:a,audioDownloadSampleRate:n}){let x=c(e=>e.restoreWorkflowFromOutput),g=y(e=>e.setLightboxOpener),T=y(e=>e.setMediaViewerOpener),R=y(e=>e.setMediaExportOpener),O=y(e=>e.setRightPanelOpen),P=y(e=>e.setRightPanelTab);return(0,w.jsxs)("div",{className:"nodrag mb-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg/80 p-2",children:[(0,w.jsxs)("div",{className:"mb-2 flex items-center justify-between gap-2 text-xs text-modiff-subtle-text",children:[(0,w.jsxs)("span",{className:"inline-flex items-center gap-1 font-semibold text-modiff-text",children:[(0,w.jsx)(t,{size:13}),"Previous"]}),(0,w.jsx)(f,{type:"button",className:"min-h-7 px-1 text-modiff-subtle-text transition hover:text-hf-yellow",onClick:()=>{O(!0),P("gallery")},children:"Gallery"})]}),(0,w.jsx)("div",{className:"flex gap-2 overflow-x-auto pb-1",children:a.map(t=>{let a=N(t),c=j(t);return(0,w.jsxs)("div",{className:"group/history relative min-w-[96px] max-w-[120px] overflow-hidden rounded-modiff-compact border border-modiff-border bg-modiff-panel",children:[(0,w.jsx)(f,{type:"button",className:"block h-16 w-full overflow-hidden border-2 border-transparent text-left focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-modiff-focus",onClick:()=>(e=>{let t=N(e);if("image"===t||"image_collection"===e.displayType){let t=b({value:e.mediaItems?.map(e=>e.url)??[e.url],artifacts:e.mediaItems?.map(t=>({url:t.url,nodeId:e.nodeId,fieldKey:e.fieldKey,index:t.index,mimeType:t.contentType,filename:t.backendPath?.split("/").pop(),width:t.width,height:t.height})),dataType:"url",mimeType:"image/webp",nodeId:e.nodeId,fieldKey:e.fieldKey});return void g({images:t.map(e=>e.url),artifacts:t,currentIndex:0,dataType:"url",mimeType:t[0]?.mimeType??"image/webp"})}if("text"!==t&&"text"!==e.displayType){if("video"===t||"audio"===t){let i=e.mediaItems&&e.mediaItems.length>0?e.mediaItems:[{index:0,url:j(e),displayType:t}];return void T({title:"video"===t?"Previous video render":"Previous audio render",currentIndex:0,items:i.filter(e=>e.url).map((a,l)=>({id:`${e.id}:${a.index??l}`,kind:t,label:a.label||`${I(e)} ${i.length>1?l+1:""}`.trim(),url:a.url,downloadName:a.backendPath?.split("/").pop()??`modiff-${e.nodeId}-${e.fieldKey}-${l+1}.${"video"===t?"mp4":"wav"}`}))})}}else T({title:"Previous text render",currentIndex:0,items:[{id:e.id,kind:"text",label:I(e),text:$(e),downloadName:`modiff-${e.nodeId}-${e.fieldKey}.txt`}]})})(t),title:`${I(t)} from ${new Date(t.createdAt).toLocaleTimeString()}`,children:"image"===a?(0,w.jsx)("img",{src:c,alt:I(t),className:"h-full w-full object-cover modiff-generated-image"}):"video"===a?(0,w.jsx)("video",{src:c,muted:!0,playsInline:!0,preload:"metadata","aria-label":I(t),className:"pointer-events-none h-full w-full object-cover"}):"audio"===a?(0,w.jsxs)("span",{className:"flex h-full w-full flex-col items-center justify-center gap-1 bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:[(0,w.jsx)(r,{size:20,className:"text-hf-yellow"}),I(t)]}):"text"===a?(0,w.jsxs)("span",{className:"flex h-full w-full items-start gap-1 overflow-hidden bg-modiff-surface p-2 text-left text-xs text-modiff-subtle-text",children:[(0,w.jsx)(l,{size:14,className:"mt-0.5 shrink-0 text-hf-yellow"}),(0,w.jsx)("span",{className:"line-clamp-3",children:$(t)})]}):(0,w.jsx)("span",{className:"flex h-full w-full items-center justify-center bg-modiff-surface px-2 text-center text-xs font-semibold text-modiff-subtle-text",children:I(t)})}),(0,w.jsxs)("div",{className:"text-modiff-label flex items-center gap-1 border-t border-modiff-border px-1 py-1 text-modiff-subtle-text",children:[(0,w.jsx)(i,{size:11}),(0,w.jsx)("span",{className:"min-w-0 flex-1 truncate",children:new Date(t.createdAt).toLocaleTimeString()})]}),(0,w.jsx)("div",{className:"absolute right-1 top-1",children:(0,w.jsxs)(h,{children:[(0,w.jsx)(p,{children:(0,w.jsx)(m,{label:"Output actions",className:"border border-modiff-border bg-modiff-panel/90 hover:bg-modiff-surface hover:text-hf-yellow",children:(0,w.jsx)(o,{size:14})})}),(0,w.jsxs)(u,{layer:"graph",anchor:"bottom end",className:"min-w-44",children:[(0,w.jsx)(v,{icon:(0,w.jsx)(d,{size:14}),onClick:()=>{"text"!==a?("video"===a||"audio"===a||"image"===a)&&R({source:c,kind:a,filename:t.mediaItems?.[0]?.backendPath?.split("/").pop()??`modiff-${t.nodeId}-${t.fieldKey}-${t.createdAt}.${"audio"===a?"wav":"video"===a?"mp4":"webp"}`,title:`Download ${a}`,defaultFormat:"audio"===a?"wav":"video"===a?"mp4":"png",defaultSampleRate:"audio"===a?n:void 0}):function(e){let t=URL.createObjectURL(new Blob([$(e)],{type:"text/plain;charset=utf-8"})),i=document.createElement("a");i.href=t,i.download=`modiff-${e.nodeId}-${e.fieldKey}.txt`,document.body.append(i),i.click(),i.remove(),window.setTimeout(()=>URL.revokeObjectURL(t),1e3)}(t)},disabled:"unknown"===a,children:"Download…"}),(0,w.jsx)(v,{icon:(0,w.jsx)(s,{size:14}),onClick:()=>{k(c)},children:"Copy URL"}),(0,w.jsx)(v,{icon:(0,w.jsx)(e,{size:14}),onClick:()=>x(t),children:"Restore settings"})]})]})})]},t.id)})})]})}export{T as default}; \ No newline at end of file diff --git a/web/assets/RunIssuesDialog.js b/web/assets/RunIssuesDialog.js index 63b8940..60b6d57 100644 --- a/web/assets/RunIssuesDialog.js +++ b/web/assets/RunIssuesDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Gt as t,K as n,Xt as r,Y as i,cr as a,dr as o,rt as s,sn as l,un as d}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$a as c,Ei as u,Hi as m,Ja as h,Jn as f,Mo as p,Nr as x,Oi as g,On as w,Or as b,Rt as y,Sa as j,Si as k,Va as C,Vr as v,_a as I,ha as _,ho as R,in as M,ir as T,ji as D,kr as S,rn as z,tn as N,wi as A}from"./studio-templates.js?v=cc046c26d6fe7aa4";var H=e(o(),1),q=a();function O(e){return"success"===e?"success":"warning"===e?"warning":"info"===e?"info":"error"}function P(){let e=S(e=>e.issues),a=S(e=>e.issueDialogOpen),o=S(e=>e.closeIssues),M=S(e=>e.failure),N=S(e=>e.failureDialogOpen),P=S(e=>e.closeFailure),G=k(e=>e.installHfModel),W=k(e=>e.refreshModelIndexes),J=f(e=>e.sid),K=j(e=>e.setRightPanelOpen),U=j(e=>e.setRightPanelTab),L=j(e=>e.setWorkflowFocusRequest),X=j(e=>e.setModelManagerOpener),Y=D(e=>e.form),Q=D(e=>e.updateForm),ee=D(e=>e.applyAutoResourcePlan),te=D(e=>e.detachManagedGraph),ne=D(e=>e.autoResourcePlan),re=D(e=>e.activeWorkflowTabId),ie=D(e=>e.currentRunContext),ae=D(e=>e.workflowCanvasHydrated),oe=D(e=>e.workflowTabs),se=D(e=>{let t=M?.taskId?.trim();if(t)return e.runContextsByTaskId[t]??null;let n=M?.clientRunId?.trim();return n?e.runContextsByClientRunId[n]??null:null}),[le,de]=(0,H.useState)("idle"),[ce,ue]=(0,H.useState)(null),me="running"===le,he=e.some(e=>"cleanup_gpu"===e.action),fe=ne?.nextCandidate,pe="backend_worker_exited"===M?.errorCode,xe=b(M,se,{activeWorkflowTabId:re,currentRunContext:ie,workflowCanvasHydrated:ae,workflowTabs:oe}),ge=()=>{K(!0),U("setup"),o(),P()},we=()=>{K(!0),U("studio"),o(),P()},be=(e,t)=>{if(K(!0),U("studio"),e){let t=v.getState();t.nodes.some(t=>t.id===e)&&t.onNodesChange(t.nodes.map(t=>({id:t.id,type:"select",selected:t.id===e}))),re&&L({workflowTabId:re,nodeId:e,requestId:Date.now(),requestedAt:Date.now()})}else re&&(L({workflowTabId:re,nodeId:null,requestId:Date.now(),requestedAt:Date.now()}),p("Graph centered. Readiness details remain visible in Studio.",{variant:"info",autoHideDuration:2600}));"issues"===t?o():P()},ye=()=>{K(!0),U("setup"),X({nodeId:null,fieldKey:null}),o(),P()},je=()=>{let e=c(Y),t=I(Y);Q(t),x({...Y,...t}),K(!0),U("studio"),o(),P();let n=C[t.offloadMode];p(`Applied ${e.label} low-VRAM defaults with ${n}.`,{variant:"success",autoHideDuration:4200})},ke=()=>{let e=h("ZImageModularPipeline"),t={...e,prompt:Y.prompt,negativePrompt:Y.negativePrompt,width:Math.min(Y.width,e.width),height:Math.min(Y.height,e.height),aspectRatio:Y.width<=e.width&&Y.height<=e.height?Y.aspectRatio:e.aspectRatio};Q(t),x(t),K(!0),U("studio"),o(),P(),p("Switched to Z-Image Turbo with safer local settings.",{variant:"success",autoHideDuration:3600})},Ce=(0,q.jsx)(z,{tone:"primary",icon:me?(0,q.jsx)(y,{size:15}):(0,q.jsx)(l,{size:15}),onClick:()=>{(async()=>{if(!me){de("running"),ue("Releasing cached models, nodes, and accelerator memory...");try{let e=await R(),t=E(e);if($(e))throw Error(t??"Accelerator cleanup failed.");let n=t??"Accelerator cache released. Cached model state was dropped, so rerun the workflow to rebuild outputs; this action does not intentionally stop the backend.";de("success"),ue(n),p(n,{variant:"success",autoHideDuration:5200})}catch(e){let t=function(e){let t=e instanceof Error?e.message:String(e);return t.includes("Failed to fetch")?"MoDiff backend did not answer the cleanup request. This button does not intentionally stop the backend; restart the backend if it is no longer running, then rerun the workflow.":t||"Accelerator cleanup failed."}(e);de("error"),ue(t),p(t,{variant:"error",autoHideDuration:8e3})}}})()},disabled:me,children:me?"Releasing...":"Release accelerator cache"});return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)(B,{open:a,onClose:o,title:"Run blocked",testId:"run-issues-dialog",footer:(0,q.jsxs)(Z,{cleanupMessage:ce,cleanupState:le,children:[he?Ce:null,(0,q.jsx)(z,{onClick:o,children:"Close"})]}),children:e.map(e=>(0,q.jsxs)(w,{tone:O(e.severity),title:e.message,meta:e.blocking?"Required before this run can start.":"This run can continue, but the setting is risky.",testId:`run-issue-${e.id}`,children:[(0,q.jsx)("div",{className:"grid min-w-0 gap-2",children:e.details&&(0,q.jsx)("p",{className:"whitespace-pre-wrap break-words",children:e.details})}),(0,q.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:["install_model"===e.action&&e.repoId&&(0,q.jsx)(z,{tone:"primary",icon:(0,q.jsx)(d,{size:15}),onClick:()=>{(async e=>{if(e.repoId)try{await G(e.repoId,J,e.installOptions)}catch(e){console.error(e)}})(e)},children:"Install"}),"refresh_cache"===e.action&&(0,q.jsx)(z,{icon:(0,q.jsx)(s,{size:15}),onClick:()=>{(async()=>{await W(!0),p("Model cache refreshed",{variant:"success",autoHideDuration:2200})})()},children:"Refresh cache"}),"select_image"===e.action&&(0,q.jsx)(z,{icon:(0,q.jsx)(r,{size:15}),onClick:we,children:"Open Studio inputs"}),"inspect_node"===e.action&&(0,q.jsx)(z,{icon:(0,q.jsx)(i,{size:15}),onClick:()=>be(e.nodeId,"issues"),children:e.nodeId?"Inspect node":"Inspect graph"}),"detach_graph"===e.action&&(0,q.jsx)(z,{icon:(0,q.jsx)(l,{size:15}),onClick:()=>{te(),o()},children:"Detach invalid receipt"}),"open_model_manager"===e.action&&(0,q.jsx)(z,{tone:"primary",icon:(0,q.jsx)(n,{size:15}),onClick:ye,children:"Models"}),"apply_low_vram_preset"===e.action&&(0,q.jsx)(z,{tone:"primary",icon:(0,q.jsx)(t,{size:15}),onClick:je,children:"Use low-VRAM preset"}),"switch_to_z_image"===e.action&&(0,q.jsx)(z,{tone:"primary",icon:(0,q.jsx)(t,{size:15}),onClick:ke,children:"Use Z-Image Turbo"}),("open_setup"===e.action||"install_model"===e.action)&&(0,q.jsx)(z,{tone:"ghost",icon:(0,q.jsx)(n,{size:15}),onClick:ge,children:"Setup"})]})]},e.id))}),(0,q.jsx)(B,{open:N,onClose:P,title:"Run failed",testId:"run-failure-dialog",footer:(0,q.jsxs)(Z,{cleanupMessage:ce,cleanupState:le,children:[fe&&xe?(0,q.jsx)(z,{icon:(0,q.jsx)(s,{size:15}),onClick:()=>{(async()=>{if(!fe||!xe)return;if(!1===fe.installed||fe.repairRequired)return K(!0),U("compatibility"),void P();if(!J)return void p("Connect to the MoDiff backend before retrying.",{variant:"error"});let e=m(fe,Y),t=ne.candidates?.find(e=>e.id!==fe.id&&e.id!==ne.selectedCandidate?.id&&_(e.proof))??null,n={...ne,selectedCandidate:fe,nextCandidate:t},r=u();try{ee(n,e),A(r),await x(D.getState().form,r),await T({sid:J,studioContext:{},workflowContext:r}),P()}catch(e){if(g(e))return;p(String(e),{variant:"error",autoHideDuration:7e3})}})()},disabled:me,children:"Retry with next option"}):null,M?.oom?Ce:null,(M?.oom||pe)&&xe?(0,q.jsx)(z,{icon:(0,q.jsx)(t,{size:15}),onClick:()=>{xe&&je()},disabled:me,children:pe?"Apply lower-memory settings":"Low-VRAM preset"}):null,M?.nodeId&&xe?(0,q.jsx)(z,{icon:(0,q.jsx)(i,{size:15}),onClick:()=>be(M.nodeId,"failure"),children:"Inspect node"}):null,(0,q.jsx)(z,{icon:(0,q.jsx)(n,{size:15}),onClick:ge,disabled:me,children:"Setup"}),(0,q.jsx)(z,{onClick:P,children:"Close"})]}),children:M&&(0,q.jsx)("div",{children:(0,q.jsxs)(w,{tone:M.oom||pe?"warning":"error",title:F(M),children:[(0,q.jsx)("p",{className:"break-words",children:V(M)}),M.message.trim()&&M.message.trim()!==V(M)?(0,q.jsx)("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-text","data-testid":"run-failure-message",children:M.message}):null,M.recoveryHint&&(0,q.jsx)("p",{className:"mt-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-text",children:M.recoveryHint}),M.memorySummary&&(0,q.jsx)("p",{className:"mt-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-subtle-text","data-testid":"run-failure-memory-summary",children:M.memorySummary})]})})})]})}function F(e){return e.oom||"oom"===e.category?"The run ran out of available accelerator memory":"backend_worker_exited"===e.errorCode?"The native model worker stopped unexpectedly":"missing_model"===e.category?"A required model is missing":"missing_dependency"===e.category?"A backend dependency is missing":"backend_unavailable"===e.category?"The backend became unavailable":"The backend stopped this run"}function V(e){return e.oom||"oom"===e.category?"This graph needs more available memory than the current settings allow.":"missing_model"===e.category?"Install or select the model needed by this workflow.":"missing_dependency"===e.category?"Complete the required setup, then try the run again.":"backend_unavailable"===e.category?"Reconnect to MoDiff, then check the queue before retrying.":"backend_worker_exited"===e.errorCode?"The accelerator or native model runtime ended the backend process before Python could return a normal error. MoDiff recovered the failed run from its supervisor instead of leaving it active.":"The generation could not finish. Check the highlighted step and try again."}function $(e){return G(e)&&!!e.error}function E(e){return G(e)?W(e.message)??W(e.error):null}function G(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function W(e){return"string"==typeof e&&e.trim()?e.trim():null}function Z({children:e,cleanupMessage:t,cleanupState:n}){return(0,q.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:["running"===n||t?(0,q.jsxs)("div",{className:"min-w-0 flex-1 text-xs",children:[(0,q.jsx)("p",{className:"error"===n?"text-modiff-red":"success"===n?"text-modiff-green":"text-modiff-subtle-text",children:t}),"running"===n?(0,q.jsx)(N,{value:null,className:"mt-2 max-w-80 rounded-modiff-compact"}):null]}):null,(0,q.jsx)("div",{className:"flex flex-wrap justify-end gap-2",children:e})]})}function B({children:e,footer:t,onClose:n,open:r,testId:i,title:a}){return r?(0,q.jsx)(M,{open:r,onClose:n,title:a,footer:t,panelClassName:"max-w-xl",bodyClassName:"min-h-0",testId:i,children:e}):null}export{P as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Gt as t,K as n,Xt as r,Y as i,cr as a,dr as o,rt as s,sn as l,un as d}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ai as c,Ar as u,Ei as m,Hr as h,Ni as f,Oi as p,Po as x,Pr as g,Ua as w,Wi as b,Xa as y,Yn as k,_a as j,_o as C,an as v,ar as I,in as _,kn as R,kr as M,nn as T,to as D,wa as z,wi as A,ya as N,zt as S}from"./studio-templates.js?v=ca6b74e6a02eedb3";var H=e(o(),1),q=a();function P(e){return"success"===e?"success":"warning"===e?"warning":"info"===e?"info":"error"}function O(){let e=u(e=>e.issues),a=u(e=>e.issueDialogOpen),o=u(e=>e.closeIssues),v=u(e=>e.failure),T=u(e=>e.failureDialogOpen),O=u(e=>e.closeFailure),U=A(e=>e.installHfModel),V=A(e=>e.refreshModelIndexes),B=k(e=>e.sid),K=z(e=>e.setRightPanelOpen),X=z(e=>e.setRightPanelTab),Y=z(e=>e.setWorkflowFocusRequest),L=z(e=>e.setModelManagerOpener),J=f(e=>e.form),Q=f(e=>e.updateForm),ee=f(e=>e.applyAutoResourcePlan),te=f(e=>e.detachManagedGraph),ne=f(e=>e.autoResourcePlan),re=f(e=>e.activeWorkflowTabId),ie=f(e=>e.currentRunContext),ae=f(e=>e.workflowCanvasHydrated),oe=f(e=>e.workflowTabs),se=f(e=>{let t=v?.taskId?.trim();if(t)return e.runContextsByTaskId[t]??null;let n=v?.clientRunId?.trim();return n?e.runContextsByClientRunId[n]??null:null}),[le,de]=(0,H.useState)("idle"),[ce,ue]=(0,H.useState)(null),me="running"===le,he=e.some(e=>"cleanup_gpu"===e.action),fe=ne?.nextCandidate,pe="backend_worker_exited"===v?.errorCode,xe=M(v,se,{activeWorkflowTabId:re,currentRunContext:ie,workflowCanvasHydrated:ae,workflowTabs:oe}),ge=()=>{K(!0),X("setup"),o(),O()},we=()=>{K(!0),X("studio"),o(),O()},be=(e,t)=>{if(K(!0),X("studio"),e){let t=h.getState();t.nodes.some(t=>t.id===e)&&t.onNodesChange(t.nodes.map(t=>({id:t.id,type:"select",selected:t.id===e}))),re&&Y({workflowTabId:re,nodeId:e,requestId:Date.now(),requestedAt:Date.now()})}else re&&(Y({workflowTabId:re,nodeId:null,requestId:Date.now(),requestedAt:Date.now()}),x("Graph centered. Readiness details remain visible in Studio.",{variant:"info",autoHideDuration:2600}));"issues"===t?o():O()},ye=()=>{K(!0),X("setup"),L({nodeId:null,fieldKey:null}),o(),O()},ke=()=>{let e=D(J),t=N(J);Q(t),g({...J,...t}),K(!0),X("studio"),o(),O();let n=w[t.offloadMode];x(`Applied ${e.label} low-VRAM defaults with ${n}.`,{variant:"success",autoHideDuration:4200})},je=()=>{let e=y("ZImageModularPipeline"),t={...e,prompt:J.prompt,negativePrompt:J.negativePrompt,width:Math.min(J.width,e.width),height:Math.min(J.height,e.height),aspectRatio:J.width<=e.width&&J.height<=e.height?J.aspectRatio:e.aspectRatio};Q(t),g(t),K(!0),X("studio"),o(),O(),x("Switched to Z-Image Turbo with safer local settings.",{variant:"success",autoHideDuration:3600})},Ce=(0,q.jsx)(_,{tone:"primary",icon:me?(0,q.jsx)(S,{size:15}):(0,q.jsx)(l,{size:15}),onClick:()=>{(async()=>{if(!me){de("running"),ue("Releasing cached models, nodes, and accelerator memory...");try{let e=await C(),t=G(e);if(E(e))throw Error(t??"Accelerator cleanup failed.");let n=t??"Accelerator cache released. Cached model state was dropped, so rerun the workflow to rebuild outputs; this action does not intentionally stop the backend.";de("success"),ue(n),x(n,{variant:"success",autoHideDuration:5200})}catch(e){let t=function(e){let t=e instanceof Error?e.message:String(e);return t.includes("Failed to fetch")?"MoDiff backend did not answer the cleanup request. This button does not intentionally stop the backend; restart the backend if it is no longer running, then rerun the workflow.":t||"Accelerator cleanup failed."}(e);de("error"),ue(t),x(t,{variant:"error",autoHideDuration:8e3})}}})()},disabled:me,children:me?"Releasing...":"Release accelerator cache"});return(0,q.jsxs)(q.Fragment,{children:[(0,q.jsx)($,{open:a,onClose:o,title:"Run blocked",testId:"run-issues-dialog",footer:(0,q.jsxs)(Z,{cleanupMessage:ce,cleanupState:le,children:[he?Ce:null,(0,q.jsx)(_,{onClick:o,children:"Close"})]}),children:e.map(e=>(0,q.jsxs)(R,{tone:P(e.severity),title:e.message,meta:e.blocking?"Required before this run can start.":"This run can continue, but the setting is risky.",testId:`run-issue-${e.id}`,children:[(0,q.jsx)("div",{className:"grid min-w-0 gap-2",children:e.details&&(0,q.jsx)("p",{className:"whitespace-pre-wrap break-words",children:e.details})}),(0,q.jsxs)("div",{className:"mt-3 flex flex-wrap gap-2",children:["install_model"===e.action&&e.repoId&&(0,q.jsx)(_,{tone:"primary",icon:(0,q.jsx)(d,{size:15}),onClick:()=>{(async e=>{if(e.repoId)try{await U(e.repoId,B,e.installOptions)}catch(e){console.error(e)}})(e)},children:"Install"}),"refresh_cache"===e.action&&(0,q.jsx)(_,{icon:(0,q.jsx)(s,{size:15}),onClick:()=>{(async()=>{await V(!0),x("Model cache refreshed",{variant:"success",autoHideDuration:2200})})()},children:"Refresh cache"}),"select_image"===e.action&&(0,q.jsx)(_,{icon:(0,q.jsx)(r,{size:15}),onClick:we,children:"Open Studio inputs"}),"inspect_node"===e.action&&(0,q.jsx)(_,{icon:(0,q.jsx)(i,{size:15}),onClick:()=>be(e.nodeId,"issues"),children:e.nodeId?"Inspect node":"Inspect graph"}),"detach_graph"===e.action&&(0,q.jsx)(_,{icon:(0,q.jsx)(l,{size:15}),onClick:()=>{te(),o()},children:"Detach invalid receipt"}),"open_model_manager"===e.action&&(0,q.jsx)(_,{tone:"primary",icon:(0,q.jsx)(n,{size:15}),onClick:ye,children:"Models"}),"apply_low_vram_preset"===e.action&&(0,q.jsx)(_,{tone:"primary",icon:(0,q.jsx)(t,{size:15}),onClick:ke,children:"Use low-VRAM preset"}),"switch_to_z_image"===e.action&&(0,q.jsx)(_,{tone:"primary",icon:(0,q.jsx)(t,{size:15}),onClick:je,children:"Use Z-Image Turbo"}),("open_setup"===e.action||"install_model"===e.action)&&(0,q.jsx)(_,{tone:"ghost",icon:(0,q.jsx)(n,{size:15}),onClick:ge,children:"Setup"})]})]},e.id))}),(0,q.jsx)($,{open:T,onClose:O,title:"Run failed",testId:"run-failure-dialog",footer:(0,q.jsxs)(Z,{cleanupMessage:ce,cleanupState:le,children:[fe&&xe?(0,q.jsx)(_,{icon:(0,q.jsx)(s,{size:15}),onClick:()=>{(async()=>{if(!fe||!xe)return;if(!1===fe.installed||fe.repairRequired)return K(!0),X("compatibility"),void O();if(!B)return void x("Connect to the MoDiff backend before retrying.",{variant:"error"});let e=b(fe,J),t=ne.candidates?.find(e=>e.id!==fe.id&&e.id!==ne.selectedCandidate?.id&&j(e.proof))??null,n={...ne,selectedCandidate:fe,nextCandidate:t},r=p();try{ee(n,e),m(r),await g(f.getState().form,r),await I({sid:B,studioContext:{},workflowContext:r}),O()}catch(e){if(c(e))return;x(String(e),{variant:"error",autoHideDuration:7e3})}})()},disabled:me,children:"Retry with next option"}):null,v?.oom?Ce:null,(v?.oom||pe)&&xe?(0,q.jsx)(_,{icon:(0,q.jsx)(t,{size:15}),onClick:()=>{xe&&ke()},disabled:me,children:pe?"Apply lower-memory settings":"Low-VRAM preset"}):null,v?.nodeId&&xe?(0,q.jsx)(_,{icon:(0,q.jsx)(i,{size:15}),onClick:()=>be(v.nodeId,"failure"),children:"Inspect node"}):null,(0,q.jsx)(_,{icon:(0,q.jsx)(n,{size:15}),onClick:ge,disabled:me,children:"Setup"}),(0,q.jsx)(_,{onClick:O,children:"Close"})]}),children:v&&(0,q.jsx)("div",{children:(0,q.jsxs)(R,{tone:v.oom||pe?"warning":"error",title:F(v),children:[(0,q.jsx)("p",{className:"break-words",children:W(v)}),v.message.trim()&&v.message.trim()!==W(v)?(0,q.jsx)("p",{className:"mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-words rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-text","data-testid":"run-failure-message",children:v.message}):null,v.recoveryHint&&(0,q.jsx)("p",{className:"mt-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-text",children:v.recoveryHint}),v.memorySummary&&(0,q.jsx)("p",{className:"mt-2 rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs text-modiff-subtle-text","data-testid":"run-failure-memory-summary",children:v.memorySummary})]})})})]})}function F(e){return e.oom||"oom"===e.category?"The run ran out of available accelerator memory":"backend_worker_exited"===e.errorCode?"The native model worker stopped unexpectedly":"missing_model"===e.category?"A required model is missing":"missing_dependency"===e.category?"A backend dependency is missing":"backend_unavailable"===e.category?"The backend became unavailable":"The backend stopped this run"}function W(e){return e.oom||"oom"===e.category?"This graph needs more available memory than the current settings allow.":"missing_model"===e.category?"Install or select the model needed by this workflow.":"missing_dependency"===e.category?"Complete the required setup, then try the run again.":"backend_unavailable"===e.category?"Reconnect to MoDiff, then check the queue before retrying.":"backend_worker_exited"===e.errorCode?"The accelerator or native model runtime ended the backend process before Python could return a normal error. MoDiff recovered the failed run from its supervisor instead of leaving it active.":"The generation could not finish. Check the highlighted step and try again."}function E(e){return U(e)&&!!e.error}function G(e){return U(e)?V(e.message)??V(e.error):null}function U(e){return!!e&&"object"==typeof e&&!Array.isArray(e)}function V(e){return"string"==typeof e&&e.trim()?e.trim():null}function Z({children:e,cleanupMessage:t,cleanupState:n}){return(0,q.jsxs)("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-end",children:["running"===n||t?(0,q.jsxs)("div",{className:"min-w-0 flex-1 text-xs",children:[(0,q.jsx)("p",{className:"error"===n?"text-modiff-red":"success"===n?"text-modiff-green":"text-modiff-subtle-text",children:t}),"running"===n?(0,q.jsx)(T,{value:null,className:"mt-2 max-w-80 rounded-modiff-compact"}):null]}):null,(0,q.jsx)("div",{className:"flex flex-wrap justify-end gap-2",children:e})]})}function $({children:e,footer:t,onClose:n,open:r,testId:i,title:a}){return r?(0,q.jsx)(v,{open:r,onClose:n,title:a,footer:t,panelClassName:"max-w-xl",bodyClassName:"min-h-0",testId:i,children:e}):null}export{O as default}; \ No newline at end of file diff --git a/web/assets/SelectionToolbar.js b/web/assets/SelectionToolbar.js index a17f3c6..855555d 100644 --- a/web/assets/SelectionToolbar.js +++ b/web/assets/SelectionToolbar.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$n as t,$t as a,F as o,Pn as n,R as l,Tt as i,X as s,at as d,cn as r,cr as c,dr as u,it as p,nt as b,pn as g,rr as k,st as h,wt as x,xt as f,yn as j,z as m}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{At as C,Ci as v,Et as y,Hn as w,In as z,Jn as S,Mo as I,Mt as N,Nt as P,Ot as E,So as R,Ts as B,Un as D,Vr as M,ar as F,ei as T,hr as H,ir as V,ji as O,pi as W,ut as A,yo as $}from"./studio-templates.js?v=cc046c26d6fe7aa4";var L=e(u(),1),_=c(),U=(0,L.lazy)(()=>v(()=>import(`./NodeInspectorDialog.js?v=cc046c26d6fe7aa4`).then(e=>e.n),[])),K=(0,L.forwardRef)(function({active:e=!1,children:t,className:a,danger:o=!1,disabled:n=!1,label:l,onClick:i,type:s="button",...d},r){return(0,_.jsx)(y,{ref:r,type:s,label:l,size:"dense",active:e&&!n,tone:o&&!n?"danger":"ghost","aria-disabled":n,onClick:e=>{n?e.preventDefault():i?.(e)},className:z(n&&"cursor-not-allowed opacity-40",a),...d,children:t})});function J(){return(0,_.jsx)("span",{className:"mx-0.5 h-6 w-px bg-modiff-border","aria-hidden":"true"})}function X({canvasSuspended:e,createBlockDisabledReason:c,nodes:u,onCreateBlockFromSelection:v,selectionDragging:y}){let X=(0,L.useRef)(null),[q,G]=(0,L.useState)(!1),[Q,Y]=(0,L.useState)(0),Z=k(),{flowToScreenPosition:ee,getNodesBounds:te}=t(),[ae,oe]=(0,L.useState)(null),[ne,le]=(0,L.useState)(null),ie=S(e=>e.sid),se=S(e=>e.isConnected),de=M(e=>e.removeNodes),re=M(e=>e.duplicateNode),ce=M(e=>e.toggleNodeCollapsed),ue=M(e=>e.toggleUserBlockExpanded),pe=M(e=>e.toggleHuggingFaceClusterExpanded),be=M(e=>e.toggleBlockContainerExpandedV2),ge=M(e=>e.setNodeUiState),ke=M(e=>e.resetNodeSize),he=M(e=>e.loopNodes),xe=M(e=>e.ungroupNodes),fe=M(e=>e.setNodeCached),je=(0,L.useMemo)(()=>u.filter(e=>e.selected),[u]),me=(0,L.useMemo)(()=>je.filter(e=>"group"!==e.data.type&&"loop"!==e.data.type),[je]),Ce=1===je.length?je[0]:null;(0,L.useEffect)(()=>{ne&&Ce?.id!==ne&&le(null)},[ne,Ce?.id]);let ve=2===je.length?je.find(e=>"custom"===e.data.type&&!e.parentId&&!e.data.blockProjectionOwnerId):void 0,ye=ve?je.find(e=>"internal"===e.data.blockProjectionKind&&!e.data.blockProjectionContainer):void 0,we=D(u,je.map(e=>e.id)),ze=we.length>0&&we.every(e=>e.data.blockProjectionOwnerId&&"internal"===e.data.blockProjectionKind||e.data.userBlockInstanceId||"execution"===e.data.huggingFaceClusterRole&&e.parentId),Se="group"===Ce?.data.type||"loop"===Ce?.data.type?Ce:null,Ie="internal"===Ce?.data.blockProjectionKind&&(!0===Ce.data.blockProjectionModular||"group"===Ce.data.type)&&Ce.data.blockProjectionOwnerId&&Ce.data.blockProjectionNodeId?Ce:null,Ne=Ie||"group"===Ce?.data.type||"loop"===Ce?.data.type?null:Ce,Pe=B(Ne?.data.blockInstanceV2),Ee=!Pe&&"block"===Ne?.data.type,Re="root"===Ne?.data.huggingFaceClusterRole,Be=!(!Ee&&!Re),De=!!Ne?.data.blockInstanceV2?.presentation.expanded||!!(Ee&&Ne&&W({nodes:u,edges:[]},Ne.id))||!!(Re&&Ne&&T({nodes:u,edges:[]},Ne.id)),Me=!(!Ne?.data.uiState?.collapsed&&!Ne?.data.minimized),Fe=!!Ne?.data.uiState?.disabled,Te=Ne?.data.uiState?.validationMessage||Ne?.data.uiState?.errorMessage,He=!!Ne,Ve=!Pe&&("custom"===Ne?.data.type||Be),Oe=me.length>0&&!Ie&&!(1===me.length&&("block"===me[0]?.data.type||"root"===me[0]?.data.huggingFaceClusterRole)),We=!!c,Ae=!e&&!y&&je.length>0&&(He||Oe||!!Se||!!Ie);(0,L.useEffect)(()=>{let e=()=>Y(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,L.useLayoutEffect)(()=>{let e=X.current;if(!Ae||!e)return void G(!1);let t=te(je),a=t.x+t.width/2,o=ee({x:a,y:t.y}),n=ee({x:a,y:t.y+t.height}),l=e.offsetWidth,i=e.offsetHeight,s=e.parentElement?.getBoundingClientRect(),d=(s?.left??0)+8,r=(s?.top??0)+8,c=Math.max(d,(s?.right??window.innerWidth)-l-8),u=Math.max(r,(s?.bottom??window.innerHeight)-i-8),p=o.x-l/2,b=o.y-i-12;b{de(je.map(e=>e.id))},[de,je]),Le=(0,L.useCallback)(()=>{he(me.map(e=>e.id))},[he,me]),_e=(0,L.useCallback)(()=>{Se&&xe(Se.id)},[Se,xe]),Ue=(0,L.useCallback)(()=>{!Ie?.data.blockProjectionContainer||!Ie.data.blockProjectionOwnerId||!Ie.data.blockProjectionNodeId||(be(Ie.data.blockProjectionOwnerId,Ie.data.blockProjectionNodeId),O.getState().saveActiveWorkflowTab(!0))},[Ie,be]),Ke=(0,L.useCallback)(()=>{Ne&&re(Ne.id)},[re,Ne]),Je=(0,L.useCallback)(async()=>{if(Ne)try{if(("root"===Ne.data.huggingFaceClusterRole||Ne.data.blockInstanceV2)&&await F([Ne.id]),!H({sid:ie,isConnected:se,includeStudio:!1,targetNodeId:Ne.id}).canRun||!ie)return;await V({sid:ie,targetNodeId:Ne.id})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error",persist:!0})}},[se,ie,Ne]),Xe=(0,L.useCallback)(()=>{Ne&&("block"===Ne.data.type?(ue(Ne.id),O.getState().saveActiveWorkflowTab(!0)):"root"===Ne.data.huggingFaceClusterRole?(pe(Ne.id),O.getState().saveActiveWorkflowTab(!0)):ce(Ne.id))},[Ne,pe,ce,ue]),qe=(0,L.useCallback)(()=>{Ne&&ge(Ne.id,{disabled:!Fe,validationSeverity:Fe?void 0:"warning",validationMessage:Fe?void 0:"Disabled nodes are skipped during run export."})},[Fe,ge,Ne]),Ge=(0,L.useCallback)(()=>{Ne&&ke(Ne.id)},[ke,Ne]),Qe=(0,L.useCallback)(async()=>{if(Ne)try{let e=await R([Ne.id]);e.nodes.length&&fe(Ne.id,!1),I(e.nodes.length?"Outputs will recompute on the next Run. Loaded models are retained.":"Loaded models retained; no computed outputs to invalidate.",{variant:"success",autoHideDuration:3500})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error"})}},[Ne,fe]),Ye=(0,L.useCallback)(async()=>{if(Ne)try{await $([Ne.id]),fe(Ne.id,!1),I("Node cache released",{variant:"success",autoHideDuration:1500})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error",autoHideDuration:2600})}},[fe,Ne]),Ze=(0,L.useCallback)(()=>{Ne&&navigator.clipboard.writeText(`${Ne.id}\n${Ne.data.module}.${Ne.data.action}`).then(()=>I("Node info copied",{variant:"success",autoHideDuration:1600})).catch(e=>I(String(e),{variant:"error",autoHideDuration:2600}))},[Ne]),et=(0,L.useCallback)(()=>{I(Te||"No issues recorded for this node.",{variant:Te?"error":"default",autoHideDuration:Te?4200:2200})},[Te]);return Ae?(0,_.jsxs)("div",{ref:X,className:z("nodrag nowheel fixed left-0 top-0 z-40 flex h-10 items-center gap-1 rounded-modiff-panel border border-modiff-border bg-modiff-panel p-1 shadow-modiff-node transition-opacity translate-x-[var(--modiff-selection-toolbar-x)] translate-y-[var(--modiff-selection-toolbar-y)]",q?"opacity-100":"opacity-0"),"data-testid":"selection-toolbar",role:"toolbar","aria-label":"Selection toolbar",onPointerDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[(0,_.jsx)(K,{label:"Delete selection",title:"Delete selection · Delete / Backspace","aria-keyshortcuts":"Delete Backspace",danger:!0,onClick:$e,"data-testid":"selection-toolbar-delete",children:(0,_.jsx)(m,{size:16})}),ve&&ye?(0,_.jsx)(K,{label:"Replace internal node with selected node","data-testid":"selection-toolbar-replace-internal",onClick:()=>{try{M.getState().replaceNodeInBlockV2(ve.id,ye.id),O.getState().saveActiveWorkflowTab(!0),I("The internal node was replaced in this workflow Block.",{variant:"success"})}catch(e){I(e instanceof Error?e.message:"Could not replace this internal node.",{variant:"error"})}},children:(0,_.jsx)(p,{size:16})}):null,ze?(0,_.jsx)(K,{label:"Move out of Block",title:"Move out of Block · Ctrl/Cmd + drag to move between Blocks","data-testid":"selection-toolbar-move-out",onClick:async()=>{try{await w(je.map(e=>e.id),null,"out"),O.getState().saveActiveWorkflowTab(!0)}catch(e){I(e instanceof Error?e.message:"Could not move this item out of the Block.",{variant:"error",autoHideDuration:6e3})}},children:(0,_.jsx)(i,{size:16})}):null,Se&&!Ie&&(0,_.jsx)(K,{label:"loop"===Se.data.type?"Remove loop container":"Ungroup nodes",onClick:_e,"data-testid":"selection-toolbar-ungroup",children:(0,_.jsx)(o,{size:16})}),Ie&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(K,{label:"Save Block changes",onClick:()=>oe(Ie.id),"data-testid":"selection-toolbar-save-modular-subtree",children:(0,_.jsx)(s,{size:16})}),Ie.data.blockProjectionContainer?(0,_.jsx)(K,{label:!1===Ie.data.blockProjectionContainerExpanded?"Expand Modular Diffusers block":"Collapse Modular Diffusers block",onClick:Ue,"data-testid":"selection-toolbar-toggle-modular-block",children:!1===Ie.data.blockProjectionContainerExpanded?(0,_.jsx)(x,{size:16}):(0,_.jsx)(f,{size:16})}):null]}),Ce?(0,_.jsx)(K,{label:Ce.data.blockInstanceV2&&!Pe?"Inspect Block":"Inspect node",onClick:()=>le(Ce.id),"data-testid":"selection-toolbar-inspect-node",children:(0,_.jsx)(n,{size:16})}):null,He&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(J,{}),(0,_.jsx)(K,{label:"Duplicate node",onClick:Ke,"data-testid":"selection-toolbar-duplicate",children:(0,_.jsx)(a,{size:16})}),(0,_.jsx)(K,{label:Ne?.data.blockInstanceV2&&!Pe?"Run Block":"Run from node",onClick:()=>{Je()},"data-testid":"selection-toolbar-run-from-node",children:(0,_.jsx)(h,{size:16})}),Ve&&(0,_.jsx)(K,{label:Be?De?Re?"Collapse Block":"Collapse block":Re?"Expand Block to view internal nodes":"Expand block to edit internal nodes":Me?"Expand node":"Collapse node",onClick:Xe,"data-testid":"selection-toolbar-collapse",children:Be?De?(0,_.jsx)(f,{size:16}):(0,_.jsx)(x,{size:16}):Me?(0,_.jsx)(x,{size:16}):(0,_.jsx)(f,{size:16})})]}),Oe&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(J,{}),(0,_.jsx)(K,{label:"Repeat selection in a loop",onClick:Le,"data-testid":"selection-toolbar-create-loop",children:(0,_.jsx)(b,{size:17})}),(0,_.jsx)(K,{label:c||"Create block from selection",active:!0,disabled:We,onClick:v,"data-testid":"selection-toolbar-create-block",children:(0,_.jsx)(n,{size:17})})]}),He&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(J,{}),(0,_.jsxs)(C,{children:[(0,_.jsx)(P,{children:(0,_.jsx)(K,{label:"More node actions","data-testid":"selection-toolbar-more",children:(0,_.jsx)(r,{size:16})})}),Ne?(0,_.jsxs)(N,{anchor:"bottom end",layer:"graph",className:"w-52","data-testid":"selection-toolbar-more-menu",children:[(0,_.jsx)(E,{icon:(0,_.jsx)(d,{size:15}),onClick:qe,children:Fe?"Enable for run":"Disable for run"}),(0,_.jsx)(E,{icon:(0,_.jsx)(p,{size:15}),onClick:()=>{Qe()},children:"Recompute on next Run"}),(0,_.jsx)(E,{icon:(0,_.jsx)(j,{size:15}),disabled:!Ne.data.isCached,onClick:()=>{Ye()},children:"Release node cache"}),(0,_.jsx)(E,{icon:(0,_.jsx)(p,{size:15}),disabled:"block"!==Ne.data.type&&void 0===Ne.width&&void 0===Ne.height,onClick:Ge,children:De?Re?"Fit Block to contents":"Fit block to contents":Be?Re?"Reset Block size":"Reset block size":"Reset automatic size"}),(0,_.jsx)(E,{icon:(0,_.jsx)(g,{size:15}),onClick:Ze,children:"Copy node info"}),(0,_.jsx)(E,{icon:(0,_.jsx)(l,{size:15}),onClick:et,children:"Inspect issues"})]}):null]})]}),ae?(0,_.jsx)(A,{nodeId:ae,onClose:()=>oe(null)},ae):null,ne?(0,_.jsx)(L.Suspense,{fallback:null,children:(0,_.jsx)(U,{nodeId:ne,onClose:()=>le(null)},ne)}):null]}):null}export{X as SelectionToolbar}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$n as t,$t as a,F as o,Pn as n,R as l,Tt as i,X as s,at as d,cn as r,cr as c,dr as u,it as p,nt as b,pn as g,rr as k,st as h,wt as x,xt as f,yn as j,z as m}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Dt as C,Hr as v,Ln as y,Ni as w,Nt as z,Os as S,Po as I,Pt as P,Ti as N,Un as R,Wn as D,Yn as E,ar as B,dt as M,gr as F,hi as T,jt as H,kt as W,or as O,ti as V,wo as L,xo as $}from"./studio-templates.js?v=ca6b74e6a02eedb3";var A=e(u(),1),_=c(),U=(0,A.lazy)(()=>N(()=>import(`./NodeInspectorDialog.js?v=ca6b74e6a02eedb3`).then(e=>e.n),[])),K=(0,A.forwardRef)(function({active:e=!1,children:t,className:a,danger:o=!1,disabled:n=!1,label:l,onClick:i,type:s="button",...d},r){return(0,_.jsx)(C,{ref:r,type:s,label:l,size:"dense",active:e&&!n,tone:o&&!n?"danger":"ghost","aria-disabled":n,onClick:e=>{n?e.preventDefault():i?.(e)},className:y(n&&"cursor-not-allowed opacity-40",a),...d,children:t})});function X(){return(0,_.jsx)("span",{className:"mx-0.5 h-6 w-px bg-modiff-border","aria-hidden":"true"})}function Y({canvasSuspended:e,createBlockDisabledReason:c,nodes:u,onCreateBlockFromSelection:C,selectionDragging:N}){let Y=(0,A.useRef)(null),[q,G]=(0,A.useState)(!1),[J,Q]=(0,A.useState)(0),Z=k(),{flowToScreenPosition:ee,getNodesBounds:te}=t(),[ae,oe]=(0,A.useState)(null),[ne,le]=(0,A.useState)(null),ie=E(e=>e.sid),se=E(e=>e.isConnected),de=v(e=>e.removeNodes),re=v(e=>e.duplicateNode),ce=v(e=>e.toggleNodeCollapsed),ue=v(e=>e.toggleUserBlockExpanded),pe=v(e=>e.toggleHuggingFaceClusterExpanded),be=v(e=>e.toggleBlockContainerExpandedV2),ge=v(e=>e.setNodeUiState),ke=v(e=>e.resetNodeSize),he=v(e=>e.loopNodes),xe=v(e=>e.ungroupNodes),fe=v(e=>e.setNodeCached),je=(0,A.useMemo)(()=>u.filter(e=>e.selected),[u]),me=(0,A.useMemo)(()=>je.filter(e=>"group"!==e.data.type&&"loop"!==e.data.type),[je]),Ce=1===je.length?je[0]:null;(0,A.useEffect)(()=>{ne&&Ce?.id!==ne&&le(null)},[ne,Ce?.id]);let ve=2===je.length?je.find(e=>"custom"===e.data.type&&!e.parentId&&!e.data.blockProjectionOwnerId):void 0,ye=ve?je.find(e=>"internal"===e.data.blockProjectionKind&&!e.data.blockProjectionContainer):void 0,we=D(u,je.map(e=>e.id)),ze=we.length>0&&we.every(e=>e.data.blockProjectionOwnerId&&"internal"===e.data.blockProjectionKind||e.data.userBlockInstanceId||"execution"===e.data.huggingFaceClusterRole&&e.parentId),Se="group"===Ce?.data.type||"loop"===Ce?.data.type?Ce:null,Ie="internal"===Ce?.data.blockProjectionKind&&(!0===Ce.data.blockProjectionModular||"group"===Ce.data.type)&&Ce.data.blockProjectionOwnerId&&Ce.data.blockProjectionNodeId?Ce:null,Pe=Ie||"group"===Ce?.data.type||"loop"===Ce?.data.type?null:Ce,Ne=S(Pe?.data.blockInstanceV2),Re=!Ne&&"block"===Pe?.data.type,De="root"===Pe?.data.huggingFaceClusterRole,Ee=!(!Re&&!De),Be=!!Pe?.data.blockInstanceV2?.presentation.expanded||!!(Re&&Pe&&T({nodes:u,edges:[]},Pe.id))||!!(De&&Pe&&V({nodes:u,edges:[]},Pe.id)),Me=!(!Pe?.data.uiState?.collapsed&&!Pe?.data.minimized),Fe=!!Pe?.data.uiState?.disabled,Te=Pe?.data.uiState?.validationMessage||Pe?.data.uiState?.errorMessage,He=!!Pe,We=!Ne&&("custom"===Pe?.data.type||Ee),Oe=me.length>0&&!Ie&&!(1===me.length&&("block"===me[0]?.data.type||"root"===me[0]?.data.huggingFaceClusterRole)),Ve=!!c,Le=!e&&!N&&je.length>0&&(He||Oe||!!Se||!!Ie);(0,A.useEffect)(()=>{let e=()=>Q(e=>e+1);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]),(0,A.useLayoutEffect)(()=>{let e=Y.current;if(!Le||!e)return void G(!1);let t=te(je),a=t.x+t.width/2,o=ee({x:a,y:t.y}),n=ee({x:a,y:t.y+t.height}),l=e.offsetWidth,i=e.offsetHeight,s=e.parentElement?.getBoundingClientRect(),d=(s?.left??0)+8,r=(s?.top??0)+8,c=Math.max(d,(s?.right??window.innerWidth)-l-8),u=Math.max(r,(s?.bottom??window.innerHeight)-i-8),p=o.x-l/2,b=o.y-i-12;b{de(je.map(e=>e.id))},[de,je]),Ae=(0,A.useCallback)(()=>{he(me.map(e=>e.id))},[he,me]),_e=(0,A.useCallback)(()=>{Se&&xe(Se.id)},[Se,xe]),Ue=(0,A.useCallback)(()=>{!Ie?.data.blockProjectionContainer||!Ie.data.blockProjectionOwnerId||!Ie.data.blockProjectionNodeId||(be(Ie.data.blockProjectionOwnerId,Ie.data.blockProjectionNodeId),w.getState().saveActiveWorkflowTab(!0))},[Ie,be]),Ke=(0,A.useCallback)(()=>{Pe&&re(Pe.id)},[re,Pe]),Xe=(0,A.useCallback)(async()=>{if(Pe)try{if(("root"===Pe.data.huggingFaceClusterRole||Pe.data.blockInstanceV2)&&await O([Pe.id]),!F({sid:ie,isConnected:se,includeStudio:!1,targetNodeId:Pe.id}).canRun||!ie)return;await B({sid:ie,targetNodeId:Pe.id})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error",persist:!0})}},[se,ie,Pe]),Ye=(0,A.useCallback)(()=>{Pe&&("block"===Pe.data.type?(ue(Pe.id),w.getState().saveActiveWorkflowTab(!0)):"root"===Pe.data.huggingFaceClusterRole?(pe(Pe.id),w.getState().saveActiveWorkflowTab(!0)):ce(Pe.id))},[Pe,pe,ce,ue]),qe=(0,A.useCallback)(()=>{Pe&&ge(Pe.id,{disabled:!Fe,validationSeverity:Fe?void 0:"warning",validationMessage:Fe?void 0:"Disabled nodes are skipped during run export."})},[Fe,ge,Pe]),Ge=(0,A.useCallback)(()=>{Pe&&ke(Pe.id)},[ke,Pe]),Je=(0,A.useCallback)(async()=>{if(Pe)try{let e=await L([Pe.id]);e.nodes.length&&fe(Pe.id,!1),I(e.nodes.length?"Outputs will recompute on the next Run. Loaded models are retained.":"Loaded models retained; no computed outputs to invalidate.",{variant:"success",autoHideDuration:3500})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error"})}},[Pe,fe]),Qe=(0,A.useCallback)(async()=>{if(Pe)try{await $([Pe.id]),fe(Pe.id,!1),I("Node cache released",{variant:"success",autoHideDuration:1500})}catch(e){I(e instanceof Error?e.message:String(e),{variant:"error",autoHideDuration:2600})}},[fe,Pe]),Ze=(0,A.useCallback)(()=>{Pe&&navigator.clipboard.writeText(`${Pe.id}\n${Pe.data.module}.${Pe.data.action}`).then(()=>I("Node info copied",{variant:"success",autoHideDuration:1600})).catch(e=>I(String(e),{variant:"error",autoHideDuration:2600}))},[Pe]),et=(0,A.useCallback)(()=>{I(Te||"No issues recorded for this node.",{variant:Te?"error":"default",autoHideDuration:Te?4200:2200})},[Te]);return Le?(0,_.jsxs)("div",{ref:Y,className:y("nodrag nowheel fixed left-0 top-0 z-40 flex h-10 items-center gap-1 rounded-modiff-panel border border-modiff-border bg-modiff-panel p-1 shadow-modiff-node transition-opacity translate-x-[var(--modiff-selection-toolbar-x)] translate-y-[var(--modiff-selection-toolbar-y)]",q?"opacity-100":"opacity-0"),"data-testid":"selection-toolbar",role:"toolbar","aria-label":"Selection toolbar",onPointerDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[(0,_.jsx)(K,{label:"Delete selection",title:"Delete selection · Delete / Backspace","aria-keyshortcuts":"Delete Backspace",danger:!0,onClick:$e,"data-testid":"selection-toolbar-delete",children:(0,_.jsx)(m,{size:16})}),ve&&ye?(0,_.jsx)(K,{label:"Replace internal node with selected node","data-testid":"selection-toolbar-replace-internal",onClick:()=>{try{v.getState().replaceNodeInBlockV2(ve.id,ye.id),w.getState().saveActiveWorkflowTab(!0),I("The internal node was replaced in this workflow Block.",{variant:"success"})}catch(e){I(e instanceof Error?e.message:"Could not replace this internal node.",{variant:"error"})}},children:(0,_.jsx)(p,{size:16})}):null,ze?(0,_.jsx)(K,{label:"Move out of Block",title:"Move out of Block · Ctrl/Cmd + drag to move between Blocks","data-testid":"selection-toolbar-move-out",onClick:async()=>{try{await R(je.map(e=>e.id),null,"out"),w.getState().saveActiveWorkflowTab(!0)}catch(e){I(e instanceof Error?e.message:"Could not move this item out of the Block.",{variant:"error",autoHideDuration:6e3})}},children:(0,_.jsx)(i,{size:16})}):null,Se&&!Ie&&(0,_.jsx)(K,{label:"loop"===Se.data.type?"Remove loop container":"Ungroup nodes",onClick:_e,"data-testid":"selection-toolbar-ungroup",children:(0,_.jsx)(o,{size:16})}),Ie&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(K,{label:"Save Block changes",onClick:()=>oe(Ie.id),"data-testid":"selection-toolbar-save-modular-subtree",children:(0,_.jsx)(s,{size:16})}),Ie.data.blockProjectionContainer?(0,_.jsx)(K,{label:!1===Ie.data.blockProjectionContainerExpanded?"Expand Modular Diffusers block":"Collapse Modular Diffusers block",onClick:Ue,"data-testid":"selection-toolbar-toggle-modular-block",children:!1===Ie.data.blockProjectionContainerExpanded?(0,_.jsx)(x,{size:16}):(0,_.jsx)(f,{size:16})}):null]}),Ce?(0,_.jsx)(K,{label:Ce.data.blockInstanceV2&&!Ne?"Inspect Block":"Inspect node",onClick:()=>le(Ce.id),"data-testid":"selection-toolbar-inspect-node",children:(0,_.jsx)(n,{size:16})}):null,He&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(X,{}),(0,_.jsx)(K,{label:"Duplicate node",onClick:Ke,"data-testid":"selection-toolbar-duplicate",children:(0,_.jsx)(a,{size:16})}),(0,_.jsx)(K,{label:Pe?.data.blockInstanceV2&&!Ne?"Run Block":"Run from node",onClick:()=>{Xe()},"data-testid":"selection-toolbar-run-from-node",children:(0,_.jsx)(h,{size:16})}),We&&(0,_.jsx)(K,{label:Ee?Be?De?"Collapse Block":"Collapse block":De?"Expand Block to view internal nodes":"Expand block to edit internal nodes":Me?"Expand node":"Collapse node",onClick:Ye,"data-testid":"selection-toolbar-collapse",children:Ee?Be?(0,_.jsx)(f,{size:16}):(0,_.jsx)(x,{size:16}):Me?(0,_.jsx)(x,{size:16}):(0,_.jsx)(f,{size:16})})]}),Oe&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(X,{}),(0,_.jsx)(K,{label:"Repeat selection in a loop",onClick:Ae,"data-testid":"selection-toolbar-create-loop",children:(0,_.jsx)(b,{size:17})}),(0,_.jsx)(K,{label:c||"Create block from selection",active:!0,disabled:Ve,onClick:C,"data-testid":"selection-toolbar-create-block",children:(0,_.jsx)(n,{size:17})})]}),He&&(0,_.jsxs)(_.Fragment,{children:[(0,_.jsx)(X,{}),(0,_.jsxs)(H,{children:[(0,_.jsx)(P,{children:(0,_.jsx)(K,{label:"More node actions","data-testid":"selection-toolbar-more",children:(0,_.jsx)(r,{size:16})})}),Pe?(0,_.jsxs)(z,{anchor:"bottom end",layer:"graph",className:"w-52","data-testid":"selection-toolbar-more-menu",children:[(0,_.jsx)(W,{icon:(0,_.jsx)(d,{size:15}),onClick:qe,children:Fe?"Enable for run":"Disable for run"}),(0,_.jsx)(W,{icon:(0,_.jsx)(p,{size:15}),onClick:()=>{Je()},children:"Recompute on next Run"}),(0,_.jsx)(W,{icon:(0,_.jsx)(j,{size:15}),disabled:!Pe.data.isCached,onClick:()=>{Qe()},children:"Release node cache"}),(0,_.jsx)(W,{icon:(0,_.jsx)(p,{size:15}),disabled:"block"!==Pe.data.type&&void 0===Pe.width&&void 0===Pe.height,onClick:Ge,children:Be?De?"Fit Block to contents":"Fit block to contents":Ee?De?"Reset Block size":"Reset block size":"Reset automatic size"}),(0,_.jsx)(W,{icon:(0,_.jsx)(g,{size:15}),onClick:Ze,children:"Copy node info"}),(0,_.jsx)(W,{icon:(0,_.jsx)(l,{size:15}),onClick:et,children:"Inspect issues"})]}):null]})]}),ae?(0,_.jsx)(M,{nodeId:ae,onClose:()=>oe(null)},ae):null,ne?(0,_.jsx)(A.Suspense,{fallback:null,children:(0,_.jsx)(U,{nodeId:ne,onClose:()=>le(null)},ne)}):null]}):null}export{Y as SelectionToolbar}; \ No newline at end of file diff --git a/web/assets/ServiceExportDialog.js b/web/assets/ServiceExportDialog.js index b410200..3df76ff 100644 --- a/web/assets/ServiceExportDialog.js +++ b/web/assets/ServiceExportDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as r}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Ei as i,Eo as a,Oo as s,Ti as n,fn as o,in as l,mn as d,oc as p,rn as c}from"./studio-templates.js?v=cc046c26d6fe7aa4";var u=e(r(),1),f=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function h(e){if(!f(e)||!1!==e.error)throw Error("Invalid service inspection response.");let t=e=>{if(!Array.isArray(e)||e.length>32768)throw Error("Invalid service fields.");return e.map(e=>{if(!f(e)||!["nodeId","field","type"].every(t=>"string"==typeof e[t]))throw Error("Invalid service field identity.");return{nodeId:String(e.nodeId),field:String(e.field),type:String(e.type)}})};return{inputs:t(e.inputs),outputs:t(e.outputs)}}function g(e,t=0){return!(t>64)&&(null===e||"string"==typeof e||"boolean"==typeof e||("number"==typeof e?Number.isFinite(e):Array.isArray(e)?e.every(e=>g(e,t+1)):f(e)&&Object.values(e).every(e=>g(e,t+1))))}function m(e){if(!f(e)||!1!==e.error||!f(e.package))throw Error("Invalid service export.");let t=e.package;if(!("modiff-service-v1"===t.schema&&"string"==typeof t.contentHash&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)&&f(t.graph)&&f(t.graph.nodes)&&Array.isArray(t.graph.paths)&&f(t.interface)&&f(t.interface.inputs)&&f(t.interface.outputs)&&f(t.requirements)&&g(t))||JSON.stringify(t).length>8388608)throw Error("Invalid service package contract.");return t}var v=e=>s(`${p.serverAddress}/service_package`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:"inspect",graph:e}),parse:h}),y=(e,t)=>s(`${p.serverAddress}/service_package`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:"build",graph:e,interface:t}),parse:m}),w=t();function b({getGraph:e,onClose:t}){let r=(0,u.useRef)(i()),[s,p]=(0,u.useState)(null),[f,h]=(0,u.useState)({inputs:[],outputs:[]}),[g,m]=(0,u.useState)({}),[b,x]=(0,u.useState)(""),[j,O]=(0,u.useState)(!0);return(0,u.useEffect)(()=>{let t=!0;return(async()=>{try{let{apiGraph:i}=await e();if(!i)throw Error("Connect to MoDiff before exporting a service.");let a=await v(i);n(r.current),t&&(p(i),h(a))}catch(e){t&&x(a(e,"Could not inspect this graph."))}finally{t&&O(!1)}})(),()=>{t=!1}},[e]),(0,w.jsx)(l,{open:!0,onClose:j?()=>{}:t,dismissible:!j,title:"Export service package",description:"Name the inputs callers supply and the outputs they receive. Leave unused fields blank.",testId:"service-export-dialog",panelClassName:"max-w-2xl",footer:(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(c,{disabled:j,onClick:t,children:"Cancel"}),(0,w.jsx)(c,{disabled:!s||j,loading:j,onClick:()=>{!async function(){if(s){O(!0),x("");try{n(r.current);let i=await e();if(JSON.stringify(i.apiGraph)!==JSON.stringify(s))throw Error("The graph changed during export. Close this dialog and review the service fields again.");let a=await y(s,function(e,t){let r={inputs:{},outputs:{}};for(let i of["inputs","outputs"])for(let a of e[i]){let e=t[JSON.stringify([i,a.nodeId,a.field])]?.trim();if(e){if(!/^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(e))throw Error("Use names starting with a letter, followed by letters, digits or underscores.");if(Object.prototype.hasOwnProperty.call(r[i],e))throw Error(`Use a different name for each ${i} field.`);Object.defineProperty(r[i],e,{value:[{nodeId:a.nodeId,field:a.field}],enumerable:!0})}}if(!Object.keys(r.outputs).length)throw Error("Name at least one preview output.");return r}(f,g));n(r.current);let o=await e();if(JSON.stringify(o.apiGraph)!==JSON.stringify(s))throw Error("The graph changed during export. Close this dialog and review the service fields again.");let l=URL.createObjectURL(new Blob([JSON.stringify(a,null,2)],{type:"application/json"})),d=document.createElement("a");d.href=l,d.download="modiff-service.json",d.click(),setTimeout(()=>URL.revokeObjectURL(l),1e3),t()}catch(e){x(a(e,"Could not export this service."))}finally{O(!1)}}}()},tone:"primary",children:"Download service package"})]}),children:(0,w.jsxs)("div",{className:"grid gap-4",children:[(0,w.jsx)("p",{className:"text-modiff-metadata text-modiff-subtle-text",children:"Named inputs are required on each call; their current values are omitted. Other graph values remain in the package. Review prompts and metadata before sharing. Models need immutable revisions and custom nodes need the same reviewed source. This package runs through a local MoDiff server."}),b&&(0,w.jsx)("p",{role:"alert",className:"text-modiff-metadata text-modiff-red",children:b}),!j&&!f.outputs.length&&(0,w.jsx)("p",{children:"Add an Image Preview, Data Viewer, or another preview node to expose a service output."}),["inputs","outputs"].map(e=>(0,w.jsxs)("fieldset",{disabled:j,className:"grid gap-2",children:[(0,w.jsx)("legend",{className:"mb-2 font-semibold",children:"inputs"===e?"Inputs":"Outputs"}),f[e].map(t=>{let r=JSON.stringify([e,t.nodeId,t.field]);return(0,w.jsx)(o,{label:`${t.nodeId} · ${t.field}`,description:t.type,children:(0,w.jsx)(d,{"aria-label":`${e} ${t.nodeId}.${t.field}`,value:g[r]??"",placeholder:"Service name (optional)",onChange:e=>m({...g,[r]:e.currentTarget.value})})},r)})]},e))]})})}export{b as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as r}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ao as i,Di as a,Oi as s,Oo as n,an as o,hn as l,in as d,lc as p,pn as c}from"./studio-templates.js?v=ca6b74e6a02eedb3";var u=e(r(),1),f=e=>"object"==typeof e&&!!e&&!Array.isArray(e);function h(e){if(!f(e)||!1!==e.error)throw Error("Invalid service inspection response.");let t=e=>{if(!Array.isArray(e)||e.length>32768)throw Error("Invalid service fields.");return e.map(e=>{if(!f(e)||!["nodeId","field","type"].every(t=>"string"==typeof e[t]))throw Error("Invalid service field identity.");return{nodeId:String(e.nodeId),field:String(e.field),type:String(e.type)}})};return{inputs:t(e.inputs),outputs:t(e.outputs)}}function g(e,t=0){return!(t>64)&&(null===e||"string"==typeof e||"boolean"==typeof e||("number"==typeof e?Number.isFinite(e):Array.isArray(e)?e.every(e=>g(e,t+1)):f(e)&&Object.values(e).every(e=>g(e,t+1))))}function m(e){if(!f(e)||!1!==e.error||!f(e.package))throw Error("Invalid service export.");let t=e.package;if(!("modiff-service-v1"===t.schema&&"string"==typeof t.contentHash&&/^sha256:[a-f0-9]{64}$/u.test(t.contentHash)&&f(t.graph)&&f(t.graph.nodes)&&Array.isArray(t.graph.paths)&&f(t.interface)&&f(t.interface.inputs)&&f(t.interface.outputs)&&f(t.requirements)&&g(t))||JSON.stringify(t).length>8388608)throw Error("Invalid service package contract.");return t}var v=e=>i(`${p.serverAddress}/service_package`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:"inspect",graph:e}),parse:h}),y=(e,t)=>i(`${p.serverAddress}/service_package`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({operation:"build",graph:e,interface:t}),parse:m}),w=t();function b({getGraph:e,onClose:t}){let r=(0,u.useRef)(s()),[i,p]=(0,u.useState)(null),[f,h]=(0,u.useState)({inputs:[],outputs:[]}),[g,m]=(0,u.useState)({}),[b,x]=(0,u.useState)(""),[j,O]=(0,u.useState)(!0);return(0,u.useEffect)(()=>{let t=!0;return(async()=>{try{let{apiGraph:i}=await e();if(!i)throw Error("Connect to MoDiff before exporting a service.");let s=await v(i);a(r.current),t&&(p(i),h(s))}catch(e){t&&x(n(e,"Could not inspect this graph."))}finally{t&&O(!1)}})(),()=>{t=!1}},[e]),(0,w.jsx)(o,{open:!0,onClose:j?()=>{}:t,dismissible:!j,title:"Export service package",description:"Name the inputs callers supply and the outputs they receive. Leave unused fields blank.",testId:"service-export-dialog",panelClassName:"max-w-2xl",footer:(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(d,{disabled:j,onClick:t,children:"Cancel"}),(0,w.jsx)(d,{disabled:!i||j,loading:j,onClick:()=>{!async function(){if(i){O(!0),x("");try{a(r.current);let s=await e();if(JSON.stringify(s.apiGraph)!==JSON.stringify(i))throw Error("The graph changed during export. Close this dialog and review the service fields again.");let n=await y(i,function(e,t){let r={inputs:{},outputs:{}};for(let i of["inputs","outputs"])for(let a of e[i]){let e=t[JSON.stringify([i,a.nodeId,a.field])]?.trim();if(e){if(!/^[A-Za-z][A-Za-z0-9_]{0,63}$/u.test(e))throw Error("Use names starting with a letter, followed by letters, digits or underscores.");if(Object.prototype.hasOwnProperty.call(r[i],e))throw Error(`Use a different name for each ${i} field.`);Object.defineProperty(r[i],e,{value:[{nodeId:a.nodeId,field:a.field}],enumerable:!0})}}if(!Object.keys(r.outputs).length)throw Error("Name at least one preview output.");return r}(f,g));a(r.current);let o=await e();if(JSON.stringify(o.apiGraph)!==JSON.stringify(i))throw Error("The graph changed during export. Close this dialog and review the service fields again.");let l=URL.createObjectURL(new Blob([JSON.stringify(n,null,2)],{type:"application/json"})),d=document.createElement("a");d.href=l,d.download="modiff-service.json",d.click(),setTimeout(()=>URL.revokeObjectURL(l),1e3),t()}catch(e){x(n(e,"Could not export this service."))}finally{O(!1)}}}()},tone:"primary",children:"Download service package"})]}),children:(0,w.jsxs)("div",{className:"grid gap-4",children:[(0,w.jsx)("p",{className:"text-modiff-metadata text-modiff-subtle-text",children:"Named inputs are required on each call; their current values are omitted. Other graph values remain in the package. Review prompts and metadata before sharing. Models need immutable revisions and custom nodes need the same reviewed source. This package runs through a local MoDiff server."}),b&&(0,w.jsx)("p",{role:"alert",className:"text-modiff-metadata text-modiff-red",children:b}),!j&&!f.outputs.length&&(0,w.jsx)("p",{children:"Add an Image Preview, Data Viewer, or another preview node to expose a service output."}),["inputs","outputs"].map(e=>(0,w.jsxs)("fieldset",{disabled:j,className:"grid gap-2",children:[(0,w.jsx)("legend",{className:"mb-2 font-semibold",children:"inputs"===e?"Inputs":"Outputs"}),f[e].map(t=>{let r=JSON.stringify([e,t.nodeId,t.field]);return(0,w.jsx)(c,{label:`${t.nodeId} · ${t.field}`,description:t.type,children:(0,w.jsx)(l,{"aria-label":`${e} ${t.nodeId}.${t.field}`,value:g[r]??"",placeholder:"Service name (optional)",onChange:e=>m({...g,[r]:e.currentTarget.value})})},r)})]},e))]})})}export{b as default}; \ No newline at end of file diff --git a/web/assets/SettingsDialog.js b/web/assets/SettingsDialog.js index fe319be..041a73a 100644 --- a/web/assets/SettingsDialog.js +++ b/web/assets/SettingsDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$ as s,K as a,Vn as t,_n as l,cr as i,dr as r,z as n}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Cr as d,Eo as o,Mo as c,Sa as m,Vr as x,an as f,fn as p,in as b,mo as u,on as h,rn as g,vn as j,xn as v}from"./studio-templates.js?v=cc046c26d6fe7aa4";var N=e(r(),1),k=i(),w=[{id:"preferences",label:"Preferences"},{id:"tasks",label:"Tasks"},{id:"about",label:"About"}],y=[{id:"default",label:"Curve"},{id:"smoothstep",label:"Step"}],C=({opener:e,onClose:i})=>{let{edgeType:r,setEdgeType:C,resetToDefault:$}=m(),z=x(e=>e.setAllEdgesType),{queuedTasks:S,currentTask:T,taskCount:A}=d(),[R,V]=(0,N.useState)("preferences");return(0,k.jsxs)(b,{open:!!e,onClose:i,title:(0,k.jsxs)("span",{className:"flex items-center gap-2",children:[(0,k.jsx)(a,{size:17,className:"text-hf-yellow"}),"Settings"]}),description:"App preferences and current task activity.",panelClassName:"max-w-2xl",bodyClassName:"!p-0",testId:"settings-dialog",footer:(0,k.jsx)(g,{onClick:i,children:"Close"}),toolbar:(0,k.jsx)(v,{"aria-label":"Settings sections",className:"p-2",options:w.map(e=>({value:e.id,label:e.label,id:`settings-tab-${e.id}`,controls:`settings-panel-${e.id}`})),value:R,onValueChange:V,size:"normal"}),children:[w.filter(e=>e.id!==R).map(e=>(0,k.jsx)("div",{id:`settings-panel-${e.id}`,role:"tabpanel","aria-labelledby":`settings-tab-${e.id}`,hidden:!0},e.id)),(0,k.jsxs)("div",{id:`settings-panel-${R}`,role:"tabpanel","aria-labelledby":`settings-tab-${R}`,className:"p-4",children:["preferences"===R&&(0,k.jsxs)("div",{className:"grid gap-5 text-sm text-modiff-text",children:[(0,k.jsxs)("section",{className:"grid gap-3",children:[(0,k.jsx)("h3",{className:"font-semibold",children:"Graph appearance"}),(0,k.jsx)(p,{label:"Connection style",description:"Applies to connections on the canvas and newly added links.",children:(0,k.jsx)(j,{"aria-label":"Line type",className:"flex flex-wrap gap-3",name:"edge-type",value:r,options:y.map(e=>({value:e.id,label:e.label})),onValueChange:e=>(e=>{C(e),z(e)})(e)})})]}),(0,k.jsxs)("section",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-modiff-border pt-4",children:[(0,k.jsxs)("div",{className:"min-w-0 flex-1 basis-56",children:[(0,k.jsx)("h3",{className:"font-semibold",children:"Restore app preferences"}),(0,k.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:"Reset view and panel preferences. Saved workflow files and downloaded models are not deleted."})]}),(0,k.jsx)(g,{icon:(0,k.jsx)(s,{size:15}),onClick:()=>{$(),z("default")},children:"Reset preferences"})]})]}),"tasks"===R&&(0,k.jsxs)("div",{className:"overflow-hidden rounded-modiff-compact border border-modiff-border",children:[(0,k.jsxs)("div",{className:"flex items-center gap-2 border-b border-modiff-border bg-modiff-panel px-3 py-3 text-sm font-semibold text-modiff-text",children:[(0,k.jsx)(l,{size:16,className:"text-modiff-subtle-text"}),A?`${A} task${1===A?"":"s"} in queue`:"No queued tasks"]}),T||0!==Object.keys(S).length?null:(0,k.jsx)("p",{className:"p-4 text-sm text-modiff-subtle-text",children:"Run a workflow to see its progress here. Pending tasks can be cancelled individually."}),T&&(0,k.jsxs)("div",{className:"flex items-center gap-3 border-b border-modiff-border px-3 py-3 text-sm text-modiff-text",children:[(0,k.jsx)(t,{size:18,className:"shrink-0 text-hf-yellow"}),(0,k.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,k.jsx)("div",{className:"truncate",children:`[${T.task_id?.substring(0,6)}] ${T.name}`}),(0,k.jsx)(h,{value:T.progress??0,className:"mt-2 max-w-[250px]"})]})]}),Object.entries(S).map(([e,s])=>(0,k.jsxs)("div",{className:"flex items-center gap-3 border-b border-modiff-border px-3 py-3 text-sm text-modiff-text last:border-b-0",children:[(0,k.jsx)(l,{size:18,className:"shrink-0 text-modiff-subtle-text"}),(0,k.jsx)("div",{className:"min-w-0 flex-1 truncate",children:`[${e.substring(0,6)}] ${s.name}`}),(0,k.jsx)(f,{label:"Cancel task",className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{(async e=>{try{await u(e)}catch(e){console.error("Failed to cancel task",e),c(o(e,"Failed to cancel task"),{variant:"error",autoHideDuration:1500})}})(e)},children:(0,k.jsx)(n,{size:15})})]},e))]}),"about"===R&&(0,k.jsxs)("div",{className:"grid gap-3 text-sm text-modiff-subtle-text",children:[(0,k.jsx)("h3",{className:"text-base font-semibold text-modiff-text",children:"MoDiff"}),(0,k.jsx)("p",{children:"A graph workspace for generating images, video and audio with modular model workflows."}),(0,k.jsx)("p",{children:"Use a Block as one node, or expand it to inspect and customize its connected blocks. Save workflow changes to keep prompts, parameters and layout."}),(0,k.jsx)("p",{children:"Models manages local artifacts and Hugging Face downloads. Setup contains runtime diagnostics and recovery actions."})]})]})]})};export{C as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$ as s,K as a,Vn as t,_n as l,cr as i,dr as r,z as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Hr as d,Oo as o,Po as c,Sn as m,an as p,go as x,in as f,on as b,pn as u,sn as h,wa as g,wr as j,yn as v}from"./studio-templates.js?v=ca6b74e6a02eedb3";var N=e(r(),1),k=i(),w=[{id:"preferences",label:"Preferences"},{id:"tasks",label:"Tasks"},{id:"about",label:"About"}],y=[{id:"default",label:"Curve"},{id:"smoothstep",label:"Step"}],C=({opener:e,onClose:i})=>{let{edgeType:r,setEdgeType:C,resetToDefault:$}=g(),z=d(e=>e.setAllEdgesType),{queuedTasks:S,currentTask:T,taskCount:A}=j(),[R,q]=(0,N.useState)("preferences");return(0,k.jsxs)(p,{open:!!e,onClose:i,title:(0,k.jsxs)("span",{className:"flex items-center gap-2",children:[(0,k.jsx)(a,{size:17,className:"text-hf-yellow"}),"Settings"]}),description:"App preferences and current task activity.",panelClassName:"max-w-2xl",bodyClassName:"!p-0",testId:"settings-dialog",footer:(0,k.jsx)(f,{onClick:i,children:"Close"}),toolbar:(0,k.jsx)(m,{"aria-label":"Settings sections",className:"p-2",options:w.map(e=>({value:e.id,label:e.label,id:`settings-tab-${e.id}`,controls:`settings-panel-${e.id}`})),value:R,onValueChange:q,size:"normal"}),children:[w.filter(e=>e.id!==R).map(e=>(0,k.jsx)("div",{id:`settings-panel-${e.id}`,role:"tabpanel","aria-labelledby":`settings-tab-${e.id}`,hidden:!0},e.id)),(0,k.jsxs)("div",{id:`settings-panel-${R}`,role:"tabpanel","aria-labelledby":`settings-tab-${R}`,className:"p-4",children:["preferences"===R&&(0,k.jsxs)("div",{className:"grid gap-5 text-sm text-modiff-text",children:[(0,k.jsxs)("section",{className:"grid gap-3",children:[(0,k.jsx)("h3",{className:"font-semibold",children:"Graph appearance"}),(0,k.jsx)(u,{label:"Connection style",description:"Applies to connections on the canvas and newly added links.",children:(0,k.jsx)(v,{"aria-label":"Line type",className:"flex flex-wrap gap-3",name:"edge-type",value:r,options:y.map(e=>({value:e.id,label:e.label})),onValueChange:e=>(e=>{C(e),z(e)})(e)})})]}),(0,k.jsxs)("section",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-modiff-border pt-4",children:[(0,k.jsxs)("div",{className:"min-w-0 flex-1 basis-56",children:[(0,k.jsx)("h3",{className:"font-semibold",children:"Restore app preferences"}),(0,k.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:"Reset view and panel preferences. Saved workflow files and downloaded models are not deleted."})]}),(0,k.jsx)(f,{icon:(0,k.jsx)(s,{size:15}),onClick:()=>{$(),z("default")},children:"Reset preferences"})]})]}),"tasks"===R&&(0,k.jsxs)("div",{className:"overflow-hidden rounded-modiff-compact border border-modiff-border",children:[(0,k.jsxs)("div",{className:"flex items-center gap-2 border-b border-modiff-border bg-modiff-panel px-3 py-3 text-sm font-semibold text-modiff-text",children:[(0,k.jsx)(l,{size:16,className:"text-modiff-subtle-text"}),A?`${A} task${1===A?"":"s"} in queue`:"No queued tasks"]}),T||0!==Object.keys(S).length?null:(0,k.jsx)("p",{className:"p-4 text-sm text-modiff-subtle-text",children:"Run a workflow to see its progress here. Pending tasks can be cancelled individually."}),T&&(0,k.jsxs)("div",{className:"flex items-center gap-3 border-b border-modiff-border px-3 py-3 text-sm text-modiff-text",children:[(0,k.jsx)(t,{size:18,className:"shrink-0 text-hf-yellow"}),(0,k.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,k.jsx)("div",{className:"truncate",children:`[${T.task_id?.substring(0,6)}] ${T.name}`}),(0,k.jsx)(h,{value:T.progress??0,className:"mt-2 max-w-[250px]"})]})]}),Object.entries(S).map(([e,s])=>(0,k.jsxs)("div",{className:"flex items-center gap-3 border-b border-modiff-border px-3 py-3 text-sm text-modiff-text last:border-b-0",children:[(0,k.jsx)(l,{size:18,className:"shrink-0 text-modiff-subtle-text"}),(0,k.jsx)("div",{className:"min-w-0 flex-1 truncate",children:`[${e.substring(0,6)}] ${s.name}`}),(0,k.jsx)(b,{label:"Cancel task",className:"border border-modiff-red text-modiff-red hover:bg-modiff-red/10 hover:text-modiff-red",onClick:()=>{(async e=>{try{await x(e)}catch(e){console.error("Failed to cancel task",e),c(o(e,"Failed to cancel task"),{variant:"error",autoHideDuration:1500})}})(e)},children:(0,k.jsx)(n,{size:15})})]},e))]}),"about"===R&&(0,k.jsxs)("div",{className:"grid gap-3 text-sm text-modiff-subtle-text",children:[(0,k.jsx)("h3",{className:"text-base font-semibold text-modiff-text",children:"MoDiff"}),(0,k.jsx)("p",{children:"A graph workspace for generating images, video and audio with modular model workflows."}),(0,k.jsx)("p",{children:"Use a Block as one node, or expand it to inspect and customize its connected blocks. Save workflow changes to keep prompts, parameters and layout."}),(0,k.jsx)("p",{children:"Models manages local artifacts and Hugging Face downloads. Setup contains runtime diagnostics and recovery actions."})]})]})]})};export{C as default}; \ No newline at end of file diff --git a/web/assets/SplineField.js b/web/assets/SplineField.js index 1fc337e..ca1ceb2 100644 --- a/web/assets/SplineField.js +++ b/web/assets/SplineField.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as r,er as l}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Rn as n,jn as i,rn as a,zn as u}from"./studio-templates.js?v=cc046c26d6fe7aa4";var o=e(r(),1),s=t(),c=u.hoverLight,f=n.splineCurve,d=n.primary,x=n.paper;function m(e){return!(!e||"object"!=typeof e||"number"!=typeof e.x||"number"!=typeof e.y)}function h(e){let t=(0,o.useRef)(null),r=(0,o.useRef)(null),n=(0,o.useRef)([]),u=(0,o.useRef)(null),h=(0,o.useRef)(null),y=l(e=>e.transform[2]),{fieldKey:p,hidden:v,label:g,style:b,updateStore:k,value:w}=e,M=(0,o.useCallback)(()=>{let e=n.current,t=e.length-1;if(t<1)return[];for(let r=0;re.x),l=e.map(e=>e.y),i=Array(t);for(let e=0;e=0;e--)u[e]=c[e]-s[e]*u[e+1];let f=Array(t);for(let e=0;e{let t=u.current;if(!t||0===t.length)return null;let r=t.findIndex(t=>t.x>e)-1;r<0&&(r=t.length-1);let l=t[r];if(!l)return null;let n=e-l.x;return l.y+l.b*n+l.c*n*n+l.d*n*n*n},[]),j=(0,o.useCallback)((e,t)=>{let r=n.current;for(let l=0;l{let e=n.current,l=t.current,i=r.current;if(!l||!i)return;let a=l.width,o=l.height,s=window.devicePixelRatio||1,m=Math.max(.4,Math.min(y,1.4));i.clearRect(0,0,a,o),i.strokeStyle=c,i.lineWidth=1*s*m;for(let e=0;e<10;e++){let t=e*a/10,r=e*o/10;i.beginPath(),i.moveTo(t,0),i.lineTo(t,o),i.stroke(),i.beginPath(),i.moveTo(0,r),i.lineTo(a,r),i.stroke()}if(e.length<2)return;let h=e[0],p=e[e.length-1];if(!h||!p)return;i.beginPath(),i.strokeStyle=f,i.lineWidth=2.5*s*m;let v=Math.max(0,Math.min(o,h.y));if(i.moveTo(0,v),i.lineTo(h.x,v),u.current&&u.current.length>0)for(let e=Math.ceil(h.x);e<=Math.floor(p.x);e++){let t=C(e);if(null!==t){let r=Math.max(0,Math.min(o,t));i.lineTo(e,r)}}let g=Math.max(0,Math.min(o,p.y));i.lineTo(p.x,g),i.lineTo(a,g),i.stroke(),e.forEach(e=>{i.beginPath(),i.arc(e.x,e.y,6*s*m,0,2*Math.PI),i.fillStyle=d,i.fill(),i.strokeStyle=x,i.lineWidth=2*s*m,i.stroke()})},[C,y]),R=(0,o.useCallback)(e=>{let r=t.current;if(!r)return{x:0,y:0};let l=r.getBoundingClientRect(),n=window.devicePixelRatio||1;return{x:(e.clientX-l.left)*n,y:(e.clientY-l.top)*n}},[]),A=(0,o.useCallback)(e=>{let r=t.current;if(!r)return;n.current=e;let l=e.map(e=>({x:Math.max(0,Math.min(1,parseFloat((e.x/r.width).toFixed(6)))),y:Math.max(0,Math.min(1,parseFloat((1-e.y/r.height).toFixed(6))))}));k(p,l)},[p,k]),L=(0,o.useCallback)(e=>{let r=h.current;if(null===r)return;e.preventDefault(),e.stopPropagation();let l=n.current;if(r>=l.length)return;let i=l[r];if(!i)return;let a=R(e),u=t.current;if(!u)return;let o=u.width,s=u.height;i.x=a.x,i.y=Math.max(0,Math.min(s,a.y)),l.sort((e,t)=>e.x-t.x);let c=l.indexOf(i);if(c<0)return;h.current=c;let f=l[c-1],d=l[c+1],x=0===c?0:(f?.x??0)+3,m=c===l.length-1?o:(d?.x??o)-3;i.x=Math.max(x,Math.min(m,i.x)),A(l)},[R,A]),P=(0,o.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),h.current=null;let t=n.current;t.sort((e,t)=>e.x-t.x),A(t),document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",P)},[L,A]),T=(0,o.useCallback)(e=>{if(0!==e.button||null==t.current)return;let r=R(e),l=n.current,i=j(r.x,r.y);if(null!==i)h.current=l.indexOf(i);else{let e=l[0],t=l[l.length-1];if(!e||!t)return;if(r.x>e.x&&r.xe.x-t.x),h.current=n.indexOf(t),A(n)}}}document.addEventListener("mousemove",L),document.addEventListener("mouseup",P)},[C,j,R,L,P,A]),N=(0,o.useCallback)(e=>{if(0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=n.current;if(t.length<=2)return;let r=R(e),l=j(r.x,r.y);if(l){let e=t.filter(e=>e!==l);A(e)}},[j,R,A]);return(0,o.useEffect)(()=>{let e=t.current;if(null==e)return;r.current||=e.getContext("2d");let l=Array.isArray(w)?w.filter(m):[];if(!Array.isArray(l)||l.length<2)return void k(p,[{x:0,y:0},{x:1,y:1}]);let i=window.devicePixelRatio||1,a=320*y*i,o=320*y*i;e.width=a,e.height=o,n.current=l.map(t=>({x:t.x*e.width,y:(1-t.y)*e.height})),u.current=M(),E()},[M,E,p,k,w,y]),(0,o.useEffect)(()=>{let e=t.current;if(null!=e)return r.current=e.getContext("2d"),e.addEventListener("mousedown",T),e.addEventListener("dblclick",N),()=>{e.removeEventListener("mousedown",T),document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",P),e.removeEventListener("dblclick",N)}},[N,T,L,P]),(0,s.jsxs)(i,{dataKey:p,hidden:v,layoutStyle:b,className:"nodrag",children:[(0,s.jsx)("div",{className:"text-modiff-control truncate text-modiff-subtle-text",title:g,children:g}),(0,s.jsxs)("div",{className:"flex w-full flex-col items-center justify-between",children:[(0,s.jsx)("div",{className:"m-0 w-[320px] overflow-hidden rounded-modiff-compact border border-modiff-border p-0",children:(0,s.jsx)("canvas",{ref:t,className:"block aspect-square w-[320px] cursor-crosshair"})}),(0,s.jsx)("div",{className:"mt-2 w-full",children:(0,s.jsx)(a,{className:"min-h-0 px-3 py-1.5",onClick:()=>{k(p,[{x:0,y:0},{x:1,y:1}])},children:"Reset"})})]})]})}export{h as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as r,er as l}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Bn as n,Mn as i,in as a,zn as u}from"./studio-templates.js?v=ca6b74e6a02eedb3";var o=e(r(),1),s=t(),c=n.hoverLight,f=u.splineCurve,d=u.primary,x=u.paper;function m(e){return!(!e||"object"!=typeof e||"number"!=typeof e.x||"number"!=typeof e.y)}function h(e){let t=(0,o.useRef)(null),r=(0,o.useRef)(null),n=(0,o.useRef)([]),u=(0,o.useRef)(null),h=(0,o.useRef)(null),y=l(e=>e.transform[2]),{fieldKey:p,hidden:v,label:g,style:b,updateStore:k,value:M}=e,w=(0,o.useCallback)(()=>{let e=n.current,t=e.length-1;if(t<1)return[];for(let r=0;re.x),l=e.map(e=>e.y),i=Array(t);for(let e=0;e=0;e--)u[e]=c[e]-s[e]*u[e+1];let f=Array(t);for(let e=0;e{let t=u.current;if(!t||0===t.length)return null;let r=t.findIndex(t=>t.x>e)-1;r<0&&(r=t.length-1);let l=t[r];if(!l)return null;let n=e-l.x;return l.y+l.b*n+l.c*n*n+l.d*n*n*n},[]),E=(0,o.useCallback)((e,t)=>{let r=n.current;for(let l=0;l{let e=n.current,l=t.current,i=r.current;if(!l||!i)return;let a=l.width,o=l.height,s=window.devicePixelRatio||1,m=Math.max(.4,Math.min(y,1.4));i.clearRect(0,0,a,o),i.strokeStyle=c,i.lineWidth=1*s*m;for(let e=0;e<10;e++){let t=e*a/10,r=e*o/10;i.beginPath(),i.moveTo(t,0),i.lineTo(t,o),i.stroke(),i.beginPath(),i.moveTo(0,r),i.lineTo(a,r),i.stroke()}if(e.length<2)return;let h=e[0],p=e[e.length-1];if(!h||!p)return;i.beginPath(),i.strokeStyle=f,i.lineWidth=2.5*s*m;let v=Math.max(0,Math.min(o,h.y));if(i.moveTo(0,v),i.lineTo(h.x,v),u.current&&u.current.length>0)for(let e=Math.ceil(h.x);e<=Math.floor(p.x);e++){let t=C(e);if(null!==t){let r=Math.max(0,Math.min(o,t));i.lineTo(e,r)}}let g=Math.max(0,Math.min(o,p.y));i.lineTo(p.x,g),i.lineTo(a,g),i.stroke(),e.forEach(e=>{i.beginPath(),i.arc(e.x,e.y,6*s*m,0,2*Math.PI),i.fillStyle=d,i.fill(),i.strokeStyle=x,i.lineWidth=2*s*m,i.stroke()})},[C,y]),A=(0,o.useCallback)(e=>{let r=t.current;if(!r)return{x:0,y:0};let l=r.getBoundingClientRect(),n=window.devicePixelRatio||1;return{x:(e.clientX-l.left)*n,y:(e.clientY-l.top)*n}},[]),L=(0,o.useCallback)(e=>{let r=t.current;if(!r)return;n.current=e;let l=e.map(e=>({x:Math.max(0,Math.min(1,parseFloat((e.x/r.width).toFixed(6)))),y:Math.max(0,Math.min(1,parseFloat((1-e.y/r.height).toFixed(6))))}));k(p,l)},[p,k]),P=(0,o.useCallback)(e=>{let r=h.current;if(null===r)return;e.preventDefault(),e.stopPropagation();let l=n.current;if(r>=l.length)return;let i=l[r];if(!i)return;let a=A(e),u=t.current;if(!u)return;let o=u.width,s=u.height;i.x=a.x,i.y=Math.max(0,Math.min(s,a.y)),l.sort((e,t)=>e.x-t.x);let c=l.indexOf(i);if(c<0)return;h.current=c;let f=l[c-1],d=l[c+1],x=0===c?0:(f?.x??0)+3,m=c===l.length-1?o:(d?.x??o)-3;i.x=Math.max(x,Math.min(m,i.x)),L(l)},[A,L]),R=(0,o.useCallback)(e=>{e.preventDefault(),e.stopPropagation(),h.current=null;let t=n.current;t.sort((e,t)=>e.x-t.x),L(t),document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",R)},[P,L]),T=(0,o.useCallback)(e=>{if(0!==e.button||null==t.current)return;let r=A(e),l=n.current,i=E(r.x,r.y);if(null!==i)h.current=l.indexOf(i);else{let e=l[0],t=l[l.length-1];if(!e||!t)return;if(r.x>e.x&&r.xe.x-t.x),h.current=n.indexOf(t),L(n)}}}document.addEventListener("mousemove",P),document.addEventListener("mouseup",R)},[C,E,A,P,R,L]),N=(0,o.useCallback)(e=>{if(0!==e.button)return;e.preventDefault(),e.stopPropagation();let t=n.current;if(t.length<=2)return;let r=A(e),l=E(r.x,r.y);if(l){let e=t.filter(e=>e!==l);L(e)}},[E,A,L]);return(0,o.useEffect)(()=>{let e=t.current;if(null==e)return;r.current||=e.getContext("2d");let l=Array.isArray(M)?M.filter(m):[];if(!Array.isArray(l)||l.length<2)return void k(p,[{x:0,y:0},{x:1,y:1}]);let i=window.devicePixelRatio||1,a=320*y*i,o=320*y*i;e.width=a,e.height=o,n.current=l.map(t=>({x:t.x*e.width,y:(1-t.y)*e.height})),u.current=w(),j()},[w,j,p,k,M,y]),(0,o.useEffect)(()=>{let e=t.current;if(null!=e)return r.current=e.getContext("2d"),e.addEventListener("mousedown",T),e.addEventListener("dblclick",N),()=>{e.removeEventListener("mousedown",T),document.removeEventListener("mousemove",P),document.removeEventListener("mouseup",R),e.removeEventListener("dblclick",N)}},[N,T,P,R]),(0,s.jsxs)(i,{dataKey:p,hidden:v,layoutStyle:b,className:"nodrag",children:[(0,s.jsx)("div",{className:"text-modiff-control truncate text-modiff-subtle-text",title:g,children:g}),(0,s.jsxs)("div",{className:"flex w-full flex-col items-center justify-between",children:[(0,s.jsx)("div",{className:"m-0 w-[320px] overflow-hidden rounded-modiff-compact border border-modiff-border p-0",children:(0,s.jsx)("canvas",{ref:t,className:"block aspect-square w-[320px] cursor-crosshair"})}),(0,s.jsx)("div",{className:"mt-2 w-full",children:(0,s.jsx)(a,{className:"min-h-0 px-3 py-1.5",onClick:()=>{k(p,[{x:0,y:0},{x:1,y:1}])},children:"Reset"})})]})]})}export{h as default}; \ No newline at end of file diff --git a/web/assets/TemplateBrowserDialog.js b/web/assets/TemplateBrowserDialog.js index f114c4a..140714f 100644 --- a/web/assets/TemplateBrowserDialog.js +++ b/web/assets/TemplateBrowserDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{D as t,H as a,It as r,K as s,Ln as l,M as o,Mn as i,Mt as n,Pt as d,Qt as c,R as m,_n as u,bn as p,cr as f,dr as g,jt as h,st as b,wn as x,yt as v}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$ as w,$i as y,An as j,Bi as k,Cr as N,Di as _,Ei as S,Fi as T,Ga as P,Gi as R,Hi as C,In as I,Ji as M,Jn as $,La as q,Li as z,Mo as A,Ms as E,Ni as L,Nr as B,Oi as O,On as V,Oo as D,Pi as F,Qi as K,Ra as U,Ro as W,Sa as G,Si as H,Ti as X,Ui as J,Vi as Q,Vr as Y,Xa as Z,Xi as ee,Yi as te,an as ae,bn as re,da as se,dr as le,fn as oe,ga as ie,in as ne,ji as de,ma as ce,nr as me,pa as ue,qa as pe,qi as fe,rn as ge,t as he,tr as be,u as xe,wi as ve,wn as we,yn as ye,za as je,zr as ke}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{r as Ne,t as _e}from"./presetDiff.js?v=cc046c26d6fe7aa4";import{a as Se,i as Te,n as Pe,t as Re}from"./templateBrowser.js?v=cc046c26d6fe7aa4";import{n as Ce,t as Ie}from"./TemplateUsageTermsDialog.js?v=cc046c26d6fe7aa4";import{a as Me,i as $e,n as qe,o as ze,r as Ae,t as Ee}from"./controlledWorkflows.js?v=cc046c26d6fe7aa4";var Le=e(g(),1);function Be(e){return"install_model"===e?"install_model":"open_models"===e?"open_model_manager":"open_assets"===e||"add_input"===e?"select_image":"open_setup"===e?"open_setup":"apply_low_vram"===e?"apply_low_vram_preset":void 0}function Oe(e){return{id:`template:${e.id}`,category:e.category,severity:"error"===e.tone?"error":"warning"===e.tone?"warning":"success"===e.tone?"success":"info",repoId:e.repoId,message:e.title,details:e.detail,blocking:e.blocking,action:Be(e.action)}}function Ve(e){return Object.keys(e).length>0}function De(e){return"hub"===e?.source&&e.value.trim().length>0}function Fe(e){let[t,a]=e.value.split("/");return t&&a?`${t}/${a}`:e.value}function Ke(e){let t=[],a=(a,r,s)=>{De(s)&&t.push({id:a,label:r,repo:Fe(s),kind:"adapter",requiredForModes:[e.mode],description:`${r} pinned by ${e.label}.`})};a(`${e.id}-lora`,"LoRA adapter",e.workflowBlockSettings?.lora?.model),a(`${e.id}-lora-base`,"LoRA base model",e.workflowBlockSettings?.lora?.baseModel);for(let[t,r]of(e.workflowBlockSettings?.lora?.additionalAdapters??[]).entries())a(`${e.id}-lora-${t+2}`,`LoRA adapter ${t+2}`,r.model),a(`${e.id}-lora-${t+2}-base`,`LoRA base model ${t+2}`,r.baseModel);return a(`${e.id}-upscaler`,"Upscaler model",e.workflowBlockSettings?.upscaler?.model),t}function Ue(e){let t=U[e.modelType];return[...!1===t.artifactInstallRequired?[]:[{id:`${e.modelType}-base`,label:t.label,repo:t.defaultRepo,kind:"base",requiredForModes:[e.mode],description:`Base model for ${t.label}.`}],...Z(t,e.mode),...Ke(e)]}function We(e,t){let a=U[e.modelType],r=L(t.autoResourcePlan,t.form),s=z(t.autoResourcePlan,t.form),l=T(t.autoResourcePlan,t.form),o=!0===t.modelIndexesRefreshing,i="planning"===e.readinessPolicy||"blocked"===e.difficulty||"blocked"===e.example?.status,n=!t.runtimeStatus&&!Ve(t.nodesRegistry),d=function(e,t){let a=e.requiredBackendCapabilities??[];return 0===a.length?[]:a.filter(e=>{let a=he(e);return!a||Ve(t)&&!a.every(e=>t[e])})}(e,t.nodesRegistry),c=function(e,t){let a=me(e).missingLabels;return t?(t.loraAdapter&&!De(e.workflowBlockSettings?.lora?.model)&&a.push("LoRA adapter"),t.upscalerModel&&!De(e.workflowBlockSettings?.upscaler?.model)&&a.push("Upscaler model"),Array.from(new Set(a))):a}(e,e.inputRequirements),m=o?[]:[...t.autoResourcePlan?Z(a,e.mode):Ue(e),...t.autoResourcePlan?Ke(e):[]].filter(e=>!E(e.repo,t.hfCache,t.localModels,t.modelCacheDiagnostics).runnable).map(e=>e.repo),u=[],p=[];i&&u.push({id:"planning",category:"graph",blocking:!0,tone:"info",title:"Planning template",detail:e.example?.blockReason??"This recipe can be opened and inspected, but MoDiff should not present it as runnable yet.",action:"open_planning"}),o&&u.push({id:"model-index-refresh",category:"model",blocking:!0,tone:"info",title:"Checking installed models",detail:"Refreshing the local model index before reporting template readiness."}),!o&&"checking"===l.state&&u.push({id:"auto-plan-checking",category:"environment",blocking:!0,tone:"info",title:l.summary,detail:l.detail}),n&&u.push({id:"backend:connection",category:"backend",blocking:!0,tone:"error",title:"Backend connection needed",detail:"Connect to the MoDiff backend before checking installed models.",action:"open_setup"}),d.forEach(e=>{u.push({id:`backend:${e}`,category:"package",blocking:!0,tone:"error",title:"Backend contract needed",detail:e,action:"open_setup"})}),m.forEach(e=>{p.push({repoId:e,actionLabel:"Install"}),u.push({id:`model:${e}`,category:"model",blocking:!0,tone:"warning",title:"Model package missing",detail:e,action:"install_model",repoId:e,actionLabel:"Install"})}),o||r||!s?!o&&!r&&t.autoResourcePlan&&!s&&u.push({id:"auto-plan-blocked",category:"environment"===t.autoResourcePlan.issue?.category?"environment":"package"===t.autoResourcePlan.issue?.category?"package":"device"===t.autoResourcePlan.issue?.category?"hardware_fit":"environment",blocking:!0,tone:"error"===l.severity?"error":"warning"===l.severity?"warning":"info",title:l.summary,detail:l.detail,action:"expert_only"===l.state?"open_planning":"open_setup"}):(p.push({repoId:s.repo,repair:s.repair,actionLabel:s.actionLabel}),u.push({id:`auto-model:${s.repo}`,category:s.repair?"model_integrity":"model",blocking:!0,tone:s.repair?"error":"warning",title:s.repair?"Model package repair required":"Auto model package missing",detail:`${s.actionLabel??"Install Auto artifact"}: ${s.repo}`,action:"install_model",repoId:s.repo,repair:s.repair,actionLabel:s.actionLabel})),c.forEach(e=>{u.push({id:`input:${e}`,category:"asset",blocking:!0,tone:"warning",title:`${e} required`,detail:"Add the required asset in Studio after creating this workflow, or open the Assets library to reuse an existing output.",action:"open_assets"})});let f=le(u.map(Oe),{preparing:o||"checking"===l.state}),g=f.primaryIssue?.category,h=i||u.some(e=>"open_planning"===e.action)?"planning":"preparing"===f.state?"preparing":"blocked"===f.state?"backend"===g||"package"===g?"needs_backend":"model"===g||"model_integrity"===g?"needs_model":"asset"===g||"user_input"===g?"needs_input":"needs_setup":"ready",b=function(e){return"ready"===e?{label:"Ready now",tone:"success"}:"needs_input"===e?{label:"Needs input",tone:"warning"}:"needs_model"===e?{label:"Needs model",tone:"warning"}:"needs_backend"===e?{label:"Backend blocked",tone:"error"}:"needs_setup"===e?{label:"Needs setup",tone:"warning"}:"preparing"===e?{label:"Checking models",tone:"info"}:{label:"Planning only",tone:"info"}}(h),x="ready"===h?`${q[e.modelType]} Auto plan is ready, hardware looks usable, and no required inputs are missing.`:u[0]?.detail??"Review the required setup before running this recipe.";return{status:h,label:b.label,tone:b.tone,summary:x,compatibility:l,issues:u,missingModelRepos:Array.from(new Set(m)),modelInstallTargets:Array.from(new Map(p.map(e=>[e.repoId,e])).values()),missingInputs:c,missingBackendCapabilities:d,decision:f}}async function Ge(e,t,a,r={}){"lora"!==e?"upscaler"!==e?"video_sequence"!==e?"quality_video_sequence"!==e?"soundtrack"!==e?await qe(t,a.workflowBlockSettings?.lyricVideo,r):await $e(t,a.workflowBlockSettings?.soundtrack,r):await Ae(t,a.workflowBlockSettings?.qualityVideoSequence,r):await ze(t,a.workflowBlockSettings?.videoSequence,r):await Me(t,a.workflowBlockSettings?.upscaler,r):await Ee(t,a.workflowBlockSettings?.lora,r)}function He(){return typeof window>"u"||"function"!=typeof window.requestAnimationFrame?Promise.resolve():new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e())})})}async function Xe(e){let t=de.getState().createWorkflowTab(e.label,void 0,"template",e.id);de.getState().setLauncherDismissed(!0);let a=S();de.getState().setCanvasTransition({type:"template_graph_building",workflowTabId:t,templateId:e.id,startedAt:Date.now()});let r,s=de.getState().form,l=s,o=!1,i=[];try{if("success"!==H.getState().discoveryRequests.capabilities.status){await H.getState().fetchStudioModelCapabilities(),X(a);let e=H.getState().discoveryRequests.capabilities;if("success"!==e.status)throw Error(e.error||"Model capabilities are not ready. Retry opening the template.")}let t=await be(e);X(a),de.getState().applyTemplate(e,t),ve(a),de.getState().saveActiveWorkflowTab(!0),l=de.getState().form,await He(),X(a);let r=await B(l,a);if(X(a),"auto"===l.resourceMode){let e=F(l),t=de.getState().autoResourcePlans[e]??await k(l);if(X(a),t.error||de.getState().setAutoResourcePlans({[e]:t}),de.getState().setAutoResourcePlan(t),L(t,l)){let e=_(t,l,de.getState().graphBinding);if(e)de.getState().setLastError(e);else{let e=C(R(t,l),l);de.getState().applyAutoResourcePlan(t,e),ve(a),l=de.getState().form,r=await B(l,a),X(a)}}}o=!0,i=r.warnings;for(let t of e.workflowBlocks??[])try{await Ge(t,l,e,{graphPrepared:!0,workflowContext:a}),X(a)}catch(a){if(O(a))throw a;let r=a instanceof Error?a.message:String(a);i.push(`${e.label} could not add the ${t} block: ${r}`)}let s=await ke(15e3,a);if(X(a),!s)throw Error(`${e.label} graph preparation timed out. No incomplete graph was kept; try again.`);await W(()=>Y.getState().nodes,500),X(a),await Y.getState().arrangeGraph({history:!1}),X(a),await He(),X(a),de.getState().saveActiveWorkflowTab(!0)}catch(e){if(O(e))throw e;X(a),r=e instanceof Error?e.message:String(e),Y.getState().replaceGraph({nodes:[],edges:[],viewport:{x:0,y:0,zoom:1}}),de.getState().setGraphBinding(null),de.getState().setGraphFinalization(null),de.getState().saveActiveWorkflowTab(!0)}finally{let a=de.getState().canvasTransition;a?.workflowTabId===t&&a.templateId===e.id&&de.getState().setCanvasTransition(null)}let n=Object.keys(ee(e)),d=_e(s,l,n);return Ne(`${e.label} recipe applied`,d,de.getState().graphBinding?.managedNodeIds??[]),G.getState().setRightPanelOpen(!0),G.getState().setRightPanelTab("studio"),{graphCreated:o,graphError:r,warnings:i}}function Je(e){let t=null,a=!1;return{hasRejected:()=>a,load:(r=!1)=>{if(t&&!r)return t;a=!1;let s=e();return t=s,s.then(()=>{t===s&&(a=!1)},()=>{t===s&&(t=null,a=!0)}),s}}}var Qe=f();function Ye({templates:e=!1}){let t=de(e=>e.activeWorkflowTabId),a=[...de(e=>e.workflowTabs)].filter(e=>e.id!==t).sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,6),r=()=>w({revealWorkspace:!1});return(0,Qe.jsxs)("div",{className:"space-y-2",children:[(0,Qe.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Qe.jsx)(ge,{onClick:()=>w(),"data-testid":"launcher-mode-advanced_workflow",children:"Empty workflow"}),(0,Qe.jsx)(ge,{onClick:()=>{r(),G.getState().setWorkflowLibraryView("saved"),G.getState().setLeftPanelTabIndex(4),G.getState().setLeftPanelOpen(!0)},children:"Open workflow"}),e?(0,Qe.jsx)(ge,{onClick:()=>{r(),G.getState().setTemplateBrowserOpen(!0)},children:"Browse templates"}):null]}),a.length?(0,Qe.jsxs)("section",{"aria-label":"Recent workflows",className:"space-y-1",children:[(0,Qe.jsx)("h3",{className:"text-xs font-semibold text-modiff-subtle-text",children:"Recent workflows"}),(0,Qe.jsx)("div",{className:"flex gap-2 overflow-x-auto pb-1",children:a.map(e=>(0,Qe.jsx)(ge,{title:e.title,className:"max-w-56 shrink-0",onClick:()=>{r(),de.getState().switchWorkflowTab(e.id)},children:(0,Qe.jsx)("span",{className:"truncate",children:e.title})},e.id))})]}):null]})}var Ze=["all","starter","intermediate","advanced","blocked"],et=[...ue,...se],tt=[{value:"recommended",label:"Recommended"},{value:"task",label:"Task"},{value:"model",label:"Model"},{value:"runtime",label:"Runtime"}],at=Array.from(new Set(ue.map(e=>e.mode))).sort((e,t)=>je[e].localeCompare(je[t]));function rt(e){let t=ee(e);return ie({...pe(e.mode,e.modelType),...ce(e.presetId)?.values??{},...t,mode:e.mode,modelType:e.modelType,prompt:e.prompt,negativePrompt:e.negativePrompt??t.negativePrompt})}var st=ue.map(e=>{let t=rt(e);return{form:t,planKey:F(t),templateId:e.id}}),lt=Je(async()=>D(fe,{credentials:"omit",timeoutMs:12e4,parse:K})),ot=Je(async()=>{let e=st.map(e=>e.templateId),t=await Q(st.map(e=>e.form),e),a={};return t.forEach((e,t)=>{let r=st[t];r&&(a[r.templateId]=e,a[r.planKey]??=e)}),a});function it(e=!1){return lt.load(e)}function nt(e=!1){return ot.load(e)}function dt(e){return"all"===e?"All levels":e.charAt(0).toUpperCase()+e.slice(1)}function ct(e){return e.outputKinds?.join(", ")||e.example?.mediaType||"image"}function mt(e){return y(e.example?.thumbnailPath??e.example?.outputPath)}function ut(e){let t=e.inputRequirements;if(!t)return["Prompt only"];let a="hub"===e.workflowBlockSettings?.lora?.model.source,r="hub"===e.workflowBlockSettings?.upscaler?.model.source,s=[];t.sourceImage&&s.push("source image"),t.referenceImages&&s.push(`${t.referenceImages} reference image${1===t.referenceImages?"":"s"}`),t.controlImage&&s.push("control image"),t.maskImage&&s.push("mask image"),t.sourceVideo&&s.push("source video"),t.maskVideo&&s.push("mask video"),t.controlVideo&&s.push("control video"),t.loraAdapter&&!a&&s.push("LoRA adapter"),t.upscalerModel&&!r&&s.push("upscaler model"),t.sampleAssets?.length&&s.push(...t.sampleAssets.filter(e=>!(a&&/lora adapter/i.test(e)||r&&/upscaler|real-esrgan/i.test(e))));let l=s.filter((e,t)=>s.findIndex(t=>t.toLocaleLowerCase()===e.toLocaleLowerCase())===t);return l.length>0?l:["Prompt only"]}function pt(e){return Re.find(t=>t.id===e)?.label??"Templates"}function ft(e,t){if(t){let a=M(e,t);return!(!a||"video"===a.mediaType&&(!a.cardPreviewPath||!a.cardPreviewSha256))}let a=e.verificationStatus??e.example?.status;return"video"!==e.example?.mediaType&&!e.outputKinds?.includes("video")&&!("reviewed"!==a&&"exact"!==a||!mt(e)&&!function(e){return y(e.example?.outputPath)}(e))}var gt=["h-3","h-7","h-5","h-10","h-6","h-12","h-8","h-14","h-9","h-5","h-11","h-7","h-12","h-8","h-4","h-9"],ht=["qwen_low_vram_product_concept","qwen_poster_logo_text","qwen_text_rendering","qwen_product_mockup","qwen_low_vram_poster_layout","qwen_low_vram_text_rendering","z_image_product_mockup","z_image_poster","z_image_cinematic_contact_sheet","z_image_quick_concept","wan_vace_cinematic_text_to_video","low_vram","high_quality"];function bt(e){let t=ht.indexOf(e);return-1===t?ht.length:t}function xt({entry:e=!1}){let t=G(e=>e.templateBrowserOpen),a=G(e=>e.setTemplateBrowserOpen),r=e||t,s=t=>{!t&&e&&w({revealWorkspace:!1}),a(t)},l=G(e=>e.templateBrowserInitialCategory),i=G(e=>e.clearTemplateBrowserInitialCategory),n=G(e=>e.setRightPanelOpen),d=G(e=>e.setRightPanelTab),c=G(e=>e.setModelManagerOpener),m=G(e=>e.setGalleryLibraryOpen),u=Ce(),p=de(e=>e.form),f=de(e=>e.activeTemplateId),g=de(e=>e.autoResourcePlans),h=de(e=>e.setAutoResourcePlans),b=N(e=>e.sessionRuns.reduce((e,t)=>"completed"===t.status?Math.max(e,t.completedAtMs??0):e,0)),x=$(e=>e.sid),v=H(e=>e.hfCache),y=H(e=>e.localModels),j=H(e=>e.modelCacheDiagnostics),k=H(e=>e.runtimeStatus),_=H(e=>e.nodesRegistry),S=H(e=>e.installHfModel),T=H(e=>["nodes","runtime","hfCache","localModels","modelCache","capabilities"].some(t=>{let a=e.discoveryRequests[t].status;return"idle"===a||"loading"===a})),R=(0,Le.useId)(),[C,M]=(0,Le.useState)(!1),[z,E]=(0,Le.useState)(null),[L,B]=(0,Le.useState)(!1),[V,D]=(0,Le.useState)(!1),[K,U]=(0,Le.useState)(!1),[W,X]=(0,Le.useState)(null),[Q,Y]=(0,Le.useState)(null),[Z,ee]=(0,Le.useState)(12),te=(0,Le.useRef)(new Map),ae=(0,Le.useRef)(!1),re=(0,Le.useRef)(!1),se=(0,Le.useRef)(b),[le,oe]=(0,Le.useState)(null),[ie,ce]=(0,Le.useState)(null),[me,pe]=(0,Le.useState)({category:"recommended",query:"",modelType:"all",mode:"all",difficulty:"all",sort:"recommended"}),fe=["all"!==me.modelType,"all"!==me.mode,"all"!==me.difficulty,"recommended"!==me.sort].filter(Boolean).length;(0,Le.useEffect)(()=>{!r||!l||(pe(e=>({...e,category:l})),Y(null),i())},[i,l,r]),(0,Le.useEffect)(()=>{r||(Y(null),ee(12))},[r]),(0,Le.useEffect)(()=>{if(!r)return;let e=!1;return it().then(t=>{e||(E(t),B(!1))}).catch(()=>{e||(E(null),B(!0))}),()=>{e=!0}},[r]),(0,Le.useEffect)(()=>{if(!r||!function(e){return e.failed&&!e.attempted}({attempted:ae.current,failed:L&<.hasRejected()}))return;ae.current=!0;let e=!1,t=globalThis.setTimeout(()=>{it().then(t=>{e||(E(t),B(!1))}).catch(e=>console.error(e))},1500);return()=>{e=!0,globalThis.clearTimeout(t),ae.current=!1}},[L,r]),(0,Le.useEffect)(()=>{if(!r)return;let e=!1;return nt().then(t=>{e||(h(t),D(!1))}).catch(t=>{e||D(!0),console.error(t)}),()=>{e=!0}},[r,h]),(0,Le.useEffect)(()=>{if(!r||!function(e){return e.failed&&e.backendReady&&!e.discoveryRefreshing&&!e.attempted}({attempted:re.current,backendReady:!!x,discoveryRefreshing:T,failed:V&&ot.hasRejected()}))return;re.current=!0;let e=!1,t=globalThis.setTimeout(()=>{nt().then(t=>{e||(h(t),D(!1))}).catch(e=>console.error(e))},1500);return()=>{e=!0,globalThis.clearTimeout(t),re.current=!1}},[V,T,r,h,x]),(0,Le.useEffect)(()=>{if(!r||!b||b<=se.current)return;se.current=b;let e=!1,t=globalThis.setTimeout(()=>{nt(!0).then(t=>{e||h(t)}).catch(e=>console.error(e))},250);return()=>{e=!0,globalThis.clearTimeout(t)}},[b,r,h]);let he=(0,Le.useMemo)(()=>({hfCache:v,localModels:y,modelCacheDiagnostics:j,runtimeStatus:k,nodesRegistry:_,modelIndexesRefreshing:T}),[v,y,j,T,_,k]),be=(0,Le.useMemo)(()=>({...me,includeBlocked:!0}),[me]),ve=(0,Le.useCallback)(e=>g[e.id]??g[F(rt(e))],[g]),we=(0,Le.useCallback)(e=>J(ve(e)),[ve]),ke=(0,Le.useCallback)(e=>!ft(e,z),[z]),Ne=(0,Le.useMemo)(()=>{let e="experimental"===me.category?et:ue,t="experimental"===me.category?"all":me.category,a=Pe(e,p,{...be,category:t},e=>we(e)?.observedSeconds??null);return"experimental"===me.category?a.filter(ke):a},[be,me.category,p,ke,we]),_e=(0,Le.useMemo)(()=>Pe(et,p,{...be,category:"all",query:"",modelType:"all",mode:"all",difficulty:"all"},e=>we(e)?.observedSeconds??null),[be,p,we]),Se=(0,Le.useMemo)(()=>_e.filter(ke).length,[_e,ke]),Me=(0,Le.useMemo)(()=>_e.filter(e=>ft(e,z)).length,[_e,z]),$e=(0,Le.useMemo)(()=>{if("recommended"!==me.category||0!==me.query.trim().length||"all"!==me.modelType||"all"!==me.mode||"all"!==me.difficulty)return Ne;let e=Ne.filter(e=>ft(e,z));return 0===e.length?Ne:"recommended"===me.sort?[...e].sort((e,t)=>bt(e.id)-bt(t.id)):e},[me.category,me.difficulty,me.mode,me.modelType,me.query,me.sort,Ne,z]),qe=(0,Le.useMemo)(()=>et.find(e=>e.id===Q)??null,[Q]),ze=(0,Le.useMemo)(()=>new Map(Re.map(e=>"recommended"===e.id&&Me>0?[e.id,Me]:"experimental"===e.id?[e.id,Se]:[e.id,Pe(ue,p,{...be,category:e.id,query:"",modelType:"all",mode:"all",difficulty:"all"}).length])),[be,Se,p,Me]),Ae=(0,Le.useMemo)(()=>Re.filter(e=>"recommended"===e.id||"all"===e.id||(ze.get(e.id)??0)>0),[ze]);(0,Le.useLayoutEffect)(()=>{r&&te.current.get(me.category)?.scrollIntoView({block:"nearest",inline:"nearest"})},[me.category,r,Ae]),(0,Le.useEffect)(()=>{ee(12),le&&(le.scrollTop=0)},[me.category,me.difficulty,me.mode,me.modelType,me.query,me.sort,le]);let Ee=(0,Le.useMemo)(()=>$e.slice(0,Z),[$e,Z]),Be=Ee.length<$e.length;(0,Le.useEffect)(()=>{if(!r||!Be||!le||!ie||typeof IntersectionObserver>"u")return;let e=new IntersectionObserver(([t])=>{t?.isIntersecting&&(e.disconnect(),ee(e=>Math.min(e+12,$e.length)))},{root:le,rootMargin:"320px 0px",threshold:.01});return e.observe(ie),()=>e.disconnect()},[le,Be,ie,r,$e.length,Ee.length]);let Oe=e=>u.needsReview(xe(e)),Ve=e=>{u.request("create",xe(e),()=>(async e=>{U(!0);try{let t=await Xe(e);if(s(!1),t.graphError)return void A(`${e.label} opened, but graph creation needs attention: ${t.graphError}`,{variant:"warning",autoHideDuration:7e3});if(t.warnings.length>0)return void A(`${Te(e)}: ${t.warnings.join(" ")}`,{variant:"warning",autoHideDuration:12e3});A(`${Te(e)} template created`,{variant:"success",autoHideDuration:2600})}catch(e){if(O(e))return;A(String(e),{variant:"error",autoHideDuration:7e3})}finally{U(!1)}})(e))},De=u.pending?.policies??[],Fe=()=>{n(!0),d("setup"),s(!1)},Ke=()=>{m(!0)};return(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsxs)(ne,{open:r,onClose:()=>s(!1),testId:e?"task-launcher":"template-browser-dialog",title:(0,Qe.jsxs)("span",{className:"inline-flex items-center gap-2",children:[(0,Qe.jsx)(o,{size:18,className:"text-hf-yellow"}),"Templates"]}),panelClassName:"!h-[90dvh] !w-[96vw] !max-h-[90dvh] !max-w-[96vw] sm:!h-[80vh] sm:!w-[82vw] sm:!max-h-[80vh] sm:!max-w-[82vw]",bodyClassName:"!h-[calc(90dvh-49px)] !max-h-[calc(90dvh-49px)] sm:!h-[calc(80vh-49px)] sm:!max-h-[calc(80vh-49px)] flex flex-col overflow-hidden p-0",children:[e?(0,Qe.jsx)("div",{className:"shrink-0 border-b border-modiff-border p-3",children:(0,Qe.jsx)(Ye,{})}):null,(0,Qe.jsxs)("div",{className:"grid min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] lg:grid-cols-[190px_minmax(0,1fr)] lg:grid-rows-1",children:[(0,Qe.jsx)("aside",{className:"min-h-0 overflow-x-auto border-b border-modiff-border bg-modiff-bg p-2 lg:overflow-y-auto lg:border-b-0 lg:border-r lg:p-3",children:(0,Qe.jsx)("div",{className:"flex min-w-max gap-1 lg:grid lg:min-w-0",role:"group","aria-label":"Template categories",children:Ae.map(e=>{let t=me.category===e.id;return(0,Qe.jsxs)(ge,{ref:t=>{t?te.current.set(e.id,t):te.current.delete(e.id)},tone:t?"primary":"ghost",size:"prominent",align:"left","aria-pressed":t,"data-testid":`template-browser-category-${e.id}`,onClick:()=>{pe(t=>({...t,category:e.id})),Y(null)},className:"shrink-0 !justify-between px-3 lg:w-full",children:[(0,Qe.jsx)("span",{className:"truncate",children:e.label}),(0,Qe.jsx)("span",{className:I("min-w-6 rounded-full px-1.5 py-0.5 text-center text-xs",t?"bg-modiff-selected-surface text-hf-yellow":"bg-modiff-panel text-modiff-subtle-text"),children:ze.get(e.id)??0})]},e.id)})})}),(0,Qe.jsxs)("section",{className:"@container grid min-h-0 min-w-0 grid-rows-[auto_minmax(0,1fr)] bg-modiff-surface",children:[(0,Qe.jsxs)("div",{className:"border-b border-modiff-border bg-modiff-panel p-3","data-testid":"template-browser-header",children:[(0,Qe.jsx)("h1",{className:"mb-2 hidden text-xl font-bold tracking-tight text-modiff-text sm:block",children:"recommended"===me.category?"Recommended templates":pt(me.category)}),(0,Qe.jsxs)("div",{className:"flex flex-wrap items-end gap-2",children:[(0,Qe.jsx)(ye,{"data-testid":"template-browser-search",value:me.query,onChange:e=>pe(t=>({...t,query:e.target.value})),onClear:me.query?()=>pe(e=>({...e,query:""})):void 0,placeholder:"Search templates, models, prompts, or techniques","aria-label":"Search templates",controlSize:"prominent",className:"min-w-52 flex-1"}),(0,Qe.jsxs)(ge,{className:"sm:hidden","aria-expanded":C,"aria-controls":R,onClick:()=>M(e=>!e),children:["Filters",fe?` (${fe})`:""]}),(0,Qe.jsxs)("div",{id:R,className:I("flex-wrap items-end gap-2 sm:contents",C?"flex":"hidden"),children:[(0,Qe.jsx)(vt,{label:"Model",value:me.modelType,onValueChange:e=>pe(t=>({...t,modelType:e})),options:[{value:"all",label:"All models"},...P({currentModelType:p.modelType,includeWorkflowOnly:!0}).map(e=>({value:e.modelType,label:e.label}))]}),(0,Qe.jsx)(vt,{label:"Operation",value:me.mode??"all",onValueChange:e=>pe(t=>({...t,mode:e})),options:[{value:"all",label:"All operations"},...at.map(e=>({value:e,label:je[e]}))]}),(0,Qe.jsx)(vt,{label:"Level",value:me.difficulty,onValueChange:e=>pe(t=>({...t,difficulty:e})),options:Ze.map(e=>({value:e,label:dt(e)}))}),(0,Qe.jsx)(vt,{label:"Sort",value:me.sort,onValueChange:e=>pe(t=>({...t,sort:e})),options:tt})]})]})]}),(0,Qe.jsxs)("div",{className:I("grid h-full min-h-0",qe&&"@[1024px]:grid-cols-[minmax(0,1fr)_minmax(420px,28vw)]"),children:[(0,Qe.jsxs)("div",{ref:oe,className:I("min-h-0 overflow-y-auto p-3",qe&&"hidden @[1024px]:block"),"data-testid":"template-browser-gallery-scroll",children:[(0,Qe.jsxs)("div",{className:"grid items-stretch gap-3 [grid-template-columns:repeat(auto-fill,minmax(280px,1fr))] max-[1400px]:[grid-template-columns:repeat(auto-fill,minmax(250px,1fr))]",children:[Ee.map((e,t)=>(0,Qe.jsx)(wt,{active:f===e.id,disabled:K,featured:"recommended"===me.category&&0===t&&$e.length>2,manifest:z,readiness:We(e,{...he,form:rt(e),autoResourcePlan:ve(e)}),selected:Q===e.id,template:e,runtimeEstimate:we(e),requiresTermsReview:Oe(e),onCreate:()=>{Ve(e)},onView:()=>Y(e.id),onReadinessAction:t=>{"needs_model"===t.status?((e,t)=>{let a=t.modelInstallTargets[0]?.repoId??t.missingModelRepos[0];c({nodeId:null,fieldKey:null,focus:{modelType:e.modelType,repo:a,label:q[e.modelType],source:"template"}}),s(!1)})(e,t):"needs_input"===t.status?(Ke(),s(!1)):("needs_backend"===t.status||"needs_setup"===t.status)&&Fe()}},e.id)),0===$e.length&&(0,Qe.jsx)("div",{className:"col-span-full rounded-modiff-compact border border-modiff-border bg-modiff-bg p-4 text-sm text-modiff-subtle-text",children:"No templates match the current filters."})]}),Be?(0,Qe.jsx)("div",{ref:ce,"aria-hidden":"true",className:"h-px w-full","data-testid":"template-browser-load-sentinel"}):null,(0,Qe.jsxs)("span",{className:"sr-only",role:"status","aria-live":"polite",children:[Ee.length," of ",$e.length," templates loaded"]})]}),qe?(0,Qe.jsx)(yt,{disabled:K,installingRepo:W,manifest:z,readiness:We(qe,{...he,form:rt(qe),autoResourcePlan:ve(qe)}),runtimeEstimate:we(qe),requiresTermsReview:Oe(qe),template:qe,onBack:()=>Y(null),onCreate:()=>{Ve(qe)},onInstallRepo:(e,t)=>{((e,t,a=!1)=>{u.request("install",xe(e),()=>(async(e,t=!1)=>{X(e);try{await S(e,x,{repair:t}),h(await nt(!0))}catch(e){console.error(e)}finally{X(null)}})(t,a))})(qe,e,t)},onOpenAssets:Ke,onOpenModels:()=>{c({nodeId:null,fieldKey:null})},onOpenSetup:Fe,onUseLowVram:()=>{let e=ue.find(e=>"low_vram"===e.id);e&&(pe(e=>({...e,category:"performance",query:""})),Y(e.id))}}):null]})]})]})]}),(0,Qe.jsx)(Ie,{open:!!u.pending,policies:De,action:u.pending?.action??"create",onCancel:u.cancel,onConfirm:u.confirm})]})}function vt({label:e,onValueChange:t,options:a,value:r}){let s=(0,Le.useId)();return(0,Qe.jsx)(oe,{className:I("Sort"===e?"w-36":"w-32","shrink-0"),htmlFor:s,label:e,children:(0,Qe.jsx)(re,{id:s,"data-testid":`template-browser-${e.toLowerCase()}-filter`,size:"normal",value:r,onValueChange:t,options:a,optionsClassName:"!min-w-44"})})}function wt({active:e,disabled:t,featured:r,manifest:s,onCreate:l,onReadinessAction:o,onView:i,readiness:n,runtimeEstimate:d,requiresTermsReview:c,selected:p,template:f}){let{beforePath:g,mediaPath:h,thumbnailPath:x}=te(f,s),v=xe(f).length>0;return(0,Qe.jsxs)("article",{"data-testid":`template-browser-card-${f.id}`,"data-active-template":e?"true":"false","data-inspected":p?"true":"false",className:I("group relative flex h-full min-h-0 flex-col overflow-hidden rounded-modiff-panel border bg-modiff-bg shadow-modiff-node",p?"border-hf-yellow ring-1 ring-hf-yellow/40":e?"border-modiff-blue ring-1 ring-modiff-blue/30":"border-modiff-border"),children:[(0,Qe.jsx)(ge,{tone:"ghost",disabled:t,"aria-label":`View details for ${Te(f)}`,"aria-current":e?"true":void 0,"aria-pressed":p,onClick:i,onFocus:i,className:"absolute inset-0 z-0 !h-auto !w-full !rounded-modiff-panel !border-0 !bg-transparent !p-0",children:(0,Qe.jsx)("span",{className:"sr-only",children:"View template details"})}),(0,Qe.jsxs)("div",{className:"pointer-events-none relative z-10 overflow-hidden bg-modiff-panel",children:[(0,Qe.jsx)(kt,{afterPath:h,beforePath:g,mediaKind:f.outputKinds?.[0],slots:Se(f),thumbnailPath:x,variant:f.thumbnailVariant}),(0,Qe.jsxs)("div",{className:"pointer-events-none absolute inset-x-0 top-0 flex items-start justify-end gap-2 bg-gradient-to-b from-modiff-bg/80 to-transparent p-3",children:[v?(0,Qe.jsx)(we,{content:"Usage restrictions — review before use",children:e=>(0,Qe.jsx)("span",{...e,"aria-label":"Usage restrictions — review before use",className:"pointer-events-auto grid size-7 place-items-center rounded-full border border-hf-orange/70 bg-modiff-bg/85 text-hf-orange backdrop-blur","data-testid":`template-usage-warning-${f.id}`,role:"img",tabIndex:0,children:(0,Qe.jsx)(m,{"aria-hidden":"true",size:14})})}):null,(0,Qe.jsx)("span",{className:"rounded-full border border-modiff-overlay-text/10 bg-modiff-bg/80 px-2 py-1 text-xs font-semibold text-modiff-text backdrop-blur",children:ct(f)})]}),r?(0,Qe.jsx)("div",{className:"pointer-events-none absolute left-3 top-3 grid size-7 place-items-center rounded-full border border-hf-yellow/50 bg-modiff-bg/85 text-hf-yellow backdrop-blur",title:"Featured template",children:(0,Qe.jsx)(a,{size:13})}):null]}),(0,Qe.jsxs)("div",{className:"pointer-events-none relative z-10 flex min-h-0 flex-1 flex-col gap-3 p-4",children:[(0,Qe.jsxs)("div",{className:"min-w-0",children:[(0,Qe.jsxs)("div",{className:"mb-1 flex min-h-12 items-start justify-between gap-2",children:[(0,Qe.jsx)("h3",{className:"min-w-0 flex-1",children:(0,Qe.jsx)(ge,{tone:"ghost",size:"compact",align:"left",disabled:t,"data-testid":`template-browser-use-${f.id}`,onClick:i,className:"pointer-events-auto !h-auto min-w-0 max-w-full !justify-start !rounded-none !p-0 text-base !font-bold !leading-6 text-modiff-text hover:bg-transparent",children:(0,Qe.jsx)("span",{className:"line-clamp-2",children:Te(f)})})}),(0,Qe.jsx)(St,{readiness:n,testId:`template-card-readiness-${f.id}`,onAction:()=>o(n)})]}),(0,Qe.jsxs)("p",{className:"truncate text-sm font-semibold text-modiff-subtle-text",children:[q[f.modelType]," · ",je[f.mode]]})]}),(0,Qe.jsx)("p",{className:"line-clamp-2 min-h-10 text-sm leading-5 text-modiff-subtle-text",children:f.recipeSummary??f.description}),(0,Qe.jsxs)("div",{className:"mt-auto grid min-w-0 gap-2 border-t border-modiff-border pt-3",children:[d?(0,Qe.jsxs)("div",{className:"inline-flex min-w-0 items-center gap-2 text-xs text-modiff-subtle-text","data-testid":`template-runtime-${f.id}`,title:d.title,children:[(0,Qe.jsx)(u,{size:13,className:"shrink-0 text-hf-yellow"}),(0,Qe.jsx)("span",{className:"truncate",children:d.label})]}):null,(0,Qe.jsx)(ge,{tone:"primary",className:"pointer-events-auto w-full",icon:(0,Qe.jsx)(b,{size:14}),disabled:t,"data-testid":`template-browser-create-card-${f.id}`,onClick:e=>{e.stopPropagation(),l()},children:c?"Review terms":"Use template"})]})]})]})}function yt({disabled:e,installingRepo:o,manifest:d,onBack:c,onCreate:u,onInstallRepo:p,onOpenAssets:f,onOpenModels:g,onOpenSetup:h,onUseLowVram:v,readiness:w,runtimeEstimate:j,requiresTermsReview:k,template:N}){let _=M(N,d,{requireCardPreview:!1}),S=_??function(e,t){return t?.examples.find(t=>t.templateId===e.id&&["approved_reviewed","approved_exact"].includes(t.qualityReviewStatus)&&!(!t.beforePath||!t.beforeMediaHash))}(N,d),T=N.inputBindings?.filter(e=>"template"===e.origin).flatMap(e=>e.defaultAssets).find(e=>e.previewPath)?.previewPath,P=y(_?.thumbnailPath??_?.posterPath)??mt(N),R=y(S?.beforePath??T),C=y(_?.afterPath??_?.outputPath),I=function(e){let t=me(e),a=t.templateDefaultBindings.map(e=>({included:!0,key:e.id,label:e.label.replace(/^Reviewed\s+/i,"")})),r=t.missingLabels.map(e=>({included:!1,key:`missing:${e}`,label:e}));return a.length>0||r.length>0?{title:0===r.length?"Included inputs":"Required inputs",items:[...a,...r]}:{title:"Required inputs",items:ut(e).map(e=>({included:!1,key:`legacy:${e}`,label:e}))}}(N),$=k?"Review terms":"Use template",z=w.issues.some(e=>"open_assets"===e.action),A=w.issues.some(e=>"open_setup"===e.action),E=w.issues.some(e=>"apply_low_vram"===e.action);return(0,Qe.jsxs)("aside",{className:"min-h-0 overflow-y-auto bg-modiff-bg p-4 @[1024px]:border-l @[1024px]:border-modiff-border","data-testid":`template-detail-${N.id}`,children:[(0,Qe.jsx)("div",{className:"mb-3 flex items-center justify-between gap-2",children:(0,Qe.jsx)(ge,{tone:"ghost",size:"dense",icon:(0,Qe.jsx)(l,{size:15}),onClick:c,children:"Templates"})}),(0,Qe.jsx)(kt,{afterPath:C,beforePath:R,detail:!0,mediaKind:N.outputKinds?.[0],slots:Se(N),thumbnailPath:P,variant:N.thumbnailVariant}),(0,Qe.jsxs)("div",{className:"mt-4 grid gap-4",children:[(0,Qe.jsxs)("div",{children:[(0,Qe.jsxs)("div",{className:"mb-2 inline-flex items-center gap-1.5 rounded-full border border-modiff-border bg-modiff-panel px-2.5 py-1 text-xs font-semibold text-hf-yellow",children:[(0,Qe.jsx)(n,{size:12}),je[N.mode]]}),(0,Qe.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,Qe.jsxs)("div",{className:"min-w-0",children:[(0,Qe.jsx)("h2",{className:"break-words text-xl font-bold tracking-tight text-modiff-text",children:Te(N)}),(0,Qe.jsxs)("p",{className:"mt-1 text-sm font-semibold text-modiff-subtle-text",children:[q[N.modelType]," · ",je[N.mode]]})]}),(0,Qe.jsx)(Tt,{readiness:w})]}),(0,Qe.jsx)("p",{className:"mt-3 text-sm leading-6 text-modiff-subtle-text",children:N.userGoal})]}),(0,Qe.jsxs)("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[j?(0,Qe.jsx)(jt,{label:"Local runtime",value:j.label}):null,(0,Qe.jsx)(jt,{label:"VRAM",value:N.vramEstimate??"TBD"}),(0,Qe.jsx)(jt,{label:"Output",value:ct(N)}),(0,Qe.jsx)(jt,{label:"Level",value:N.difficulty??"starter"})]}),(0,Qe.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Qe.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"What this creates"}),(0,Qe.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:N.recipeSummary??N.description})]}),(0,Qe.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Qe.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:I.title}),(0,Qe.jsx)("div",{className:"mt-2 flex flex-wrap gap-1",children:I.items.map(e=>(0,Qe.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:[e.included?(0,Qe.jsx)(x,{"aria-hidden":"true",className:"text-modiff-green",size:12}):null,e.label]},e.key))})]}),(0,Qe.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Qe.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Default prompt"}),(0,Qe.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-xs leading-5 text-modiff-text",children:N.prompt}),N.negativePrompt?(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsx)("h4",{className:"mt-3 text-xs font-semibold uppercase text-modiff-subtle-text",children:"Negative prompt"}),(0,Qe.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs leading-5 text-modiff-subtle-text",children:N.negativePrompt})]}):null]}),(0,Qe.jsxs)("section",{className:"grid gap-2","data-testid":`template-readiness-${N.id}`,children:[(0,Qe.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,Qe.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Preflight"}),(0,Qe.jsx)(Tt,{readiness:w})]}),0===w.issues.length?(0,Qe.jsx)(V,{tone:"success",title:"Ready now",meta:w.summary,children:"Create a graph tab, build the graph, and then run when you are ready."}):w.issues.map(e=>(0,Qe.jsx)(V,{tone:e.tone,title:e.title,meta:e.detail},e.id))]}),(0,Qe.jsxs)("div",{className:"flex flex-wrap gap-2",children:[w.modelInstallTargets.map(e=>(0,Qe.jsx)(ge,{icon:(0,Qe.jsx)(i,{size:15}),disabled:o===e.repoId,"aria-label":`Install ${e.repoId}`,onClick:()=>p(e.repoId,e.repair),children:o===e.repoId?"Installing...":e.actionLabel??"Install"},e.repoId)),z?(0,Qe.jsx)(ge,{icon:(0,Qe.jsx)(r,{size:15}),onClick:f,children:"Open assets"}):null,A?(0,Qe.jsx)(ge,{icon:(0,Qe.jsx)(t,{size:15}),onClick:h,children:"Open setup"}):null,E?(0,Qe.jsx)(ge,{icon:(0,Qe.jsx)(a,{size:15}),onClick:v,children:"Try Low VRAM"}):null,(0,Qe.jsx)(ge,{icon:(0,Qe.jsx)(s,{size:15}),onClick:g,children:"Models"})]}),(0,Qe.jsx)("div",{className:"sticky bottom-0 -mx-4 bg-gradient-to-t from-modiff-bg via-modiff-bg to-transparent px-4 pb-1 pt-5",children:(0,Qe.jsx)(ge,{tone:"primary",className:"h-10 w-full",icon:"planning"===w.status||"needs_backend"===w.status||"needs_setup"===w.status?(0,Qe.jsx)(m,{size:15}):(0,Qe.jsx)(b,{size:15}),disabled:e,"data-testid":`template-browser-create-${N.id}`,onClick:u,children:$})})]})]})}function jt({label:e,value:t}){return(0,Qe.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",children:[(0,Qe.jsx)("div",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,Qe.jsx)("div",{className:"mt-1 break-words text-xs font-semibold text-modiff-text",children:t})]})}function kt({afterPath:e,beforePath:t,detail:a=!1,mediaKind:r="image",slots:s,thumbnailPath:l}){if("image"===r&&t&&e)return(0,Qe.jsx)(Nt,{afterPath:e,beforePath:t,detail:a});if(!e&&!t&&l)return(0,Qe.jsx)(_t,{slot:{id:"editorial-poster",label:"Template preview",kind:"poster",placeholder:"template poster pending"},path:l,detail:a,large:!0});let o=2===s.length&&s.some(e=>"compare-before"===e.kind);if(o&&"video"===r&&!a&&e)return(0,Qe.jsx)(_t,{slot:{id:"published-result",label:"Generated video preview",kind:"video",posterPath:l,placeholder:"video preview pending"},path:e,large:!0});if(o){let o=(e,t)=>{if(!e)return t;let a=e.split(/[?#]/,1)[0]?.toLowerCase()??"";return/\.(mp4|webm|mov|mkv)$/.test(a)?"video":/\.(png|jpe?g|webp|gif|avif)$/.test(a)?"image":t};return(0,Qe.jsxs)("div",{className:"grid aspect-video grid-cols-2 overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-border",children:[(0,Qe.jsx)(_t,{slot:"video"===r?{...s[0],kind:o(t,"image")}:s[0],path:t,detail:a}),(0,Qe.jsx)(_t,{slot:"video"===r?{...s[1],kind:o(e??l,e?"video":"image"),posterPath:l}:s[1],path:e??l,detail:a})]})}if(s.length>1&&(e||l)){let t="video"===r?"video":"audio"===r?"audio":"image";return(0,Qe.jsx)(_t,{slot:{id:"published-result",label:"Generated result",kind:t,posterPath:l,placeholder:`${t} preview pending`},path:"image"===t?l??e:e??l,detail:a,large:!0})}if(s.length>1)return(0,Qe.jsx)("div",{className:"grid aspect-video grid-cols-2 gap-px overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-border",children:s.slice(0,4).map((e,t)=>(0,Qe.jsx)(_t,{slot:e,path:e.path??(0===t?l:void 0),compact:!0,detail:a},e.id))});let i=s[0],n="video"===r||"audio"===r;return(0,Qe.jsx)(_t,{slot:"video"===r?{...i,kind:"video",posterPath:i.posterPath??l}:"audio"===r?{...i,kind:"audio"}:i,path:n?e??t??i.path:l??i.path,detail:a,large:!0})}function Nt({afterPath:e,beforePath:t,detail:a}){let[r,s]=(0,Le.useState)(50),[l,o]=(0,Le.useState)(!1),i=(0,Le.useRef)(null),n=(e,t)=>{let a=e.getBoundingClientRect();if(a.width<=0)return;let r=(t-a.left)/a.width*100;s(Math.max(0,Math.min(100,r)))};return(0,Qe.jsxs)("div",{className:"relative aspect-video overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-panel",children:[(0,Qe.jsx)(j,{ref:i,"aria-label":"Before and after comparison",testId:"template-ab-comparison",imageFrom:t,imageTo:e,sliderPosition:r,onSliderPositionChange:s,onError:e=>{e.currentTarget.src="/assets/modiff-icon-256.png"},onMouseDown:e=>{o(!0),n(e.currentTarget,e.clientX)},onMouseEnter:e=>{n(e.currentTarget,e.clientX)},onMouseMove:e=>{n(e.currentTarget,e.clientX)},onPointerMove:e=>{"mouse"===e.pointerType&&n(e.currentTarget,e.clientX)},onMouseUp:()=>o(!1),onTouchStart:e=>{o(!0),n(e.currentTarget,e.touches[0]?.clientX??0)},onTouchMove:e=>{l&&n(e.currentTarget,e.touches[0]?.clientX??0)},onTouchEnd:()=>o(!1)}),a?(0,Qe.jsx)("span",{className:"pointer-events-none absolute left-1/2 top-2 -translate-x-1/2 rounded-full bg-modiff-bg/80 px-2 py-1 text-xs font-semibold text-modiff-text backdrop-blur",children:"Hover or drag to compare"}):null]})}function _t({compact:e=!1,detail:t=!1,large:a=!1,path:s,slot:l}){let o=(0,Le.useRef)(null),i=(0,Le.useRef)(null),[n,d]=(0,Le.useState)(null),[m,u]=(0,Le.useState)(t),[p,f]=(0,Le.useState)(!1),[g,x]=(0,Le.useState)(!1),[w,y]=(0,Le.useState)(!1),j=s&&n!==s?s:void 0,k="video"===l.kind,N="audio"===l.kind,_="json"===l.kind,S=k||"gif"===l.kind?c:N?v:_?h:r,T=t||m&&(!p||g),P=!t&&m&&(!p||g);return(0,Le.useEffect)(()=>{if(t||!k||!j)return;let e=o.current;if(!e||typeof IntersectionObserver>"u")return void u(!0);let a=new IntersectionObserver(([e])=>u(!!e?.isIntersecting),{rootMargin:"160px 0px",threshold:.01});return a.observe(e),()=>a.disconnect()},[t,k,j]),(0,Le.useEffect)(()=>{if(t||!k)return;let e=window.matchMedia("(prefers-reduced-motion: reduce)"),a=navigator.connection,r=()=>f(e.matches||!0===a?.saveData);return r(),e.addEventListener("change",r),a?.addEventListener?.("change",r),()=>{e.removeEventListener("change",r),a?.removeEventListener?.("change",r)}},[t,k]),(0,Le.useEffect)(()=>{if(!t&&i.current){if(!T||!P)return void i.current.pause();i.current.play().catch(()=>{})}},[T,P,t]),(0,Le.useEffect)(()=>{d(null),x(!1),y(!1)},[s]),(0,Qe.jsxs)("div",{ref:o,className:I("relative grid place-items-center overflow-hidden bg-gradient-to-br from-modiff-panel via-modiff-bg to-modiff-surface",a&&"rounded-modiff-panel border border-modiff-border",a&&"aspect-video"),children:[j&&k?(0,Qe.jsxs)(Qe.Fragment,{children:[l.posterPath?(0,Qe.jsx)("img",{src:l.posterPath,alt:"","aria-hidden":"true",loading:"eager",decoding:"async",className:"absolute inset-0 h-full w-full object-cover"}):null,(0,Qe.jsx)("video",{ref:i,src:T?j:void 0,poster:l.posterPath,muted:!t,loop:!t,controls:t,autoPlay:P,playsInline:!0,preload:t||T?"metadata":"none","aria-label":l.label,"data-testid":t?"template-detail-video":"template-card-video","data-preview-attached":T?"true":"false",className:I("relative h-full w-full object-cover transition-opacity duration-150",w||!l.posterPath?"opacity-100":"opacity-0"),onError:()=>d(j),onLoadedData:()=>y(!0),onPlaying:()=>y(!0),onCanPlay:()=>{P&&i.current?.play().catch(()=>{})}})]}):k&&l.posterPath?(0,Qe.jsx)("img",{src:l.posterPath,alt:l.label,loading:"lazy",decoding:"async",className:"h-full w-full object-cover"}):N?(0,Qe.jsxs)("div",{className:"grid h-full w-full content-center gap-4 bg-gradient-to-br from-hf-yellow/15 via-modiff-panel to-modiff-bg p-4",children:[(0,Qe.jsxs)("div",{className:"flex items-center gap-3",children:[(0,Qe.jsx)("div",{className:"grid size-10 shrink-0 place-items-center rounded-full bg-hf-yellow text-modiff-on-accent",children:(0,Qe.jsx)(v,{size:18})}),(0,Qe.jsx)("div",{className:"flex h-16 flex-1 items-center justify-center gap-1 overflow-hidden",children:gt.map((e,t)=>(0,Qe.jsx)("span",{className:I("w-1 rounded-full bg-hf-yellow/80",e)},`${e}-${t}`))})]}),j?(0,Qe.jsx)("audio",{src:j,controls:!0,preload:t?"metadata":"none",className:"pointer-events-auto h-9 w-full","aria-label":l.label,onError:()=>d(j)}):(0,Qe.jsx)("p",{className:"text-center text-xs font-semibold text-modiff-subtle-text",children:"No preview yet"})]}):j&&!_?a?t?(0,Qe.jsxs)(Qe.Fragment,{children:[(0,Qe.jsx)("img",{src:j,alt:"","aria-hidden":"true",loading:"eager",decoding:"async",className:"absolute inset-0 h-full w-full scale-110 object-cover opacity-30 blur-xl",onError:()=>d(j)}),(0,Qe.jsx)("img",{src:j,alt:l.label,loading:"eager",decoding:"async",className:"relative h-full w-full object-contain p-1.5",onError:()=>d(j)})]}):(0,Qe.jsx)("img",{src:j,alt:l.label,loading:"eager",decoding:"async",className:"h-full w-full object-cover",onError:()=>d(j)}):(0,Qe.jsx)("img",{src:j,alt:l.label,loading:"lazy",decoding:"async",className:"h-full w-full object-cover",onError:()=>d(j)}):(0,Qe.jsx)("div",{className:"grid h-full min-h-28 w-full place-items-center p-3 text-center",children:(0,Qe.jsxs)("div",{children:[(0,Qe.jsx)("div",{className:"mx-auto mb-2 grid size-9 place-items-center rounded-full border border-modiff-border bg-modiff-bg/70 text-modiff-subtle-text",children:(0,Qe.jsx)(S,{size:e?16:19})}),(0,Qe.jsx)("p",{className:"text-xs font-semibold text-modiff-subtle-text",children:s?"Preview unavailable":"No preview yet"}),e?null:(0,Qe.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:s&&n===s?"The published media could not be decoded":l.placeholder})]})}),!N&&t?(0,Qe.jsx)("span",{className:"absolute left-2 top-2 rounded-full border border-modiff-overlay-text/10 bg-modiff-bg/75 px-2 py-1 text-xs font-semibold text-modiff-overlay-text backdrop-blur",children:l.label}):null,k&&j&&!t&&p&&!g?(0,Qe.jsx)(ae,{label:"Play video preview",onClick:e=>{e.stopPropagation(),x(!0)},className:"pointer-events-auto absolute inset-0 m-auto !size-10 rounded-full border border-modiff-overlay-text/20 bg-modiff-bg/80 text-modiff-overlay-text shadow-modiff-node backdrop-blur hover:border-hf-yellow hover:text-hf-yellow",children:(0,Qe.jsx)(b,{size:17,fill:"currentColor"})}):null]})}function St({onAction:e,readiness:t,testId:a}){let r=["needs_input","needs_model","needs_backend","needs_setup"].includes(t.status),s="ready"===t.status?(0,Qe.jsx)(x,{size:18}):"needs_backend"===t.status?(0,Qe.jsx)(p,{size:18}):"preparing"===t.status||"planning"===t.status?(0,Qe.jsx)(d,{size:18}):(0,Qe.jsx)(m,{size:18}),l=I("pointer-events-auto relative grid size-8 shrink-0 place-items-center rounded-full border bg-modiff-panel/90 transition","success"===t.tone&&"border-modiff-green/70 text-modiff-green","warning"===t.tone&&"border-hf-orange/70 text-hf-orange","error"===t.tone&&"border-modiff-red/70 text-modiff-red","info"===t.tone&&"border-modiff-blue/70 text-modiff-blue","default"===t.tone&&"border-modiff-border text-modiff-subtle-text",r&&"hover:scale-105 hover:bg-modiff-surface-hover"),o=`${t.label}: ${t.summary}`;return r?(0,Qe.jsx)(ae,{label:o,className:l,"data-testid":a,onClick:e,children:s}):(0,Qe.jsx)(we,{content:o,children:e=>(0,Qe.jsx)("span",{...e,className:l,"data-testid":a,"aria-label":o,role:"img",tabIndex:0,children:s})})}function Tt({readiness:e}){return(0,Qe.jsxs)("span",{className:I("inline-flex shrink-0 items-center gap-1 rounded-modiff-compact border px-1.5 py-0.5 text-xs font-semibold","success"===e.tone&&"border-modiff-green/70 text-modiff-green","warning"===e.tone&&"border-hf-orange/70 text-hf-orange","error"===e.tone&&"border-modiff-red/70 text-modiff-red","info"===e.tone&&"border-modiff-blue/70 text-modiff-blue","default"===e.tone&&"border-modiff-border text-modiff-subtle-text"),children:["success"===e.tone?(0,Qe.jsx)(x,{size:12}):"error"===e.tone?(0,Qe.jsx)(m,{size:12}):(0,Qe.jsx)(d,{size:12}),e.label]})}export{xt as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{D as t,H as a,It as r,K as s,Ln as l,M as o,Mn as i,Mt as n,Pt as d,Qt as c,R as m,_n as u,bn as p,cr as f,dr as g,jt as h,st as b,wn as x,yt as v}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ai as w,Ao as y,Ba as j,Br as k,Di as N,Ei as _,Fi as S,Fs as P,Gi as T,Hi as R,Hr as I,Ii as C,Li as M,Ln as $,Ni as q,Oi as z,Po as A,Pr as E,Qa as L,Qi as B,Tn as O,Ui as V,Va as D,Vo as F,Wi as W,Xi as K,Ya as U,Yi as H,Yn as G,Zi as X,an as Q,bn as Y,ea as Z,et as J,fr as ee,ga as te,ha as ae,in as re,jn as se,ki as le,kn as oe,nr as ie,on as ne,pa as de,pn as ce,qa as me,qi as ue,rr as pe,t as fe,ta as ge,u as he,va as be,wa as xe,wi as ve,wr as we,xn as ye,za as je,zi as ke}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{r as Ne,t as _e}from"./presetDiff.js?v=ca6b74e6a02eedb3";import{a as Se,i as Pe,n as Te,t as Re}from"./templateBrowser.js?v=ca6b74e6a02eedb3";import{n as Ie,t as Ce}from"./TemplateUsageTermsDialog.js?v=ca6b74e6a02eedb3";import{a as Me,i as $e,n as qe,o as ze,r as Ae,t as Ee}from"./controlledWorkflows.js?v=ca6b74e6a02eedb3";var Le=e(g(),1);function Be(e){return"install_model"===e?"install_model":"open_models"===e?"open_model_manager":"open_assets"===e||"add_input"===e?"select_image":"open_setup"===e?"open_setup":"apply_low_vram"===e?"apply_low_vram_preset":void 0}function Oe(e){return{id:`template:${e.id}`,category:e.category,severity:"error"===e.tone?"error":"warning"===e.tone?"warning":"success"===e.tone?"success":"info",repoId:e.repoId,message:e.title,details:e.detail,blocking:e.blocking,action:Be(e.action)}}function Ve(e){return Object.keys(e).length>0}function De(e){return"hub"===e?.source&&e.value.trim().length>0}function Fe(e){let[t,a]=e.value.split("/");return t&&a?`${t}/${a}`:e.value}function We(e){let t=[],a=(a,r,s)=>{De(s)&&t.push({id:a,label:r,repo:Fe(s),kind:"adapter",requiredForModes:[e.mode],description:`${r} pinned by ${e.label}.`})};a(`${e.id}-lora`,"LoRA adapter",e.workflowBlockSettings?.lora?.model),a(`${e.id}-lora-base`,"LoRA base model",e.workflowBlockSettings?.lora?.baseModel);for(let[t,r]of(e.workflowBlockSettings?.lora?.additionalAdapters??[]).entries())a(`${e.id}-lora-${t+2}`,`LoRA adapter ${t+2}`,r.model),a(`${e.id}-lora-${t+2}-base`,`LoRA base model ${t+2}`,r.baseModel);return a(`${e.id}-upscaler`,"Upscaler model",e.workflowBlockSettings?.upscaler?.model),t}function Ke(e){let t=j[e.modelType];return[...!1===t.artifactInstallRequired?[]:[{id:`${e.modelType}-base`,label:t.label,repo:t.defaultRepo,kind:"base",requiredForModes:[e.mode],description:`Base model for ${t.label}.`}],...L(t,e.mode),...We(e)]}function Ue(e,t){let a=j[e.modelType],r=S(t.autoResourcePlan,t.form),s=ke(t.autoResourcePlan,t.form),l=M(t.autoResourcePlan,t.form),o=!0===t.modelIndexesRefreshing,i="planning"===e.readinessPolicy||"blocked"===e.difficulty||"blocked"===e.example?.status,n=!t.runtimeStatus&&!Ve(t.nodesRegistry),d=function(e,t){let a=e.requiredBackendCapabilities??[];return 0===a.length?[]:a.filter(e=>{let a=fe(e);return!a||Ve(t)&&!a.every(e=>t[e])})}(e,t.nodesRegistry),c=function(e,t){let a=pe(e).missingLabels;return t?(t.loraAdapter&&!De(e.workflowBlockSettings?.lora?.model)&&a.push("LoRA adapter"),t.upscalerModel&&!De(e.workflowBlockSettings?.upscaler?.model)&&a.push("Upscaler model"),Array.from(new Set(a))):a}(e,e.inputRequirements),m=o?[]:[...t.autoResourcePlan?L(a,e.mode):Ke(e),...t.autoResourcePlan?We(e):[]].filter(e=>!P(e.repo,t.hfCache,t.localModels,t.modelCacheDiagnostics).runnable).map(e=>e.repo),u=[],p=[];i&&u.push({id:"planning",category:"graph",blocking:!0,tone:"info",title:"Planning template",detail:e.example?.blockReason??"This recipe can be opened and inspected, but MoDiff should not present it as runnable yet.",action:"open_planning"}),o&&u.push({id:"model-index-refresh",category:"model",blocking:!0,tone:"info",title:"Checking installed models",detail:"Refreshing the local model index before reporting template readiness."}),!o&&"checking"===l.state&&u.push({id:"auto-plan-checking",category:"environment",blocking:!0,tone:"info",title:l.summary,detail:l.detail}),n&&u.push({id:"backend:connection",category:"backend",blocking:!0,tone:"error",title:"Backend connection needed",detail:"Connect to the MoDiff backend before checking installed models.",action:"open_setup"}),d.forEach(e=>{u.push({id:`backend:${e}`,category:"package",blocking:!0,tone:"error",title:"Backend contract needed",detail:e,action:"open_setup"})}),m.forEach(e=>{p.push({repoId:e,actionLabel:"Install"}),u.push({id:`model:${e}`,category:"model",blocking:!0,tone:"warning",title:"Model package missing",detail:e,action:"install_model",repoId:e,actionLabel:"Install"})}),o||r||!s?!o&&!r&&t.autoResourcePlan&&!s&&u.push({id:"auto-plan-blocked",category:"environment"===t.autoResourcePlan.issue?.category?"environment":"package"===t.autoResourcePlan.issue?.category?"package":"device"===t.autoResourcePlan.issue?.category?"hardware_fit":"environment",blocking:!0,tone:"error"===l.severity?"error":"warning"===l.severity?"warning":"info",title:l.summary,detail:l.detail,action:"expert_only"===l.state?"open_planning":"open_setup"}):(p.push({repoId:s.repo,repair:s.repair,actionLabel:s.actionLabel}),u.push({id:`auto-model:${s.repo}`,category:s.repair?"model_integrity":"model",blocking:!0,tone:s.repair?"error":"warning",title:s.repair?"Model package repair required":"Auto model package missing",detail:`${s.actionLabel??"Install Auto artifact"}: ${s.repo}`,action:"install_model",repoId:s.repo,repair:s.repair,actionLabel:s.actionLabel})),c.forEach(e=>{u.push({id:`input:${e}`,category:"asset",blocking:!0,tone:"warning",title:`${e} required`,detail:"Add the required asset in Studio after creating this workflow, or open the Assets library to reuse an existing output.",action:"open_assets"})});let f=ee(u.map(Oe),{preparing:o||"checking"===l.state}),g=f.primaryIssue?.category,h=i||u.some(e=>"open_planning"===e.action)?"planning":"preparing"===f.state?"preparing":"blocked"===f.state?"backend"===g||"package"===g?"needs_backend":"model"===g||"model_integrity"===g?"needs_model":"asset"===g||"user_input"===g?"needs_input":"needs_setup":"ready",b=function(e){return"ready"===e?{label:"Ready now",tone:"success"}:"needs_input"===e?{label:"Needs input",tone:"warning"}:"needs_model"===e?{label:"Needs model",tone:"warning"}:"needs_backend"===e?{label:"Backend blocked",tone:"error"}:"needs_setup"===e?{label:"Needs setup",tone:"warning"}:"preparing"===e?{label:"Checking models",tone:"info"}:{label:"Planning only",tone:"info"}}(h),x="ready"===h?`${je[e.modelType]} Auto plan is ready, hardware looks usable, and no required inputs are missing.`:u[0]?.detail??"Review the required setup before running this recipe.";return{status:h,label:b.label,tone:b.tone,summary:x,compatibility:l,issues:u,missingModelRepos:Array.from(new Set(m)),modelInstallTargets:Array.from(new Map(p.map(e=>[e.repoId,e])).values()),missingInputs:c,missingBackendCapabilities:d,decision:f}}async function He(e,t,a,r={}){"lora"!==e?"upscaler"!==e?"video_sequence"!==e?"quality_video_sequence"!==e?"soundtrack"!==e?await qe(t,a.workflowBlockSettings?.lyricVideo,r):await $e(t,a.workflowBlockSettings?.soundtrack,r):await Ae(t,a.workflowBlockSettings?.qualityVideoSequence,r):await ze(t,a.workflowBlockSettings?.videoSequence,r):await Me(t,a.workflowBlockSettings?.upscaler,r):await Ee(t,a.workflowBlockSettings?.lora,r)}function Ge(){return typeof window>"u"||"function"!=typeof window.requestAnimationFrame?Promise.resolve():new Promise(e=>{window.requestAnimationFrame(()=>{window.requestAnimationFrame(()=>e())})})}async function Xe(e){let t=q.getState().createWorkflowTab(e.label,void 0,"template",e.id);q.getState().setLauncherDismissed(!0);let a=z();q.getState().setCanvasTransition({type:"template_graph_building",workflowTabId:t,templateId:e.id,startedAt:Date.now()});let r,s=q.getState().form,l=s,o=!1,i=[];try{if("success"!==ve.getState().discoveryRequests.capabilities.status){await ve.getState().fetchStudioModelCapabilities(),N(a);let e=ve.getState().discoveryRequests.capabilities;if("success"!==e.status)throw Error(e.error||"Model capabilities are not ready. Retry opening the template.")}let t=await ie(e);N(a),q.getState().applyTemplate(e,t),_(a),q.getState().saveActiveWorkflowTab(!0),l=q.getState().form,await Ge(),N(a);let r=await E(l,a);if(N(a),"auto"===l.resourceMode){let e=C(l),t=q.getState().autoResourcePlans[e]??await R(l);if(N(a),t.error||q.getState().setAutoResourcePlans({[e]:t}),q.getState().setAutoResourcePlan(t),S(t,l)){let e=le(t,l,q.getState().graphBinding);if(e)q.getState().setLastError(e);else{let e=W(ue(t,l),l);q.getState().applyAutoResourcePlan(t,e),_(a),l=q.getState().form,r=await E(l,a),N(a)}}}o=!0,i=r.warnings;for(let t of e.workflowBlocks??[])try{await He(t,l,e,{graphPrepared:!0,workflowContext:a}),N(a)}catch(a){if(w(a))throw a;let r=a instanceof Error?a.message:String(a);i.push(`${e.label} could not add the ${t} block: ${r}`)}let s=await k(15e3,a);if(N(a),!s)throw Error(`${e.label} graph preparation timed out. No incomplete graph was kept; try again.`);await F(()=>I.getState().nodes,500),N(a),await I.getState().arrangeGraph({history:!1}),N(a),await Ge(),N(a),q.getState().saveActiveWorkflowTab(!0)}catch(e){if(w(e))throw e;N(a),r=e instanceof Error?e.message:String(e),I.getState().replaceGraph({nodes:[],edges:[],viewport:{x:0,y:0,zoom:1}}),q.getState().setGraphBinding(null),q.getState().setGraphFinalization(null),q.getState().saveActiveWorkflowTab(!0)}finally{let a=q.getState().canvasTransition;a?.workflowTabId===t&&a.templateId===e.id&&q.getState().setCanvasTransition(null)}let n=Object.keys(B(e)),d=_e(s,l,n);return Ne(`${e.label} recipe applied`,d,q.getState().graphBinding?.managedNodeIds??[]),xe.getState().setRightPanelOpen(!0),xe.getState().setRightPanelTab("studio"),{graphCreated:o,graphError:r,warnings:i}}function Qe(e){let t=null,a=!1;return{hasRejected:()=>a,load:(r=!1)=>{if(t&&!r)return t;a=!1;let s=e();return t=s,s.then(()=>{t===s&&(a=!1)},()=>{t===s&&(t=null,a=!0)}),s}}}var Ye=f();function Ze({templates:e=!1}){let t=q(e=>e.activeWorkflowTabId),a=[...q(e=>e.workflowTabs)].filter(e=>e.id!==t).sort((e,t)=>t.updatedAt-e.updatedAt).slice(0,6),r=()=>J({revealWorkspace:!1});return(0,Ye.jsxs)("div",{className:"space-y-2",children:[(0,Ye.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ye.jsx)(re,{onClick:()=>J(),"data-testid":"launcher-mode-advanced_workflow",children:"Empty workflow"}),(0,Ye.jsx)(re,{onClick:()=>{r(),xe.getState().setWorkflowLibraryView("saved"),xe.getState().setLeftPanelTabIndex(4),xe.getState().setLeftPanelOpen(!0)},children:"Open workflow"}),e?(0,Ye.jsx)(re,{onClick:()=>{r(),xe.getState().setTemplateBrowserOpen(!0)},children:"Browse templates"}):null]}),a.length?(0,Ye.jsxs)("section",{"aria-label":"Recent workflows",className:"space-y-1",children:[(0,Ye.jsx)("h3",{className:"text-xs font-semibold text-modiff-subtle-text",children:"Recent workflows"}),(0,Ye.jsx)("div",{className:"flex gap-2 overflow-x-auto pb-1",children:a.map(e=>(0,Ye.jsx)(re,{title:e.title,className:"max-w-56 shrink-0",onClick:()=>{r(),q.getState().switchWorkflowTab(e.id)},children:(0,Ye.jsx)("span",{className:"truncate",children:e.title})},e.id))})]}):null]})}var Je=["all","starter","intermediate","advanced","blocked"],et=[...ae,...de],tt=[{value:"recommended",label:"Recommended"},{value:"task",label:"Task"},{value:"model",label:"Model"},{value:"runtime",label:"Runtime"}],at=Array.from(new Set(ae.map(e=>e.mode))).sort((e,t)=>D[e].localeCompare(D[t]));function rt(e){let t=B(e);return be({...U(e.mode,e.modelType),...te(e.presetId)?.values??{},...t,mode:e.mode,modelType:e.modelType,prompt:e.prompt,negativePrompt:e.negativePrompt??t.negativePrompt})}var st=ae.map(e=>{let t=rt(e);return{form:t,planKey:C(t),templateId:e.id}}),lt=Qe(async()=>y(H,{credentials:"omit",timeoutMs:12e4,parse:Z})),ot=Qe(async()=>{let e=st.map(e=>e.templateId),t=await V(st.map(e=>e.form),e),a={};return t.forEach((e,t)=>{let r=st[t];r&&(a[r.templateId]=e,a[r.planKey]??=e)}),a});function it(e=!1){return lt.load(e)}function nt(e=!1){return ot.load(e)}function dt(e){return"all"===e?"All levels":e.charAt(0).toUpperCase()+e.slice(1)}function ct(e){return e.outputKinds?.join(", ")||e.example?.mediaType||"image"}function mt(e){return ge(e.example?.thumbnailPath??e.example?.outputPath)}function ut(e){let t=e.inputRequirements;if(!t)return["Prompt only"];let a="hub"===e.workflowBlockSettings?.lora?.model.source,r="hub"===e.workflowBlockSettings?.upscaler?.model.source,s=[];t.sourceImage&&s.push("source image"),t.referenceImages&&s.push(`${t.referenceImages} reference image${1===t.referenceImages?"":"s"}`),t.controlImage&&s.push("control image"),t.maskImage&&s.push("mask image"),t.sourceVideo&&s.push("source video"),t.maskVideo&&s.push("mask video"),t.controlVideo&&s.push("control video"),t.loraAdapter&&!a&&s.push("LoRA adapter"),t.upscalerModel&&!r&&s.push("upscaler model"),t.sampleAssets?.length&&s.push(...t.sampleAssets.filter(e=>!(a&&/lora adapter/i.test(e)||r&&/upscaler|real-esrgan/i.test(e))));let l=s.filter((e,t)=>s.findIndex(t=>t.toLocaleLowerCase()===e.toLocaleLowerCase())===t);return l.length>0?l:["Prompt only"]}function pt(e){return Re.find(t=>t.id===e)?.label??"Templates"}function ft(e,t){if(t){let a=K(e,t);return!(!a||"video"===a.mediaType&&(!a.cardPreviewPath||!a.cardPreviewSha256))}let a=e.verificationStatus??e.example?.status;return"video"!==e.example?.mediaType&&!e.outputKinds?.includes("video")&&!("reviewed"!==a&&"exact"!==a||!mt(e)&&!function(e){return ge(e.example?.outputPath)}(e))}var gt=["h-3","h-7","h-5","h-10","h-6","h-12","h-8","h-14","h-9","h-5","h-11","h-7","h-12","h-8","h-4","h-9"],ht=["qwen_low_vram_product_concept","qwen_poster_logo_text","qwen_text_rendering","qwen_product_mockup","qwen_low_vram_poster_layout","qwen_low_vram_text_rendering","z_image_product_mockup","z_image_poster","z_image_cinematic_contact_sheet","z_image_quick_concept","wan_vace_cinematic_text_to_video","low_vram","high_quality"];function bt(e){let t=ht.indexOf(e);return-1===t?ht.length:t}function xt({entry:e=!1}){let t=xe(e=>e.templateBrowserOpen),a=xe(e=>e.setTemplateBrowserOpen),r=e||t,s=t=>{!t&&e&&J({revealWorkspace:!1}),a(t)},l=xe(e=>e.templateBrowserInitialCategory),i=xe(e=>e.clearTemplateBrowserInitialCategory),n=xe(e=>e.setRightPanelOpen),d=xe(e=>e.setRightPanelTab),c=xe(e=>e.setModelManagerOpener),m=xe(e=>e.setGalleryLibraryOpen),u=Ie(),p=q(e=>e.form),f=q(e=>e.activeTemplateId),g=q(e=>e.autoResourcePlans),h=q(e=>e.setAutoResourcePlans),b=we(e=>e.sessionRuns.reduce((e,t)=>"completed"===t.status?Math.max(e,t.completedAtMs??0):e,0)),x=G(e=>e.sid),v=ve(e=>e.hfCache),y=ve(e=>e.localModels),j=ve(e=>e.modelCacheDiagnostics),k=ve(e=>e.runtimeStatus),N=ve(e=>e.nodesRegistry),_=ve(e=>e.installHfModel),S=ve(e=>["nodes","runtime","hfCache","localModels","modelCache","capabilities"].some(t=>{let a=e.discoveryRequests[t].status;return"idle"===a||"loading"===a})),P=(0,Le.useId)(),[R,I]=(0,Le.useState)(!1),[M,z]=(0,Le.useState)(null),[E,L]=(0,Le.useState)(!1),[B,O]=(0,Le.useState)(!1),[V,F]=(0,Le.useState)(!1),[W,K]=(0,Le.useState)(null),[U,H]=(0,Le.useState)(null),[X,Z]=(0,Le.useState)(12),ee=(0,Le.useRef)(new Map),te=(0,Le.useRef)(!1),se=(0,Le.useRef)(!1),le=(0,Le.useRef)(b),[oe,ie]=(0,Le.useState)(null),[ne,de]=(0,Le.useState)(null),[ce,ue]=(0,Le.useState)({category:"recommended",query:"",modelType:"all",mode:"all",difficulty:"all",sort:"recommended"}),pe=["all"!==ce.modelType,"all"!==ce.mode,"all"!==ce.difficulty,"recommended"!==ce.sort].filter(Boolean).length;(0,Le.useEffect)(()=>{!r||!l||(ue(e=>({...e,category:l})),H(null),i())},[i,l,r]),(0,Le.useEffect)(()=>{r||(H(null),Z(12))},[r]),(0,Le.useEffect)(()=>{if(!r)return;let e=!1;return it().then(t=>{e||(z(t),L(!1))}).catch(()=>{e||(z(null),L(!0))}),()=>{e=!0}},[r]),(0,Le.useEffect)(()=>{if(!r||!function(e){return e.failed&&!e.attempted}({attempted:te.current,failed:E&<.hasRejected()}))return;te.current=!0;let e=!1,t=globalThis.setTimeout(()=>{it().then(t=>{e||(z(t),L(!1))}).catch(e=>console.error(e))},1500);return()=>{e=!0,globalThis.clearTimeout(t),te.current=!1}},[E,r]),(0,Le.useEffect)(()=>{if(!r)return;let e=!1;return nt().then(t=>{e||(h(t),O(!1))}).catch(t=>{e||O(!0),console.error(t)}),()=>{e=!0}},[r,h]),(0,Le.useEffect)(()=>{if(!r||!function(e){return e.failed&&e.backendReady&&!e.discoveryRefreshing&&!e.attempted}({attempted:se.current,backendReady:!!x,discoveryRefreshing:S,failed:B&&ot.hasRejected()}))return;se.current=!0;let e=!1,t=globalThis.setTimeout(()=>{nt().then(t=>{e||(h(t),O(!1))}).catch(e=>console.error(e))},1500);return()=>{e=!0,globalThis.clearTimeout(t),se.current=!1}},[B,S,r,h,x]),(0,Le.useEffect)(()=>{if(!r||!b||b<=le.current)return;le.current=b;let e=!1,t=globalThis.setTimeout(()=>{nt(!0).then(t=>{e||h(t)}).catch(e=>console.error(e))},250);return()=>{e=!0,globalThis.clearTimeout(t)}},[b,r,h]);let fe=(0,Le.useMemo)(()=>({hfCache:v,localModels:y,modelCacheDiagnostics:j,runtimeStatus:k,nodesRegistry:N,modelIndexesRefreshing:S}),[v,y,j,S,N,k]),ge=(0,Le.useMemo)(()=>({...ce,includeBlocked:!0}),[ce]),be=(0,Le.useCallback)(e=>g[e.id]??g[C(rt(e))],[g]),ye=(0,Le.useCallback)(e=>T(be(e)),[be]),ke=(0,Le.useCallback)(e=>!ft(e,M),[M]),Ne=(0,Le.useMemo)(()=>{let e="experimental"===ce.category?et:ae,t="experimental"===ce.category?"all":ce.category,a=Te(e,p,{...ge,category:t},e=>ye(e)?.observedSeconds??null);return"experimental"===ce.category?a.filter(ke):a},[ge,ce.category,p,ke,ye]),_e=(0,Le.useMemo)(()=>Te(et,p,{...ge,category:"all",query:"",modelType:"all",mode:"all",difficulty:"all"},e=>ye(e)?.observedSeconds??null),[ge,p,ye]),Se=(0,Le.useMemo)(()=>_e.filter(ke).length,[_e,ke]),Me=(0,Le.useMemo)(()=>_e.filter(e=>ft(e,M)).length,[_e,M]),$e=(0,Le.useMemo)(()=>{if("recommended"!==ce.category||0!==ce.query.trim().length||"all"!==ce.modelType||"all"!==ce.mode||"all"!==ce.difficulty)return Ne;let e=Ne.filter(e=>ft(e,M));return 0===e.length?Ne:"recommended"===ce.sort?[...e].sort((e,t)=>bt(e.id)-bt(t.id)):e},[ce.category,ce.difficulty,ce.mode,ce.modelType,ce.query,ce.sort,Ne,M]),qe=(0,Le.useMemo)(()=>et.find(e=>e.id===U)??null,[U]),ze=(0,Le.useMemo)(()=>new Map(Re.map(e=>"recommended"===e.id&&Me>0?[e.id,Me]:"experimental"===e.id?[e.id,Se]:[e.id,Te(ae,p,{...ge,category:e.id,query:"",modelType:"all",mode:"all",difficulty:"all"}).length])),[ge,Se,p,Me]),Ae=(0,Le.useMemo)(()=>Re.filter(e=>"recommended"===e.id||"all"===e.id||(ze.get(e.id)??0)>0),[ze]);(0,Le.useLayoutEffect)(()=>{r&&ee.current.get(ce.category)?.scrollIntoView({block:"nearest",inline:"nearest"})},[ce.category,r,Ae]),(0,Le.useEffect)(()=>{Z(12),oe&&(oe.scrollTop=0)},[ce.category,ce.difficulty,ce.mode,ce.modelType,ce.query,ce.sort,oe]);let Ee=(0,Le.useMemo)(()=>$e.slice(0,X),[$e,X]),Be=Ee.length<$e.length;(0,Le.useEffect)(()=>{if(!r||!Be||!oe||!ne||typeof IntersectionObserver>"u")return;let e=new IntersectionObserver(([t])=>{t?.isIntersecting&&(e.disconnect(),Z(e=>Math.min(e+12,$e.length)))},{root:oe,rootMargin:"320px 0px",threshold:.01});return e.observe(ne),()=>e.disconnect()},[oe,Be,ne,r,$e.length,Ee.length]);let Oe=e=>u.needsReview(he(e)),Ve=e=>{u.request("create",he(e),()=>(async e=>{F(!0);try{let t=await Xe(e);if(s(!1),t.graphError)return void A(`${e.label} opened, but graph creation needs attention: ${t.graphError}`,{variant:"warning",autoHideDuration:7e3});if(t.warnings.length>0)return void A(`${Pe(e)}: ${t.warnings.join(" ")}`,{variant:"warning",autoHideDuration:12e3});A(`${Pe(e)} template created`,{variant:"success",autoHideDuration:2600})}catch(e){if(w(e))return;A(String(e),{variant:"error",autoHideDuration:7e3})}finally{F(!1)}})(e))},De=u.pending?.policies??[],Fe=()=>{n(!0),d("setup"),s(!1)},We=()=>{m(!0)};return(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsxs)(Q,{open:r,onClose:()=>s(!1),testId:e?"task-launcher":"template-browser-dialog",title:(0,Ye.jsxs)("span",{className:"inline-flex items-center gap-2",children:[(0,Ye.jsx)(o,{size:18,className:"text-hf-yellow"}),"Templates"]}),panelClassName:"!h-[90dvh] !w-[96vw] !max-h-[90dvh] !max-w-[96vw] sm:!h-[80vh] sm:!w-[82vw] sm:!max-h-[80vh] sm:!max-w-[82vw]",bodyClassName:"!h-[calc(90dvh-49px)] !max-h-[calc(90dvh-49px)] sm:!h-[calc(80vh-49px)] sm:!max-h-[calc(80vh-49px)] flex flex-col overflow-hidden p-0",children:[e?(0,Ye.jsx)("div",{className:"shrink-0 border-b border-modiff-border p-3",children:(0,Ye.jsx)(Ze,{})}):null,(0,Ye.jsxs)("div",{className:"grid min-h-0 flex-1 grid-rows-[auto_minmax(0,1fr)] lg:grid-cols-[190px_minmax(0,1fr)] lg:grid-rows-1",children:[(0,Ye.jsx)("aside",{className:"min-h-0 overflow-x-auto border-b border-modiff-border bg-modiff-bg p-2 lg:overflow-y-auto lg:border-b-0 lg:border-r lg:p-3",children:(0,Ye.jsx)("div",{className:"flex min-w-max gap-1 lg:grid lg:min-w-0",role:"group","aria-label":"Template categories",children:Ae.map(e=>{let t=ce.category===e.id;return(0,Ye.jsxs)(re,{ref:t=>{t?ee.current.set(e.id,t):ee.current.delete(e.id)},tone:t?"primary":"ghost",size:"prominent",align:"left","aria-pressed":t,"data-testid":`template-browser-category-${e.id}`,onClick:()=>{ue(t=>({...t,category:e.id})),H(null)},className:"shrink-0 !justify-between px-3 lg:w-full",children:[(0,Ye.jsx)("span",{className:"truncate",children:e.label}),(0,Ye.jsx)("span",{className:$("min-w-6 rounded-full px-1.5 py-0.5 text-center text-xs",t?"bg-modiff-selected-surface text-hf-yellow":"bg-modiff-panel text-modiff-subtle-text"),children:ze.get(e.id)??0})]},e.id)})})}),(0,Ye.jsxs)("section",{className:"@container grid min-h-0 min-w-0 grid-rows-[auto_minmax(0,1fr)] bg-modiff-surface",children:[(0,Ye.jsxs)("div",{className:"border-b border-modiff-border bg-modiff-panel p-3","data-testid":"template-browser-header",children:[(0,Ye.jsx)("h1",{className:"mb-2 hidden text-xl font-bold tracking-tight text-modiff-text sm:block",children:"recommended"===ce.category?"Recommended templates":pt(ce.category)}),(0,Ye.jsxs)("div",{className:"flex flex-wrap items-end gap-2",children:[(0,Ye.jsx)(Y,{"data-testid":"template-browser-search",value:ce.query,onChange:e=>ue(t=>({...t,query:e.target.value})),onClear:ce.query?()=>ue(e=>({...e,query:""})):void 0,placeholder:"Search templates, models, prompts, or techniques","aria-label":"Search templates",controlSize:"prominent",className:"min-w-52 flex-1"}),(0,Ye.jsxs)(re,{className:"sm:hidden","aria-expanded":R,"aria-controls":P,onClick:()=>I(e=>!e),children:["Filters",pe?` (${pe})`:""]}),(0,Ye.jsxs)("div",{id:P,className:$("flex-wrap items-end gap-2 sm:contents",R?"flex":"hidden"),children:[(0,Ye.jsx)(vt,{label:"Model",value:ce.modelType,onValueChange:e=>ue(t=>({...t,modelType:e})),options:[{value:"all",label:"All models"},...me({currentModelType:p.modelType,includeWorkflowOnly:!0}).map(e=>({value:e.modelType,label:e.label}))]}),(0,Ye.jsx)(vt,{label:"Operation",value:ce.mode??"all",onValueChange:e=>ue(t=>({...t,mode:e})),options:[{value:"all",label:"All operations"},...at.map(e=>({value:e,label:D[e]}))]}),(0,Ye.jsx)(vt,{label:"Level",value:ce.difficulty,onValueChange:e=>ue(t=>({...t,difficulty:e})),options:Je.map(e=>({value:e,label:dt(e)}))}),(0,Ye.jsx)(vt,{label:"Sort",value:ce.sort,onValueChange:e=>ue(t=>({...t,sort:e})),options:tt})]})]})]}),(0,Ye.jsxs)("div",{className:$("grid h-full min-h-0",qe&&"@[1024px]:grid-cols-[minmax(0,1fr)_minmax(420px,28vw)]"),children:[(0,Ye.jsxs)("div",{ref:ie,className:$("min-h-0 overflow-y-auto p-3",qe&&"hidden @[1024px]:block"),"data-testid":"template-browser-gallery-scroll",children:[(0,Ye.jsxs)("div",{className:"grid items-stretch gap-3 [grid-template-columns:repeat(auto-fill,minmax(280px,1fr))] max-[1400px]:[grid-template-columns:repeat(auto-fill,minmax(250px,1fr))]",children:[Ee.map((e,t)=>(0,Ye.jsx)(wt,{active:f===e.id,disabled:V,featured:"recommended"===ce.category&&0===t&&$e.length>2,manifest:M,readiness:Ue(e,{...fe,form:rt(e),autoResourcePlan:be(e)}),selected:U===e.id,template:e,runtimeEstimate:ye(e),requiresTermsReview:Oe(e),onCreate:()=>{Ve(e)},onView:()=>H(e.id),onReadinessAction:t=>{"needs_model"===t.status?((e,t)=>{let a=t.modelInstallTargets[0]?.repoId??t.missingModelRepos[0];c({nodeId:null,fieldKey:null,focus:{modelType:e.modelType,repo:a,label:je[e.modelType],source:"template"}}),s(!1)})(e,t):"needs_input"===t.status?(We(),s(!1)):("needs_backend"===t.status||"needs_setup"===t.status)&&Fe()}},e.id)),0===$e.length&&(0,Ye.jsx)("div",{className:"col-span-full rounded-modiff-compact border border-modiff-border bg-modiff-bg p-4 text-sm text-modiff-subtle-text",children:"No templates match the current filters."})]}),Be?(0,Ye.jsx)("div",{ref:de,"aria-hidden":"true",className:"h-px w-full","data-testid":"template-browser-load-sentinel"}):null,(0,Ye.jsxs)("span",{className:"sr-only",role:"status","aria-live":"polite",children:[Ee.length," of ",$e.length," templates loaded"]})]}),qe?(0,Ye.jsx)(yt,{disabled:V,installingRepo:W,manifest:M,readiness:Ue(qe,{...fe,form:rt(qe),autoResourcePlan:be(qe)}),runtimeEstimate:ye(qe),requiresTermsReview:Oe(qe),template:qe,onBack:()=>H(null),onCreate:()=>{Ve(qe)},onInstallRepo:(e,t)=>{((e,t,a=!1)=>{u.request("install",he(e),()=>(async(e,t=!1)=>{K(e);try{await _(e,x,{repair:t}),h(await nt(!0))}catch(e){console.error(e)}finally{K(null)}})(t,a))})(qe,e,t)},onOpenAssets:We,onOpenModels:()=>{c({nodeId:null,fieldKey:null})},onOpenSetup:Fe,onUseLowVram:()=>{let e=ae.find(e=>"low_vram"===e.id);e&&(ue(e=>({...e,category:"performance",query:""})),H(e.id))}}):null]})]})]})]}),(0,Ye.jsx)(Ce,{open:!!u.pending,policies:De,action:u.pending?.action??"create",onCancel:u.cancel,onConfirm:u.confirm})]})}function vt({label:e,onValueChange:t,options:a,value:r}){let s=(0,Le.useId)();return(0,Ye.jsx)(ce,{className:$("Sort"===e?"w-36":"w-32","shrink-0"),htmlFor:s,label:e,children:(0,Ye.jsx)(ye,{id:s,"data-testid":`template-browser-${e.toLowerCase()}-filter`,size:"normal",value:r,onValueChange:t,options:a,optionsClassName:"!min-w-44"})})}function wt({active:e,disabled:t,featured:r,manifest:s,onCreate:l,onReadinessAction:o,onView:i,readiness:n,runtimeEstimate:d,requiresTermsReview:c,selected:p,template:f}){let{beforePath:g,mediaPath:h,thumbnailPath:x}=X(f,s),v=he(f).length>0;return(0,Ye.jsxs)("article",{"data-testid":`template-browser-card-${f.id}`,"data-active-template":e?"true":"false","data-inspected":p?"true":"false",className:$("group relative flex h-full min-h-0 flex-col overflow-hidden rounded-modiff-panel border bg-modiff-bg shadow-modiff-node",p?"border-hf-yellow ring-1 ring-hf-yellow/40":e?"border-modiff-blue ring-1 ring-modiff-blue/30":"border-modiff-border"),children:[(0,Ye.jsx)(re,{tone:"ghost",disabled:t,"aria-label":`View details for ${Pe(f)}`,"aria-current":e?"true":void 0,"aria-pressed":p,onClick:i,onFocus:i,className:"absolute inset-0 z-0 !h-auto !w-full !rounded-modiff-panel !border-0 !bg-transparent !p-0",children:(0,Ye.jsx)("span",{className:"sr-only",children:"View template details"})}),(0,Ye.jsxs)("div",{className:"pointer-events-none relative z-10 overflow-hidden bg-modiff-panel",children:[(0,Ye.jsx)(kt,{afterPath:h,beforePath:g,mediaKind:f.outputKinds?.[0],slots:Se(f),thumbnailPath:x,variant:f.thumbnailVariant}),(0,Ye.jsxs)("div",{className:"pointer-events-none absolute inset-x-0 top-0 flex items-start justify-end gap-2 bg-gradient-to-b from-modiff-bg/80 to-transparent p-3",children:[v?(0,Ye.jsx)(O,{content:"Usage restrictions — review before use",children:e=>(0,Ye.jsx)("span",{...e,"aria-label":"Usage restrictions — review before use",className:"pointer-events-auto grid size-7 place-items-center rounded-full border border-hf-orange/70 bg-modiff-bg/85 text-hf-orange backdrop-blur","data-testid":`template-usage-warning-${f.id}`,role:"img",tabIndex:0,children:(0,Ye.jsx)(m,{"aria-hidden":"true",size:14})})}):null,(0,Ye.jsx)("span",{className:"rounded-full border border-modiff-overlay-text/10 bg-modiff-bg/80 px-2 py-1 text-xs font-semibold text-modiff-text backdrop-blur",children:ct(f)})]}),r?(0,Ye.jsx)("div",{className:"pointer-events-none absolute left-3 top-3 grid size-7 place-items-center rounded-full border border-hf-yellow/50 bg-modiff-bg/85 text-hf-yellow backdrop-blur",title:"Featured template",children:(0,Ye.jsx)(a,{size:13})}):null]}),(0,Ye.jsxs)("div",{className:"pointer-events-none relative z-10 flex min-h-0 flex-1 flex-col gap-3 p-4",children:[(0,Ye.jsxs)("div",{className:"min-w-0",children:[(0,Ye.jsxs)("div",{className:"mb-1 flex min-h-12 items-start justify-between gap-2",children:[(0,Ye.jsx)("h3",{className:"min-w-0 flex-1",children:(0,Ye.jsx)(re,{tone:"ghost",size:"compact",align:"left",disabled:t,"data-testid":`template-browser-use-${f.id}`,onClick:i,className:"pointer-events-auto !h-auto min-w-0 max-w-full !justify-start !rounded-none !p-0 text-base !font-bold !leading-6 text-modiff-text hover:bg-transparent",children:(0,Ye.jsx)("span",{className:"line-clamp-2",children:Pe(f)})})}),(0,Ye.jsx)(St,{readiness:n,testId:`template-card-readiness-${f.id}`,onAction:()=>o(n)})]}),(0,Ye.jsxs)("p",{className:"truncate text-sm font-semibold text-modiff-subtle-text",children:[je[f.modelType]," · ",D[f.mode]]})]}),(0,Ye.jsx)("p",{className:"line-clamp-2 min-h-10 text-sm leading-5 text-modiff-subtle-text",children:f.recipeSummary??f.description}),(0,Ye.jsxs)("div",{className:"mt-auto grid min-w-0 gap-2 border-t border-modiff-border pt-3",children:[d?(0,Ye.jsxs)("div",{className:"inline-flex min-w-0 items-center gap-2 text-xs text-modiff-subtle-text","data-testid":`template-runtime-${f.id}`,title:d.title,children:[(0,Ye.jsx)(u,{size:13,className:"shrink-0 text-hf-yellow"}),(0,Ye.jsx)("span",{className:"truncate",children:d.label})]}):null,(0,Ye.jsx)(re,{tone:"primary",className:"pointer-events-auto w-full",icon:(0,Ye.jsx)(b,{size:14}),disabled:t,"data-testid":`template-browser-create-card-${f.id}`,onClick:e=>{e.stopPropagation(),l()},children:c?"Review terms":"Use template"})]})]})]})}function yt({disabled:e,installingRepo:o,manifest:d,onBack:c,onCreate:u,onInstallRepo:p,onOpenAssets:f,onOpenModels:g,onOpenSetup:h,onUseLowVram:v,readiness:w,runtimeEstimate:y,requiresTermsReview:j,template:k}){let N=K(k,d,{requireCardPreview:!1}),_=N??function(e,t){return t?.examples.find(t=>t.templateId===e.id&&["approved_reviewed","approved_exact"].includes(t.qualityReviewStatus)&&!(!t.beforePath||!t.beforeMediaHash))}(k,d),S=k.inputBindings?.filter(e=>"template"===e.origin).flatMap(e=>e.defaultAssets).find(e=>e.previewPath)?.previewPath,P=ge(N?.thumbnailPath??N?.posterPath)??mt(k),T=ge(_?.beforePath??S),R=ge(N?.afterPath??N?.outputPath),I=function(e){let t=pe(e),a=t.templateDefaultBindings.map(e=>({included:!0,key:e.id,label:e.label.replace(/^Reviewed\s+/i,"")})),r=t.missingLabels.map(e=>({included:!1,key:`missing:${e}`,label:e}));return a.length>0||r.length>0?{title:0===r.length?"Included inputs":"Required inputs",items:[...a,...r]}:{title:"Required inputs",items:ut(e).map(e=>({included:!1,key:`legacy:${e}`,label:e}))}}(k),C=j?"Review terms":"Use template",M=w.issues.some(e=>"open_assets"===e.action),$=w.issues.some(e=>"open_setup"===e.action),q=w.issues.some(e=>"apply_low_vram"===e.action);return(0,Ye.jsxs)("aside",{className:"min-h-0 overflow-y-auto bg-modiff-bg p-4 @[1024px]:border-l @[1024px]:border-modiff-border","data-testid":`template-detail-${k.id}`,children:[(0,Ye.jsx)("div",{className:"mb-3 flex items-center justify-between gap-2",children:(0,Ye.jsx)(re,{tone:"ghost",size:"dense",icon:(0,Ye.jsx)(l,{size:15}),onClick:c,children:"Templates"})}),(0,Ye.jsx)(kt,{afterPath:R,beforePath:T,detail:!0,mediaKind:k.outputKinds?.[0],slots:Se(k),thumbnailPath:P,variant:k.thumbnailVariant}),(0,Ye.jsxs)("div",{className:"mt-4 grid gap-4",children:[(0,Ye.jsxs)("div",{children:[(0,Ye.jsxs)("div",{className:"mb-2 inline-flex items-center gap-1.5 rounded-full border border-modiff-border bg-modiff-panel px-2.5 py-1 text-xs font-semibold text-hf-yellow",children:[(0,Ye.jsx)(n,{size:12}),D[k.mode]]}),(0,Ye.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,Ye.jsxs)("div",{className:"min-w-0",children:[(0,Ye.jsx)("h2",{className:"break-words text-xl font-bold tracking-tight text-modiff-text",children:Pe(k)}),(0,Ye.jsxs)("p",{className:"mt-1 text-sm font-semibold text-modiff-subtle-text",children:[je[k.modelType]," · ",D[k.mode]]})]}),(0,Ye.jsx)(Pt,{readiness:w})]}),(0,Ye.jsx)("p",{className:"mt-3 text-sm leading-6 text-modiff-subtle-text",children:k.userGoal})]}),(0,Ye.jsxs)("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[y?(0,Ye.jsx)(jt,{label:"Local runtime",value:y.label}):null,(0,Ye.jsx)(jt,{label:"VRAM",value:k.vramEstimate??"TBD"}),(0,Ye.jsx)(jt,{label:"Output",value:ct(k)}),(0,Ye.jsx)(jt,{label:"Level",value:k.difficulty??"starter"})]}),(0,Ye.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Ye.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"What this creates"}),(0,Ye.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:k.recipeSummary??k.description})]}),(0,Ye.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Ye.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:I.title}),(0,Ye.jsx)("div",{className:"mt-2 flex flex-wrap gap-1",children:I.items.map(e=>(0,Ye.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-xs font-semibold text-modiff-subtle-text",children:[e.included?(0,Ye.jsx)(x,{"aria-hidden":"true",className:"text-modiff-green",size:12}):null,e.label]},e.key))})]}),(0,Ye.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Ye.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Default prompt"}),(0,Ye.jsx)("p",{className:"mt-2 whitespace-pre-wrap break-words text-xs leading-5 text-modiff-text",children:k.prompt}),k.negativePrompt?(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsx)("h4",{className:"mt-3 text-xs font-semibold uppercase text-modiff-subtle-text",children:"Negative prompt"}),(0,Ye.jsx)("p",{className:"mt-1 whitespace-pre-wrap break-words text-xs leading-5 text-modiff-subtle-text",children:k.negativePrompt})]}):null]}),(0,Ye.jsxs)("section",{className:"grid gap-2","data-testid":`template-readiness-${k.id}`,children:[(0,Ye.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,Ye.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Preflight"}),(0,Ye.jsx)(Pt,{readiness:w})]}),0===w.issues.length?(0,Ye.jsx)(oe,{tone:"success",title:"Ready now",meta:w.summary,children:"Create a graph tab, build the graph, and then run when you are ready."}):w.issues.map(e=>(0,Ye.jsx)(oe,{tone:e.tone,title:e.title,meta:e.detail},e.id))]}),(0,Ye.jsxs)("div",{className:"flex flex-wrap gap-2",children:[w.modelInstallTargets.map(e=>(0,Ye.jsx)(re,{icon:(0,Ye.jsx)(i,{size:15}),disabled:o===e.repoId,"aria-label":`Install ${e.repoId}`,onClick:()=>p(e.repoId,e.repair),children:o===e.repoId?"Installing...":e.actionLabel??"Install"},e.repoId)),M?(0,Ye.jsx)(re,{icon:(0,Ye.jsx)(r,{size:15}),onClick:f,children:"Open assets"}):null,$?(0,Ye.jsx)(re,{icon:(0,Ye.jsx)(t,{size:15}),onClick:h,children:"Open setup"}):null,q?(0,Ye.jsx)(re,{icon:(0,Ye.jsx)(a,{size:15}),onClick:v,children:"Try Low VRAM"}):null,(0,Ye.jsx)(re,{icon:(0,Ye.jsx)(s,{size:15}),onClick:g,children:"Models"})]}),(0,Ye.jsx)("div",{className:"sticky bottom-0 -mx-4 bg-gradient-to-t from-modiff-bg via-modiff-bg to-transparent px-4 pb-1 pt-5",children:(0,Ye.jsx)(re,{tone:"primary",className:"h-10 w-full",icon:"planning"===w.status||"needs_backend"===w.status||"needs_setup"===w.status?(0,Ye.jsx)(m,{size:15}):(0,Ye.jsx)(b,{size:15}),disabled:e,"data-testid":`template-browser-create-${k.id}`,onClick:u,children:C})})]})]})}function jt({label:e,value:t}){return(0,Ye.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-2",children:[(0,Ye.jsx)("div",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,Ye.jsx)("div",{className:"mt-1 break-words text-xs font-semibold text-modiff-text",children:t})]})}function kt({afterPath:e,beforePath:t,detail:a=!1,mediaKind:r="image",slots:s,thumbnailPath:l}){if("image"===r&&t&&e)return(0,Ye.jsx)(Nt,{afterPath:e,beforePath:t,detail:a});if(!e&&!t&&l)return(0,Ye.jsx)(_t,{slot:{id:"editorial-poster",label:"Template preview",kind:"poster",placeholder:"template poster pending"},path:l,detail:a,large:!0});let o=2===s.length&&s.some(e=>"compare-before"===e.kind);if(o&&"video"===r&&!a&&e)return(0,Ye.jsx)(_t,{slot:{id:"published-result",label:"Generated video preview",kind:"video",posterPath:l,placeholder:"video preview pending"},path:e,large:!0});if(o){let o=(e,t)=>{if(!e)return t;let a=e.split(/[?#]/,1)[0]?.toLowerCase()??"";return/\.(mp4|webm|mov|mkv)$/.test(a)?"video":/\.(png|jpe?g|webp|gif|avif)$/.test(a)?"image":t};return(0,Ye.jsxs)("div",{className:"grid aspect-video grid-cols-2 overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-border",children:[(0,Ye.jsx)(_t,{slot:"video"===r?{...s[0],kind:o(t,"image")}:s[0],path:t,detail:a}),(0,Ye.jsx)(_t,{slot:"video"===r?{...s[1],kind:o(e??l,e?"video":"image"),posterPath:l}:s[1],path:e??l,detail:a})]})}if(s.length>1&&(e||l)){let t="video"===r?"video":"audio"===r?"audio":"image";return(0,Ye.jsx)(_t,{slot:{id:"published-result",label:"Generated result",kind:t,posterPath:l,placeholder:`${t} preview pending`},path:"image"===t?l??e:e??l,detail:a,large:!0})}if(s.length>1)return(0,Ye.jsx)("div",{className:"grid aspect-video grid-cols-2 gap-px overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-border",children:s.slice(0,4).map((e,t)=>(0,Ye.jsx)(_t,{slot:e,path:e.path??(0===t?l:void 0),compact:!0,detail:a},e.id))});let i=s[0],n="video"===r||"audio"===r;return(0,Ye.jsx)(_t,{slot:"video"===r?{...i,kind:"video",posterPath:i.posterPath??l}:"audio"===r?{...i,kind:"audio"}:i,path:n?e??t??i.path:l??i.path,detail:a,large:!0})}function Nt({afterPath:e,beforePath:t,detail:a}){let[r,s]=(0,Le.useState)(50),[l,o]=(0,Le.useState)(!1),i=(0,Le.useRef)(null),n=(e,t)=>{let a=e.getBoundingClientRect();if(a.width<=0)return;let r=(t-a.left)/a.width*100;s(Math.max(0,Math.min(100,r)))};return(0,Ye.jsxs)("div",{className:"relative aspect-video overflow-hidden rounded-modiff-panel border border-modiff-border bg-modiff-panel",children:[(0,Ye.jsx)(se,{ref:i,"aria-label":"Before and after comparison",testId:"template-ab-comparison",imageFrom:t,imageTo:e,sliderPosition:r,onSliderPositionChange:s,onError:e=>{e.currentTarget.src="/assets/modiff-icon-256.png"},onMouseDown:e=>{o(!0),n(e.currentTarget,e.clientX)},onMouseEnter:e=>{n(e.currentTarget,e.clientX)},onMouseMove:e=>{n(e.currentTarget,e.clientX)},onPointerMove:e=>{"mouse"===e.pointerType&&n(e.currentTarget,e.clientX)},onMouseUp:()=>o(!1),onTouchStart:e=>{o(!0),n(e.currentTarget,e.touches[0]?.clientX??0)},onTouchMove:e=>{l&&n(e.currentTarget,e.touches[0]?.clientX??0)},onTouchEnd:()=>o(!1)}),a?(0,Ye.jsx)("span",{className:"pointer-events-none absolute left-1/2 top-2 -translate-x-1/2 rounded-full bg-modiff-bg/80 px-2 py-1 text-xs font-semibold text-modiff-text backdrop-blur",children:"Hover or drag to compare"}):null]})}function _t({compact:e=!1,detail:t=!1,large:a=!1,path:s,slot:l}){let o=(0,Le.useRef)(null),i=(0,Le.useRef)(null),[n,d]=(0,Le.useState)(null),[m,u]=(0,Le.useState)(t),[p,f]=(0,Le.useState)(!1),[g,x]=(0,Le.useState)(!1),[w,y]=(0,Le.useState)(!1),j=s&&n!==s?s:void 0,k="video"===l.kind,N="audio"===l.kind,_="json"===l.kind,S=k||"gif"===l.kind?c:N?v:_?h:r,P=t||m&&(!p||g),T=!t&&m&&(!p||g);return(0,Le.useEffect)(()=>{if(t||!k||!j)return;let e=o.current;if(!e||typeof IntersectionObserver>"u")return void u(!0);let a=new IntersectionObserver(([e])=>u(!!e?.isIntersecting),{rootMargin:"160px 0px",threshold:.01});return a.observe(e),()=>a.disconnect()},[t,k,j]),(0,Le.useEffect)(()=>{if(t||!k)return;let e=window.matchMedia("(prefers-reduced-motion: reduce)"),a=navigator.connection,r=()=>f(e.matches||!0===a?.saveData);return r(),e.addEventListener("change",r),a?.addEventListener?.("change",r),()=>{e.removeEventListener("change",r),a?.removeEventListener?.("change",r)}},[t,k]),(0,Le.useEffect)(()=>{if(!t&&i.current){if(!P||!T)return void i.current.pause();i.current.play().catch(()=>{})}},[P,T,t]),(0,Le.useEffect)(()=>{d(null),x(!1),y(!1)},[s]),(0,Ye.jsxs)("div",{ref:o,className:$("relative grid place-items-center overflow-hidden bg-gradient-to-br from-modiff-panel via-modiff-bg to-modiff-surface",a&&"rounded-modiff-panel border border-modiff-border",a&&"aspect-video"),children:[j&&k?(0,Ye.jsxs)(Ye.Fragment,{children:[l.posterPath?(0,Ye.jsx)("img",{src:l.posterPath,alt:"","aria-hidden":"true",loading:"eager",decoding:"async",className:"absolute inset-0 h-full w-full object-cover"}):null,(0,Ye.jsx)("video",{ref:i,src:P?j:void 0,poster:l.posterPath,muted:!t,loop:!t,controls:t,autoPlay:T,playsInline:!0,preload:t||P?"metadata":"none","aria-label":l.label,"data-testid":t?"template-detail-video":"template-card-video","data-preview-attached":P?"true":"false",className:$("relative h-full w-full object-cover transition-opacity duration-150",w||!l.posterPath?"opacity-100":"opacity-0"),onError:()=>d(j),onLoadedData:()=>y(!0),onPlaying:()=>y(!0),onCanPlay:()=>{T&&i.current?.play().catch(()=>{})}})]}):k&&l.posterPath?(0,Ye.jsx)("img",{src:l.posterPath,alt:l.label,loading:"lazy",decoding:"async",className:"h-full w-full object-cover"}):N?(0,Ye.jsxs)("div",{className:"grid h-full w-full content-center gap-4 bg-gradient-to-br from-hf-yellow/15 via-modiff-panel to-modiff-bg p-4",children:[(0,Ye.jsxs)("div",{className:"flex items-center gap-3",children:[(0,Ye.jsx)("div",{className:"grid size-10 shrink-0 place-items-center rounded-full bg-hf-yellow text-modiff-on-accent",children:(0,Ye.jsx)(v,{size:18})}),(0,Ye.jsx)("div",{className:"flex h-16 flex-1 items-center justify-center gap-1 overflow-hidden",children:gt.map((e,t)=>(0,Ye.jsx)("span",{className:$("w-1 rounded-full bg-hf-yellow/80",e)},`${e}-${t}`))})]}),j?(0,Ye.jsx)("audio",{src:j,controls:!0,preload:t?"metadata":"none",className:"pointer-events-auto h-9 w-full","aria-label":l.label,onError:()=>d(j)}):(0,Ye.jsx)("p",{className:"text-center text-xs font-semibold text-modiff-subtle-text",children:"No preview yet"})]}):j&&!_?a?t?(0,Ye.jsxs)(Ye.Fragment,{children:[(0,Ye.jsx)("img",{src:j,alt:"","aria-hidden":"true",loading:"eager",decoding:"async",className:"absolute inset-0 h-full w-full scale-110 object-cover opacity-30 blur-xl",onError:()=>d(j)}),(0,Ye.jsx)("img",{src:j,alt:l.label,loading:"eager",decoding:"async",className:"relative h-full w-full object-contain p-1.5",onError:()=>d(j)})]}):(0,Ye.jsx)("img",{src:j,alt:l.label,loading:"eager",decoding:"async",className:"h-full w-full object-cover",onError:()=>d(j)}):(0,Ye.jsx)("img",{src:j,alt:l.label,loading:"lazy",decoding:"async",className:"h-full w-full object-cover",onError:()=>d(j)}):(0,Ye.jsx)("div",{className:"grid h-full min-h-28 w-full place-items-center p-3 text-center",children:(0,Ye.jsxs)("div",{children:[(0,Ye.jsx)("div",{className:"mx-auto mb-2 grid size-9 place-items-center rounded-full border border-modiff-border bg-modiff-bg/70 text-modiff-subtle-text",children:(0,Ye.jsx)(S,{size:e?16:19})}),(0,Ye.jsx)("p",{className:"text-xs font-semibold text-modiff-subtle-text",children:s?"Preview unavailable":"No preview yet"}),e?null:(0,Ye.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:s&&n===s?"The published media could not be decoded":l.placeholder})]})}),!N&&t?(0,Ye.jsx)("span",{className:"absolute left-2 top-2 rounded-full border border-modiff-overlay-text/10 bg-modiff-bg/75 px-2 py-1 text-xs font-semibold text-modiff-overlay-text backdrop-blur",children:l.label}):null,k&&j&&!t&&p&&!g?(0,Ye.jsx)(ne,{label:"Play video preview",onClick:e=>{e.stopPropagation(),x(!0)},className:"pointer-events-auto absolute inset-0 m-auto !size-10 rounded-full border border-modiff-overlay-text/20 bg-modiff-bg/80 text-modiff-overlay-text shadow-modiff-node backdrop-blur hover:border-hf-yellow hover:text-hf-yellow",children:(0,Ye.jsx)(b,{size:17,fill:"currentColor"})}):null]})}function St({onAction:e,readiness:t,testId:a}){let r=["needs_input","needs_model","needs_backend","needs_setup"].includes(t.status),s="ready"===t.status?(0,Ye.jsx)(x,{size:18}):"needs_backend"===t.status?(0,Ye.jsx)(p,{size:18}):"preparing"===t.status||"planning"===t.status?(0,Ye.jsx)(d,{size:18}):(0,Ye.jsx)(m,{size:18}),l=$("pointer-events-auto relative grid size-8 shrink-0 place-items-center rounded-full border bg-modiff-panel/90 transition","success"===t.tone&&"border-modiff-green/70 text-modiff-green","warning"===t.tone&&"border-hf-orange/70 text-hf-orange","error"===t.tone&&"border-modiff-red/70 text-modiff-red","info"===t.tone&&"border-modiff-blue/70 text-modiff-blue","default"===t.tone&&"border-modiff-border text-modiff-subtle-text",r&&"hover:scale-105 hover:bg-modiff-surface-hover"),o=`${t.label}: ${t.summary}`;return r?(0,Ye.jsx)(ne,{label:o,className:l,"data-testid":a,onClick:e,children:s}):(0,Ye.jsx)(O,{content:o,children:e=>(0,Ye.jsx)("span",{...e,className:l,"data-testid":a,"aria-label":o,role:"img",tabIndex:0,children:s})})}function Pt({readiness:e}){return(0,Ye.jsxs)("span",{className:$("inline-flex shrink-0 items-center gap-1 rounded-modiff-compact border px-1.5 py-0.5 text-xs font-semibold","success"===e.tone&&"border-modiff-green/70 text-modiff-green","warning"===e.tone&&"border-hf-orange/70 text-hf-orange","error"===e.tone&&"border-modiff-red/70 text-modiff-red","info"===e.tone&&"border-modiff-blue/70 text-modiff-blue","default"===e.tone&&"border-modiff-border text-modiff-subtle-text"),children:["success"===e.tone?(0,Ye.jsx)(x,{size:12}):"error"===e.tone?(0,Ye.jsx)(m,{size:12}):(0,Ye.jsx)(d,{size:12}),e.label]})}export{xt as default}; \ No newline at end of file diff --git a/web/assets/TemplateUsageTermsDialog.js b/web/assets/TemplateUsageTermsDialog.js index 0696695..7f5fb3f 100644 --- a/web/assets/TemplateUsageTermsDialog.js +++ b/web/assets/TemplateUsageTermsDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{R as s,an as r,cr as t,dr as n}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{Sa as i,f as l,in as a,rn as o}from"./studio-templates.js?v=cc046c26d6fe7aa4";var d=e(n(),1);function c(){let e=i(e=>e.modelTermsAcknowledgements),s=i(e=>e.acknowledgeModelTerms),r=(0,d.useRef)(null),[t,n]=(0,d.useState)(null),a=s=>{let r=l(s);return!(!r||e[r])};return{pending:t,needsReview:a,request:(e,s,t)=>{if(a(s))return r.current=t,void n({action:e,policies:s});t()},cancel:()=>{r.current=null,n(null)},confirm:()=>{let e=l(t?.policies??[]);e&&s(e);let i=r.current;r.current=null,n(null),i?.()}}}var m=t();function u(e){return"personal_noncommercial"===e.useScope?"Personal / non-commercial":"research_academic_only"===e.useScope?"Research / academic only":"noncommercial_only"===e.useScope?"Restricted model license":"license_review_required"===e.useScope?"Product and user review required":"rights_undetermined"===e.useScope?"No weight license declared":"Usage terms"}function f({open:e,policies:t,action:n,onCancel:i,onConfirm:l}){let d="run"===n,c=t.some(e=>"rights_undetermined"===e.useScope);return(0,m.jsx)(a,{open:e,onClose:i,testId:d?"model-usage-terms-dialog":"template-usage-terms-dialog",title:(0,m.jsxs)("span",{className:"inline-flex items-center gap-2",children:[(0,m.jsx)(s,{"aria-hidden":"true",className:"text-hf-yellow",size:18}),"Review model terms"]}),panelClassName:"max-w-xl",footer:(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(o,{onClick:i,children:"Cancel"}),(0,m.jsxs)(o,{tone:"primary",onClick:l,"data-testid":d?"model-usage-terms-confirm":"template-usage-terms-confirm",children:[d?"I acknowledge":c?"I understand":"I have reviewed and agree"," —"," ","install"===n?"Install":"run"===n?"Run":"Create graph"]})]}),children:(0,m.jsxs)("div",{className:"grid gap-3",children:[(0,m.jsxs)("p",{className:"text-sm leading-5 text-modiff-subtle-text",children:["This ",d?"model run":"template"," uses ",t.length," model"," ",1===t.length?"dependency":"dependencies"," with usage restrictions. Review the original terms before"," ","install"===n?"installing its models":"run"===n?"running the workflow":"creating the graph","."]}),(0,m.jsx)("div",{className:"grid gap-2",children:t.map(e=>(0,m.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,m.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,m.jsxs)("div",{className:"min-w-0",children:[(0,m.jsx)("div",{className:"break-words text-sm font-semibold text-modiff-text",children:e.repository}),(0,m.jsx)("div",{className:"mt-1 text-xs font-semibold text-hf-yellow",children:u(e)}),(0,m.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:e.shortSummary})]}),(0,m.jsxs)("a",{className:"inline-flex shrink-0 items-center gap-1 text-xs font-semibold text-modiff-blue hover:underline",href:e.termsUrl,target:"_blank",rel:"noreferrer",children:["View terms",(0,m.jsx)(r,{"aria-hidden":"true",size:12})]})]}),"huggingface_gated"===e.access?(0,m.jsxs)("a",{className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-modiff-blue hover:underline",href:e.modelCardUrl,target:"_blank",rel:"noreferrer",children:["Open on Hugging Face to request or review access",(0,m.jsx)(r,{"aria-hidden":"true",size:12})]}):null]},`${e.id}:${e.revision??""}`))}),(0,m.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"MoDiff does not grant model-use rights. This acknowledgement does not change or replace the model authors’ terms."})]})})}export{c as n,f as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{R as s,an as r,cr as t,dr as n}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{an as i,f as l,in as a,wa as o}from"./studio-templates.js?v=ca6b74e6a02eedb3";var d=e(n(),1);function c(){let e=o(e=>e.modelTermsAcknowledgements),s=o(e=>e.acknowledgeModelTerms),r=(0,d.useRef)(null),[t,n]=(0,d.useState)(null),i=s=>{let r=l(s);return!(!r||e[r])};return{pending:t,needsReview:i,request:(e,s,t)=>{if(i(s))return r.current=t,void n({action:e,policies:s});t()},cancel:()=>{r.current=null,n(null)},confirm:()=>{let e=l(t?.policies??[]);e&&s(e);let i=r.current;r.current=null,n(null),i?.()}}}var m=t();function u(e){return"personal_noncommercial"===e.useScope?"Personal / non-commercial":"research_academic_only"===e.useScope?"Research / academic only":"noncommercial_only"===e.useScope?"Restricted model license":"license_review_required"===e.useScope?"Product and user review required":"rights_undetermined"===e.useScope?"No weight license declared":"Usage terms"}function f({open:e,policies:t,action:n,onCancel:l,onConfirm:o}){let d="run"===n,c=t.some(e=>"rights_undetermined"===e.useScope);return(0,m.jsx)(i,{open:e,onClose:l,testId:d?"model-usage-terms-dialog":"template-usage-terms-dialog",title:(0,m.jsxs)("span",{className:"inline-flex items-center gap-2",children:[(0,m.jsx)(s,{"aria-hidden":"true",className:"text-hf-yellow",size:18}),"Review model terms"]}),panelClassName:"max-w-xl",footer:(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(a,{onClick:l,children:"Cancel"}),(0,m.jsxs)(a,{tone:"primary",onClick:o,"data-testid":d?"model-usage-terms-confirm":"template-usage-terms-confirm",children:[d?"I acknowledge":c?"I understand":"I have reviewed and agree"," —"," ","install"===n?"Install":"run"===n?"Run":"Create graph"]})]}),children:(0,m.jsxs)("div",{className:"grid gap-3",children:[(0,m.jsxs)("p",{className:"text-sm leading-5 text-modiff-subtle-text",children:["This ",d?"model run":"template"," uses ",t.length," model"," ",1===t.length?"dependency":"dependencies"," with usage restrictions. Review the original terms before"," ","install"===n?"installing its models":"run"===n?"running the workflow":"creating the graph","."]}),(0,m.jsx)("div",{className:"grid gap-2",children:t.map(e=>(0,m.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",children:[(0,m.jsxs)("div",{className:"flex items-start justify-between gap-3",children:[(0,m.jsxs)("div",{className:"min-w-0",children:[(0,m.jsx)("div",{className:"break-words text-sm font-semibold text-modiff-text",children:e.repository}),(0,m.jsx)("div",{className:"mt-1 text-xs font-semibold text-hf-yellow",children:u(e)}),(0,m.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:e.shortSummary})]}),(0,m.jsxs)("a",{className:"inline-flex shrink-0 items-center gap-1 text-xs font-semibold text-modiff-blue hover:underline",href:e.termsUrl,target:"_blank",rel:"noreferrer",children:["View terms",(0,m.jsx)(r,{"aria-hidden":"true",size:12})]})]}),"huggingface_gated"===e.access?(0,m.jsxs)("a",{className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-modiff-blue hover:underline",href:e.modelCardUrl,target:"_blank",rel:"noreferrer",children:["Open on Hugging Face to request or review access",(0,m.jsx)(r,{"aria-hidden":"true",size:12})]}):null]},`${e.id}:${e.revision??""}`))}),(0,m.jsx)("p",{className:"text-xs leading-5 text-modiff-subtle-text",children:"MoDiff does not grant model-use rights. This acknowledgement does not change or replace the model authors’ terms."})]})})}export{c as n,f as t}; \ No newline at end of file diff --git a/web/assets/UIAudioField.js b/web/assets/UIAudioField.js index 63b47da..d6b1237 100644 --- a/web/assets/UIAudioField.js +++ b/web/assets/UIAudioField.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cn as a,cr as t,dr as s,un as o}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$t as n,At as l,Do as i,Et as r,Mt as d,Nt as u,Ot as c,Sa as f,Vr as m,_i as p,en as h,jn as y,jt as x,mt as g,pt as j,ta as w}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as b,t as v}from"./mediaDownload.js?v=cc046c26d6fe7aa4";var R=e(s(),1),S=t();function k(e,a,t){return e&&"string"==typeof e?w(e,a,t):null}function I({source:e,downloadSampleRate:t}){let s=(0,R.useRef)(null),[n,m]=(0,R.useState)(b(e)?null:e),[p,h]=(0,R.useState)(1),y=f(e=>e.setMediaExportOpener);(0,R.useEffect)(()=>{if(!b(e))return void m(e);let a=new AbortController,t=null;return m(null),i(e,{signal:a.signal}).then(e=>{a.signal.aborted||(t=URL.createObjectURL(e),m(t))}).catch(()=>{a.signal.aborted||m(e)}),()=>{a.abort(),t&&URL.revokeObjectURL(t)}},[e]);let g=e=>e.stopPropagation();return(0,S.jsxs)("div",{className:"nodrag nopan nowheel relative min-w-80",children:[(0,S.jsx)("audio",{ref:s,controls:!0,controlsList:"nodownload noplaybackrate noremoteplayback",preload:"metadata",src:n??void 0,"aria-busy":null===n,className:"modiff-audio-player w-full",onClick:g,onMouseDown:g,onPointerDown:g,onTouchStart:g}),(0,S.jsx)("div",{className:"absolute right-2 top-1/2 z-10 -translate-y-1/2",children:(0,S.jsxs)(l,{children:[(0,S.jsx)(u,{children:(0,S.jsx)(r,{label:"Audio actions",isRound:!0,className:"bg-modiff-surface/90 text-modiff-text hover:bg-modiff-selected-surface hover:text-hf-yellow",children:(0,S.jsx)(a,{size:17})})}),(0,S.jsxs)(d,{layer:"graph",anchor:"bottom end",className:"min-w-48",children:[(0,S.jsx)(c,{icon:(0,S.jsx)(o,{size:14}),onClick:()=>y({source:e,kind:"audio",filename:v(e,"MoDiff-audio.wav"),title:"Download audio",defaultFormat:"wav",defaultSampleRate:t}),children:"Download…"}),(0,S.jsx)(x,{}),[.75,1,1.25,1.5,2].map(e=>(0,S.jsxs)(c,{selected:p===e,onClick:()=>(e=>{h(e),s.current&&(s.current.playbackRate=e)})(e),children:["Playback ",e,"×"]},e))]})]})})]})}function K(e){let a=!0===e.fieldOptions?.compactPreview,t=p(e.nodeId,e.fieldKey,e.fieldOptions),s=g(t.nodeId,t.fieldKey),o=m(e=>{let a=e.nodes.find(e=>e.id===t.nodeId),s=a?.data.params.sample_rate?.value??a?.data.params.sample_rate?.default,o=Number(s);return[44100,48e3,88200,96e3].includes(o)?o:null}),l=s.hasAuthority?s.value:e.value,i=(Array.isArray(l)?l.map(e=>k(e,t.nodeId,t.fieldKey)):[k(l,t.nodeId,t.fieldKey)]).filter(e=>!!e),r=s.statusMessage||("string"==typeof e.uiStateMessage?e.uiStateMessage:""),d=r.startsWith("Waiting")||r.startsWith("Run failed")?r:"running"===e.executionStatus?e.progressMessage||"Waiting for this run":"failed"===e.executionStatus?"Run failed before producing new audio":"No current audio";return(0,S.jsxs)(y,{dataKey:e.fieldKey,hidden:e.hidden,layoutStyle:e.style,className:"flex flex-col gap-2",children:[0===i.length?(0,S.jsx)(n,{compact:a,kind:"audio",message:d,testId:`node-preview-empty-${e.nodeId}-${e.fieldKey}`}):i.map((t,s)=>(0,S.jsx)(h,{compact:a,kind:"audio",className:"p-2",testId:`node-preview-audio-${e.nodeId}-${e.fieldKey}-${s}`,children:(0,S.jsx)(I,{source:t,downloadSampleRate:o})},`${t}-${s}`)),(0,S.jsx)(j,{nodeId:t.nodeId,fieldKey:t.fieldKey,currentUrls:i,audioDownloadSampleRate:o})]})}export{K as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cn as a,cr as t,dr as s,un as o}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Dt as n,Hr as l,Mn as r,Mt as i,Nt as d,Pt as u,en as c,ht as f,jt as m,ko as p,kt as h,mt as y,ra as x,tn as g,wa as j,yi as w}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as b,t as v}from"./mediaDownload.js?v=ca6b74e6a02eedb3";var k=e(s(),1),R=t();function S(e,a,t){return e&&"string"==typeof e?x(e,a,t):null}function I({source:e,downloadSampleRate:t}){let s=(0,k.useRef)(null),[l,r]=(0,k.useState)(b(e)?null:e),[c,f]=(0,k.useState)(1),y=j(e=>e.setMediaExportOpener);(0,k.useEffect)(()=>{if(!b(e))return void r(e);let a=new AbortController,t=null;return r(null),p(e,{signal:a.signal}).then(e=>{a.signal.aborted||(t=URL.createObjectURL(e),r(t))}).catch(()=>{a.signal.aborted||r(e)}),()=>{a.abort(),t&&URL.revokeObjectURL(t)}},[e]);let x=e=>e.stopPropagation();return(0,R.jsxs)("div",{className:"nodrag nopan nowheel relative min-w-80",children:[(0,R.jsx)("audio",{ref:s,controls:!0,controlsList:"nodownload noplaybackrate noremoteplayback",preload:"metadata",src:l??void 0,"aria-busy":null===l,className:"modiff-audio-player w-full",onClick:x,onMouseDown:x,onPointerDown:x,onTouchStart:x}),(0,R.jsx)("div",{className:"absolute right-2 top-1/2 z-10 -translate-y-1/2",children:(0,R.jsxs)(m,{children:[(0,R.jsx)(u,{children:(0,R.jsx)(n,{label:"Audio actions",isRound:!0,className:"bg-modiff-surface/90 text-modiff-text hover:bg-modiff-selected-surface hover:text-hf-yellow",children:(0,R.jsx)(a,{size:17})})}),(0,R.jsxs)(d,{layer:"graph",anchor:"bottom end",className:"min-w-48",children:[(0,R.jsx)(h,{icon:(0,R.jsx)(o,{size:14}),onClick:()=>y({source:e,kind:"audio",filename:v(e,"MoDiff-audio.wav"),title:"Download audio",defaultFormat:"wav",defaultSampleRate:t}),children:"Download…"}),(0,R.jsx)(i,{}),[.75,1,1.25,1.5,2].map(e=>(0,R.jsxs)(h,{selected:c===e,onClick:()=>(e=>{f(e),s.current&&(s.current.playbackRate=e)})(e),children:["Playback ",e,"×"]},e))]})]})})]})}function K(e){let a=!0===e.fieldOptions?.compactPreview,t=w(e.nodeId,e.fieldKey,e.fieldOptions),s=f(t.nodeId,t.fieldKey),o=l(e=>{let a=e.nodes.find(e=>e.id===t.nodeId),s=a?.data.params.sample_rate?.value??a?.data.params.sample_rate?.default,o=Number(s);return[44100,48e3,88200,96e3].includes(o)?o:null}),n=s.hasAuthority?s.value:e.value,i=(Array.isArray(n)?n.map(e=>S(e,t.nodeId,t.fieldKey)):[S(n,t.nodeId,t.fieldKey)]).filter(e=>!!e),d=s.statusMessage||("string"==typeof e.uiStateMessage?e.uiStateMessage:""),u=d.startsWith("Waiting")||d.startsWith("Run failed")?d:"running"===e.executionStatus?e.progressMessage||"Waiting for this run":"failed"===e.executionStatus?"Run failed before producing new audio":"No current audio";return(0,R.jsxs)(r,{dataKey:e.fieldKey,hidden:e.hidden,layoutStyle:e.style,className:"flex flex-col gap-2",children:[0===i.length?(0,R.jsx)(c,{compact:a,kind:"audio",message:u,testId:`node-preview-empty-${e.nodeId}-${e.fieldKey}`}):i.map((t,s)=>(0,R.jsx)(g,{compact:a,kind:"audio",className:"p-2",testId:`node-preview-audio-${e.nodeId}-${e.fieldKey}-${s}`,children:(0,R.jsx)(I,{source:t,downloadSampleRate:o})},`${t}-${s}`)),(0,R.jsx)(y,{nodeId:t.nodeId,fieldKey:t.fieldKey,currentUrls:i,audioDownloadSampleRate:o})]})}export{K as default}; \ No newline at end of file diff --git a/web/assets/UIVideoField.js b/web/assets/UIVideoField.js index f170346..88f92f5 100644 --- a/web/assets/UIVideoField.js +++ b/web/assets/UIVideoField.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cn as o,cr as a,dr as t,un as s}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$t as n,At as r,Et as i,Mt as d,Nt as l,Ot as c,Sa as p,_i as f,_t as u,bn as m,en as g,gt as h,ht as x,jn as j,mt as v,pt as y,ra as w}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as b}from"./mediaDownload.js?v=cc046c26d6fe7aa4";var I=e(t(),1),K=a();function N(e){let[a,t]=(0,I.useState)(0),N=f(e.nodeId,e.fieldKey,e.fieldOptions),S=v(N.nodeId,N.fieldKey),M=!0===e.fieldOptions?.compactPreview,$=p(e=>e.setMediaExportOpener),D=u(S.hasAuthority?S.value:e.value,e=>w(e,N.nodeId,N.fieldKey)),P=h(a,D.length);(0,I.useEffect)(()=>{a!==P&&t(P)},[P,a]);let k=D[P]||null,E=S.statusMessage||("string"==typeof e.uiStateMessage?e.uiStateMessage:""),O=E.startsWith("Waiting")||E.startsWith("Run failed")?E:"running"===e.executionStatus?e.progressMessage||"Waiting for this run":"failed"===e.executionStatus?"Run failed before producing a new video":"No current video";return(0,K.jsxs)(j,{dataKey:e.fieldKey,hidden:e.hidden,layoutStyle:e.style,className:"flex flex-col flex-wrap items-start justify-center gap-2",children:[D.length>1&&(0,K.jsx)(m,{value:String(P),className:"nodrag","aria-label":"Preview Video",onValueChange:e=>t(h(Number(e),D.length)),options:D.map((e,o)=>({value:String(o),label:`Video ${o+1}`}))}),k?(0,K.jsxs)(g,{compact:M,className:"group/video",testId:`node-preview-video-${e.nodeId}-${e.fieldKey}`,children:[(0,K.jsx)("video",{src:k,controls:!0,controlsList:"nodownload noremoteplayback",preload:"metadata",className:"nodrag nopan nowheel block h-full w-full object-contain p-0.5",onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),onError:e=>{e.currentTarget.poster=x},onLoadedData:e=>{e.currentTarget.poster=""}},P),(0,K.jsx)("div",{className:"nodrag nopan absolute right-2 top-2 z-10",children:(0,K.jsxs)(r,{children:[(0,K.jsx)(l,{children:(0,K.jsx)(i,{label:"Video actions",isRound:!0,className:"border border-modiff-border bg-modiff-panel/90 text-modiff-text hover:bg-modiff-surface-hover hover:text-hf-yellow",children:(0,K.jsx)(o,{size:17})})}),(0,K.jsx)(d,{layer:"graph",anchor:"bottom end",className:"min-w-48",children:(0,K.jsx)(c,{icon:(0,K.jsx)(s,{size:14}),onClick:()=>{k&&$({source:k,kind:"video",filename:b(k,`MoDiff-${e.nodeId}-${e.fieldKey}.mp4`),title:"Download video",defaultFormat:"mp4"})},children:"Download…"})})]})})]}):(0,K.jsx)(n,{compact:M,message:O,testId:`node-preview-empty-${e.nodeId}-${e.fieldKey}`}),(0,K.jsx)(y,{nodeId:N.nodeId,fieldKey:N.fieldKey,currentUrls:D})]})}export{N as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cn as o,cr as a,dr as t,un as s}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Dt as n,Mn as r,Nt as i,Pt as d,_t as l,aa as c,en as f,gt as p,ht as u,jt as m,kt as g,mt as h,tn as x,vt as v,wa as j,xn as y,yi as w}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as b}from"./mediaDownload.js?v=ca6b74e6a02eedb3";var I=e(t(),1),K=a();function N(e){let[a,t]=(0,I.useState)(0),N=w(e.nodeId,e.fieldKey,e.fieldOptions),S=u(N.nodeId,N.fieldKey),D=!0===e.fieldOptions?.compactPreview,M=j(e=>e.setMediaExportOpener),P=v(S.hasAuthority?S.value:e.value,e=>c(e,N.nodeId,N.fieldKey)),$=l(a,P.length);(0,I.useEffect)(()=>{a!==$&&t($)},[$,a]);let k=P[$]||null,V=S.statusMessage||("string"==typeof e.uiStateMessage?e.uiStateMessage:""),W=V.startsWith("Waiting")||V.startsWith("Run failed")?V:"running"===e.executionStatus?e.progressMessage||"Waiting for this run":"failed"===e.executionStatus?"Run failed before producing a new video":"No current video";return(0,K.jsxs)(r,{dataKey:e.fieldKey,hidden:e.hidden,layoutStyle:e.style,className:"flex flex-col flex-wrap items-start justify-center gap-2",children:[P.length>1&&(0,K.jsx)(y,{value:String($),className:"nodrag","aria-label":"Preview Video",onValueChange:e=>t(l(Number(e),P.length)),options:P.map((e,o)=>({value:String(o),label:`Video ${o+1}`}))}),k?(0,K.jsxs)(x,{compact:D,className:"group/video",testId:`node-preview-video-${e.nodeId}-${e.fieldKey}`,children:[(0,K.jsx)("video",{src:k,controls:!0,controlsList:"nodownload noremoteplayback",preload:"metadata",className:"nodrag nopan nowheel block h-full w-full object-contain p-0.5",onClick:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),onTouchStart:e=>e.stopPropagation(),onError:e=>{e.currentTarget.poster=p},onLoadedData:e=>{e.currentTarget.poster=""}},$),(0,K.jsx)("div",{className:"nodrag nopan absolute right-2 top-2 z-10",children:(0,K.jsxs)(m,{children:[(0,K.jsx)(d,{children:(0,K.jsx)(n,{label:"Video actions",isRound:!0,className:"border border-modiff-border bg-modiff-panel/90 text-modiff-text hover:bg-modiff-surface-hover hover:text-hf-yellow",children:(0,K.jsx)(o,{size:17})})}),(0,K.jsx)(i,{layer:"graph",anchor:"bottom end",className:"min-w-48",children:(0,K.jsx)(g,{icon:(0,K.jsx)(s,{size:14}),onClick:()=>{k&&M({source:k,kind:"video",filename:b(k,`MoDiff-${e.nodeId}-${e.fieldKey}.mp4`),title:"Download video",defaultFormat:"mp4"})},children:"Download…"})})]})})]}):(0,K.jsx)(f,{compact:D,message:W,testId:`node-preview-empty-${e.nodeId}-${e.fieldKey}`}),(0,K.jsx)(h,{nodeId:N.nodeId,fieldKey:N.fieldKey,currentUrls:P})]})}export{N as default}; \ No newline at end of file diff --git a/web/assets/VisualStageControls.js b/web/assets/VisualStageControls.js index b57056c..4ca4347 100644 --- a/web/assets/VisualStageControls.js +++ b/web/assets/VisualStageControls.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{cr as t,dr as s,ln as a}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{At as n,Ei as o,Go as r,Mt as i,Nt as l,Ot as d,Si as c,Uo as p,Vo as u,Vr as g,an as h,in as m,ji as j}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as x,t as f}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{n as w,t as k}from"./mediaAttachment.js?v=cc046c26d6fe7aa4";import{t as A}from"./MediaAttachmentControls.js?v=cc046c26d6fe7aa4";var C=e(s(),1),S=t();function b({node:e}){let[t,s]=(0,C.useState)(null),[b,v]=(0,C.useState)(!1),G=r(e),E=c(e=>e.operationContracts),N=c(e=>e.pipelineSupport),y=!G&&w(k(E,N),e.data.operationAuthoring?.operation.pipelineClass??"").length>0;function F(t){try{let a=g.getState().toObject(),n=o(),r=t?u(a,e.id,[t]):p(a,new Set([e.id])).graph;if(r===a&&!G)throw Error("No eligible ungrouped stages on this model branch. Existing groups are unchanged.");f(r,n,x(a),t?"Group workflow stages":"Ungroup workflow stages"),j.getState().saveActiveWorkflowTab(!0),s(null)}catch(e){s(e instanceof Error?e.message:"Could not group these stages.")}}return(0,S.jsxs)("div",{className:"nodrag nowheel grid gap-2 py-2",children:[(0,S.jsxs)(n,{children:[(0,S.jsx)(l,{children:(0,S.jsx)(h,{label:"Workflow stage actions",size:"compact",children:(0,S.jsx)(a,{size:16})})}),(0,S.jsx)(i,{layer:"graph",children:G?(0,S.jsx)(d,{onClick:()=>F(),children:"Ungroup stages"}):(0,S.jsxs)(S.Fragment,{children:[e.data.blockProjectionOwnerId?null:(0,S.jsxs)(S.Fragment,{children:[(0,S.jsx)(d,{onClick:()=>F("inputs"),children:"Group input encoders"}),(0,S.jsx)(d,{onClick:()=>F("guidance"),children:"Group guidance"})]}),y?(0,S.jsx)(d,{onClick:()=>requestAnimationFrame(()=>v(!0)),children:"Add image / audio input…"}):null]})})]}),b?(0,S.jsx)(m,{open:!0,title:"Add image / audio input",onClose:()=>v(!1),children:(0,S.jsx)(A,{node:e,onAttached:()=>v(!1),inline:!0})}):null,t?(0,S.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:t}):null]})}export{b as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{cr as t,dr as s,ln as a}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Hr as o,Jo as n,Ko as r,Ni as i,Nt as l,Oi as d,Pt as c,Wo as p,an as u,jt as g,kt as h,on as m,wi as j}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as x,t as f}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{n as w,t as k}from"./mediaAttachment.js?v=ca6b74e6a02eedb3";import{t as C}from"./MediaAttachmentControls.js?v=ca6b74e6a02eedb3";var A=e(s(),1),b=t();function S({node:e}){let[t,s]=(0,A.useState)(null),[S,v]=(0,A.useState)(!1),N=n(e),G=j(e=>e.operationContracts),y=j(e=>e.pipelineSupport),E=!N&&w(k(G,y),e.data.operationAuthoring?.operation.pipelineClass??"").length>0;function F(t){try{let a=o.getState().toObject(),n=d(),l=t?p(a,e.id,[t]):r(a,new Set([e.id])).graph;if(l===a&&!N)throw Error("No eligible ungrouped stages on this model branch. Existing groups are unchanged.");f(l,n,x(a),t?"Group workflow stages":"Ungroup workflow stages"),i.getState().saveActiveWorkflowTab(!0),s(null)}catch(e){s(e instanceof Error?e.message:"Could not group these stages.")}}return(0,b.jsxs)("div",{className:"nodrag nowheel grid gap-2 py-2",children:[(0,b.jsxs)(g,{children:[(0,b.jsx)(c,{children:(0,b.jsx)(m,{label:"Workflow stage actions",size:"compact",children:(0,b.jsx)(a,{size:16})})}),(0,b.jsx)(l,{layer:"graph",children:N?(0,b.jsx)(h,{onClick:()=>F(),children:"Ungroup stages"}):(0,b.jsxs)(b.Fragment,{children:[e.data.blockProjectionOwnerId?null:(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(h,{onClick:()=>F("inputs"),children:"Group input encoders"}),(0,b.jsx)(h,{onClick:()=>F("guidance"),children:"Group guidance"})]}),E?(0,b.jsx)(h,{onClick:()=>requestAnimationFrame(()=>v(!0)),children:"Add image / audio input…"}):null]})})]}),S?(0,b.jsx)(u,{open:!0,title:"Add image / audio input",onClose:()=>v(!1),children:(0,b.jsx)(C,{node:e,onAttached:()=>v(!1),inline:!0})}):null,t?(0,b.jsx)("p",{role:"alert",className:"text-xs text-modiff-red",children:t}):null]})}export{S as default}; \ No newline at end of file diff --git a/web/assets/WorkflowArtifactRequirementRow.js b/web/assets/WorkflowArtifactRequirementRow.js index 1ad4e41..d21f033 100644 --- a/web/assets/WorkflowArtifactRequirementRow.js +++ b/web/assets/WorkflowArtifactRequirementRow.js @@ -1 +1 @@ -import{cr as e}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{In as a,S as l,Zt as t,co as s,lo as r,so as i}from"./studio-templates.js?v=cc046c26d6fe7aa4";var n=e();function o(e){return"use_local"===e?"Use local":"repair"===e?"Repair":"retry"===e?"Retry":"installing"===e?"Installing":"ready"===e?"Ready":"install"===e?"Install":"Details"}function c(e){return"use_local"===e?"use_local":"repair"===e?"repair":"retry"===e?"retry":"installing"===e?"installing":"ready"===e?"ready":"install"===e?"install":"details"}function d(e,a){return e.status.runnable?"ready":r(a)?"installing":s(a)?"retry":"Repair"===e.primaryAction?"repair":"Use local"===e.primaryAction?"use_local":"Details"===e.primaryAction?"details":"install"}function p({activeInstallCount:e=0,actionTestId:s,className:r,compact:p=!1,installProgress:u,onInstall:m,onUseLocal:x,requirement:f,rightSlot:g,testId:b}){let y=u[f.repo],h=d(f,y),j=function(e,a){return["install","repair","retry"].includes(a)?e.installTarget??{repo:e.repo,label:e.label,actionLabel:o(a),repair:"repair"===a}:null}(f,h),v="installing"===h,N=function(e,a){return e.status.runnable||"ready"===a?"success":"use_local"===a||"repair"===a||"installing"===a||e.installTarget||"details"!==a?"warning":"error"}(f,h),I=v||!!j&&e>=2||"use_local"===h&&!x||!!j&&!m,_=[f.details||f.status.reason,f.modelPath?f.modelPath:f.repo,f.nodeLabel?`Node: ${f.nodeLabel}`:null].filter(Boolean).join(" | "),L=j&&m?()=>{m(j,f)}:"use_local"===h&&x?()=>x(f):void 0;return(0,n.jsxs)("article",{className:a("rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",r),"data-testid":b,title:_,children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text",children:f.label}),(0,n.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,n.jsx)(t,{action:"details",className:"min-h-7 px-2 py-0.5 text-xs",label:f.role,title:f.repo,tone:"neutral"}),"graph"===f.source?(0,n.jsx)(t,{action:"details",className:"min-h-7 px-2 py-0.5 text-xs",label:"Graph",title:f.nodeLabel??f.nodeId,tone:"neutral"}):null]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[g,(0,n.jsx)(t,{action:c(h),className:"min-h-7 px-2 py-0.5 text-xs",disabled:I,label:o(h),onClick:L,progress:v?i(y):null,testId:s??(b?`${b}-action`:void 0),title:_,tone:N})]})]}),y&&!p?(0,n.jsx)("div",{className:"mt-2",children:(0,n.jsx)(l,{compact:!0,progress:y,repoId:f.repo,testId:b?`${b}-progress`:void 0})}):null]})}export{p as t}; \ No newline at end of file +import{cr as e}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{Ln as a,Qt as l,S as t,do as s,lo as r,uo as i}from"./studio-templates.js?v=ca6b74e6a02eedb3";var n=e();function o(e){return"use_local"===e?"Use local":"repair"===e?"Repair":"retry"===e?"Retry":"installing"===e?"Installing":"ready"===e?"Ready":"install"===e?"Install":"Details"}function c(e){return"use_local"===e?"use_local":"repair"===e?"repair":"retry"===e?"retry":"installing"===e?"installing":"ready"===e?"ready":"install"===e?"install":"details"}function d(e,a){return e.status.runnable?"ready":s(a)?"installing":i(a)?"retry":"Repair"===e.primaryAction?"repair":"Use local"===e.primaryAction?"use_local":"Details"===e.primaryAction?"details":"install"}function p({activeInstallCount:e=0,actionTestId:s,className:i,compact:p=!1,installProgress:u,onInstall:m,onUseLocal:x,requirement:f,rightSlot:g,testId:b}){let y=u[f.repo],h=d(f,y),j=function(e,a){return["install","repair","retry"].includes(a)?e.installTarget??{repo:e.repo,label:e.label,actionLabel:o(a),repair:"repair"===a}:null}(f,h),v="installing"===h,N=function(e,a){return e.status.runnable||"ready"===a?"success":"use_local"===a||"repair"===a||"installing"===a||e.installTarget||"details"!==a?"warning":"error"}(f,h),I=v||!!j&&e>=2||"use_local"===h&&!x||!!j&&!m,_=[f.details||f.status.reason,f.modelPath?f.modelPath:f.repo,f.nodeLabel?`Node: ${f.nodeLabel}`:null].filter(Boolean).join(" | "),L=j&&m?()=>{m(j,f)}:"use_local"===h&&x?()=>x(f):void 0;return(0,n.jsxs)("article",{className:a("rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",i),"data-testid":b,title:_,children:[(0,n.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("div",{className:"truncate text-sm font-semibold text-modiff-text",children:f.label}),(0,n.jsxs)("div",{className:"mt-1 flex flex-wrap gap-1",children:[(0,n.jsx)(l,{action:"details",className:"min-h-7 px-2 py-0.5 text-xs",label:f.role,title:f.repo,tone:"neutral"}),"graph"===f.source?(0,n.jsx)(l,{action:"details",className:"min-h-7 px-2 py-0.5 text-xs",label:"Graph",title:f.nodeLabel??f.nodeId,tone:"neutral"}):null]})]}),(0,n.jsxs)("div",{className:"flex shrink-0 items-center gap-1",children:[g,(0,n.jsx)(l,{action:c(h),className:"min-h-7 px-2 py-0.5 text-xs",disabled:I,label:o(h),onClick:L,progress:v?r(y):null,testId:s??(b?`${b}-action`:void 0),title:_,tone:N})]})]}),y&&!p?(0,n.jsx)("div",{className:"mt-2",children:(0,n.jsx)(t,{compact:!0,progress:y,repoId:f.repo,testId:b?`${b}-progress`:void 0})}):null]})}export{p as t}; \ No newline at end of file diff --git a/web/assets/WorkflowSaveDialog.js b/web/assets/WorkflowSaveDialog.js index 216b96b..5c5f3af 100644 --- a/web/assets/WorkflowSaveDialog.js +++ b/web/assets/WorkflowSaveDialog.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Jt as a,cr as o,dr as s,in as i}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{_n as l,fn as r,in as n,mn as t,rn as d}from"./studio-templates.js?v=cc046c26d6fe7aa4";var f=e(s(),1),c=o(),m=[{value:"library",label:"My workflows",description:"Create a named workflow in MoDiff that stays available across sessions.",meta:"Recommended"},{value:"file",label:"JSON file",description:"Choose a folder and filename on this device. Unsupported browsers use Downloads."}];function p({initialDestination:e="library",initialName:o,loading:s=!1,onClose:p,onSave:u,open:w}){let[v,b]=(0,f.useState)(o),[h,k]=(0,f.useState)(e);(0,f.useEffect)(()=>{w&&(b(o),k(e))},[e,o,w]);let x=v.trim();return(0,c.jsx)(n,{open:w,onClose:s?()=>{}:p,title:"Save workflow as",description:"Keep a reusable workflow in MoDiff or download a portable JSON copy.",dismissible:!s,testId:"save-workflow-dialog",panelClassName:"max-w-lg",footer:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(d,{disabled:s,onClick:p,children:"Cancel"}),(0,c.jsx)(d,{"data-testid":"confirm-save-workflow",disabled:!x,loading:s,onClick:()=>u(x,h),tone:"primary",icon:"library"===h?(0,c.jsx)(a,{size:16}):(0,c.jsx)(i,{size:16}),children:"library"===h?"Save to My workflows":"Choose location"})]}),children:(0,c.jsxs)("div",{className:"grid gap-4",children:[(0,c.jsx)(r,{label:"Workflow name",description:"file"===h?"This name is used as the suggested JSON filename.":"You can rename it later from My workflows.",required:!0,children:(0,c.jsx)(t,{autoFocus:!0,disabled:s,"data-testid":"save-workflow-name",value:v,onChange:e=>b(e.currentTarget.value),onKeyDown:e=>{"Enter"===e.key&&x&&!s&&(e.preventDefault(),u(x,h))}})}),(0,c.jsx)(r,{label:"Save to",children:(0,c.jsx)(l,{"aria-label":"Workflow save destination",disabled:s,value:h,onValueChange:e=>k(e),options:m})}),(0,c.jsx)("p",{className:"text-modiff-metadata leading-5 text-modiff-subtle-text",children:"MoDiff keeps recovery snapshots automatically. Save creates a named workflow; saving a JSON copy is for portable backups and sharing."})]})})}export{p as default}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Jt as a,cr as o,dr as s,in as i}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{an as l,hn as r,in as n,pn as t,vn as d}from"./studio-templates.js?v=ca6b74e6a02eedb3";var f=e(s(),1),c=o(),m=[{value:"library",label:"My workflows",description:"Create a named workflow in MoDiff that stays available across sessions.",meta:"Recommended"},{value:"file",label:"JSON file",description:"Choose a folder and filename on this device. Unsupported browsers use Downloads."}];function p({initialDestination:e="library",initialName:o,loading:s=!1,onClose:p,onSave:u,open:w}){let[v,b]=(0,f.useState)(o),[h,k]=(0,f.useState)(e);(0,f.useEffect)(()=>{w&&(b(o),k(e))},[e,o,w]);let x=v.trim();return(0,c.jsx)(l,{open:w,onClose:s?()=>{}:p,title:"Save workflow as",description:"Keep a reusable workflow in MoDiff or download a portable JSON copy.",dismissible:!s,testId:"save-workflow-dialog",panelClassName:"max-w-lg",footer:(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(n,{disabled:s,onClick:p,children:"Cancel"}),(0,c.jsx)(n,{"data-testid":"confirm-save-workflow",disabled:!x,loading:s,onClick:()=>u(x,h),tone:"primary",icon:"library"===h?(0,c.jsx)(a,{size:16}):(0,c.jsx)(i,{size:16}),children:"library"===h?"Save to My workflows":"Choose location"})]}),children:(0,c.jsxs)("div",{className:"grid gap-4",children:[(0,c.jsx)(t,{label:"Workflow name",description:"file"===h?"This name is used as the suggested JSON filename.":"You can rename it later from My workflows.",required:!0,children:(0,c.jsx)(r,{autoFocus:!0,disabled:s,"data-testid":"save-workflow-name",value:v,onChange:e=>b(e.currentTarget.value),onKeyDown:e=>{"Enter"===e.key&&x&&!s&&(e.preventDefault(),u(x,h))}})}),(0,c.jsx)(t,{label:"Save to",children:(0,c.jsx)(d,{"aria-label":"Workflow save destination",disabled:s,value:h,onValueChange:e=>k(e),options:m})}),(0,c.jsx)("p",{className:"text-modiff-metadata leading-5 text-modiff-subtle-text",children:"MoDiff keeps recovery snapshots automatically. Save creates a named workflow; saving a JSON copy is for portable backups and sharing."})]})})}export{p as default}; \ No newline at end of file diff --git a/web/assets/WorkspacePanel.js b/web/assets/WorkspacePanel.js index ba56286..ca9d796 100644 --- a/web/assets/WorkspacePanel.js +++ b/web/assets/WorkspacePanel.js @@ -1 +1 @@ -import{r as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{$ as t,An as a,B as s,Dn as i,E as l,Fn as n,Ft as r,Gt as o,Ht as d,J as c,K as u,Kt as m,Lt as p,M as f,Mt as h,Pn as x,Pt as g,Q as b,R as j,Rn as v,Rt as y,U as w,W as k,X as C,Xt as N,Yt as S,_n as I,bn as R,cr as $,dr as M,gt as T,jn as A,on as P,ot as _,pt as z,rt as q,sn as B,st as D,un as G,vn as E,wn as O,z as L,zn as F}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$a as H,$n as K,Aa as W,Ai as V,Ba as U,Bi as Q,Bt as J,C as Z,Ca as X,Ci as Y,Co as ee,Cr as te,Da as ae,Dn as se,Dr as ie,Ea as le,Ei as ne,En as re,Eo as oe,Fa as de,Fi as ce,Fn as ue,Fr as me,Gi as pe,Gt as fe,Ha as he,Hi as xe,Ht as ge,Ia as be,Ii as je,In as ve,Ir as ye,Jn as we,Jt as ke,Ka as Ce,Kt as Ne,La as Se,Li as Ie,Lr as Re,Lt as $e,Ma as Me,Mi as Te,Mo as Ae,Na as Pe,Ni as _e,Nr as ze,Ns as qe,Oa as Be,Oi as De,On as Ge,Oo as Ee,Pa as Oe,Pi as Le,Pr as Fe,Qa as He,Qt as Ke,Ra as We,Ri as Ve,Rt as Ue,S as Qe,Sa as Je,Si as Ze,Sr as Xe,St as Ye,Ti as et,Tn as tt,Tr as at,Ua as st,Ut as it,Vi as lt,Vn as nt,Vr as rt,Vt as ot,Wt as dt,Xt as ct,Yt as ut,Zi as mt,Zt as pt,_a as ft,bn as ht,c as xt,co as gt,dn as bt,dt as jt,eo as vt,er as yt,fa as wt,fn as kt,fr as Ct,hr as Nt,in as St,ir as It,ja as Rt,ji as $t,ka as Mt,ki as Tt,kn as At,kr as Pt,lo as _t,mo as zt,mr as qt,na as Bt,oc as Dt,pa as Gt,pn as Et,pr as Ot,q as Lt,qt as Ft,rn as Ht,ro as Kt,rr as Wt,so as Vt,tn as Ut,to as Qt,ua as Jt,uo as Zt,ur as Xt,vt as Yt,w as ea,wa as ta,wi as aa,wn as sa,wr as ia,xr as la,za as na,zi as ra,zo as oa,zt as da}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{i as ca,n as ua,r as ma}from"./block-composition-tools.js?v=cc046c26d6fe7aa4";import{n as pa,r as fa,t as ha}from"./presetDiff.js?v=cc046c26d6fe7aa4";import{t as xa}from"./WorkflowArtifactRequirementRow.js?v=cc046c26d6fe7aa4";import{n as ga,t as ba}from"./GraphNodeInputs.js?v=cc046c26d6fe7aa4";import{n as ja,t as va}from"./TemplateUsageTermsDialog.js?v=cc046c26d6fe7aa4";import{a as ya,t as wa}from"./controlledWorkflows.js?v=cc046c26d6fe7aa4";var ka=e(M(),1),Ca=$();function Na(e){navigator.clipboard?.writeText(e)}function Sa({error:e,status:t}){let a=t?.runtimeEnvironment,s=a?.devices.find(e=>e.device===a.defaultDevice),i=!(!t?.ready||!a?.executionReady),l="experimental"===a?.supportTier||"preview"===a?.supportTier,n=a?.installation,r=a?.issues.map(e=>e.message).join(" "),o=n?.steps?.filter(e=>"complete"!==e.status&&"skipped"!==e.status)??[];return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"runtime-environment-card",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Runtime environment"}),(0,Ca.jsx)(pt,{label:i?"Ready":"Needs setup",tone:i?"success":"error",title:e||r||a?.status})]}),(0,Ca.jsxs)("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[(0,Ca.jsx)(pt,{label:`${a?.installedProfile??"Profile unverified"} · ${a?.supportTier??"unverified"}`,tone:l||!a?.profileVerified?"warning":"neutral",title:a?.profileVerified?`Requested: ${a.requestedProfile??"auto"}. Qualification: ${a.supportTier}.`:"Legacy backend: installation profile cannot be verified."}),(0,Ca.jsx)(pt,{label:s?`${s.backend} · ${s.device}`:"Detecting hardware",tone:s&&"cpu"!==s.backend?"success":"neutral",title:s?`${s.name} · ${s.vendor} · ${s.memoryKind} memory`:"Hardware has not been reported."}),(0,Ca.jsx)(pt,{label:`Torch ${t?.packages?.torch?.version??"unknown"}`,tone:"neutral",title:`Torch ${t?.packages?.torch?.version??"unknown"}`})]}),l&&(0,Ca.jsx)("p",{className:"mt-2 text-xs text-modiff-warning",children:"This profile passed local checks; model recipes still need physical qualification."}),!i&&a?.issues.length?(0,Ca.jsx)("ul",{className:"mt-2 grid gap-1 text-xs text-modiff-red","data-testid":"runtime-profile-issues",children:a.issues.map((e,t)=>(0,Ca.jsx)("li",{children:e.message},`${e.code??"runtime"}-${t}`))}):null,o.length>0&&(0,Ca.jsx)("ol",{className:"mt-3 grid gap-2","data-testid":"runtime-installation-checklist",children:o.map((e,t)=>(0,Ca.jsxs)("li",{className:"rounded-modiff-compact border border-modiff-border-subtle p-2 text-xs text-modiff-text",children:[(0,Ca.jsxs)("div",{className:"font-semibold",children:[t+1,". ",e.title??e.id]}),e.explanation&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:e.explanation}),e.requiresAdmin&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-warning",children:"Administrator approval required."}),e.requiresReboot&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-warning",children:"Resume after reboot or complete sign-out."}),e.command&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-modiff-subtle-text",children:e.command}),(0,Ca.jsx)(Ht,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1",onClick:()=>Na(e.command),children:"Copy"})]}),e.verification&&(0,Ca.jsxs)("p",{className:"mt-1 text-modiff-subtle-text",children:["Verify: ",e.verification]}),e.failureHelp&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:e.failureHelp})]},e.id??`${e.phase??"step"}-${t}`))}),n?.resumeCommand&&"complete"!==n.status&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-xs text-modiff-subtle-text",children:n.resumeCommand}),(0,Ca.jsx)(Ht,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1 text-xs",onClick:()=>Na(n.resumeCommand),children:"Copy resume"})]}),a?.repairCommand&&!i&&(!n?.resumeCommand||"complete"===n.status)&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-xs text-modiff-subtle-text",children:a.repairCommand}),(0,Ca.jsx)(Ht,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1 text-xs",onClick:()=>Na(a.repairCommand),children:"Copy repair"})]})]})}function Ia(e,t,a){return Ee(`${Dt.serverAddress}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),timeoutMs:3e4,parse:a})}function Ra(e,t){let a="active"===t&&"active"===e.overlayStatus&&e.cutoverReady&&"qualified"===e.contractState,s="active"!==t&&"base"!==t?t:a?"active":"qualified"===e.contractState&&e.cutoverReady?e.overlayStatus:"unavailable";return`${s.replace(/_/g," ")}${"unavailable"===s?` (${e.contractState})`:""}.`}function $a(e){return`${"macos"===e.platform?"macOS":"windows"===e.platform?"Windows":"Linux"} ${"arm64"===e.machine?"ARM64":"x86-64"}`}function Ma(){let e=Ze(e=>e.optionalRuntimeCatalog),t=Ze(e=>e.discoveryRequests.optionalRuntimes),a=Ze(e=>e.fetchOptionalRuntimes),s=Je(e=>e.setAlertOpener),[i,l]=(0,ka.useState)(null),[n,r]=(0,ka.useState)([]),[o,d]=(0,ka.useState)(null),[c,u]=(0,ka.useState)(!0),[m,p]=(0,ka.useState)(null),[f,h]=(0,ka.useState)(null),x=(0,ka.useRef)(0),g=(0,ka.useRef)(!1),b=(0,ka.useRef)(0),j=(0,ka.useRef)(0),v=(0,ka.useCallback)(async()=>{let e=++x.current;u(!0);try{let[t,a]=await Promise.all([Ee(`${Dt.serverAddress}/runtime/optimizations`,{timeoutMs:15e3,parse:ae}),Ee(`${Dt.serverAddress}/runtime/optimizations/receipts`,{timeoutMs:15e3,parse:Mt})]);if(e!==x.current)return;l(t),r(a.receipts),p(null)}catch(t){throw e===x.current&&p(oe(t,"Could not load runtime optimizations.")),t}finally{e===x.current&&u(!1)}},[]);(0,ka.useEffect)(()=>{v().catch(()=>{})},[v]),(0,ka.useEffect)(()=>()=>{j.current+=1},[]);let y=(0,ka.useCallback)(async(e,t)=>{let s=++j.current,i=Date.now()+3e5;for(;s===j.current&&Date.now()window.setTimeout(e,1e3)),s!==j.current)return;await a();let i=Ze.getState().optionalRuntimeCatalog,l=i?.profiles.find(t=>t.id===e);if("active"===i?.processLoadStatus&&l?.specDigest===t&&"active"===l.overlayStatus){let e=Ze.getState();return void await Promise.all([e.fetchRuntimeStatus(),e.fetchStudioModelCapabilities()])}}s===j.current&&Ae("Runtime activation is still restarting. Refresh Setup before running this workflow.",{variant:"warning"})},[a]);(0,ka.useEffect)(()=>{if(!f||["cancelled","failed","ready"].includes(f.status))return;let e=new AbortController,t=window.setTimeout(async()=>{if(++b.current>2400)Ae("Runtime setup polling stopped. Refresh status to continue.",{variant:"warning"});else try{let t=await Ee(`${Dt.serverAddress}/runtime/optional-runtimes/jobs/${encodeURIComponent(f.id)}`,{signal:e.signal,parse:X});if(t.id!==f.id||t.profileId!==f.profileId||t.specDigest!==f.specDigest)throw Error("The optional-runtime job identity changed.");h(t),["cancelled","failed","ready"].includes(t.status)&&a()}catch{e.signal.aborted||h({...f})}},750);return()=>{e.abort(),window.clearTimeout(t)}},[a,f]);let w=async(e,t)=>{if(!g.current){g.current=!0,d(e);try{await t()}catch(e){Ae(oe(e,"Action failed."),{variant:"error"})}finally{g.current=!1,d(null)}}},k=(e,t,a)=>w(e,async()=>{Ae((await Ia(t,a,Be)).message??"Updated.",{variant:"success"}),v().catch(()=>{})}),C=(e,t,a,i)=>s({title:e,message:t,confirmText:a,cancelText:"Cancel",onConfirm:()=>{s(null),w(a.toLowerCase(),i)},onCancel:()=>s(null)}),N=(e,t)=>{let s=t?"Activate":"repair_required"===e.overlayStatus||"staged_unchecked"===e.overlayStatus?"Repair":"Install";C(`${s} optional runtime?`,t?`Activate validated ${e.label} and restart MoDiff.`:`Install ${e.label} from reviewed, locked artifacts. Activation is separate.`,s,t?async()=>{Ae((await Ia("/runtime/optional-runtimes/activate",{environmentId:t,profileId:e.id,specDigest:e.specDigest,consent:!0},ta)).message??"Activation selected.",{variant:"success"}),h(null),await a(),y(e.id,e.specDigest)}:async()=>{let t=await Ia("/runtime/optional-runtimes/install",{profileId:e.id,specDigest:e.specDigest,consent:!0},X);if(t.profileId!==e.id||t.specDigest!==e.specDigest)throw Error("Runtime job mismatch.");b.current=0,h(t),await a()})},S=()=>{f&&w("cancel",async()=>{let e=await Ia(`/runtime/optional-runtimes/jobs/${encodeURIComponent(f.id)}/cancel`,{},X);if(e.id!==f.id)throw Error("The cancellation response does not match the active job.");h(e),["cancelled","failed"].includes(e.status)&&await a()})},I=n.filter(e=>"workload"===e.kind&&"observed"===e.status),R=!(!e?.activeEnvironmentId||e.previousEnvironmentId||"repair_required"!==e.processLoadStatus),$=!(!e?.previousEnvironmentId&&!R);return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Ca.jsxs)("div",{className:"grid gap-1 pb-2",children:[(0,Ca.jsx)("strong",{children:"Optional runtimes"}),t.error?(0,Ca.jsx)("p",{className:"text-xs text-modiff-warning",children:t.error}):"loading"===t.status?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading optional runtimes..."}):"success"===t.status&&e?e.profiles.map(t=>{let a=le(e,t),s=f?.profileId===t.id&&f.specDigest===t.specDigest?f.result?.environmentId:void 0,i="qualified"===t.contractState&&t.cutoverReady,l=s??a,n=l?"Activate":"repair_required"===t.overlayStatus||"staged_unchecked"===t.overlayStatus?"Repair":"Install",r=i&&(l?t.activationAvailable:t.installActionAvailable&&"active"!==t.overlayStatus);return(0,Ca.jsxs)("div",{className:"grid gap-1 text-xs text-modiff-text","data-testid":`optional-runtime-${t.id}`,children:[(0,Ca.jsxs)("span",{children:[t.label," (",$a(t),"):"," ",Ra(t,e.processLoadStatus)]}),f?.profileId===t.id?(0,Ca.jsxs)("div",{className:"flex items-center gap-2","data-testid":"optional-runtime-progress",children:[(0,Ca.jsx)("span",{children:f.progress.message}),["queued","running"].includes(f.status)?(0,Ca.jsx)(Ht,{size:"compact",disabled:null!==o,onClick:S,children:"Cancel"}):null]}):null,(0,Ca.jsx)("div",{className:"flex gap-1.5",children:r?(0,Ca.jsx)(Ht,{size:"compact",disabled:null!==o||e.installBusy,loading:o===n.toLowerCase(),onClick:()=>N(t,l),children:n}):null})]},t.id)}):(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No optional runtimes."}),e&&$&&e.profiles.some(e=>e.activationAvailable&&e.cutoverReady&&"qualified"===e.contractState)?(0,Ca.jsx)(Ht,{size:"compact",disabled:null!==o||e.installBusy,loading:"rollback"===o,onClick:()=>C(R?"Roll back optional runtime to base?":"Roll back optional runtime?",R?"Remove the broken active optional environment and restart MoDiff with the validated base runtime. Active and queued runs must be stopped first.":"Select the previous validated optional environment and restart MoDiff. Active and queued runs must be stopped first.","Rollback",async()=>{Ae((await Ia("/runtime/optional-runtimes/rollback",{consent:!0},ta)).message??"Optional runtime rollback selected.",{variant:"success"}),await a()}),children:R?"Rollback to base":"Rollback"}):null]}),(0,Ca.jsxs)(bt,{label:"Optimizations",panelClassName:"grid gap-2 pt-2",children:[m?(0,Ca.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-modiff-compact border border-modiff-warning p-2",children:[(0,Ca.jsx)("span",{className:"text-xs text-modiff-warning",children:m}),(0,Ca.jsx)(Ht,{size:"compact",loading:c,onClick:()=>{v().catch(()=>{})},children:"Retry"})]}):c&&!i?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading runtime optimizations…"}):null,i?.capabilities.map(e=>{let t=W(e.documentation);return(0,Ca.jsx)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:(0,Ca.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:e.label}),(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:e.summary}),e.disabledReason?(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-warning",children:e.disabledReason}):null]}),(0,Ca.jsxs)("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:[(0,Ca.jsx)(Ht,{size:"compact",disabled:!t||null!==o,onClick:()=>{t&&window.open(t,"_blank","noopener,noreferrer")},children:"Docs"}),e.canEnable?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Ht,{size:"compact",disabled:null!==o,tone:e.enabled?"primary":"secondary",loading:o===`toggle:${e.id}`,onClick:()=>{k(`toggle:${e.id}`,"/runtime/optimizations/enable",{capabilityId:e.id,enabled:!e.enabled})},children:e.enabled?"Enabled":"Enable"}),(0,Ca.jsx)(Ht,{size:"compact",disabled:null!==o,loading:o===`probe:${e.id}`,onClick:()=>{k(`probe:${e.id}`,"/runtime/optimizations/probe",{capabilityId:e.id})},children:"Probe"})]}):null]})]})},e.id)}),I.map(e=>(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,Ca.jsxs)("span",{className:"text-xs text-modiff-text",children:["Review ",e.capabilityId," · ",e.modelType||e.artifact||"workload"]}),(0,Ca.jsx)(Ht,{size:"compact",loading:o===`qualify:${e.id}`,disabled:null!==o,onClick:()=>{k(`qualify:${e.id}`,"/runtime/optimizations/qualify",{receiptId:e.id,outputReviewed:!0})},children:"Reviewed"})]},e.id))]})]})}var Ta=/^[0-9a-f]{40}$/,Aa=/^sha256:canonical-json:[0-9a-f]{64}$/,Pa=/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/,_a=new Set(["installing","missing","ready","repair_required","unavailable"]);function za(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object.`);return e}function qa(e,t,a){if("string"!=typeof e||!e||e.length>512||a&&!a.test(e))throw Error(`${t} is invalid.`);return e}function Ba(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw Error(`${t} is invalid.`);return Number(e)}function Da(e,t){if("boolean"!=typeof e)throw Error(`${t} is invalid.`);return e}function Ga(e){let t=za(e,"Template Gallery status");if(!1!==t.error||1!==t.schemaVersion)throw Error("Template Gallery status reports an unsupported contract.");let a=qa(t.status,"Template Gallery status");if(!_a.has(a))throw Error("Template Gallery status is unknown.");let s={status:a,installed:Da(t.installed,"Template Gallery installed state"),complete:Da(t.complete,"Template Gallery completion state"),repairRequired:Da(t.repairRequired,"Template Gallery repair state"),installing:Da(t.installing,"Template Gallery installation state"),...void 0===t.repoId?{}:{repoId:qa(t.repoId,"Template Gallery repository",Pa)},...void 0===t.revision?{}:{revision:qa(t.revision,"Template Gallery revision",Ta)},...void 0===t.assetSetId?{}:{assetSetId:qa(t.assetSetId,"Template Gallery asset set",Aa)},...void 0===t.assetCount?{}:{assetCount:Ba(t.assetCount,"Template Gallery asset count")},...void 0===t.totalBytes?{}:{totalBytes:Ba(t.totalBytes,"Template Gallery byte size")},...void 0===t.code?{}:{code:qa(t.code,"Template Gallery status code")},...void 0===t.message?{}:{message:qa(t.message,"Template Gallery status message")}};if("ready"===s.status&&(!s.installed||!s.complete||s.repairRequired||s.installing)||"missing"===s.status&&(s.installed||s.complete||s.repairRequired)||"repair_required"===s.status&&!s.repairRequired||"installing"===s.status&&!s.installing||"unavailable"!==s.status&&(!s.repoId||!s.revision||!s.assetSetId)||"ready"===s.status&&(void 0===s.assetCount||void 0===s.totalBytes))throw Error("Template Gallery status fields conflict.");return s}function Ea(e){let t=za(e,"Template Gallery plan");if(!1!==t.error||1!==t.schemaVersion)throw Error("Template Gallery plan reports an unsupported contract.");let a={repoId:qa(t.repoId,"Template Gallery repository",Pa),repoType:qa(t.repoType,"Template Gallery repository type"),revision:qa(t.revision,"Template Gallery revision",Ta),assetSetId:qa(t.assetSetId,"Template Gallery asset set",Aa),assetCount:Ba(t.assetCount,"Template Gallery asset count"),totalBytes:Ba(t.totalBytes,"Template Gallery total bytes"),downloadBytes:Ba(t.downloadBytes,"Template Gallery download bytes"),stagingBytes:Ba(t.stagingBytes,"Template Gallery staging bytes"),reservationBytes:Ba(t.reservationBytes,"Template Gallery reservation bytes"),queuedReservationBytes:Ba(t.queuedReservationBytes,"Model queue reservation bytes"),reserveBytes:Ba(t.reserveBytes,"Safety reserve bytes"),cacheFreeBytes:Ba(t.cacheFreeBytes,"Gallery cache free bytes"),destinationFreeBytes:Ba(t.destinationFreeBytes,"Gallery destination free bytes"),sameFilesystem:Da(t.sameFilesystem,"Template Gallery filesystem identity"),sizeKnown:Da(t.sizeKnown,"Template Gallery size state"),fitsWithQueue:Da(t.fitsWithQueue,"Template Gallery fit state"),installed:Da(t.installed,"Template Gallery installed state"),repairRequired:Da(t.repairRequired,"Template Gallery repair state"),repairReason:null===t.repairReason||void 0===t.repairReason?null:qa(t.repairReason,"Template Gallery repair reason"),installing:Da(t.installing,"Template Gallery installation state")};if("dataset"!==a.repoType||a.reservationBytes!==a.downloadBytes+a.stagingBytes||a.installed&&a.repairRequired||a.installed&&(0!==a.downloadBytes||0!==a.stagingBytes||0!==a.reservationBytes))throw Error("Template Gallery plan fields conflict.");return a}function Oa(e){let t=za(e,"Template Gallery install result");if(!1!==t.error||!0!==t.complete||"boolean"!=typeof t.alreadyInstalled)throw Error("Template Gallery install did not complete.");let a=Ea({...za(t.plan,"Template Gallery result plan"),error:!1});if(void 0===t.result){if(!t.alreadyInstalled)throw Error("Template Gallery install result is missing.");return{complete:!0,alreadyInstalled:!0,plan:a}}let s=za(t.result,"Installed Template Gallery receipt");if(!0!==s.installed||!0!==s.complete||!1!==s.repairRequired||s.assetSetId!==a.assetSetId||s.repoId!==a.repoId||s.revision!==a.revision||s.assetCount!==a.assetCount||s.totalBytes!==a.totalBytes)throw Error("Installed Template Gallery receipt does not match its plan.");return{complete:!0,alreadyInstalled:!1,plan:a,result:{installed:!0,complete:!0,repairRequired:!1,assetCount:Ba(s.assetCount,"Installed Template Gallery asset count"),totalBytes:Ba(s.totalBytes,"Installed Template Gallery byte size"),assetSetId:qa(s.assetSetId,"Installed Template Gallery asset set",Aa),repoId:qa(s.repoId,"Installed Template Gallery repository",Pa),revision:qa(s.revision,"Installed Template Gallery revision",Ta),restartRequired:Da(s.restartRequired,"Template Gallery restart requirement")}}}function La(e){if(!e||e<=0)return"0 B";let t=["B","KiB","MiB","GiB","TiB"],a=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),s=e/1024**a;return`${s.toFixed(s>=10||0===a?0:1)} ${t[a]}`}function Fa(e,t){return t&&!e?"Checking":e?"ready"===e.status?"Ready":"installing"===e.status?"Installing":"repair_required"===e.status?"Repair required":"missing"===e.status?"Not installed":"Unavailable":"Unavailable"}function Ha(){let e=Je(e=>e.setAlertOpener),[t,a]=(0,ka.useState)(null),[s,i]=(0,ka.useState)(!0),[l,n]=(0,ka.useState)(!1),[o,d]=(0,ka.useState)(null),c=(0,ka.useRef)(0),u=(0,ka.useCallback)(async()=>{let e=++c.current;i(!0);try{let t=await Ee(`${Dt.serverAddress}/template_gallery/status`,{timeoutMs:12e4,parse:Ga});if(e!==c.current)return;a(t),d(null)}catch(t){if(e!==c.current)return;d(oe(t,"Could not inspect Template Gallery assets."))}finally{e===c.current&&i(!1)}},[]);(0,ka.useEffect)(()=>{u()},[u]);let m="ready"===t?.status,p="missing"===t?.status||"repair_required"===t?.status;return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"template-gallery-setup-card",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(r,{size:15,className:"text-hf-yellow"}),(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Template Gallery assets"})]}),(0,Ca.jsx)(pt,{label:Fa(t,s),tone:m?"success":o||t?.repairRequired?"error":"warning",title:o||t?.message||t?.assetSetId})]}),(0,Ca.jsx)("p",{className:"mt-2 text-xs leading-5 text-modiff-subtle-text",children:"Byte-pinned Gallery previews and default workflow inputs are installed from the app's immutable public Dataset. Model caches are separate and are never removed by this action."}),t?.complete&&(0,Ca.jsxs)("p",{className:"mt-1 text-xs text-modiff-green",children:[t.assetCount??0," files · ",La(t.totalBytes)," · ",t.revision?.slice(0,12)]}),o&&(0,Ca.jsx)("p",{className:"mt-1 break-words text-xs text-modiff-red",children:o}),(0,Ca.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[p&&(0,Ca.jsx)(Ht,{size:"compact",loading:l||t?.installing,disabled:s||l||t?.installing,onClick:()=>{(async()=>{if(!l){n(!0);try{let t=await Ee(`${Dt.serverAddress}/template_gallery/plan`,{timeoutMs:12e4,parse:Ea});if(!t.sizeKnown||!t.fitsWithQueue)throw Error(`The verified ${La(t.reservationBytes)} Gallery reservation does not fit alongside ${La(t.queuedReservationBytes)} of active model reservations and the ${La(t.reserveBytes)} safety reserve.`);e({title:t.repairRequired?"Repair Template Gallery assets?":"Install Template Gallery assets?",message:`Download and hash-verify ${t.assetCount} files (${La(t.totalBytes)}) from ${t.repoId} at immutable revision ${t.revision.slice(0,12)}. Existing model downloads and cached models will not be removed.`,confirmText:t.repairRequired?"Repair":"Install",cancelText:"Cancel",onConfirm:()=>{e(null),(async()=>{try{Ae((await Ee(`${Dt.serverAddress}/template_gallery/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),timeoutMs:864e5,parse:Oa})).result?.restartRequired?"Template Gallery installed. Restart MoDiff after active downloads finish to serve it locally.":"Template Gallery is already installed.",{variant:"success"}),await u()}catch(e){let t=oe(e,"Template Gallery installation failed.");d(t),Ae(t,{variant:"error"})}finally{n(!1)}})()},onCancel:()=>{e(null),n(!1)}})}catch(e){let t=oe(e,"Could not plan the Template Gallery installation.");d(t),Ae(t,{variant:"error"}),n(!1)}}})()},"data-testid":"template-gallery-install",children:t?.repairRequired?"Check & repair":"Check & install"}),(0,Ca.jsx)(Ht,{size:"compact",tone:"secondary",icon:(0,Ca.jsx)(q,{size:14}),disabled:s||l,onClick:()=>{u()},"data-testid":"template-gallery-refresh",children:"Refresh"})]})]})}var Ka=(0,ka.lazy)(()=>Y(()=>import(`./CompositeMigrationCard.js?v=cc046c26d6fe7aa4`).then(e=>({default:e.CompositeMigrationCard})),[]));function Wa(e){if(!e||e<=0)return"0 B";let t=["B","KB","MB","GB","TB"],a=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),s=e/1024**a;return`${s.toFixed(s>=10||0===a?0:1)} ${t[a]}`}function Va(e){return e&&0!==Object.keys(e).length?Object.entries(e).slice(0,5).map(([e,t])=>`${e}: ${t}`).join(", "):"no files"}function Ua(e){return e?e.details?`${e.message} ${e.details}`:e.message:""}var Qa=["environment","package","backend","model_integrity","model","hardware_fit","asset","user_input","graph"],Ja={environment:"Environment",package:"Packages",backend:"Backend",model_integrity:"Model integrity",model:"Models",hardware_fit:"Hardware fit",asset:"Assets",user_input:"Inputs",graph:"Graph"};function Za(e){return"success"===e?"success":"warning"===e?"warning":"info"===e?"info":"error"}function Xa({children:e,tone:t="muted",testId:a}){return(0,Ca.jsx)("p",{"data-testid":a,className:ve("break-words text-xs leading-5","muted"===t&&"text-modiff-subtle-text","success"===t&&"text-modiff-green","error"===t&&"text-modiff-red","warning"===t&&"text-hf-orange"),children:e})}function Ya({children:e,disabled:t,onClick:a,progress:s,testId:i,title:l,tone:n}){return(0,Ca.jsx)(pt,{action:"Installing"===("string"==typeof e?e:void 0)?"installing":a?"install":"success"===n?"ready":"warning"===n||"error"===n?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:t,label:e,onClick:a,progress:s,testId:i,title:l,tone:"default"===n?"neutral":n})}function es(){let e=Ze(e=>e.hfCache),t=Ze(e=>e.localModels),a=Ze(e=>e.modelCacheDiagnostics),s=Ze(e=>e.studioModelCapabilities),i=Ze(e=>e.runtimeStatus),l=Ze(e=>e.runtimeError),n=Ze(e=>e.hfDownloadProgress),r=Ze(e=>e.refreshModelIndexes),o=Ze(e=>e.fetchRuntimeStatus),d=Ze(e=>e.fetchStudioModelCapabilities),c=Ze(e=>e.installHfModel),m=$t(e=>e.form),p=$t(e=>e.activeTemplateId),f=$t(e=>e.graphBinding),h=$t(e=>e.sourceOutputId);rt(e=>[e.nodes.map(e=>{let t=Object.entries(e.data.params).filter(([e])=>/repo|model|checkpoint|ckpt|safetensors|lora|vae|controlnet|adapter/i.test(e)).map(([e,t])=>`${e}:${JSON.stringify(t.value??t.default??"")}`).join(",");return`${e.id}:${e.data.module}:${e.data.action}:${e.data.uiState?.disabled?"disabled":"enabled"}:${t}`}).join("|"),e.edges.map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}->${e.target}:${e.targetHandle??""}`).join("|")].join("||"));let x=$t(e=>e.autoResourcePlans),b=$t(e=>e.setAutoResourcePlans),j=Je(e=>e.setModelManagerOpener),v=Je(e=>e.setRightPanelOpen),y=Je(e=>e.setRightPanelTab),w=Pt(e=>e.showIssues),k=we(e=>e.sid),C=we(e=>e.isConnected),I=Object.values(n).filter(_t).length,R=Object.entries(n).filter(([,e])=>_t(e)||gt(e)||Zt(e)),$=Ot(),M=!!(p||f||h),T=!(!f||!ye(f))||!M&&!f&&($.nodeCount>0||$.blockingIssues.length>0),A=Le(m),P=We[m.modelType],_=M&&P?[{profile:P,mode:m.mode,status:qe(P,e,t,a),backendCapability:s.find(e=>e.modelType===P.modelType),autoPlanKey:A,autoPlan:x[A]}]:[],z=M&&P?Xe({autoResourcePlan:x[A],form:m,hfCache:e,includePipeline:!1,localModels:t,modelCacheDiagnostics:a}):[],B=T?la({references:$.modelRefs,hfCache:e,localModels:t,modelCacheDiagnostics:a}).filter(e=>!e.status.runnable):[],D=$.blockingIssues[0]??null,E=function(e){return new Set(e.modelRefs.map(e=>`${e.kind}:${e.value}`)).size}($),O=ea({sid:k,isConnected:C,includeStudio:!T}),L=(0,ka.useMemo)(()=>Qa.map(e=>({category:e,label:Ja[e],issues:O.blockingIssues.filter(t=>t.category===e)})).filter(e=>e.issues.length>0),[O.blockingIssues]),F=async()=>{if(!M)return;let e=await lt([m],[A]),t={};e.forEach(e=>{let a=e.planKey??A;a&&(t[a]=e)}),b(t)},H=async()=>{await r(!0,{invalidateAutoPlans:!1}),await F()},K=()=>{v(!0),y("studio")},W=()=>{w(O.issues)},V=e=>"install_model"===e.action&&e.repoId?(0,Ca.jsx)(Ht,{tone:"primary",icon:(0,Ca.jsx)(G,{size:15}),onClick:()=>{(async e=>{try{await c(e,k),await H()}catch(e){console.error(e)}})(e.repoId)},children:"Install"}):"open_model_manager"===e.action?(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(u,{size:15}),onClick:()=>j({nodeId:null,fieldKey:null}),children:"Models"}):"refresh_cache"===e.action?(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(q,{size:15}),onClick:()=>{H()},children:"Refresh"}):"select_image"===e.action?(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(N,{size:15}),onClick:K,children:"Studio"}):(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(g,{size:15}),onClick:W,children:"Review"});(0,ka.useEffect)(()=>{o(),d()},[o,d]),(0,ka.useEffect)(()=>{if(!M)return;let e=!1;return lt([m],[A]).then(t=>{if(e)return;let a={};t.forEach(e=>{let t=e.planKey??A;t&&(a[t]=e)}),b(a)}).catch(e=>{console.error(e)}),()=>{e=!0}},[m,M,e.length,t.length,i?.ready,b,A]);let U=async e=>{try{await c(e.repo,k,{repair:e.repair,revision:e.revision,files:e.files}),await H()}catch(e){console.error(e)}},Q=async e=>{try{await Ve({modelType:e.modelType}),await F()}catch(e){console.error(e)}};return(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"setup-panel",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("div",{children:(0,Ca.jsx)("h2",{className:"text-base font-bold text-modiff-text",children:"Model Health"})}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(u,{size:15}),"data-testid":"setup-models",onClick:()=>j({nodeId:null,fieldKey:null}),children:"Models"}),(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(q,{size:15}),"data-testid":"setup-refresh",onClick:()=>{H()},children:"Refresh"})]})]}),(0,Ca.jsx)(Sa,{error:l,status:i}),(0,Ca.jsx)(Ma,{}),(0,Ca.jsx)(Ha,{}),L.length>0&&(0,Ca.jsxs)("section",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-current-issues",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("div",{children:(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Current issues"})}),(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(g,{size:15}),onClick:W,children:"Review all"})]}),L.map(e=>(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:[e.label," (",e.issues.length,")"]}),(0,Ca.jsx)("div",{className:"grid gap-2",children:e.issues.map(e=>(0,Ca.jsx)(ue,{tone:Za(e.severity),title:e.message,action:V(e),testId:`setup-current-issue-${e.id}`},e.id))})]},e.category))]}),R.length>0&&(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-downloads",children:[(0,Ca.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold",children:"Downloads"}),(0,Ca.jsxs)(Ya,{tone:I>0?"default":"warning",title:`${I} active model download${1===I?"":"s"}`,children:[I," active"]})]}),(0,Ca.jsx)("div",{className:"grid gap-2",children:R.map(([e,t])=>(0,Ca.jsx)(Qe,{repoId:e,progress:t,testId:`setup-download-${e}`},e))})]}),(0,Ca.jsxs)(bt,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-advanced-diagnostics",label:(0,Ca.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(S,{size:15,className:"text-hf-yellow"}),"Advanced diagnostics"]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-3",children:[(0,Ca.jsx)(ka.Suspense,{fallback:(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading migration tools…"}),children:(0,Ca.jsx)(Ka,{})}),T?(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"setup-workflow-model-health",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Current graph"}),(0,Ca.jsx)(Ya,{tone:"default",title:"Models referenced by the visible canvas graph are shown here.",children:"Contextual"})]}),(0,Ca.jsx)(Ge,{tone:D||B.length>0?"error":"success",title:D?"Graph needs attention":"Graph model checks",meta:Ua(D)||`${$.nodeCount} nodes, ${$.outputPathCount} connected output path${1===$.outputPathCount?"":"s"}.`,testId:"setup-current-graph-health",children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,Ca.jsxs)(Ya,{tone:$.outputPathCount>0?"success":"error",title:`${$.outputPathCount} connected output path${1===$.outputPathCount?"":"s"}.`,children:[$.outputPathCount," outputs"]}),(0,Ca.jsxs)(Ya,{tone:B.length>0?"warning":"success",title:`${E} detected model reference${1===E?"":"s"}.`,children:[E," models"]})]}),B.length>0&&(0,Ca.jsx)("div",{className:"grid gap-2 border-t border-modiff-border pt-2",children:B.map(e=>(0,Ca.jsx)(xa,{activeInstallCount:I,actionTestId:`setup-install-graph-requirement-${e.id}`,installProgress:n,onInstall:e=>U(e),onUseLocal:e=>j({nodeId:null,fieldKey:null,focus:{label:e.label,repo:e.repo,requirementId:e.id,source:"setup"}}),requirement:e,testId:`setup-graph-requirement-${e.id}`},e.id))})]})})]}):M?(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"setup-workflow-model-health",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Workflow model"}),(0,Ca.jsx)(Ya,{tone:"default",title:"Only models used by the current workflow are shown here.",children:"Contextual"})]}),_.map(({autoPlan:e,backendCapability:t,profile:a,status:s})=>(0,Ca.jsx)(ts,{activeInstallCount:I,autoPlan:e,form:m,backendCapability:t,hfDownloadProgress:n,onInstall:U,onUseLocal:e=>j({nodeId:null,fieldKey:null,focus:{label:e.label,repo:e.repo,requirementId:e.id,source:"setup"}}),onClearHistory:Q,profile:a,requirements:z,status:s},a.modelType))]}):(0,Ca.jsxs)("section",{className:"flex items-center gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-xs text-modiff-subtle-text","data-testid":"setup-workflow-model-empty",children:[(0,Ca.jsx)(g,{size:15,className:"shrink-0 text-modiff-subtle-text"}),(0,Ca.jsx)("span",{children:"Workflow model checks appear after you create, update, or restore a workflow."})]}),a&&(0,Ca.jsxs)(bt,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",label:(0,Ca.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(S,{size:15,className:"text-hf-yellow"}),"Diagnostics and scanned locations"]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-3",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"Scanned model locations"}),(a.locations||[]).map(e=>{let t=e.repo_count??e.file_count??0,a=void 0===e.repo_count?`${t} files`:`${t} repos`,s=[e.external_package_count?`${e.external_package_count} external packages`:null,e.compatible_hf_repo_count?`${e.compatible_hf_repo_count} HF-compatible repos`:null,e.model_file_bytes?`${Wa(e.model_file_bytes)} model weights`:null].filter(Boolean).join(" | ");return(0,Ca.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,Ca.jsxs)(Xa,{tone:e.exists?"muted":"warning",children:[e.label,": ",e.path||"default"," | ",e.exists?"exists":"missing"," |"," ",a," | ",!1===e.runnable?"discovered but not runnable":"runnable"]}),s&&(0,Ca.jsxs)(Xa,{children:[s," | ",Va(e.extension_counts)]}),e.reason&&!1===e.runnable&&(0,Ca.jsx)(Xa,{tone:"warning",children:e.reason}),e.error&&(0,Ca.jsx)(Xa,{tone:"error",children:e.error})]},`${e.label}-${e.path}`)})]}),(a.external_model_packages?.length??0)>0&&(0,Ca.jsxs)("section",{"data-testid":"setup-external-models",children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"Detected external packages"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:a.external_model_packages?.slice(0,8).map(e=>(0,Ca.jsxs)(Ge,{tone:e.runnable?"success":"warning",title:e.label,meta:`${e.format} | ${e.file_count??0} files | ${Wa(e.model_file_bytes)}`,children:[(0,Ca.jsx)(Xa,{children:e.path}),(0,Ca.jsx)(Xa,{tone:e.runnable?"success":"warning",children:e.reason})]},`${e.source}-${e.path}`))})]}),(a.hf_compatible_external_repos?.length??0)>0&&(0,Ca.jsxs)("section",{"data-testid":"setup-external-hf-repos",children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"HF-compatible external repos"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:a.hf_compatible_external_repos?.slice(0,8).map(e=>(0,Ca.jsxs)(Ge,{tone:"warning",title:e.repo_id,meta:e.source,children:[(0,Ca.jsx)(Xa,{children:e.path}),(0,Ca.jsx)(Xa,{tone:"warning",children:e.reason})]},`${e.source}-${e.path}`))})]})]})]})]})}function ts({activeInstallCount:e,autoPlan:t,form:a,backendCapability:s,hfDownloadProgress:i,onClearHistory:l,onInstall:n,onUseLocal:r,profile:o,requirements:d,status:c}){let u=Ie(t,a),m=pe(t,a),p=_e(t,a),f=t?p:c.runnable,h=u?.repo??o.defaultRepo,x=i[h],g=_t(x),b=s?.inpaintContract??o.inpaintContract,j=je(t,a),v=ce(t,a),y=f?"success":"unsuitable"===v.state?"error":"warning",w=f?"success":"error"===y?"error":"warning",k=m?.resolvedArtifact??m?.artifact??u?.repo??o.defaultRepo,C=f?j:g?"Installing":gt(x)?"Retry":u?.actionLabel??"Install",N=g||!f&&e>=2;return(0,Ca.jsx)(Ge,{testId:`setup-model-${o.modelType}`,tone:y,title:o.label,meta:k,action:(0,Ca.jsx)(Ya,{tone:w,title:f?j:u?.reason??u?.repo??j,disabled:N,progress:g?Vt(x):null,testId:`setup-install-${o.modelType}`,onClick:!f&&u?()=>{n(u)}:void 0,children:C}),children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,Ca.jsx)(Ya,{tone:c.runnable?"success":"warning",title:c.reason,children:c.runnable?"Cached":"Missing"}),(0,Ca.jsx)(Ya,{tone:f?"success":"error"===y?"error":"warning",title:t?.blockingReason||m?.reason||u?.reason||t?.willNotWorkReason||j,children:"Auto"}),(0,Ca.jsx)(Ya,{tone:s?"success":"warning",title:s?`Backend modes: ${(s.modes||[]).join(", ")}`:"Backend capability metadata not reported for this profile.",children:"Backend"}),(0,Ca.jsx)(Ya,{tone:"success"===v.severity?"success":"error"===v.severity?"error":"info"===v.severity?"default":"warning",title:`${v.summary} ${v.detail}`,children:"Compatibility"}),b&&(0,Ca.jsx)(Ya,{tone:b.available?"success":"warning",title:b.available?"Native mask execution available.":b.reason,children:"Inpaint"})]}),c.matchingExternalPackages.length>0&&(0,Ca.jsx)(Ya,{tone:"warning",title:`Matching external package: ${c.matchingExternalPackages.slice(0,3).join(", ")}`,children:"External package"}),c.matchingExternalRepos.length>0&&(0,Ca.jsx)(Ya,{tone:"warning",title:`Matching HF-compatible external repo: ${c.matchingExternalRepos.slice(0,3).join(", ")}`,children:"External repo"}),x&&(0,Ca.jsx)(Qe,{testId:`setup-download-progress-${o.modelType}`,repoId:h,progress:x}),(t?.failureHistory?.length??0)>0&&(0,Ca.jsx)("div",{children:(0,Ca.jsx)(Ht,{tone:"secondary","data-testid":`setup-clear-auto-history-${o.modelType}`,onClick:()=>{l(o)},children:"Clear Auto history"})}),d.length>0&&(0,Ca.jsx)("div",{className:"grid gap-2 border-t border-modiff-border pt-2",children:d.map(t=>(0,Ca.jsx)(xa,{activeInstallCount:e,actionTestId:`setup-install-requirement-${t.id}`,installProgress:i,onInstall:e=>n(e),onUseLocal:r,requirement:t,testId:`setup-model-requirement-${t.id}`},t.id))})]})})}function as({children:e,disabled:t,icon:a,onClick:s,testId:i}){return(0,Ca.jsx)(Ht,{tone:"primary",icon:a,"data-testid":i,disabled:t,onClick:s,children:(0,Ca.jsx)("span",{children:e})})}function ss(e){if("number"!=typeof e||!Number.isFinite(e))return"-";if(e<1e3)return`${Math.max(0,Math.round(e))}ms`;let t=e/1e3;return t<60?`${t.toFixed(+(t<10))}s`:`${Math.floor(t/60)}:${Math.round(t%60).toString().padStart(2,"0")}`}function is(e){return"number"==typeof e&&Number.isFinite(e)?ss(1e3*e):null}function ls(e){return"number"==typeof e.durationMs?e.durationMs:e.completedAtMs&&e.startedAtMs?Math.max(0,e.completedAtMs-e.startedAtMs):void 0}function ns({children:e,fallbackStatus:t,focused:a=!1,pending:s=!1,severity:i="default",task:l,taskId:n,testId:r}){if(!l)return null;let o=re(l,n),d=ia(at(l))||l.error||l.message||`${o} · ${t}`;return(0,Ca.jsx)(sa,{content:d,placement:"top",children:c=>(0,Ca.jsx)(Ht,{...c,align:"left",fullWidth:!0,tone:"secondary",loading:s,"data-testid":r,"aria-label":`Open ${o} run details. ${d}`,onClick:()=>{tt(se(l,n,t))},className:ve("h-auto! min-w-0 rounded-none p-2","success"===i&&"border-modiff-green/60","error"===i&&"border-modiff-red/70 bg-modiff-red/10 hover:border-modiff-red",a&&"ring-2 ring-hf-yellow"),children:e})})}function rs(){let e=te(e=>e.currentTask),t=te(e=>e.queuedTasks),a=te(e=>e.failedTasks),i=te(e=>e.sessionRuns),l=te(e=>e.fetchTasks),n=te(e=>e.clearCompletedSessionRuns),r=te(e=>e.focusedTaskId),o=Je(e=>e.runActivityPendingTaskId),d=Object.entries(t),c=Object.entries(a).slice(0,8),u=i.filter(e=>"completed"===e.status||"failed"===e.status||"cancelled"===e.status).slice(0,10);return(0,ka.useEffect)(()=>{l()},[l]),(0,ka.useEffect)(()=>{r&&document.getElementById(`queue-task-${r}`)?.scrollIntoView({block:"nearest",behavior:"smooth"})},[r,e,t,i,a]),(0,Ca.jsxs)("div",{className:"p-3 text-sm text-modiff-text","data-testid":"queue-panel",children:[(0,Ca.jsxs)("div",{className:"mb-2 flex flex-wrap gap-2",children:[(0,Ca.jsx)(as,{icon:(0,Ca.jsx)(q,{size:15}),testId:"queue-refresh",onClick:()=>{l()},children:"Refresh"}),(0,Ca.jsx)(as,{icon:(0,Ca.jsx)(s,{size:15}),testId:"queue-stop",onClick:()=>{(async()=>{try{Ae((await ee()).message||"Stop requested",{variant:"success",autoHideDuration:3e3})}catch(e){Ae(oe(e,"Could not stop the current execution."),{variant:"error",autoHideDuration:5e3})}})()},disabled:!e,children:"Stop"})]}),(0,Ca.jsx)("h2",{className:"mb-2 text-sm font-bold",children:"Current run"}),e?(0,Ca.jsx)(ns,{fallbackStatus:"running",focused:r===e.task_id,pending:o===e.task_id,task:e,taskId:e.task_id||"current",testId:"queue-current-run",children:(0,Ca.jsxs)("span",{id:`queue-task-${e.task_id||"current"}`,className:"block min-w-0 flex-1",children:[(0,Ca.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,Ca.jsxs)("span",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:re(e,e.task_id||"Running task")}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.message||e.task_id||e.sid})]}),(0,Ca.jsx)(I,{size:16,className:"flex-none text-hf-yellow"})]}),(e.current_step||e.eta_seconds||e.average_step_seconds)&&(0,Ca.jsxs)("span",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-modiff-subtle-text",children:[e.current_step&&e.total_steps?(0,Ca.jsx)("span",{children:`Step ${e.current_step}/${e.total_steps}`}):null,is(e.eta_seconds)?(0,Ca.jsx)("span",{children:`ETA ${is(e.eta_seconds)}`}):null,is(e.average_step_seconds)?(0,Ca.jsx)("span",{children:`${is(e.average_step_seconds)}/step`}):null]}),(0,Ca.jsx)(Ut,{value:e.progress,className:"mt-2"})]})}):(0,Ca.jsx)("p",{className:"mb-4 text-xs text-modiff-subtle-text",children:"No current run."}),(0,Ca.jsx)("h2",{className:"mb-2 text-sm font-bold",children:"Queued runs"}),0===d.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No queued runs."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:d.map(([e,t])=>(0,Ca.jsxs)("div",{id:`queue-task-${e}`,"data-testid":`queue-run-${e}`,className:ve("flex items-stretch border border-modiff-border bg-modiff-surface",r===e&&"ring-2 ring-hf-yellow"),children:[(0,Ca.jsx)(Ht,{align:"left",fullWidth:!0,tone:"ghost",loading:o===(t.task_id||e),"aria-label":`Open ${re(t,e)} run details`,onClick:()=>{tt(se(t,e,"queued"))},className:"h-auto! min-w-0 flex-1 rounded-none p-2",children:(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:re(t,e)}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:t.task_id||t.sid})]})}),(0,Ca.jsx)(Ht,{tone:"ghost",size:"dense",title:"Cancel queued task",onClick:()=>{(async e=>{try{await zt(e),Ae("Queued task cancelled",{variant:"success",autoHideDuration:2200}),await l()}catch(e){Ae(oe(e,"Could not cancel the queued task."),{variant:"error",autoHideDuration:5e3})}})(e)},icon:(0,Ca.jsx)(R,{size:15}),className:"h-auto! flex-none rounded-none border-l border-modiff-border px-2 text-modiff-subtle-text",children:(0,Ca.jsx)("span",{children:"Cancel"})})]},e))}),(0,Ca.jsxs)("div",{className:"mb-2 mt-4 flex items-center justify-between gap-2",children:[(0,Ca.jsx)("h2",{className:"text-sm font-bold",children:"Session history"}),(0,Ca.jsx)(Ht,{tone:"ghost",size:"dense",disabled:0===u.length,onClick:n,icon:(0,Ca.jsx)(L,{size:14}),className:"px-2 text-xs",children:"Clear finished"})]}),0===u.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Completed runs will appear here for this browser session."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:u.map(e=>(0,Ca.jsx)(ns,{fallbackStatus:e.status??"completed",focused:r===(e.task_id||e.id),pending:o===(e.task_id||e.id),severity:"failed"===e.status?"error":"completed"===e.status?"success":"default",task:e,taskId:e.task_id||e.id,testId:`queue-session-run-${e.id}`,children:(0,Ca.jsx)("span",{id:`queue-task-${e.task_id||e.id}`,className:"block min-w-0 flex-1",children:(0,Ca.jsxs)("span",{className:"flex items-start gap-2",children:["completed"===e.status?(0,Ca.jsx)(O,{size:16,className:"mt-0.5 flex-none text-modiff-green"}):(0,Ca.jsx)(R,{size:16,className:"mt-0.5 flex-none text-modiff-red"}),(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:re(e,e.task_id||e.id)}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.error||e.message||e.task_id||e.sid})]}),(0,Ca.jsx)("span",{className:"flex-none text-xs font-semibold text-modiff-subtle-text",children:ss(ls(e))})]})})},e.id))}),(0,Ca.jsx)("h2",{className:"mb-2 mt-4 text-sm font-bold",children:"Failed runs"}),0===c.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No failed runs recorded in this session."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:c.map(([e,t])=>(0,Ca.jsx)(ns,{fallbackStatus:"failed",focused:r===e,pending:o===(t.task_id||e),severity:"error",task:t,taskId:e,testId:`queue-failed-run-${e}`,children:(0,Ca.jsxs)("span",{id:`queue-task-${e}`,className:"block min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm text-modiff-red",children:re(t,e)}),(0,Ca.jsx)("span",{className:"block break-all text-xs text-modiff-subtle-text",children:t.task_id||t.sid}),t.error&&(0,Ca.jsx)("span",{className:"block break-words text-xs text-modiff-red",children:t.error})]})},e))})]})}function os(){let e=(0,ka.useRef)(null),[t,a]=(0,ka.useState)(""),[s,i]=(0,ka.useState)(!1),{referenceImages:l,addReferenceImage:r,replaceReferenceImage:o,removeReferenceImage:d,moveReferenceImage:c,setReferenceImages:u,alphaMode:m,updateForm:p}=$t(nt(e=>({referenceImages:e.form.referenceImages,alphaMode:e.form.alphaMode,addReferenceImage:e.addReferenceImage,replaceReferenceImage:e.replaceReferenceImage,removeReferenceImage:e.removeReferenceImage,moveReferenceImage:e.moveReferenceImage,setReferenceImages:e.setReferenceImages,updateForm:e.updateForm})));return(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)($e,{title:"Image input workspace",action:(0,Ca.jsx)(dt,{title:"Upload images",onClick:()=>e.current?.click(),disabled:s,children:s?(0,Ca.jsx)(Ue,{size:18}):(0,Ca.jsx)(N,{size:16})})}),(0,Ca.jsx)(Et,{ref:e,"aria-label":"Upload reference images",accept:Ye(["image"]),multiple:!0,hidden:!0,onChange:e=>{(async e=>{if(!e||0===e.length)return;let t=ne();i(!0);try{let a=[];for(let s of Array.from(e))a.push(...await Wt(s,"images")),et(t);u([...$t.getState().form.referenceImages,...a]),aa(t),Re()}catch(e){if(De(e))return;Ae(oe(e,"Could not upload the reference image."),{variant:"error",autoHideDuration:5e3})}finally{i(!1)}})(e.target.files)}}),(0,Ca.jsxs)("div",{className:"mb-2 flex gap-2",children:[(0,Ca.jsx)(ut,{"aria-label":"Reference image path or URL",value:t,onChange:e=>a(e.target.value),placeholder:"Image path or URL",className:"flex-1"}),(0,Ca.jsx)(dt,{title:"Add image",onClick:()=>{r(t),a(""),queueMicrotask(()=>Re())},disabled:!t.trim(),children:(0,Ca.jsx)(y,{size:17})})]}),(0,Ca.jsx)(Ft,{"aria-label":"Reference image alpha handling",value:m,onValueChange:e=>{p({alphaMode:e}),queueMicrotask(()=>Re())},options:[{value:"ignore",label:"Alpha: ignore"},{value:"add alpha",label:"Alpha: add alpha"},{value:"remove alpha",label:"Alpha: remove alpha"}],className:"mb-2 w-full"}),(0,Ca.jsx)("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(86px,1fr))] gap-2",children:l.map((e,t)=>(0,Ca.jsxs)("div",{className:"border border-modiff-border bg-modiff-bg",children:[(0,Ca.jsx)(At,{src:Bt(e),alt:e,fit:"cover",aspectRatio:"1 / 1",bordered:!1}),(0,Ca.jsx)(ut,{"aria-label":`Reference image ${t+1} path`,value:e,onChange:e=>{o(t,e.target.value),queueMicrotask(()=>Re())},className:"h-7 w-full border-0 bg-transparent px-1 text-xs"}),(0,Ca.jsxs)("div",{className:"flex justify-between",children:[(0,Ca.jsx)(dt,{title:"Move up",disabled:0===t,onClick:()=>{c(t,-1),queueMicrotask(()=>Re())},children:(0,Ca.jsx)(n,{size:15})}),(0,Ca.jsx)(dt,{title:"Move down",disabled:t===l.length-1,onClick:()=>{c(t,1),queueMicrotask(()=>Re())},children:(0,Ca.jsx)(F,{size:15})}),(0,Ca.jsx)(dt,{title:"Remove",onClick:()=>{d(t),queueMicrotask(()=>Re())},children:(0,Ca.jsx)(L,{size:15})})]})]},`${e}-${t}`))})]})}function ds({isWorking:e,runBlocked:a,expertMode:s=!1,hasManagedForm:i=!0,hasComparePair:l,hasGalleryItems:n,onCompareLatest:o,onExport:d,onInterrupt:c,onRun:p,onUpdateGraph:f,onSavePrompt:h,onOpenGallery:x,onOpenTemplateGallery:g,onOpenSetup:b,onRestoreLatest:j,onRerunLatest:y}){let[w,k]=(0,ka.useState)(!1),[N,S]=(0,ka.useState)(""),I=(0,ka.useMemo)(()=>[{id:"run",label:"Run workflow",detail:"Queue the current Studio graph.",icon:(0,Ca.jsx)(D,{size:15}),disabled:e||a,run:p},...s&&i?[{id:"update",label:"Sync graph",detail:"Reconcile Studio fields with visible graph nodes.",icon:(0,Ca.jsx)(q,{size:15}),disabled:e,run:f}]:[],{id:"interrupt",label:"Interrupt run",detail:"Ask the backend to stop the active or queued execution.",icon:(0,Ca.jsx)(T,{size:15}),run:c},...i?[{id:"save-prompt",label:"Save prompt",detail:"Store the current prompt as a reusable snippet.",icon:(0,Ca.jsx)(C,{size:15}),run:h}]:[],...s?[{id:"export",label:"Export API graph",detail:"Download the current runnable graph JSON.",icon:(0,Ca.jsx)(G,{size:15}),run:d}]:[],{id:"gallery",label:"Open gallery",detail:"Inspect, compare, restore, rerun, and export outputs.",icon:(0,Ca.jsx)(r,{size:15}),run:x},{id:"compare",label:"Compare latest",detail:"Open the latest two Gallery outputs side by side.",icon:(0,Ca.jsx)(v,{size:15}),disabled:!l,run:o},{id:"restore-latest",label:"Restore latest",detail:"Restore the newest Gallery workflow into Studio.",icon:(0,Ca.jsx)(t,{size:15}),disabled:!n,run:j},{id:"rerun-latest",label:"Rerun latest",detail:"Restore and queue the newest Gallery workflow.",icon:(0,Ca.jsx)(D,{size:15}),disabled:!n||e||a,run:y},{id:"templates",label:"Browse templates",detail:"Search categorized workflow templates for the current task.",icon:(0,Ca.jsx)(m,{size:15}),run:g},{id:"setup",label:"Open setup",detail:"Repair missing models and runtime readiness.",icon:(0,Ca.jsx)(u,{size:15}),run:b}],[s,i,l,n,e,o,d,c,x,b,g,j,y,p,h,f,a]),R=(0,ka.useMemo)(()=>{let e=N.trim().toLowerCase();return e?I.filter(t=>`${t.label} ${t.detail}`.toLowerCase().includes(e)):I},[I,N]);return(0,ka.useEffect)(()=>{let t=t=>{let s=t.ctrlKey||t.metaKey;s&&"k"===t.key.toLowerCase()&&(t.preventDefault(),k(!0)),s&&"Enter"===t.key&&!e&&!a&&(t.preventDefault(),p())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e,p,a]),(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(J,{tone:"ghost",fullWidth:!0,icon:(0,Ca.jsx)(m,{size:15}),onClick:()=>k(!0),children:"Command palette"}),(0,Ca.jsxs)(St,{open:w,onClose:()=>{k(!1),S("")},title:"Command palette",panelClassName:"max-w-xl",bodyClassName:"!p-2",children:[(0,Ca.jsx)(Ne,{autoFocus:!0,"aria-label":"Search commands",value:N,onChange:e=>S(e.target.value),onClear:()=>S(""),placeholder:"Search commands",className:"mb-2"}),(0,Ca.jsxs)("div",{className:"grid gap-1",children:[R.map(e=>(0,Ca.jsxs)(J,{tone:"ghost",align:"left",fullWidth:!0,disabled:e.disabled,onClick:()=>(e=>{e.disabled||(e.run(),k(!1),S(""))})(e),className:"h-auto border border-transparent px-2 py-2 hover:border-hf-yellow hover:bg-modiff-bg",children:[(0,Ca.jsx)("span",{className:"grid size-7 shrink-0 place-items-center text-hf-yellow",children:e.icon}),(0,Ca.jsxs)("span",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"block text-sm font-bold text-modiff-text",children:e.label}),(0,Ca.jsx)("span",{className:"block text-xs text-modiff-subtle-text",children:e.detail})]})]},e.id)),0===R.length&&(0,Ca.jsx)("p",{className:"p-2 text-xs text-modiff-subtle-text",children:"No matching commands."})]})]})]})}function cs(e){return"ready"===e?"success":"blocked"===e?"error":"default"}function us(e){return"ready"===e?"Ready":"draft"===e?"Draft":"blocked"===e?"Blocked":"Registry"}function ms({disabled:e=!1,form:t,onChange:a}){let[s,i]=(0,ka.useState)(null),l=Ze(e=>e.nodesRegistry),n=Object.keys(l).length>0,r=We[t.modelType],o=!!l[Jt.lora],d=!!l[Jt.upscaler],c=!!l[de],u=async(e,s)=>{let l={...t,...s};i(e);try{a(s),await ze(l),Ae("Controlled workflow prepared",{variant:"success",autoHideDuration:1800})}catch(e){Ae(String(e),{variant:"error",autoHideDuration:6500})}finally{i(null)}},m=async(e,t)=>{i(e);try{await t()}catch(e){Ae(String(e),{variant:"error",autoHideDuration:6500})}finally{i(null)}},f=[{id:"control",title:"ControlNet control image",detail:"Qwen Image plus Qwen ControlNet Union.",status:"ready",icon:(0,Ca.jsx)(y,{size:15}),button:"Use control",onClick:()=>u("control",{mode:"control_image",modelType:"QwenImageModularPipeline",controlImage:t.controlImage||t.referenceImages[0]||""})},{id:"lora",title:"LoRA adapter",detail:r.supportsLora?"Adds Lora -> ModelsLoader lora_list.":"Current model metadata does not support LoRA.",status:r.supportsLora?o||!n?"ready":"needs-registry":"blocked",icon:(0,Ca.jsx)(x,{size:15}),button:"Add block",onClick:r.supportsLora?()=>m("lora",()=>wa()):void 0},{id:"upscale",title:"Upscale finish",detail:"Adds Spandrel Upscaler and a second Preview.",status:d||!n?"ready":"needs-registry",icon:(0,Ca.jsx)(p,{size:15}),button:"Add block",onClick:()=>m("upscale",()=>ya())},{id:"inpaint",title:"Inpaint mask draft",detail:"Source image, mask image, Apply Mask, and image encode.",status:"draft",icon:(0,Ca.jsx)(z,{size:15}),button:"Prepare draft",onClick:()=>u("inpaint",{mode:"inpaint",modelType:"QwenImageEditModularPipeline",referenceImages:t.referenceImages,maskImage:t.maskImage})},{id:"strength",title:"Image-to-image strength sweep",detail:"Use edit mode, then run the sweep grid.",status:"ready",icon:(0,Ca.jsx)(w,{size:15}),button:"Edit sweep",onClick:()=>u("strength",{mode:"edit_image",modelType:"QwenImageEditModularPipeline",strength:t.strength||.65,randomSeed:!1})},{id:"multi-reference",title:"Multi-reference edit",detail:"Qwen Edit Plus with multiple source images.",status:"ready",icon:(0,Ca.jsx)(h,{size:15}),button:"Use refs",onClick:()=>u("multi-reference",{mode:"multi_image_reference_edit",modelType:"QwenImageEditPlusModularPipeline",referenceImages:t.referenceImages})},{id:"outpaint",title:"Outpaint canvas",detail:"Expands the source image, generates a boundary mask, and feeds Qwen inpaint.",status:c||!n?"ready":"needs-registry",icon:(0,Ca.jsx)(P,{size:15}),button:"Use outpaint",onClick:()=>u("outpaint",{mode:"outpaint",modelType:"QwenImageEditModularPipeline",referenceImages:t.referenceImages,aspectRatio:"16:9",width:1344,height:768,outpaintLeft:t.outpaintLeft||256,outpaintRight:t.outpaintRight||256,outpaintTop:t.outpaintTop||0,outpaintBottom:t.outpaintBottom||0,outpaintOverlap:t.outpaintOverlap||24,outpaintFeather:t.outpaintFeather||8})}];return(0,Ca.jsxs)("section",{"data-testid":"studio-controlled-workflows",children:[(0,Ca.jsx)($e,{title:"Controlled workflows"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:f.map(t=>{let a=s===t.id,i=e||null!==s||"blocked"===t.status||!t.onClick;return(0,Ca.jsx)("article",{className:"border border-modiff-border bg-modiff-bg p-2",children:(0,Ca.jsxs)("div",{className:"flex items-start gap-2",children:[(0,Ca.jsx)("div",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact bg-modiff-panel text-hf-yellow",children:t.icon}),(0,Ca.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,Ca.jsx)("h4",{className:"text-xs font-bold text-modiff-text",children:t.title}),(0,Ca.jsx)(ge,{tone:cs(t.status),children:us(t.status)})]}),(0,Ca.jsx)("p",{className:ve("mt-1 text-xs","blocked"===t.status?"text-hf-orange":"text-modiff-subtle-text"),children:t.detail})]}),(0,Ca.jsx)(J,{tone:"blocked"===t.status?"ghost":"secondary",icon:a?(0,Ca.jsx)(Ue,{size:14}):t.icon,disabled:i,onClick:()=>{t.onClick?.()},children:t.button})]})},t.id)})})]})}var ps=512,fs={25:"opacity-25",50:"opacity-50",75:"opacity-75",100:"opacity-100"};function hs({sourceImage:e,maskImage:a,onCancel:s,onSave:i}){let n=(0,ka.useRef)(null),r=(0,ka.useRef)(!1),[o,d]=(0,ka.useState)("brush"),[c,u]=(0,ka.useState)(34),[m,p]=(0,ka.useState)(50),[f,h]=(0,ka.useState)([]),[x,g]=(0,ka.useState)([]),j=()=>n.current?.toDataURL("image/png")??"",v=()=>{let e=j();e&&(h(t=>[e,...t].slice(0,20)),g([]))},y=e=>{let t=n.current,a=t?.getContext("2d");if(!t||!a)return;let s=new Image;s.onload=()=>{a.clearRect(0,0,ps,ps),a.fillStyle="black",a.fillRect(0,0,ps,ps),a.drawImage(s,0,0,ps,ps)},s.src=e};(0,ka.useEffect)(()=>{let e=n.current,t=e?.getContext("2d");!e||!t||(t.fillStyle="black",t.fillRect(0,0,ps,ps),a&&y(a))},[a]);let w=e=>{let t=n.current,a=t?.getContext("2d");if(!t||!a)return;let s=t.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*ps,l=(e.clientY-s.top)/s.height*ps;a.beginPath(),a.arc(i,l,c/2,0,2*Math.PI),a.fillStyle="brush"===o?"white":"black",a.fill()},k=e=>{r.current=!1,e.currentTarget.releasePointerCapture(e.pointerId)};return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Mask editor"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"relative aspect-square overflow-hidden border border-modiff-border bg-modiff-bg",children:[e&&(0,Ca.jsx)("img",{src:e,alt:"Source overlay",className:ve("absolute inset-0 h-full w-full object-contain",fs[m])}),(0,Ca.jsx)("canvas",{ref:n,width:ps,height:ps,className:"relative z-10 h-full w-full touch-none mix-blend-screen",onPointerDown:e=>{v(),r.current=!0,e.currentTarget.setPointerCapture(e.pointerId),w(e)},onPointerMove:e=>{r.current&&w(e)},onPointerUp:k,onPointerCancel:k})]}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,Ca.jsxs)(ge,{active:"brush"===o,onClick:()=>d("brush"),children:[(0,Ca.jsx)(A,{size:13})," Brush"]}),(0,Ca.jsxs)(ge,{active:"erase"===o,onClick:()=>d("erase"),children:[(0,Ca.jsx)(B,{size:13})," Erase"]}),(0,Ca.jsx)(ge,{onClick:()=>{let e=n.current,t=e?.getContext("2d");if(!e||!t)return;v();let a=t.getImageData(0,0,ps,ps);for(let e=0;e{let e=n.current,t=e?.getContext("2d");!e||!t||(v(),t.fillStyle="black",t.fillRect(0,0,ps,ps))},children:[(0,Ca.jsx)(L,{size:13})," Clear"]}),(0,Ca.jsxs)(ge,{onClick:()=>{let e=f[0];if(!e)return;let t=j();g(e=>t?[t,...e].slice(0,20):e),h(e=>e.slice(1)),y(e)},disabled:0===f.length,children:[(0,Ca.jsx)(t,{size:13})," Undo"]}),(0,Ca.jsxs)(ge,{onClick:()=>{let e=x[0];if(!e)return;let t=j();h(e=>t?[t,...e].slice(0,20):e),g(e=>e.slice(1)),y(e)},disabled:0===x.length,children:[(0,Ca.jsx)(b,{size:13})," Redo"]})]}),(0,Ca.jsx)(kt,{label:`Brush size: ${c}`,children:(0,Ca.jsx)(ke,{min:4,max:120,value:c,onChange:u})}),(0,Ca.jsxs)("div",{children:[(0,Ca.jsxs)("p",{className:"mb-1 text-xs text-modiff-subtle-text",children:["Source overlay: ",m,"%"]}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:[25,50,75,100].map(e=>(0,Ca.jsxs)(ge,{active:m===e,onClick:()=>p(e),children:[e,"%"]},e))})]}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(J,{tone:"primary",icon:(0,Ca.jsx)(C,{size:15}),onClick:()=>i(j()),children:"Save mask"}),(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(l,{size:15}),onClick:s,children:"Cancel"})]})]})]})}function xs({form:e}){let t=[["Seed",e.randomSeed?"Random on run, so exact examples cannot be promised.":`Locked to ${e.seed} for reruns.`],["Guidance",`${e.guidanceScale} balances prompt obedience against natural detail.`],["Steps",`${e.steps} sampling steps sets quality/runtime tradeoff.`],["Strength",`${e.strength} controls how much source images can change in edit workflows.`],["Size",`${e.width}x${e.height} changes composition and exactness hash.`],["Dtype",`${e.dtype} affects memory use and can affect reproducibility.`],["Model",Se[e.modelType]]];return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Parameter notes"}),(0,Ca.jsx)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2",children:t.map(([e,t])=>(0,Ca.jsxs)("div",{className:"flex items-start gap-2 text-xs",children:[(0,Ca.jsx)(g,{size:13,className:"mt-0.5 shrink-0 text-modiff-subtle-text"}),(0,Ca.jsxs)("p",{className:"min-w-0 text-modiff-subtle-text",children:[(0,Ca.jsxs)("span",{className:"font-semibold text-modiff-text",children:[e,":"]})," ",t]})]},e))})]})}var gs=["Describe the subject first, then composition, style, lighting, camera, and constraints.","Keep exact text short and put it in quotes when the model needs to render letters."],bs=[["Subject",["one clear subject","premium product","same character identity"]],["Composition",["centered composition","negative space","preserve composition"]],["Style",["cinematic realism","editorial design","minimal studio look"]]],js=[["Subject","subject"],["Environment","environment"],["Preserve","preservation"],["Change","change"],["Composition","composition"],["Texture / materials","materials"],["Style","style"],["Lighting","lighting"],["Camera","camera"],["Motion","motion"],["Continuity","continuity"],["Arrangement","arrangement"],["Mix","mix"],["Parameters","parameters"],["Text","textRendering"]];function vs({form:e,template:t,onChange:a}){let s=t?.promptGuide,i=s?js.map(([e,t])=>[e,s[t]]).filter(e=>Array.isArray(e[1])&&e[1].length>0):bs,l=s?.negative??["low quality","blurry","warped text","distorted anatomy"],n=s?.modelHints??gs,r=t=>{let s=e.prompt.trim();a({prompt:s?`${s}, ${t}`:t})},o=t=>{let s=e.negativePrompt.trim();a({negativePrompt:s?`${s}, ${t}`:t})};return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Prompt composer"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[i.map(([e,t])=>(0,Ca.jsxs)("fieldset",{children:[(0,Ca.jsx)("legend",{className:"mb-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:t.map(t=>(0,Ca.jsx)(ge,{"aria-label":`Add ${e.toLowerCase()} detail: ${t}`,onClick:()=>r(t),children:t},`${e}-${t}`))})]},e)),l.length>0&&(0,Ca.jsxs)("fieldset",{children:[(0,Ca.jsx)("legend",{className:"mb-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:"Avoid"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:l.map(e=>(0,Ca.jsx)(ge,{"aria-label":`Add negative prompt detail: ${e}`,onClick:()=>o(e),children:e},`negative-${e}`))})]}),n.length>0&&(0,Ca.jsx)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2","aria-label":"Prompt guidance",children:n.map(e=>(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:e},e))}),t&&(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>a({prompt:t.prompt,negativePrompt:t.negativePrompt??e.negativePrompt}),children:"Restore template prompt"})]})]})}function ys(e){return e.match(/\S+/g)||[]}function ws(e,t){let a=ys(e),s=ys(t),i=Array.from({length:a.length+1},()=>Array(s.length+1).fill(0));for(let e=a.length-1;e>=0;--e)for(let t=s.length-1;t>=0;--t){let l=a[e]??"",n=s[t]??"",r=i[e];r&&(r[t]=l===n?(i[e+1]?.[t+1]??0)+1:Math.max(i[e+1]?.[t]??0,r[t+1]??0))}let l=[],n=0,r=0;for(;n=(i[n]?.[r+1]??0)?(l.push({text:e,kind:"removed"}),n+=1):(l.push({text:t,kind:"added"}),r+=1)}for(;n[...a.map((e,t)=>({id:`snippet-${t}`,label:`Snippet ${t+1}`,prompt:e})),...t.map((e,t)=>({id:`history-${t}`,label:`History ${t+1}`,prompt:e}))].filter(t=>t.prompt.trim()&&t.prompt!==e),[e,t,a]),r=n.find(e=>e.id===i)||n[0],o=(0,ka.useMemo)(()=>r?ws(r.prompt,e):[],[e,r]),d=o.filter(e=>"added"===e.kind).length,c=o.filter(e=>"removed"===e.kind).length;return 0===n.length?null:(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)($e,{title:"Prompt diff",action:(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(ge,{tone:d?"success":"default",children:`+${d}`}),(0,Ca.jsx)(ge,{tone:c?"error":"default",children:`-${c}`})]})}),(0,Ca.jsx)(Ft,{"aria-label":"Prompt version to compare",value:r?.id||"",onValueChange:l,options:n.map(e=>({value:e.id,label:e.label})),className:"mb-2 w-full"}),(0,Ca.jsx)("div",{className:"max-h-40 overflow-y-auto border border-modiff-border bg-modiff-bg p-2",children:o.map((e,t)=>(0,Ca.jsx)("span",{className:ve("mb-1 mr-1 inline-block rounded-modiff-compact px-1 text-xs","same"===e.kind&&"text-modiff-subtle-text","added"===e.kind&&"bg-modiff-green/10 text-modiff-green","removed"===e.kind&&"bg-modiff-red/10 text-modiff-red line-through"),children:e.text},`${e.text}-${t}`))}),(0,Ca.jsxs)("div",{className:"mt-2 flex gap-2",children:[(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(E,{size:15}),onClick:()=>r&&function(e){navigator.clipboard.writeText(e),Ae("Prompt diff copied",{variant:"success",autoHideDuration:1800})}(function(e,t,a){let s=a.filter(e=>"added"===e.kind).map(e=>e.text).join(" "),i=a.filter(e=>"removed"===e.kind).map(e=>e.text).join(" ");return["Prompt diff","","Base:",e,"","Current:",t,"","Added:",s||"None","","Removed:",i||"None"].join("\n")}(r.prompt,e,o)),children:"Copy diff"}),(0,Ca.jsx)(J,{tone:"ghost",onClick:()=>r&&s(r.prompt),children:"Use baseline"})]})]})}function Cs(e){return e.split(",").map(e=>e.trim()).filter(Boolean)}function Ns(e,t){let a=new Set(e.map(e=>e.toLowerCase()));return t.forEach(t=>{let s=t.toLowerCase();a.has(s)||(a.add(s),e.push(t))}),e}function Ss(e){return"edit_image"===e.mode?["preserve source identity","match original lighting","localized edit"]:"multi_image_reference_edit"===e.mode?["coherent blend of references","consistent perspective","preserve strongest design details"]:"control_image"===e.mode?["follow the control image structure","clean edges","stable composition"]:"control_edit_image"===e.mode?["preserve source identity","follow the control image structure","stable composition"]:"control_inpaint"===e.mode?["edit only inside the mask","follow the control image structure","preserve unmasked areas"]:"inpaint"===e.mode?["edit only inside the mask","preserve unmasked areas","consistent texture"]:"layer_decomposition"===e.mode?["clean layer boundaries","separated foreground and background","editable alpha"]:["one clear subject","balanced composition","professional finish"]}function Is({form:e,template:t,onApply:s}){let[i,n]=(0,ka.useState)(null),r=(0,ka.useMemo)(()=>i?ws(e.prompt,i.prompt):[],[e.prompt,i]),o=r.filter(e=>"added"===e.kind).length,d=r.filter(e=>"removed"===e.kind).length;return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Prompt enhancer",action:i?(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(ge,{tone:o?"success":"default",children:`+${o}`}),(0,Ca.jsx)(ge,{tone:d?"error":"default",children:`-${d}`})]}):void 0}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>n(function(e,t){let a=Cs(e.prompt||t?.prompt||""),s=t?.promptGuide,i=[...Ss(e),s?.lighting?.[0],s?.camera?.[0],s?.style?.[0]].filter(e=>!!e);return{prompt:Ns(a.length>0?a:["A polished image"],i).join(", "),negativePrompt:Ns(Cs(e.negativePrompt),s?.negative?.slice(0,3)??["low quality","blurry","artifacts"]).join(", ")}}(e,t)),children:"Suggest"}),i&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(J,{tone:"primary",icon:(0,Ca.jsx)(a,{size:15}),onClick:()=>{s(i),n(null)},children:"Apply"}),(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(E,{size:15}),onClick:()=>function(e){navigator.clipboard.writeText(e),Ae("Enhanced prompt copied",{variant:"success",autoHideDuration:1800})}(`${i.prompt}\n\nNegative:\n${i.negativePrompt}`),children:"Copy"}),(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(l,{size:15}),onClick:()=>n(null),children:"Dismiss"})]})]}),i&&(0,Ca.jsxs)("div",{className:"grid gap-2 border border-modiff-border bg-modiff-bg p-2","data-testid":"studio-prompt-enhancer-diff",children:[(0,Ca.jsx)("div",{className:"max-h-40 overflow-y-auto",children:r.map((e,t)=>(0,Ca.jsx)("span",{className:ve("mb-1 mr-1 inline-block rounded-modiff-compact px-1 text-xs","same"===e.kind&&"text-modiff-subtle-text","added"===e.kind&&"bg-modiff-green/10 text-modiff-green","removed"===e.kind&&"bg-modiff-red/10 text-modiff-red line-through"),children:e.text},`${e.text}-${t}`))}),(0,Ca.jsxs)("div",{className:"grid gap-1 border-t border-modiff-border pt-2",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:"Negative"}),(0,Ca.jsx)("p",{className:"break-words text-xs text-modiff-subtle-text",children:i.negativePrompt||"None"})]})]})]})]})}function Rs({disabled:e=!1,form:t,template:a,onChange:s,onRunSweep:i}){let l=!!a&&mt(a,t),n=st.includes(t.mode),r="edit_image"===t.mode||"multi_image_reference_edit"===t.mode||"inpaint"===t.mode||"control_edit_image"===t.mode||"control_inpaint"===t.mode||"layer_decomposition"===t.mode?[{label:"Lower strength",detail:`Strength ${Math.max(0,Number((t.strength-.1).toFixed(2)))}`,values:{strength:Math.max(0,Number((t.strength-.1).toFixed(2)))}},{label:"Higher strength",detail:`Strength ${Math.min(1,Number((t.strength+.1).toFixed(2)))}`,values:{strength:Math.min(1,Number((t.strength+.1).toFixed(2)))}}]:[],o=n?[{label:"Lower conditioning",detail:`Conditioning ${Math.max(0,Number((t.conditioningScale-.15).toFixed(2)))}`,values:{conditioningScale:Math.max(0,Number((t.conditioningScale-.15).toFixed(2)))}},{label:"Higher conditioning",detail:`Conditioning ${Math.min(2,Number((t.conditioningScale+.15).toFixed(2)))}`,values:{conditioningScale:Math.min(2,Number((t.conditioningScale+.15).toFixed(2)))}},{label:"Shorter clip",detail:`${Math.max(17,t.numFrames-32)} frames`,values:{numFrames:Math.max(17,t.numFrames-32)}},{label:"Quality clip",detail:"50 steps, 81 frames",values:{steps:50,numFrames:81,randomSeed:!1}}]:[],d=[{label:"Next seed",detail:`Seed ${t.seed+1}`,values:{seed:t.seed+1,randomSeed:!1}},{label:"Lower guidance",detail:`Guidance ${Math.max(0,Number((t.guidanceScale-.5).toFixed(1)))}`,values:{guidanceScale:Math.max(0,Number((t.guidanceScale-.5).toFixed(1)))}},{label:"Higher guidance",detail:`Guidance ${Math.min(10,Number((t.guidanceScale+.5).toFixed(1)))}`,values:{guidanceScale:Math.min(10,Number((t.guidanceScale+.5).toFixed(1)))}},{label:"Quality pass",detail:`${Math.min(80,t.steps+12)} steps`,values:{steps:Math.min(80,t.steps+12)}},...r,...o];return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Variation planner"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:l?"Current settings match the locked template. Any sweep below will become Modified.":"Current settings already differ from the locked template or no active template is selected."}),(0,Ca.jsx)("div",{className:"grid grid-cols-2 gap-2",children:d.map((e,t)=>(0,Ca.jsx)(J,{tone:"ghost",align:"left",icon:0===t?(0,Ca.jsx)(k,{size:15}):(0,Ca.jsx)(w,{size:15}),onClick:()=>s(e.values),children:(0,Ca.jsxs)("span",{children:[(0,Ca.jsx)("span",{className:"block text-xs font-bold text-modiff-text",children:e.label}),(0,Ca.jsxs)("span",{className:"block text-xs text-hf-orange",children:[e.detail," | Modified"]})]})},e.label))}),(0,Ca.jsx)(J,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(k,{size:15}),disabled:e,onClick:()=>i(d),children:"Run sweep"})]})]})}function $s({issues:e}){let{installHfModel:t,refreshModelIndexes:a,hfDownloadProgress:s}=Ze(nt(e=>({installHfModel:e.installHfModel,refreshModelIndexes:e.refreshModelIndexes,hfDownloadProgress:e.hfDownloadProgress}))),i=we(e=>e.sid);return e.filter((t,a)=>"install_model"===t.action&&t.repoId&&e.findIndex(e=>"install_model"===e.action&&e.repoId===t.repoId&&JSON.stringify(e.installOptions??{})===JSON.stringify(t.installOptions??{}))===a).map(e=>{let l=e.repoId,n=_t(s[l]);return(0,Ca.jsxs)(J,{fullWidth:!0,tone:"secondary",disabled:n||!i,"data-testid":`studio-install-graph-model-${l}`,title:`${l}: ${e.message}`,onClick:()=>{(async()=>{try{await t(l,i,e.installOptions),await a(!0)}catch(e){Ae(oe(e,`Could not install ${l}.`),{variant:"error"})}})()},children:[n?"Installing":e.installOptions?.repair?"Repair":"Install"," ",l.split("/").pop()]},e.id)})}function Ms({form:e,hfCache:t,localModels:a,modelCacheDiagnostics:s,autoResourcePlan:i,backendCapabilities:l=[],backendCapabilitiesAuthoritative:n=!1}){let r=(0,ka.useMemo)(()=>{let t=H(e),a=l.find(t=>t.modelType===e.modelType);return He(a?{...t,...a}:t,e.mode)},[l,e]),o=(0,ka.useMemo)(()=>n?l.filter(t=>Me(t).includes(e.mode)).map(e=>e.modelType):Ce(e.mode,{currentModelType:e.modelType}),[l,n,e.mode,e.modelType]),d=(0,ka.useMemo)(()=>{if(!n)return r.modes;let t=l.find(t=>t.modelType===e.modelType);return t?Me(t):[]},[l,n,r.modes,e.modelType]),c=(0,ka.useMemo)(()=>qe(r,t,a,s),[r,t,a,s]),u=(0,ka.useMemo)(()=>Xe({form:e,autoResourcePlan:i,hfCache:t,localModels:a,modelCacheDiagnostics:s,includePipeline:!1}),[i,e,t,a,s]),m=r.modeRequirements?.[e.mode]?.requiredImages??[],p=m.includes("referenceImages"),f=m.includes("maskImage"),h=m.includes("controlImage"),x=m.includes("ipAdapterImage"),g=p||"control_image"===e.mode||"inpaint"===e.mode||"layer_decomposition"===e.mode,b=r.supportsMask,j=r.inpaintContract,v=u.find(e=>!e.status.runnable),y=(0,ka.useMemo)(()=>"auto"===e.resourceMode?Ie(i,e):null,[i,e]),w=1===r.revisionCandidates?.length?r.revisionCandidates[0]:void 0;return{capability:r,compatibleModels:o,compatibleModes:d,showImageTray:g,requiresMaskImage:f,requiresControlImage:h,requiresIPAdapterImage:x,supportsMask:b,inpaintContract:j,missingInstallTarget:y??("auto"===e.resourceMode||!1===r.artifactInstallRequired||c.runnable?v?{repo:v.repo,label:v.label}:null:{repo:r.defaultRepo,label:r.label,revision:w,files:r.downloadFiles})}}var Ts=[{label:"1:1",width:1024,height:1024},{label:"4:3",width:1152,height:864},{label:"3:4",width:864,height:1152},{label:"16:9",width:1344,height:768},{label:"9:16",width:768,height:1344}];function As(e,t){let a=Number(e);return Number.isFinite(a)?a:t}function Ps(){let[e,t]=(0,ka.useState)(!1),a=ja(),[s,i]=(0,ka.useState)(!1),l=(0,ka.useRef)(null),[n,r]=(0,ka.useState)(0),o=Je(e=>e.setRightPanelOpen),d=Je(e=>e.setRightPanelTab),c=Je(e=>e.setLightboxOpener),u=Je(e=>e.setTemplateBrowserOpen),p=Je(e=>e.setGalleryLibraryOpen),h=Pt(e=>e.showIssues),{sid:x,isConnected:b}=we(nt(e=>({sid:e.sid,isConnected:e.isConnected}))),{hfCache:j,localModels:v,modelCacheDiagnostics:y,runtimeStatus:w,nodesRegistry:k,studioModelCapabilities:N,studioModelCapabilitiesAuthoritative:S,studioExecutionSpecInvalid:I,installHfModel:R}=Ze(nt(e=>({hfCache:e.hfCache,localModels:e.localModels,modelCacheDiagnostics:e.modelCacheDiagnostics,runtimeStatus:e.runtimeStatus,nodesRegistry:e.nodesRegistry,studioModelCapabilities:e.studioModelCapabilities,studioModelCapabilitiesAuthoritative:e.studioModelCapabilitiesAuthoritative,studioExecutionSpecInvalid:e.studioExecutionSpecInvalid,installHfModel:e.installHfModel}))),{form:$,autoResourcePlan:M,promptHistory:T,savedSnippets:A,negativePromptPresets:P,activeTemplateId:_,activeWorkflowTabId:z,outputs:q,lastError:B,recentChange:D,pinnedGraphInputIds:G,workflowCanvasHydrated:O,applyPreset:F,addPromptHistory:H,togglePinnedGraphInput:W,saveCurrentPromptAsSnippet:Q,removeSnippet:X,applySnippet:Y,applyNegativePreset:te,detachManagedGraph:ae}=$t(nt(e=>({form:e.form,promptHistory:e.promptHistory,savedSnippets:e.savedSnippets,negativePromptPresets:e.negativePromptPresets,autoResourcePlan:e.autoResourcePlan,activeTemplateId:e.activeTemplateId,activeWorkflowTabId:e.activeWorkflowTabId,outputs:e.outputs,lastError:e.lastError,recentChange:e.recentChange,pinnedGraphInputIds:e.pinnedGraphInputIds,workflowCanvasHydrated:e.workflowCanvasHydrated,applyPreset:e.applyPreset,addPromptHistory:e.addPromptHistory,togglePinnedGraphInput:e.togglePinnedGraphInput,saveCurrentPromptAsSnippet:e.saveCurrentPromptAsSnippet,removeSnippet:e.removeSnippet,applySnippet:e.applySnippet,applyNegativePreset:e.applyNegativePreset,detachManagedGraph:e.detachManagedGraph}))),se=(0,ka.useMemo)(()=>Gt.find(e=>e.id===_),[_]),ie=(0,ka.useMemo)(()=>V(q,z),[z,q]),le=(0,ka.useMemo)(()=>wt.filter(e=>{let t=!!e.compatibleModes?.some(e=>st.includes(e)),a=!!e.compatibleModes?.some(e=>Pe.includes(e));if(st.includes($.mode)&&!t||Pe.includes($.mode)&&!a)return!1;let s=!e.compatibleModes||e.compatibleModes.includes($.mode),i=!e.compatibleModelTypes||e.compatibleModelTypes.includes($.modelType);return s&&i}),[$.mode,$.modelType]),re=st.includes($.mode),de=Pe.includes($.mode),ce="unconditional_image"===$.mode,pe="depth_estimation"===$.mode,xe=be.includes($.mode),je=he.includes($.mode),Ce=!ce&&!pe&&!xe&&!1!==We[$.modelType].supportsPrompt,Ne=Qt(We[$.modelType]),Ie=Kt(We[$.modelType],$),Me=vt(We[$.modelType]),_e=Rt(N,I,$),qe=_e?.available_expert_quantization_modes??_e?.expert_quantization_modes??[],Be=`${Ie}. ${Ne} defaults to ${We[$.modelType].recommendedSteps} steps, ${We[$.modelType].guidanceLabel.toLowerCase()} ${We[$.modelType].recommendedGuidance}, ${We[$.modelType].defaultDtype}. ${Me}`,Ge=$t(e=>e.graphBinding),Ee=$t(e=>e.graphFinalization),Le=Ge?me($):null,He=Ee??(Le?{status:"warning",message:Le}:null),Ve=$t(e=>e.canvasTransition),Ue="template_graph_building"===Ve?.type&&Ve.workflowTabId===z;rt(nt(e=>({nodes:e.nodes.map(e=>{let t=Object.entries(e.data.params).filter(([e])=>/repo|model|checkpoint|ckpt|safetensors|lora|vae|controlnet|adapter/i.test(e)).map(([e,t])=>`${e}:${JSON.stringify(t.value??t.default??"")}`).join(",");return`${e.id}:${e.data.module}:${e.data.action}:${e.data.uiState?.disabled?"disabled":"enabled"}:${t}`}).join("|"),edges:e.edges.map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}->${e.target}:${e.targetHandle??""}`).join("|")})));let Qe=Ot(),Xe=O&&!Ue&&Ge?ye(Ge):null,Ye=Xe?`${Xe.kind}:${Xe.details??Xe.message}`:"",tt=O&&!Ue&&(!Ge&&Qe.nodeCount>0||!!Xe),at=Qe.modelRefs.length>0?`${new Set(Qe.modelRefs.map(e=>`${e.kind}:${e.value}`)).size} model refs`:"Graph-defined",lt=ea({sid:x,isConnected:b,includeStudio:!tt}),mt=(0,ka.useMemo)(()=>Z(lt.issues),[lt.issues]),pt=lt.blockingIssues.length>0?`${lt.blockingIssues.length} issue${1===lt.blockingIssues.length?"":"s"}`:lt.warningIssues.length>0?`${lt.warningIssues.length} warning${1===lt.warningIssues.length?"":"s"}`:void 0,ht=rt(nt(e=>e.nodes)),gt=O&&!Ue&&!_&&0===ht.length,jt=(0,ka.useMemo)(()=>ht.filter(e=>e.selected),[ht]),St=(0,ka.useMemo)(()=>ga(ht,G),[ht,!0,G]),Mt=G.filter(e=>St.some(t=>t.id===e)),At=(0,ka.useMemo)(()=>{let e=new Set(Mt);return St.filter(t=>e.has(t.id))},[Mt,St]),{capability:_t,compatibleModels:zt,compatibleModes:Bt,showImageTray:Dt,requiresMaskImage:Et,requiresControlImage:Lt,requiresIPAdapterImage:Ht,supportsMask:Wt,inpaintContract:Vt,missingInstallTarget:Ut}=Ms({form:$,hfCache:j,localModels:v,modelCacheDiagnostics:y,autoResourcePlan:M,backendCapabilities:N,backendCapabilitiesAuthoritative:S}),Jt=_t.modeRequirements?.[$.mode]?.requiredVideos??[],Zt=Jt.includes("sourceVideo"),ta=Jt.includes("referenceVideos"),sa=Jt.includes("controlVideo"),ia=lt.blockingIssues[0]?.message??"",la=!lt.canRun,ra=!tt&&!gt,{updateAndSync:oa,handleCreateGraph:da,handleModeChange:ca,handleModelTypeChange:ua,handleRun:ma,handleInstallMissingModel:xa,isInstallingMissingModel:ya,openSetup:wa}=yt({sid:x,isConnected:b,missingInstallTarget:Ut,installHfModel:R,setIsWorking:t}),Na=(e,t=$)=>{let s=xt(t);a.request("run",s,e)};(0,ka.useEffect)(()=>{!O||Ue||Nt({sid:x,isConnected:b,includeStudio:!0,showDialog:!1})},[x,b,$,Ge,Ee,j,v,y,w,k,Ue,O]),(0,ka.useEffect)(()=>{!Ge||!Xe||"pending"===Ee?.status||"template_graph_building"===Ve?.type||ae()},[Ve?.type,ae,Ge,Xe,Ye,Ee?.status]),(0,ka.useEffect)(()=>{if(!w)return;let e=Ct(w);e===$.device||qt(w,$.device)||$.device!==Oe.device&&!$.device.toLowerCase().startsWith("cuda")||oa({device:e})},[$.device,w,oa]);let Sa=(0,ka.useCallback)(e=>{let t=$t.getState().form,a="low_vram"===e.id?{...e,values:{...e.values,...ft(t)}}:e;F(a);let s=$t.getState().form,i=ha(t,s,Object.keys(a.values)),l=t.quantizationMode!==s.quantizationMode||t.resourceMode!==s.resourceMode;queueMicrotask(()=>{l?ze(s):Re(s)}),fa(`${e.label} applied`,i,$t.getState().graphBinding?.managedNodeIds??[]),i.length>0&&Ae(`${e.label} updated ${i.map(e=>e.label).join(", ")}`,{variant:"success",autoHideDuration:2600})},[F]),Ia=(0,ka.useCallback)(()=>{p(!0)},[p]),Ra=(0,ka.useCallback)(()=>{u(!0)},[u]),$a=(0,ka.useCallback)(async()=>{try{let e=await ee();Ae("string"==typeof e.message&&e.message.trim()?e.message:"Interrupt requested",{variant:"success",autoHideDuration:3e3})}catch(e){Ae(oe(e,"Could not stop the current execution."),{variant:"error",autoHideDuration:5e3})}},[]),Ma=(0,ka.useCallback)(()=>{if(!x)return void Ae("Connect to the MoDiff server before exporting the API graph.",{variant:"error",autoHideDuration:3e3});let e=Xt(rt.getState().exportGraph(x)),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),a=document.createElement("a");a.href=URL.createObjectURL(t),a.download="modiff-api-graph.json",a.click(),URL.revokeObjectURL(a.href)},[x]),Ta=(0,ka.useCallback)(()=>{let e=$t.getState(),t=Tt(e.outputs,e.activeWorkflowTabId,{includeUnscopedFallback:!1});t&&($t.getState().restoreWorkflowFromOutput(t),o(!0),d("studio"),Ae("Latest Gallery workflow restored",{variant:"success",autoHideDuration:2e3}))},[o,d]),Aa=(0,ka.useCallback)(async()=>{let e=$t.getState(),a=Tt(e.outputs,e.activeWorkflowTabId,{includeUnscopedFallback:!1});if(a&&x&&b){t(!0);try{$t.getState().restoreWorkflowFromOutput(a);let e=ne();if(!await K(e))return;await It({sid:x,studioContext:{forceDeterministic:!a.formSnapshot.randomSeed},workflowContext:e})}catch(e){if(De(e))return;Ae(String(e),{variant:"error",autoHideDuration:6e3})}finally{t(!1)}}else Ae("Connect to the MoDiff server and keep a Gallery output available before rerunning.",{variant:"error",autoHideDuration:4e3})},[b,x]),Pa=(0,ka.useCallback)(()=>{let e=$t.getState(),[t,a]=V(e.outputs,e.activeWorkflowTabId);!t||!a||c(Yt([a.url,t.url],1))},[c]),_a=(0,ka.useCallback)(()=>{h(lt.issues)},[lt.issues,h]),za=(0,ka.useCallback)(async e=>{if(!x||!b)return void Ae("Connect to the MoDiff server before running a sweep.",{variant:"error",autoHideDuration:4e3});if(ia)return void Ae(ia,{variant:"error",autoHideDuration:5e3});let a={...$t.getState().form,referenceImages:[...$t.getState().form.referenceImages]},s=ne(),i=`sweep-${Date.now()}`;t(!0),$t.getState().addPromptHistory(a.prompt);try{for(let t of e){et(s);let e={...t.values,randomSeed:!1};$t.getState().updateForm(e),aa(s);let a=$t.getState().form;if(Re(a),!await K(s))break;await Fe($t.getState().form,s),et(s);let{response:l}=await It({sid:x,workflowContext:s,studioContext:{forceDeterministic:!0,variation:{variationGroupId:i,variationLabel:t.label}}});if(et(s),l.error){$t.getState().setLastError(l.message||"MoDiff could not queue this sweep variation.");break}}Ae("Variation sweep queued",{variant:"success",autoHideDuration:2200})}catch(e){if(De(e))return;let t=String(e);$t.getState().setLastError(t),Ae(t,{variant:"error",autoHideDuration:7e3})}finally{Te(s)&&($t.getState().updateForm(a),aa(s),Re(a),await ze(a,s).catch(e=>{De(e)||console.error("Could not restore the sweep graph",e)})),t(!1)}},[b,ia,x]);return(0,ka.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let t=()=>{let t=Math.ceil(e.getBoundingClientRect().height);r(e=>e===t?e:t)};if(t(),typeof ResizeObserver>"u")return;let a=0,s=new ResizeObserver(()=>{window.cancelAnimationFrame(a),a=window.requestAnimationFrame(t)});return s.observe(e),()=>{window.cancelAnimationFrame(a),s.disconnect()}},[]),(0,Ca.jsxs)("div",{className:"flex flex-col gap-3 p-3","data-testid":"studio-panel",children:[(0,Ca.jsxs)("div",{ref:l,className:"sticky top-0 z-20 -mx-3 -mt-3 grid gap-2 border-b border-modiff-border bg-modiff-bg p-3 shadow-modiff-node","data-testid":"studio-sticky-header",children:[(0,Ca.jsx)(ds,{isWorking:e,runBlocked:la,expertMode:!0,hasManagedForm:ra,hasGalleryItems:ie.length>0,hasComparePair:ie.length>1,onRun:()=>{Na(ma)},onInterrupt:()=>{$a()},onUpdateGraph:()=>{da()},onExport:Ma,onSavePrompt:Q,onOpenGallery:Ia,onOpenTemplateGallery:Ra,onOpenSetup:wa,onRestoreLatest:Ta,onRerunLatest:()=>{Na(Aa,ie[0]?.formSnapshot)},onCompareLatest:Pa}),He&&"complete"!==He.status&&"idle"!==He.status&&(0,Ca.jsxs)(Ke,{severity:"error"===He.status?"error":"warning"===He.status?"warning":"info",testId:"studio-graph-finalization",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold text-modiff-text",children:"pending"===He.status?"Finalizing graph...":"warning"===He.status?"Graph still finalizing":"Graph finalization failed"}),(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:He.message||"Preparing dynamic fields and managed links in the background."})]}),B&&(0,Ca.jsx)(Ke,{severity:"error",children:(0,Ca.jsxs)("div",{className:"flex items-start gap-2",children:[(0,Ca.jsx)(bt,{className:"min-w-0 flex-1",label:"Last error",buttonClassName:"min-h-0 justify-start p-0 text-xs text-modiff-invalid hover:bg-transparent",panelClassName:"mt-1",children:(0,Ca.jsx)("p",{className:"mt-1 max-h-28 overflow-auto break-words text-xs text-modiff-red",children:B})}),(0,Ca.jsx)(dt,{title:"Copy error",onClick:()=>function(e){navigator.clipboard.writeText(e),Ae("Error copied",{variant:"success",autoHideDuration:1800})}(B),children:(0,Ca.jsx)(E,{size:15})})]})})]}),(0,Ca.jsx)(ct,{id:"task",title:"Task",defaultOpen:!0,children:gt?(0,Ca.jsxs)("div",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"studio-empty-workflow",children:[(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)("p",{className:"text-sm font-semibold text-modiff-text",children:"No task or model selected"}),(0,Ca.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:"Choose a task in the canvas, browse templates, or add a node from the Nodes panel to build manually."})]}),(0,Ca.jsx)(J,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(m,{size:15}),"data-testid":"studio-open-template-browser",onClick:Ra,children:"Browse templates"})]}):(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"studio-task-model-summary",children:(0,Ca.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:tt?"Current graph":"Current task"}),(0,Ca.jsx)("h2",{className:"truncate text-base font-bold text-modiff-text",children:tt?"Custom graph":na[$.mode]})]}),(0,Ca.jsxs)("div",{className:"min-w-0 text-right",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:tt?"Graph models":"Selected model"}),(0,Ca.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,Ca.jsx)("h3",{className:"truncate text-base font-bold text-hf-yellow",children:tt?at:Ne}),!tt&&(0,Ca.jsx)(dt,{title:Be,children:(0,Ca.jsx)(g,{size:13})})]})]})]})}),ra&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Ft,{"aria-label":"Task",value:$.mode,"data-testid":"studio-task-select",onValueChange:e=>{ca(e)},options:Bt.map(e=>({value:e,label:na[e]}))}),(0,Ca.jsx)(Ft,{"aria-label":"Model",value:$.modelType,"data-testid":"studio-model-select",onValueChange:e=>{ua(e)},options:zt.map(e=>({value:e,label:Se[e]}))})]}),tt?(0,Ca.jsx)($s,{issues:lt.issues}):null,ra&&Ut?(0,Ca.jsx)(J,{fullWidth:!0,tone:"secondary","data-testid":"studio-install-missing-model",disabled:e||ya,onClick:()=>{xa()},title:`${Ut.label} | ${Ut.repo}`,children:ya?"Installing model...":`${Ut.actionLabel??(Ut.repair?"Repair":"Install")} ${Ut.label}`}):null,Ue?(0,Ca.jsx)(ue,{tone:"info",title:"Preparing graph",testId:"studio-run-readiness"}):(0,Ca.jsx)(ue,{tone:mt.tone,title:pt?`${mt.title} - ${pt}`:mt.title,meta:lt.primaryIssue?.message,testId:"studio-run-readiness",onClick:lt.issues.length>0?_a:void 0}),ht.length>0?(0,Ca.jsx)(ba,{candidates:St,nodes:ht,pinnedInputs:At,pinnedIds:Mt,selectedNodes:jt,workflowId:z,onTogglePin:W},z):null,0===ht.length?(0,Ca.jsx)(J,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(m,{size:15}),"data-testid":"studio-open-template-browser",onClick:Ra,children:"Templates"}):null]})}),ra&&(0,Ca.jsxs)(Ca.Fragment,{children:[Ce&&(0,Ca.jsxs)("div",{className:"relative grid gap-3",children:[(0,Ca.jsxs)(ct,{id:"prompt",title:"Prompt",defaultOpen:!0,testId:"studio-sticky-prompt",className:"sticky z-10 rounded-modiff-panel border border-modiff-border bg-modiff-bg px-2 pb-2 shadow-modiff-node before:absolute before:-inset-x-3 before:-top-3 before:h-3 before:bg-modiff-bg before:content-['']",stickyTop:n+12,children:[(0,Ca.jsx)("div",{"data-testid":"studio-prompt-input",children:(0,Ca.jsx)(fe,{label:"Prompt",value:$.prompt,multiline:!0,onChange:e=>oa({prompt:e})})}),!1!==_t.supportsNegativePrompt&&(0,Ca.jsx)("div",{"data-testid":"studio-negative-prompt-input",children:(0,Ca.jsx)(fe,{label:"Negative prompt",value:$.negativePrompt,multiline:!0,onChange:e=>oa({negativePrompt:e})})}),(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(C,{size:15}),onClick:Q,children:"Snippet"}),(0,Ca.jsx)(J,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>H($.prompt),children:"History"})]})]}),(0,Ca.jsxs)(ct,{id:"prompt-tools",title:"Prompt tools",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Presets"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1.5",children:le.map(e=>(0,Ca.jsx)(ge,{title:e.description,onClick:()=>Sa(e),children:e.label},e.id))}),D&&(0,Ca.jsxs)("div",{className:"mt-2 rounded-modiff-compact border border-hf-yellow/60 bg-modiff-surface p-2 text-xs text-modiff-text","data-testid":"studio-recent-change",children:[(0,Ca.jsx)("p",{className:"font-semibold text-hf-yellow",children:D.label}),(0,Ca.jsx)("div",{className:"mt-1 flex flex-wrap gap-1",children:D.fields.slice(0,6).map(e=>(0,Ca.jsxs)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-modiff-subtle-text",children:[e.label,": ",pa(e.before)," -> ",pa(e.after)]},String(e.key)))})]})]}),(0,Ca.jsx)(it,{}),(0,Ca.jsx)(vs,{form:$,template:se,onChange:oa}),(0,Ca.jsx)(it,{}),(0,Ca.jsx)(Is,{form:$,template:se,onApply:oa}),(T.length>0||A.length>0||P.length>0)&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(it,{}),(0,Ca.jsxs)("div",{className:"grid gap-3",children:[A.length>0&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Saved snippets"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:A.slice(0,4).map(e=>(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(J,{fullWidth:!0,tone:"ghost",align:"left",onClick:()=>{Y(e),queueMicrotask(()=>Re())},children:e}),(0,Ca.jsx)(dt,{title:"Remove snippet",onClick:()=>X(e),children:(0,Ca.jsx)(L,{size:15})})]},e))})]}),T.length>0&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Prompt history"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:T.slice(0,4).map(e=>(0,Ca.jsx)(J,{tone:"ghost",align:"left",onClick:()=>oa({prompt:e}),children:e},e))})]}),!1!==_t.supportsNegativePrompt&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Negative presets"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:P.map(e=>(0,Ca.jsx)(ge,{onClick:()=>{te(e),queueMicrotask(()=>Re())},children:e},e))})]})]})]}),(0,Ca.jsx)(it,{}),(0,Ca.jsx)(ks,{currentPrompt:$.prompt,promptHistory:T,savedSnippets:A,onApplyPrompt:e=>oa({prompt:e})})]})]}),(0,Ca.jsxs)(ct,{id:"advanced-generation",title:"Advanced generation",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:re?"Video frame":je?"Rendered orbit frame":ce?"Native sample size":pe?"Prediction map":xe?"Speech recognition":"Image size"}),ce?(0,Ca.jsxs)("p",{className:"text-xs text-modiff-subtle-text","data-testid":"studio-unconditional-native-size",children:["This checkpoint produces fixed ",$.width,"×",$.height," samples."]}):pe?(0,Ca.jsxs)("div",{className:"grid gap-2","data-testid":"studio-perception-controls",children:[(0,Ca.jsx)(fe,{label:"Processing resolution",value:$.processingResolution,onChange:e=>oa({processingResolution:As(e,$.processingResolution)})}),(0,Ca.jsx)(ot,{checked:$.matchInputResolution,onChange:e=>oa({matchInputResolution:e}),label:"Match output to source resolution"}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Output is a normalized relative-depth map: near is 0, far is 1. Studio also previews it as grayscale."})]}):xe?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text","data-testid":"studio-speech-summary",children:"Transcribe local audio into a normalized transcript with bounded chunking and timestamps."}):_t.layerResolutions?.length?(0,Ca.jsx)(Ft,{"aria-label":"Layer resolution","data-testid":"studio-layer-resolution-select",value:String($.width),onValueChange:e=>{let t=As(e,$.width);oa({width:t,height:t,aspectRatio:"1:1"})},options:_t.layerResolutions.map(e=>({value:String(e),label:`${e} × ${e}`}))}):(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(Ft,{"aria-label":"Aspect ratio",value:$.aspectRatio,onValueChange:e=>(e=>{let t=Ts.find(t=>t.label===e);oa(t?{aspectRatio:e,width:t.width,height:t.height}:{aspectRatio:e})})(e),options:[...Ts.map(e=>({value:e.label,label:e.label})),{value:"custom",label:"Custom"}],className:"flex-1"}),(0,Ca.jsx)(ut,{"aria-label":"Width",value:$.width,"data-testid":"studio-width-input",onChange:e=>oa({width:As(e.target.value,$.width),aspectRatio:"custom"}),className:"w-[86px]"}),(0,Ca.jsx)(ut,{"aria-label":"Height",value:$.height,"data-testid":"studio-height-input",onChange:e=>oa({height:As(e.target.value,$.height),aspectRatio:"custom"}),className:"w-[86px]"})]})]}),"outpaint"===$.mode&&(0,Ca.jsxs)("section",{"data-testid":"studio-outpaint-controls",children:[(0,Ca.jsx)($e,{title:"Outpaint canvas"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(fe,{label:"Left margin",value:$.outpaintLeft,onChange:e=>oa({outpaintLeft:As(e,$.outpaintLeft)})}),(0,Ca.jsx)(fe,{label:"Right margin",value:$.outpaintRight,onChange:e=>oa({outpaintRight:As(e,$.outpaintRight)})}),(0,Ca.jsx)(fe,{label:"Top margin",value:$.outpaintTop,onChange:e=>oa({outpaintTop:As(e,$.outpaintTop)})}),(0,Ca.jsx)(fe,{label:"Bottom margin",value:$.outpaintBottom,onChange:e=>oa({outpaintBottom:As(e,$.outpaintBottom)})})]}),(0,Ca.jsx)(kt,{label:`Seam overlap: ${$.outpaintOverlap}`,children:(0,Ca.jsx)(ke,{min:0,max:128,step:4,value:$.outpaintOverlap,onChange:e=>oa({outpaintOverlap:e})})}),(0,Ca.jsx)(kt,{label:`Mask feather: ${$.outpaintFeather}`,children:(0,Ca.jsx)(ke,{min:0,max:64,step:1,value:$.outpaintFeather,onChange:e=>oa({outpaintFeather:e})})}),(0,Ca.jsx)(fe,{label:"Fill color",value:$.outpaintFillColor,onChange:e=>oa({outpaintFillColor:e})})]})]}),!xe&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Generation"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("div",{"data-testid":"studio-seed-input",children:(0,Ca.jsx)(fe,{label:"Seed",value:$.seed,onChange:e=>oa({seed:As(e,$.seed)}),disabled:$.randomSeed})}),(0,Ca.jsx)(ot,{checked:$.randomSeed,onChange:e=>oa({randomSeed:e}),label:"Randomize seed on export"}),(0,Ca.jsx)(kt,{label:`Steps: ${$.steps}`,children:(0,Ca.jsx)(ke,{min:1,max:ce?1e3:80,value:$.steps,onChange:e=>oa({steps:e})})}),ce&&(0,Ca.jsx)(fe,{label:"Batch size",value:$.batchSize,onChange:e=>oa({batchSize:As(e,$.batchSize)})}),"DDIMPipeline"===$.modelType&&(0,Ca.jsx)(kt,{label:`Eta: ${$.eta}`,children:(0,Ca.jsx)(ke,{min:0,max:1,step:.01,value:$.eta,onChange:e=>oa({eta:e})})}),"ConsistencyModelPipeline"===$.modelType&&(0,Ca.jsx)(fe,{label:"Class label (-1 is unconditional)",value:$.classLabel,onChange:e=>oa({classLabel:As(e,$.classLabel)})}),Ce&&(0,Ca.jsx)(kt,{label:`${_t.guidanceLabel}: ${$.guidanceScale}`,children:(0,Ca.jsx)(ke,{min:0,max:10,step:.1,value:$.guidanceScale,onChange:e=>oa({guidanceScale:e})})}),void 0!==_t.recommendedPagScale&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(kt,{label:`PAG scale: ${$.pagScale}`,children:(0,Ca.jsx)(ke,{min:0,max:10,step:.1,value:$.pagScale,onChange:e=>oa({pagScale:e})})}),(0,Ca.jsx)(kt,{label:`PAG adaptive scale: ${$.pagAdaptiveScale}`,children:(0,Ca.jsx)(ke,{min:0,max:10,step:.1,value:$.pagAdaptiveScale,onChange:e=>oa({pagAdaptiveScale:e})})})]}),re&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(fe,{label:"Frames",value:$.numFrames,onChange:e=>oa({numFrames:As(e,$.numFrames)})}),(0,Ca.jsx)(fe,{label:"FPS",value:$.fps,onChange:e=>oa({fps:As(e,$.fps)})})]}),(0,Ca.jsx)(kt,{label:`Conditioning: ${$.conditioningScale}`,children:(0,Ca.jsx)(ke,{min:0,max:2,step:.05,value:$.conditioningScale,onChange:e=>oa({conditioningScale:e})})}),(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(kt,{label:`Guidance 2: ${$.guidanceScale2}`,children:(0,Ca.jsx)(ke,{min:0,max:20,step:.1,value:$.guidanceScale2,onChange:e=>oa({guidanceScale2:e})})}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Ft,{"aria-label":"Output type",value:$.outputType,onValueChange:e=>oa({outputType:e}),options:[{value:"pil",label:"Output: PIL"},{value:"np",label:"Output: NumPy"},{value:"pt",label:"Output: Torch"}]}),(0,Ca.jsx)(fe,{label:"Max tokens",value:$.maxSequenceLength,onChange:e=>oa({maxSequenceLength:As(e,$.maxSequenceLength)})})]}),(0,Ca.jsx)(fe,{label:"Attention kwargs JSON",value:$.attentionKwargsJson,multiline:!0,onChange:e=>oa({attentionKwargsJson:e})})]})]}),_t.supportsImageInput&&!re&&!pe&&(0,Ca.jsx)(Ca.Fragment,{children:(0,Ca.jsx)(kt,{label:`Strength: ${$.strength}`,children:(0,Ca.jsx)(ke,{min:0,max:1,step:.05,value:$.strength,onChange:e=>oa({strength:e})})})}),(Lt||sa)&&(0,Ca.jsx)(kt,{label:`Control conditioning: ${$.conditioningScale}`,children:(0,Ca.jsx)(ke,{min:0,max:2,step:.05,value:$.conditioningScale,onChange:e=>oa({conditioningScale:e})})}),Ht&&(0,Ca.jsx)(kt,{label:`IP-Adapter scale: ${$.ipAdapterScale}`,children:(0,Ca.jsx)(ke,{min:0,max:2,step:.05,value:$.ipAdapterScale,onChange:e=>oa({ipAdapterScale:e})})}),_t.supportsLayers&&(0,Ca.jsx)(fe,{label:_t.layerCount?`Layers (${_t.layerCount.min}–${_t.layerCount.max})`:"Layers",value:$.layers,onChange:e=>{let t=As(e,$.layers);oa({layers:_t.layerCount?Math.min(_t.layerCount.max,Math.max(_t.layerCount.min,t)):t})}})]})]}),Ce&&(0,Ca.jsx)(xs,{form:$}),Ce&&(0,Ca.jsx)(Rs,{form:$,template:se,onChange:oa,onRunSweep:e=>{Na(()=>za(e))},disabled:e||!!ia})]}),Ce&&(0,Ca.jsx)(ct,{id:"controlled-workflows",title:"Controlled workflows",children:(0,Ca.jsx)(ms,{form:$,onChange:oa,disabled:e})}),re&&(0,Ca.jsx)(ct,{id:"video-inputs",title:"Video inputs",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[Zt&&(0,Ca.jsx)(fe,{label:"Source video path",value:$.sourceVideo,onChange:e=>oa({sourceVideo:e})}),ta&&(0,Ca.jsx)(fe,{label:"Source video paths (one per line)",value:$.referenceVideos.join("\n"),onChange:e=>oa({referenceVideos:e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)}),multiline:!0}),("video_inpaint"===$.mode||"video_outpaint"===$.mode)&&(0,Ca.jsx)(fe,{label:"Mask video path",value:$.maskVideo,onChange:e=>oa({maskVideo:e})}),sa&&(0,Ca.jsx)(fe,{label:"Control video path",value:$.controlVideo,onChange:e=>oa({controlVideo:e})}),"image_to_video"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Use Reference inputs below for the starting image."}),"reference_to_video"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Use Reference inputs below for subject and style images."})]})}),de&&(0,Ca.jsx)(ct,{id:"audio-inputs",title:"Audio",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:["text_to_audio"!==$.mode&&(0,Ca.jsx)(fe,{label:"Source audio path",value:$.sourceAudio,onChange:e=>oa({sourceAudio:e})}),"audio_variation"===$.mode&&(0,Ca.jsx)(fe,{label:"Reference audio path",value:$.referenceAudio,onChange:e=>oa({referenceAudio:e})}),(0,Ca.jsx)(fe,{label:"Lyrics",value:$.lyrics,onChange:e=>oa({lyrics:e}),multiline:!0}),(0,Ca.jsxs)("div",{className:ve("grid gap-2","grid-cols-2"),children:[(0,Ca.jsx)(kt,{label:`Duration ${$.audioDuration}s`,children:(0,Ca.jsx)(ke,{value:$.audioDuration,min:1,max:240,step:.5,onChange:e=>oa({audioDuration:e})})}),(0,Ca.jsx)(kt,{label:`Shift ${$.shift}`,children:(0,Ca.jsx)(ke,{value:$.shift,min:0,max:10,step:.1,onChange:e=>oa({shift:e})})})]}),"audio_continuation"===$.mode&&(0,Ca.jsx)(kt,{label:`Continuation length ${$.extensionDuration}s`,children:(0,Ca.jsx)(ke,{value:$.extensionDuration,min:1,max:180,step:.5,onChange:e=>oa({extensionDuration:e})})}),"audio_repaint"===$.mode&&(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(kt,{label:`Repaint start ${$.repaintingStart}s`,children:(0,Ca.jsx)(ke,{value:$.repaintingStart,min:0,max:240,step:.1,onChange:e=>oa({repaintingStart:e})})}),(0,Ca.jsx)(kt,{label:`Repaint end ${$.repaintingEnd}s`,children:(0,Ca.jsx)(ke,{value:$.repaintingEnd,min:0,max:240,step:.1,onChange:e=>oa({repaintingEnd:e})})})]}),"audio_variation"===$.mode&&(0,Ca.jsx)(kt,{label:`Cover strength ${$.audioCoverStrength}`,children:(0,Ca.jsx)(ke,{value:$.audioCoverStrength,min:0,max:1,step:.01,onChange:e=>oa({audioCoverStrength:e})})}),(0,Ca.jsxs)("div",{className:"grid grid-cols-3 gap-2",children:[(0,Ca.jsx)(ut,{value:$.vocalLanguage,onChange:e=>oa({vocalLanguage:e.target.value}),"aria-label":"Audio language"}),(0,Ca.jsx)(ut,{value:$.keyscale,onChange:e=>oa({keyscale:e.target.value}),"aria-label":"Audio key"}),(0,Ca.jsx)(ut,{value:$.timesignature,onChange:e=>oa({timesignature:e.target.value}),"aria-label":"Audio time signature"})]})]})}),xe&&(0,Ca.jsx)(ct,{id:"speech-inputs",title:"Speech recognition",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2","data-testid":"studio-speech-controls",children:[(0,Ca.jsx)(fe,{label:"Source audio path",value:$.sourceAudio,onChange:e=>oa({sourceAudio:e})}),(0,Ca.jsx)(fe,{label:"Language hint (optional)",value:$.speechLanguage,onChange:e=>oa({speechLanguage:e})}),(0,Ca.jsx)(Ft,{"aria-label":"Speech timestamps",value:$.speechTimestamps,onValueChange:e=>oa({speechTimestamps:e}),options:[{value:"none",label:"No timestamps"},{value:"segment",label:"Segment timestamps"},{value:"word",label:"Word timestamps"}]}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(fe,{label:"Chunk length (seconds)",value:$.speechChunkSeconds,onChange:e=>oa({speechChunkSeconds:As(e,$.speechChunkSeconds)})}),(0,Ca.jsx)(fe,{label:"Chunk stride (seconds)",value:$.speechStrideSeconds,onChange:e=>oa({speechStrideSeconds:As(e,$.speechStrideSeconds)})})]}),"speech_translation"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Translation output is normalized to English."})]})}),(0,Ca.jsx)(ct,{id:"runtime",title:"Runtime",children:(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"studio-expert-runtime-controls",children:[(0,Ca.jsx)($e,{title:"Custom runtime settings"}),(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(Ft,{"aria-label":"Data type",value:$.dtype,onValueChange:e=>oa({dtype:e}),options:[{value:"bfloat16",label:"bfloat16"},{value:"float16",label:"float16"},{value:"float32",label:"float32"}],className:"flex-1"}),(0,Ca.jsx)(ut,{"aria-label":"Device",value:$.device,onChange:e=>oa({device:e.target.value}),className:"w-24"})]}),(0,Ca.jsx)(ot,{checked:$.autoOffload,onChange:e=>oa({autoOffload:e}),label:"Auto-offload model components"}),(0,Ca.jsxs)("div",{className:ve("grid gap-2",qe.length?"grid-cols-2":"grid-cols-1"),children:[qe.length>0&&(0,Ca.jsx)(Ft,{"aria-label":"Quantization","data-testid":"studio-quantization-select",value:$.quantizationMode,onValueChange:e=>{oa({quantizationMode:e})},options:[{value:"none",label:"No quantization"},...qe.map(e=>({value:e,label:"bnb_4bit"===e?"4-bit BnB":"bnb_8bit"===e?"8-bit BnB":"quanto_float8"===e?"Quanto float8":"TorchAO float8"}))]}),(0,Ca.jsx)(Ft,{"aria-label":"Offload mode","data-testid":"studio-offload-mode-select",value:$.offloadMode,onValueChange:e=>oa({offloadMode:e}),options:_t.offloadSupport.modes.map(e=>({value:e,label:U[e]}))})]})]})}),(Dt||"image_to_video"===$.mode||"reference_to_video"===$.mode)&&(0,Ca.jsx)(ct,{id:"reference-inputs",title:pe?"Source image":"Reference inputs",defaultOpen:!0,children:(0,Ca.jsx)(os,{})}),(Et||Lt||Ht)&&(0,Ca.jsxs)(ct,{id:"mask-control",title:[Et,Lt,Ht].filter(Boolean).length>1?"Conditioning inputs":Et?"Mask draft":Lt?"Control image":"IP-Adapter image",defaultOpen:!0,children:[Et&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(fe,{label:"Mask image path",value:$.maskImage,onChange:e=>oa({maskImage:e})}),(0,Ca.jsx)("p",{className:ve("text-xs",Wt?"text-modiff-subtle-text":"text-hf-orange"),children:Wt?"The mask limits which source-image region can change.":Vt?.reason??"Brush, erase, invert, feather, clear, and fill are frontend draft controls until backend support is confirmed."}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(J,{tone:"ghost",onClick:()=>i(!0),children:"Open mask editor"}),$.maskImage&&(0,Ca.jsx)(J,{tone:"ghost",onClick:()=>oa({maskImage:""}),children:"Clear saved mask"})]}),s&&(0,Ca.jsx)(hs,{sourceImage:$.referenceImages[0],maskImage:$.maskImage,onSave:e=>{oa({maskImage:e}),i(!1)},onCancel:()=>i(!1)})]}),Lt&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(fe,{label:"Control image path",value:$.controlImage,onChange:e=>oa({controlImage:e})}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"The control image is a separate structural guide declared by the selected task contract."}),$.mode.includes("control_union")&&(0,Ca.jsx)(fe,{label:"ControlNet Union mode (0–5)",value:$.controlMode,onChange:e=>oa({controlMode:As(e,$.controlMode)})})]}),Ht&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(fe,{label:"IP-Adapter image path",value:$.ipAdapterImage,onChange:e=>oa({ipAdapterImage:e})}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"This reference is encoded by the separately editable IP-Adapter block; it is not the source or ControlNet image."})]})]}),(0,Ca.jsx)("p",{className:"border-t border-modiff-border pt-3 text-xs text-modiff-subtle-text",children:Ge?"Studio is linked to graph nodes. Workflow edits remain visible on the canvas.":"Custom graph mode: add nodes, connect an output, or start from a template."})]}),(0,Ca.jsx)(va,{open:!!a.pending,policies:a.pending?.policies??[],action:"run",onCancel:a.cancel,onConfirm:a.confirm})]})}var _s=[{id:"studio:prompt",kind:"studio-form",label:"Prompt",formKey:"prompt"},{id:"studio:negativePrompt",kind:"studio-form",label:"Negative prompt",formKey:"negativePrompt"},{id:"studio:seed",kind:"studio-form",label:"Seed",formKey:"seed"},{id:"studio:steps",kind:"studio-form",label:"Steps",formKey:"steps"},{id:"studio:guidanceScale",kind:"studio-form",label:"Guidance",formKey:"guidanceScale"},{id:"studio:pagScale",kind:"studio-form",label:"PAG scale",formKey:"pagScale"},{id:"studio:pagAdaptiveScale",kind:"studio-form",label:"PAG adaptive scale",formKey:"pagAdaptiveScale"},{id:"studio:processingResolution",kind:"studio-form",label:"Processing resolution",formKey:"processingResolution"},{id:"studio:matchInputResolution",kind:"studio-form",label:"Match input resolution",formKey:"matchInputResolution"},{id:"studio:strength",kind:"studio-form",label:"Strength",formKey:"strength"},{id:"studio:width",kind:"studio-form",label:"Width",formKey:"width"},{id:"studio:height",kind:"studio-form",label:"Height",formKey:"height"},{id:"studio:referenceImages",kind:"studio-form",label:"Reference images",formKey:"referenceImages"},{id:"studio:controlImage",kind:"studio-form",label:"Control image",formKey:"controlImage"},{id:"studio:maskImage",kind:"studio-form",label:"Mask image",formKey:"maskImage"},{id:"studio:sourceAudio",kind:"studio-form",label:"Source audio",formKey:"sourceAudio"},{id:"studio:speechLanguage",kind:"studio-form",label:"Speech language",formKey:"speechLanguage"},{id:"studio:speechTimestamps",kind:"studio-form",label:"Speech timestamps",formKey:"speechTimestamps"},{id:"studio:speechChunkSeconds",kind:"studio-form",label:"Speech chunk length",formKey:"speechChunkSeconds"},{id:"studio:speechStrideSeconds",kind:"studio-form",label:"Speech chunk stride",formKey:"speechStrideSeconds"}];function zs(e){return!(!e||"object"!=typeof e||!("id"in e)||"string"!=typeof e.id)}function qs(e){return e.filter(zs).flatMap(e=>Object.entries(e.data?.params??{}).filter(([e,t])=>!t.isInput&&!["image","output","images","latents"].includes(e)).slice(0,10).map(([t,a])=>({id:`graph:${e.id}:${t}`,kind:"graph-param",label:`${e.data?.label||e.id} / ${a.label||t}`,nodeId:e.id,paramKey:t})))}function Bs(e){return Array.isArray(e)?e.join("\n"):String(e??"")}function Ds(e,t,a){let s=e[t];return Array.isArray(s)?a.split("\n").map(e=>e.trim()).filter(Boolean):"number"==typeof s?function(e,t){let a=Number(e);return Number.isFinite(a)?a:t}(a,s):"boolean"==typeof s?"true"===a:a}function Gs(e,t){return e.exposedInputs.some(e=>e.id===t.id)}function Es(){let e=$t(e=>e.form),t=$t(e=>e.workflowTabs),a=$t(e=>e.activeWorkflowTabId),s=$t(e=>e.appModeConfigs),i=$t(e=>e.activeAppModeConfigId),l=$t(e=>e.createAppModeConfig),n=$t(e=>e.updateAppModeConfig),r=$t(e=>e.deleteAppModeConfig),o=$t(e=>e.setActiveAppModeConfig),d=$t(e=>e.switchWorkflowTab),c=$t(e=>e.updateForm),u=rt(e=>e.nodes),m=we(e=>e.sid),p=we(e=>e.isConnected),f=s.find(e=>e.id===i)??s[0]??null,h=t.find(e=>e.id===f?.workflowTabId)??t.find(e=>e.id===a)??null,x=!(!f||f.workflowTabId!==a),g=(0,ka.useMemo)(()=>x?u:h?.snapshot.nodes??[],[x,u,h]),b=(0,ka.useMemo)(()=>[..._s,...qs(g)],[g]),j=(0,ka.useMemo)(()=>function(e){return e.filter(zs).filter(e=>/preview|save|output|video|audio|image/i.test(`${e.data?.label??""} ${e.id}`)).map(e=>({id:`output:${e.id}`,label:e.data?.label||e.id,nodeId:e.id,fieldKey:"output"}))}(g),[g]),v=!!(a&&g.length>0&&j.length>0),y=!!(f&&f.exposedOutputs.length>0&&m&&p),w=(t,a)=>{"studio-form"!==t.kind||!t.formKey||(c({[t.formKey]:Ds(e,t.formKey,a)}),queueMicrotask(()=>Re()))};return(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"app-mode-panel",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Run as app",action:(0,Ca.jsx)(J,{tone:"primary",icon:(0,Ca.jsx)(_,{size:15}),disabled:!v,onClick:()=>{v?l(a)&&Ae("Run as app created for this workflow",{variant:"success",autoHideDuration:2e3}):Ae("Use a graph with at least one output node before creating Run as app.",{variant:"error",autoHideDuration:3500})},"data-testid":"app-mode-create",children:"Create"})}),(0,Ca.jsx)(da,{children:"Expose selected inputs and outputs from this graph."})]}),s.length>0&&(0,Ca.jsx)(Ft,{"aria-label":"Saved app configuration",value:f?.id??"",onValueChange:o,options:s.map(e=>({value:e.id,label:e.name}))}),f?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("section",{className:"grid gap-2 border border-modiff-border bg-modiff-panel p-3",children:[(0,Ca.jsx)(fe,{label:"App name",value:f.name,onChange:e=>n(f.id,{name:e})}),(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,Ca.jsx)(ge,{active:x,children:x?"Workflow open":"Workflow saved"}),(0,Ca.jsx)(ge,{children:h?.title??"Missing workflow"}),!x&&(0,Ca.jsx)(J,{tone:"ghost",onClick:()=>d(f.workflowTabId),children:"Open workflow"}),(0,Ca.jsx)(J,{tone:"danger",icon:(0,Ca.jsx)(L,{size:15}),onClick:()=>r(f.id),children:"Delete"})]})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Choose inputs"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:b.slice(0,36).map(e=>(0,Ca.jsx)(ot,{checked:Gs(f,e),label:e.label,onChange:()=>(e=>{if(!f)return;let t=Gs(f,e)?f.exposedInputs.filter(t=>t.id!==e.id):[...f.exposedInputs,e];n(f.id,{exposedInputs:t})})(e)},e.id))})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Guided inputs"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[0===f.exposedInputs.length&&(0,Ca.jsx)(da,{children:"No inputs exposed yet."}),f.exposedInputs.map(t=>{if("studio-form"===t.kind&&t.formKey){let a=e[t.formKey];return"guidanceScale"===t.formKey||"pagScale"===t.formKey||"pagAdaptiveScale"===t.formKey||"strength"===t.formKey?(0,Ca.jsx)(kt,{label:`${t.label}: ${String(a)}`,children:(0,Ca.jsx)(ke,{min:0,max:"strength"===t.formKey?1:12,step:.05,value:"number"==typeof a?a:0,onChange:e=>w(t,String(e))})},t.id):(0,Ca.jsx)(fe,{label:t.label,disabled:!x,multiline:"prompt"===t.formKey||"negativePrompt"===t.formKey||"referenceImages"===t.formKey,value:Bs(a),onChange:e=>w(t,e)},t.id)}return(0,Ca.jsx)(fe,{label:t.label,disabled:!x,value:String(t.nodeId&&t.paramKey?rt.getState().getParam(t.nodeId,t.paramKey,"value")??"":""),onChange:e=>((e,t)=>{"graph-param"!==e.kind||!e.nodeId||!e.paramKey||rt.getState().setParamWithHistory(e.nodeId,e.paramKey,t)})(t,e)},t.id)})]})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)($e,{title:"Outputs"}),(0,Ca.jsxs)("div",{className:"grid gap-1",children:[0===j.length&&(0,Ca.jsx)(da,{children:"No output nodes detected."}),j.map(e=>(0,Ca.jsx)(ot,{checked:f.exposedOutputs.some(t=>t.id===e.id),label:e.label,onChange:()=>(e=>{if(!f)return;let t=f.exposedOutputs.some(t=>t.id===e.id)?f.exposedOutputs.filter(t=>t.id!==e.id):[...f.exposedOutputs,e];n(f.id,{exposedOutputs:t})})(e)},e.id))]})]}),(0,Ca.jsx)(J,{tone:"primary",icon:(0,Ca.jsx)(D,{size:15}),disabled:!y,onClick:()=>{(async()=>{if(!f||!m||!p)return void Ae("Connect to the MoDiff server before running as app.",{variant:"error",autoHideDuration:4e3});if(0===f.exposedOutputs.length)return void Ae("Expose at least one output before running as app.",{variant:"error",autoHideDuration:3500});f.workflowTabId!==a&&d(f.workflowTabId);let e=ne(),t=!!$t.getState().graphBinding;try{if(t&&!await K(e)||!Nt({sid:m,isConnected:p,includeStudio:t,showDialog:!0}).canRun)return;await It({sid:m,studioContext:{applyRuntimeMetadata:t},workflowContext:e}),Ae("Run as app queued",{variant:"success",autoHideDuration:2200})}catch(e){if(De(e))return;Ae(String(e),{variant:"error",autoHideDuration:7e3})}})()},"data-testid":"app-mode-run",children:"Run app"})]}):(0,Ca.jsx)("div",{className:"border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"Create Run as app from the active graph."})]})}function Os(){let e=(0,ka.useMemo)(oa,[]),t=rt(t=>e(t.nodes)),a=rt(e=>e.edges),s=$t(e=>e.activeWorkflowTabId),[i,l]=(0,ka.useState)(""),[n,r]=(0,ka.useState)(null),[d,c]=(0,ka.useState)(""),[u,m]=(0,ka.useState)(!1),[p,f]=(0,ka.useState)(null),h=(0,ka.useRef)(null),x=(0,ka.useMemo)(()=>{try{return{request:ca(t,a,i||void 0),error:""}}catch(e){return{request:null,error:e instanceof Error?e.message:String(e)}}},[t,a,i]),g=x.request?.key;(0,ka.useEffect)(()=>(h.current?.abort(),m(!1),r(null),c(""),f(null),()=>h.current?.abort()),[g,i,s]);let b=x.request,j=n?.request.key===g?n:null;return(0,Ca.jsxs)("section",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"workflow-resource-assessment",children:[(0,Ca.jsxs)("h2",{className:"flex items-center gap-2 font-semibold",children:[(0,Ca.jsx)(o,{size:17}),"Workflow resources"]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Memory → Automatic chooses supported technical settings. Custom keeps your configured settings. Creator and Developer workspaces can use either memory policy; changing workspace preserves this workflow’s settings."}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"A loader’s Auto Offload controls where its weights reside. Repeat/Loop controls repeated runs. They are separate from Auto resource planning."}),(0,Ca.jsx)(ht,{"aria-label":"Resource assessment scope",value:i,onValueChange:l,options:[{value:"",label:"Whole workflow"},...t.filter(e=>e.data.blockInstanceV2||e.data.blockProjectionContainer).map(e=>({value:e.id,label:`Only ${e.data.label??e.id}`}))]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:i?"Only contained nodes are assessed. Outside suppliers are excluded, as with Run Block.":"Includes connected outside nodes and every enabled Block."}),b?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("p",{className:"text-xs",children:[b.nodeCount," executable nodes · ",b.loaderCount," model loaders · ",b.adapterCount," adapters"]}),(0,Ca.jsx)("p",{className:"rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-auto-reason",children:"Auto can plan custom workflows and multiple Blocks. Each model recipe and the combined memory requirement must pass the backend check."})]}):null,(0,Ca.jsxs)(Ht,{onClick:()=>{(async()=>{if(!x.request)return;h.current?.abort();let e=new AbortController;h.current=e,m(!0),c(""),r(null);try{let t=await ma(x.request,e.signal);if(!e.signal.aborted&&$t.getState().activeWorkflowTabId===s){let e=rt.getState();if(ca(e.nodes,e.edges,i||void 0).key!==t.request.key)throw Error("The workflow changed. Assess its current settings again.");r(t)}}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||m(!1)}})()},disabled:u||!b||!b.nodeCount,"data-testid":"assess-workflow-resources",children:[(0,Ca.jsx)(q,{size:14}),u?"Assessing resources…":"Assess workflow resources"]}),(0,Ca.jsx)(Ht,{onClick:()=>{(async()=>{h.current?.abort();let e=new AbortController;h.current=e,m(!0),c(""),f(null);try{let t=await(await Y(async()=>{let{inspectWorkflowAutoPlanV2:e}=await import(`./block-composition-tools.js?v=cc046c26d6fe7aa4`).then(e=>e.t);return{inspectWorkflowAutoPlanV2:e}},[])).inspectWorkflowAutoPlanV2(i||void 0,e.signal);!e.signal.aborted&&$t.getState().activeWorkflowTabId===s&&f(t)}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||m(!1)}})()},disabled:u||!b?.nodeCount,"data-testid":"plan-workflow-auto",children:"Check Auto execution plan"}),p?(0,Ca.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-auto-plan",children:[(0,Ca.jsx)("p",{className:"font-semibold",children:p.canAutoRun?p.requiresPreparation?"Check computed inputs when Run starts":"Ready for Auto execution":"Auto needs attention"}),(0,Ca.jsx)("p",{children:p.message}),(0,Ca.jsxs)("p",{children:[p.requiresPreparation?"Resolved so far: ":"Peak planned resources: ",p.loaders.length," model owners · RAM"," ",ie(p.requirements.systemRamBytes??null)," · GPU"," ",ie(p.requirements.vramBytes??null)]}),p.loaders.map(e=>(0,Ca.jsxs)("p",{children:[e.repository," · ",e.consumers.length," consumers"]},e.nodeId)),p.patches.length?(0,Ca.jsxs)("p",{children:["Run will apply ",p.patches.length," resource-setting changes to the visible workflow."]}):null,p.issues.map((e,t)=>(0,Ca.jsx)("p",{className:"break-words text-modiff-subtle-text",children:e},t)),(0,Ca.jsx)("p",{children:"Run checks the current graph and available memory again. Custom preserves your explicit settings."})]}):null,x.error||d?(0,Ca.jsx)("p",{role:"alert",className:"break-words text-xs text-modiff-red",children:x.error||d}):null,j?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border p-2 text-xs",children:[(0,Ca.jsxs)("p",{children:["Available RAM: ",ie(j.resources.system.ramAvailableBytes)]}),j.resources.accelerators.map(e=>(0,Ca.jsxs)("p",{children:[e.name,": ",ie(e.memoryFreeBytes)," free · ",e.memoryKind," memory"]},e.device)),(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:"Shared GPU memory and RAM overlap; they are not added together."})]}),j.request.items.map(e=>{let t=j.plans[e.id],a=t?pe(t,e.form??void 0):null;return(0,Ca.jsxs)("div",{className:"grid gap-1 rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-resource-item",children:[(0,Ca.jsx)("p",{className:"break-words font-semibold",children:e.label}),(0,Ca.jsxs)("p",{children:[e.loaderIds.length," loader",1===e.loaderIds.length?"":"s"," · ",e.consumers," downstream consumers"]}),e.currentSettings.map((t,a)=>(0,Ca.jsxs)("p",{className:"break-words text-modiff-subtle-text",children:["Current: ",t]},e.loaderIds[a])),a?(0,Ca.jsxs)("p",{className:"break-words",children:["Source recipe recommendation: ",a.dtype," · ",a.offloadMode,"."," ",t?.statusLabel??a.reason]}):t?(0,Ca.jsx)("p",{children:t.blockingReason??t.message??"No supported local source recipe was selected."}):null,e.details.map(e=>(0,Ca.jsx)("p",{className:"text-modiff-subtle-text",children:e},e))]},e.id)}),j.request.issues.map(e=>(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:e},e)),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Assessment preserves the graph and current settings. Check Auto execution plan to validate the actual combined graph, connected adapters and available memory before running."})]}):null]})}var Ls=[{value:"recommended",label:"Recommended"},{value:"best_quality",label:"Best quality"},{value:"faster",label:"Faster"},{value:"lowest_memory",label:"Lowest memory"}];function Fs(e){return e.resolvedArtifact||e.artifact||e.modelRepo||""}function Hs(e){let t=e.artifactResolution?.resolved,a=t?.format||e.artifactFormat||e.quantizationMode||"native",s=t?.bits?` ${t.bits}-bit`:"";return`${Fs(e)} · ${a}${s}`}function Ks(e){let t=e.requirements?.minimum||e.requirements?.lowerMemory;if(!t)return[];let a=1024**3,s=[];return"number"==typeof t.vramBytes&&t.vramBytes>0&&s.push(`${Math.ceil(t.vramBytes/a)} GB VRAM`),"number"==typeof t.systemRamBytes&&s.push(`${Math.ceil(t.systemRamBytes/a)} GB RAM`),"number"==typeof t.diskFreeBytes&&s.push(`${Math.ceil(t.diskFreeBytes/a)} GB disk`),s}function Ws(){let[e,t]=(0,ka.useState)(null),a=Je(e=>e.setRightPanelTab),s=Je(e=>e.setRightPanelOpen),l=Je(e=>e.setAlertOpener),n=we(e=>e.sid),{installHfModel:r}=Ze(nt(e=>({installHfModel:e.installHfModel}))),{form:u,graphBinding:m,plan:p,applyAutoResourcePlan:f,createWorkflowTab:h,updateForm:x,setAutoResourcePlan:g}=$t(nt(e=>({form:e.form,graphBinding:e.graphBinding,plan:e.autoResourcePlan,applyAutoResourcePlan:e.applyAutoResourcePlan,createWorkflowTab:e.createWorkflowTab,updateForm:e.updateForm,setAutoResourcePlan:e.setAutoResourcePlan}))),b=pe(p,u)||null,v=ra(b,m?.controlled?.contractIds),y=(0,ka.useMemo)(()=>(p?.candidates||[]).filter(e=>e.id!==b?.id),[p?.candidates,b?.id]);if(!m)return(0,Ca.jsx)(Os,{});if(!b)return(0,Ca.jsxs)("div",{className:"grid gap-3 p-4 text-sm text-modiff-text","data-testid":"compatibility-panel",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[(0,Ca.jsx)(O,{size:17,className:"text-modiff-green"}),"No model substitution"]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Select a Studio model to inspect local compatibility."})]});let w=async e=>{let a=Fs(e);if(!a)return;let s=ne();t(a);try{await r(a,n,{repair:!!e.repairRequired}),et(s),Ae(`${a} is ready. Refreshing compatibility.`,{variant:"success"});let t=await Q($t.getState().form);et(s),g(t)}catch(e){if(De(e))return;Ae(e instanceof Error?e.message:`Could not install ${a}.`,{variant:"error"})}finally{t(null)}},k=e=>{let t=Fs(e);l({title:e.repairRequired?"Repair artifact?":"Install artifact?",message:`${t} will be downloaded and managed by MoDiff.`,confirmText:e.repairRequired?"Repair":"Install",cancelText:"Cancel",onConfirm:()=>{l(null),w(e)},onCancel:()=>l(null)})},C=async(e,t="")=>{let a=ne();try{let s={...xe(e,u),confirmedCommunityArtifact:t},i={...u,...s},l=await Q(i);et(a);let n=pe(l,i)??e;f(l,{...xe(n,i),confirmedCommunityArtifact:t}),aa(a),Ae("Next local option selected.",{variant:"info"})}catch(e){if(De(e))return;Ae(String(e),{variant:"error"})}},N=b.compatibilityEvidence,S=v?.message||N?.message||b.reason||b.skipReason||p?.blockingReason||"Compatibility was estimated from the current runtime and model metadata.",I=b.artifactResolution?.base?.repo||b.baseArtifact||Fs(b),R=!!(b.artifactResolution?.substituted||I&&I!==Fs(b));return(0,Ca.jsx)(Ca.Fragment,{children:(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"compatibility-panel",children:[(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Automatic memory selects a supported local resource recipe. Custom keeps your configured technical settings. Switching preserves the workflow’s nodes, connections and creative controls."}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Auto Offload on a loader controls weight placement. Repeat/Loop controls repeated runs. These are separate from Auto resource planning."}),(0,Ca.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-hf-yellow/50 bg-hf-yellow/10 p-3",children:[(0,Ca.jsx)(j,{size:17,className:"mt-0.5 shrink-0 text-hf-yellow"}),(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("p",{className:"font-semibold",children:v?.label||N?.label||b.healthBadge||"This should work"}),(0,Ca.jsx)("p",{className:"mt-1 line-clamp-2 text-xs text-modiff-subtle-text",children:S})]})]}),(0,Ca.jsx)(kt,{label:"Recommendation",children:(0,Ca.jsx)(Ft,{value:u.resourcePreference||"recommended",onValueChange:e=>{(async e=>{let t=ne(),a={...u,resourcePreference:e};x({resourcePreference:e}),aa(t);try{let e=await Q(a);et(t),g(e)}catch(e){if(De(e))return;Ae(String(e),{variant:"error"})}})(e)},options:Ls.map(e=>({value:e.value,label:e.label})),"data-testid":"compatibility-preference"})}),(0,Ca.jsxs)("section",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[R?(0,Ca.jsxs)("p",{className:"truncate text-xs text-modiff-subtle-text",title:I,children:["Base: ",I]}):null,(0,Ca.jsx)("p",{className:"break-all font-semibold text-hf-yellow",children:Hs(b)}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1.5",children:Ks(b).map(e=>(0,Ca.jsx)("span",{className:"rounded bg-modiff-bg px-2 py-1 text-modiff-label text-modiff-subtle-text",children:e},e))}),!1===b.installed||b.repairRequired?(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(G,{size:15}),onClick:()=>k(b),disabled:e===Fs(b),children:b.repairRequired?"Repair artifact":"Install in app"}):null]}),y.length?(0,Ca.jsxs)("section",{className:"grid gap-2",children:[(0,Ca.jsx)("h3",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:"Other options"}),y.map(e=>(0,Ca.jsxs)(Ht,{tone:"secondary",align:"left",fullWidth:!0,className:"h-auto p-2",onClick:()=>(e=>{if(e.requiresConfirmation&&"manual_only"===e.proof?.status){if(!e.installed||e.repairRequired)return void k(e);let t=Fs(e);return void l({title:"Use community artifact?",message:`${t} is popularity-qualified but not quality-qualified by MoDiff. Use it for this workflow and machine?`,confirmText:"Use artifact",cancelText:"Cancel",onConfirm:()=>{l(null),C(e,t)},onCancel:()=>l(null)})}C(e)})(e),icon:"gguf"===e.artifactFormat?(0,Ca.jsx)(d,{size:15}):(0,Ca.jsx)(o,{size:15}),children:[(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-xs font-semibold",children:Fs(e)}),(0,Ca.jsx)("span",{className:"block truncate text-modiff-label text-modiff-subtle-text",children:e.compatibilityEvidence?.label||e.healthBadge})]}),(0,Ca.jsx)(i,{size:14,className:"text-modiff-subtle-text"})]},e.id))]}):null,(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(c,{size:15}),onClick:()=>a("setup"),children:"Open setup"}),(0,Ca.jsx)(Ht,{icon:(0,Ca.jsx)(o,{size:15}),onClick:()=>{(async()=>{let e=ne(),t="modules.ModelArtifact.QuantizeDiffusersComponents",a=Ze.getState().nodesRegistry;a[t]||(await Ze.getState().fetchNodes(),et(e),a=Ze.getState().nodesRegistry);let i=Lt(t,a,{x:120,y:100});if(!i)return void Ae("The optimized-artifact node is unavailable in this backend.",{variant:"error"});let l=b.artifactResolution?.base?.repo||b.baseArtifact||Fs(b);h(`Optimize ${l.split("/").pop()||"model"}`),rt.getState().addNode(i),rt.getState().setParam(i.id,"model_id",{source:"hub",value:l}),rt.getState().setParam(i.id,"source_revision",b.artifactResolution?.base?.revision||"main"),b.pipelineClass&&rt.getState().setParam(i.id,"pipeline_class",b.pipelineClass),$t.getState().saveActiveWorkflowTab(!0),s(!1),Ae("Optimized-copy workflow created. Review its admission and quality settings before running.",{variant:"success"})})()},children:"Create optimized copy"}),(0,Ca.jsxs)(bt,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs",label:"Evidence and requirements",buttonClassName:"min-h-0 p-0 text-xs",panelClassName:"mt-2 grid gap-2 break-words text-modiff-subtle-text",children:[(0,Ca.jsx)("p",{children:S}),b.requirementsMissing?.map(e=>(0,Ca.jsx)("p",{children:e},e)),N?.popularity?(0,Ca.jsxs)("p",{children:["Hub snapshot: ",N.popularity.downloads??0," downloads · ",N.popularity.likes??0," likes. Popularity is not compatibility proof."]}):null]})]})})}var Vs=(0,ka.lazy)(()=>Y(()=>import(`./block-composition-tools.js?v=cc046c26d6fe7aa4`).then(e=>e.l),[])),Us=(0,ka.lazy)(()=>Y(()=>import(`./BlockInterfaceDialogContentV2.js?v=cc046c26d6fe7aa4`),[]));function Qs(){let e=jt(e=>e.target),t=jt(e=>e.close),a=$t(e=>e.activeWorkflowTabId),s=$t(e=>e.workflowCanvasEpoch),i=rt(t=>{let a=t.nodes.find(t=>t.id===e?.snapshot.instanceId)?.data.blockInstanceV2;return!(!a||e?.subtreeId&&!a.effectiveGraph.nodes.some(t=>t.nodeId===e.subtreeId))})&&e?.context.workflowTabId===a&&e?.context.canvasEpoch===s;return(0,ka.useEffect)(()=>{e&&!i&&t()},[e,i,t]),e&&i?(0,Ca.jsx)(ka.Suspense,{fallback:(0,Ca.jsx)("p",{className:"p-3 text-sm",role:"status",children:"Loading Block editor…"}),children:"save"===e.mode?(0,Ca.jsx)(Vs,{nodeId:e.nodeId,context:e.context,onClose:t},e.requestId):(0,Ca.jsx)(Us,{...e,onClose:t},e.requestId)}):null}export{rs as a,ua as default,Ps as i,Ws as n,es as o,Es as r,Qs as t}; \ No newline at end of file +import{r as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{$ as t,An as a,B as s,Dn as i,E as l,Fn as n,Ft as r,Gt as o,Ht as d,J as c,K as u,Kt as m,Lt as p,M as f,Mt as h,Pn as x,Pt as g,Q as b,R as j,Rn as v,Rt as y,U as w,W as k,X as C,Xt as N,Yt as S,_n as I,bn as R,cr as $,dr as M,gt as T,jn as A,on as P,ot as _,pt as z,rt as q,sn as B,st as G,un as D,vn as O,wn as E,z as L,zn as F}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$i as H,$t as K,Aa as W,Ai as V,An as U,Ao as Q,Ar as J,Ba as Z,Bi as X,Bt as Y,C as ee,Cr as te,Ct as ae,Di as se,Dn as ie,Ea as le,Ei as ne,En as re,Er as oe,Fa as de,Fi as ce,Fr as ue,Ga as me,Gt as pe,Ha as fe,Hi as he,Hn as xe,Ho as ge,Hr as be,Ht as je,Ia as ve,Ii as ye,In as we,Ir as ke,Is as Ce,Ja as Ne,Jt as Se,Kt as Ie,La as Re,Li as $e,Ln as Me,Lr as Te,Ma as Ae,Mi as Pe,Na as _e,Ni as ze,Oa as qe,Oi as Be,On as Ge,Oo as De,Or as Oe,Pa as Ee,Pi as Le,Po as Fe,Pr as He,Qt as Ke,Ra as We,Ri as Ve,Rr as Ue,Rt as Qe,S as Je,Sr as Ze,Ta as Xe,Ti as Ye,Tn as et,To as tt,Tr as at,Ui as st,Ut as it,Va as lt,Vi as nt,Vt as rt,Wa as ot,Wi as dt,Wt as ct,Xt as ut,Yn as mt,Yt as pt,Zt as ft,an as ht,ao as xt,ar as gt,c as bt,do as jt,dr as vt,eo as yt,er as wt,fa as kt,fn as Ct,fo as Nt,ft as St,go as It,gr as Rt,ha as $t,hr as Mt,ia as Tt,in as At,ir as Pt,ja as _t,ji as zt,ka as qt,kn as Bt,lc as Gt,lo as Dt,ma as Ot,mn as Et,mr as Lt,nn as Ft,no as Ht,pn as Kt,pr as Wt,q as Vt,qi as Ut,qt as Qt,ro as Jt,to as Zt,tr as Xt,uo as Yt,w as ea,wa as ta,wi as aa,wr as sa,xn as ia,ya as la,yt as na,za as ra,zi as oa,zt as da}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{i as ca,n as ua,r as ma}from"./block-composition-tools.js?v=ca6b74e6a02eedb3";import{n as pa,r as fa,t as ha}from"./presetDiff.js?v=ca6b74e6a02eedb3";import{t as xa}from"./WorkflowArtifactRequirementRow.js?v=ca6b74e6a02eedb3";import{n as ga,t as ba}from"./GraphNodeInputs.js?v=ca6b74e6a02eedb3";import{n as ja,t as va}from"./TemplateUsageTermsDialog.js?v=ca6b74e6a02eedb3";import{a as ya,t as wa}from"./controlledWorkflows.js?v=ca6b74e6a02eedb3";var ka=e(M(),1),Ca=$();function Na(e){navigator.clipboard?.writeText(e)}function Sa({error:e,status:t}){let a=t?.runtimeEnvironment,s=a?.devices.find(e=>e.device===a.defaultDevice),i=!(!t?.ready||!a?.executionReady),l="experimental"===a?.supportTier||"preview"===a?.supportTier,n=a?.installation,r=a?.issues.map(e=>e.message).join(" "),o=n?.steps?.filter(e=>"complete"!==e.status&&"skipped"!==e.status)??[];return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"runtime-environment-card",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Runtime environment"}),(0,Ca.jsx)(Ke,{label:i?"Ready":"Needs setup",tone:i?"success":"error",title:e||r||a?.status})]}),(0,Ca.jsxs)("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[(0,Ca.jsx)(Ke,{label:`${a?.installedProfile??"Profile unverified"} · ${a?.supportTier??"unverified"}`,tone:l||!a?.profileVerified?"warning":"neutral",title:a?.profileVerified?`Requested: ${a.requestedProfile??"auto"}. Qualification: ${a.supportTier}.`:"Legacy backend: installation profile cannot be verified."}),(0,Ca.jsx)(Ke,{label:s?`${s.backend} · ${s.device}`:"Detecting hardware",tone:s&&"cpu"!==s.backend?"success":"neutral",title:s?`${s.name} · ${s.vendor} · ${s.memoryKind} memory`:"Hardware has not been reported."}),(0,Ca.jsx)(Ke,{label:`Torch ${t?.packages?.torch?.version??"unknown"}`,tone:"neutral",title:`Torch ${t?.packages?.torch?.version??"unknown"}`})]}),l&&(0,Ca.jsx)("p",{className:"mt-2 text-xs text-modiff-warning",children:"This profile passed local checks; model recipes still need physical qualification."}),!i&&a?.issues.length?(0,Ca.jsx)("ul",{className:"mt-2 grid gap-1 text-xs text-modiff-red","data-testid":"runtime-profile-issues",children:a.issues.map((e,t)=>(0,Ca.jsx)("li",{children:e.message},`${e.code??"runtime"}-${t}`))}):null,o.length>0&&(0,Ca.jsx)("ol",{className:"mt-3 grid gap-2","data-testid":"runtime-installation-checklist",children:o.map((e,t)=>(0,Ca.jsxs)("li",{className:"rounded-modiff-compact border border-modiff-border-subtle p-2 text-xs text-modiff-text",children:[(0,Ca.jsxs)("div",{className:"font-semibold",children:[t+1,". ",e.title??e.id]}),e.explanation&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:e.explanation}),e.requiresAdmin&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-warning",children:"Administrator approval required."}),e.requiresReboot&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-warning",children:"Resume after reboot or complete sign-out."}),e.command&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-modiff-subtle-text",children:e.command}),(0,Ca.jsx)(At,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1",onClick:()=>Na(e.command),children:"Copy"})]}),e.verification&&(0,Ca.jsxs)("p",{className:"mt-1 text-modiff-subtle-text",children:["Verify: ",e.verification]}),e.failureHelp&&(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:e.failureHelp})]},e.id??`${e.phase??"step"}-${t}`))}),n?.resumeCommand&&"complete"!==n.status&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-xs text-modiff-subtle-text",children:n.resumeCommand}),(0,Ca.jsx)(At,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1 text-xs",onClick:()=>Na(n.resumeCommand),children:"Copy resume"})]}),a?.repairCommand&&!i&&(!n?.resumeCommand||"complete"===n.status)&&(0,Ca.jsxs)("div",{className:"mt-2 flex items-start gap-2",children:[(0,Ca.jsx)("code",{className:"min-w-0 flex-1 select-all break-all text-xs text-modiff-subtle-text",children:a.repairCommand}),(0,Ca.jsx)(At,{tone:"secondary",size:"compact",className:"h-auto px-2 py-1 text-xs",onClick:()=>Na(a.repairCommand),children:"Copy repair"})]})]})}function Ia(e,t,a){return Q(`${Gt.serverAddress}${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),timeoutMs:3e4,parse:a})}function Ra(e,t){let a="active"===t&&"active"===e.overlayStatus&&e.cutoverReady&&"qualified"===e.contractState,s="active"!==t&&"base"!==t?t:a?"active":"qualified"===e.contractState&&e.cutoverReady?e.overlayStatus:"unavailable";return`${s.replace(/_/g," ")}${"unavailable"===s?` (${e.contractState})`:""}.`}function $a(e){return`${"macos"===e.platform?"macOS":"windows"===e.platform?"Windows":"Linux"} ${"arm64"===e.machine?"ARM64":"x86-64"}`}function Ma(){let e=aa(e=>e.optionalRuntimeCatalog),t=aa(e=>e.discoveryRequests.optionalRuntimes),a=aa(e=>e.fetchOptionalRuntimes),s=ta(e=>e.setAlertOpener),[i,l]=(0,ka.useState)(null),[n,r]=(0,ka.useState)([]),[o,d]=(0,ka.useState)(null),[c,u]=(0,ka.useState)(!0),[m,p]=(0,ka.useState)(null),[f,h]=(0,ka.useState)(null),x=(0,ka.useRef)(0),g=(0,ka.useRef)(!1),b=(0,ka.useRef)(0),j=(0,ka.useRef)(0),v=(0,ka.useCallback)(async()=>{let e=++x.current;u(!0);try{let[t,a]=await Promise.all([Q(`${Gt.serverAddress}/runtime/optimizations`,{timeoutMs:15e3,parse:qt}),Q(`${Gt.serverAddress}/runtime/optimizations/receipts`,{timeoutMs:15e3,parse:_t})]);if(e!==x.current)return;l(t),r(a.receipts),p(null)}catch(t){throw e===x.current&&p(De(t,"Could not load runtime optimizations.")),t}finally{e===x.current&&u(!1)}},[]);(0,ka.useEffect)(()=>{v().catch(()=>{})},[v]),(0,ka.useEffect)(()=>()=>{j.current+=1},[]);let y=(0,ka.useCallback)(async(e,t)=>{let s=++j.current,i=Date.now()+3e5;for(;s===j.current&&Date.now()window.setTimeout(e,1e3)),s!==j.current)return;await a();let i=aa.getState().optionalRuntimeCatalog,l=i?.profiles.find(t=>t.id===e);if("active"===i?.processLoadStatus&&l?.specDigest===t&&"active"===l.overlayStatus){let e=aa.getState();return void await Promise.all([e.fetchRuntimeStatus(),e.fetchStudioModelCapabilities()])}}s===j.current&&Fe("Runtime activation is still restarting. Refresh Setup before running this workflow.",{variant:"warning"})},[a]);(0,ka.useEffect)(()=>{if(!f||["cancelled","failed","ready"].includes(f.status))return;let e=new AbortController,t=window.setTimeout(async()=>{if(++b.current>2400)Fe("Runtime setup polling stopped. Refresh status to continue.",{variant:"warning"});else try{let t=await Q(`${Gt.serverAddress}/runtime/optional-runtimes/jobs/${encodeURIComponent(f.id)}`,{signal:e.signal,parse:Xe});if(t.id!==f.id||t.profileId!==f.profileId||t.specDigest!==f.specDigest)throw Error("The optional-runtime job identity changed.");h(t),["cancelled","failed","ready"].includes(t.status)&&a()}catch{e.signal.aborted||h({...f})}},750);return()=>{e.abort(),window.clearTimeout(t)}},[a,f]);let w=async(e,t)=>{if(!g.current){g.current=!0,d(e);try{await t()}catch(e){Fe(De(e,"Action failed."),{variant:"error"})}finally{g.current=!1,d(null)}}},k=(e,t,a)=>w(e,async()=>{Fe((await Ia(t,a,W)).message??"Updated.",{variant:"success"}),v().catch(()=>{})}),C=(e,t,a,i)=>s({title:e,message:t,confirmText:a,cancelText:"Cancel",onConfirm:()=>{s(null),w(a.toLowerCase(),i)},onCancel:()=>s(null)}),N=(e,t)=>{let s=t?"Activate":"repair_required"===e.overlayStatus||"staged_unchecked"===e.overlayStatus?"Repair":"Install";C(`${s} optional runtime?`,t?`Activate validated ${e.label} and restart MoDiff.`:`Install ${e.label} from reviewed, locked artifacts. Activation is separate.`,s,t?async()=>{Fe((await Ia("/runtime/optional-runtimes/activate",{environmentId:t,profileId:e.id,specDigest:e.specDigest,consent:!0},le)).message??"Activation selected.",{variant:"success"}),h(null),await a(),y(e.id,e.specDigest)}:async()=>{let t=await Ia("/runtime/optional-runtimes/install",{profileId:e.id,specDigest:e.specDigest,consent:!0},Xe);if(t.profileId!==e.id||t.specDigest!==e.specDigest)throw Error("Runtime job mismatch.");b.current=0,h(t),await a()})},S=()=>{f&&w("cancel",async()=>{let e=await Ia(`/runtime/optional-runtimes/jobs/${encodeURIComponent(f.id)}/cancel`,{},Xe);if(e.id!==f.id)throw Error("The cancellation response does not match the active job.");h(e),["cancelled","failed"].includes(e.status)&&await a()})},I=n.filter(e=>"workload"===e.kind&&"observed"===e.status),R=!(!e?.activeEnvironmentId||e.previousEnvironmentId||"repair_required"!==e.processLoadStatus),$=!(!e?.previousEnvironmentId&&!R);return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[(0,Ca.jsxs)("div",{className:"grid gap-1 pb-2",children:[(0,Ca.jsx)("strong",{children:"Optional runtimes"}),t.error?(0,Ca.jsx)("p",{className:"text-xs text-modiff-warning",children:t.error}):"loading"===t.status?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading optional runtimes..."}):"success"===t.status&&e?e.profiles.map(t=>{let a=qe(e,t),s=f?.profileId===t.id&&f.specDigest===t.specDigest?f.result?.environmentId:void 0,i="qualified"===t.contractState&&t.cutoverReady,l=s??a,n=l?"Activate":"repair_required"===t.overlayStatus||"staged_unchecked"===t.overlayStatus?"Repair":"Install",r=i&&(l?t.activationAvailable:t.installActionAvailable&&"active"!==t.overlayStatus);return(0,Ca.jsxs)("div",{className:"grid gap-1 text-xs text-modiff-text","data-testid":`optional-runtime-${t.id}`,children:[(0,Ca.jsxs)("span",{children:[t.label," (",$a(t),"):"," ",Ra(t,e.processLoadStatus)]}),f?.profileId===t.id?(0,Ca.jsxs)("div",{className:"flex items-center gap-2","data-testid":"optional-runtime-progress",children:[(0,Ca.jsx)("span",{children:f.progress.message}),["queued","running"].includes(f.status)?(0,Ca.jsx)(At,{size:"compact",disabled:null!==o,onClick:S,children:"Cancel"}):null]}):null,(0,Ca.jsx)("div",{className:"flex gap-1.5",children:r?(0,Ca.jsx)(At,{size:"compact",disabled:null!==o||e.installBusy,loading:o===n.toLowerCase(),onClick:()=>N(t,l),children:n}):null})]},t.id)}):(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No optional runtimes."}),e&&$&&e.profiles.some(e=>e.activationAvailable&&e.cutoverReady&&"qualified"===e.contractState)?(0,Ca.jsx)(At,{size:"compact",disabled:null!==o||e.installBusy,loading:"rollback"===o,onClick:()=>C(R?"Roll back optional runtime to base?":"Roll back optional runtime?",R?"Remove the broken active optional environment and restart MoDiff with the validated base runtime. Active and queued runs must be stopped first.":"Select the previous validated optional environment and restart MoDiff. Active and queued runs must be stopped first.","Rollback",async()=>{Fe((await Ia("/runtime/optional-runtimes/rollback",{consent:!0},le)).message??"Optional runtime rollback selected.",{variant:"success"}),await a()}),children:R?"Rollback to base":"Rollback"}):null]}),(0,Ca.jsxs)(Ct,{label:"Optimizations",panelClassName:"grid gap-2 pt-2",children:[m?(0,Ca.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-modiff-compact border border-modiff-warning p-2",children:[(0,Ca.jsx)("span",{className:"text-xs text-modiff-warning",children:m}),(0,Ca.jsx)(At,{size:"compact",loading:c,onClick:()=>{v().catch(()=>{})},children:"Retry"})]}):c&&!i?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading runtime optimizations…"}):null,i?.capabilities.map(e=>{let t=Ae(e.documentation);return(0,Ca.jsx)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:(0,Ca.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"text-sm font-semibold text-modiff-text",children:e.label}),(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:e.summary}),e.disabledReason?(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-warning",children:e.disabledReason}):null]}),(0,Ca.jsxs)("div",{className:"flex shrink-0 flex-wrap gap-1.5",children:[(0,Ca.jsx)(At,{size:"compact",disabled:!t||null!==o,onClick:()=>{t&&window.open(t,"_blank","noopener,noreferrer")},children:"Docs"}),e.canEnable?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(At,{size:"compact",disabled:null!==o,tone:e.enabled?"primary":"secondary",loading:o===`toggle:${e.id}`,onClick:()=>{k(`toggle:${e.id}`,"/runtime/optimizations/enable",{capabilityId:e.id,enabled:!e.enabled})},children:e.enabled?"Enabled":"Enable"}),(0,Ca.jsx)(At,{size:"compact",disabled:null!==o,loading:o===`probe:${e.id}`,onClick:()=>{k(`probe:${e.id}`,"/runtime/optimizations/probe",{capabilityId:e.id})},children:"Probe"})]}):null]})]})},e.id)}),I.map(e=>(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,Ca.jsxs)("span",{className:"text-xs text-modiff-text",children:["Review ",e.capabilityId," · ",e.modelType||e.artifact||"workload"]}),(0,Ca.jsx)(At,{size:"compact",loading:o===`qualify:${e.id}`,disabled:null!==o,onClick:()=>{k(`qualify:${e.id}`,"/runtime/optimizations/qualify",{receiptId:e.id,outputReviewed:!0})},children:"Reviewed"})]},e.id))]})]})}var Ta=/^[0-9a-f]{40}$/,Aa=/^sha256:canonical-json:[0-9a-f]{64}$/,Pa=/^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/,_a=new Set(["installing","missing","ready","repair_required","unavailable"]);function za(e,t){if(!e||"object"!=typeof e||Array.isArray(e))throw Error(`${t} must be an object.`);return e}function qa(e,t,a){if("string"!=typeof e||!e||e.length>512||a&&!a.test(e))throw Error(`${t} is invalid.`);return e}function Ba(e,t){if(!Number.isSafeInteger(e)||Number(e)<0)throw Error(`${t} is invalid.`);return Number(e)}function Ga(e,t){if("boolean"!=typeof e)throw Error(`${t} is invalid.`);return e}function Da(e){let t=za(e,"Template Gallery status");if(!1!==t.error||1!==t.schemaVersion)throw Error("Template Gallery status reports an unsupported contract.");let a=qa(t.status,"Template Gallery status");if(!_a.has(a))throw Error("Template Gallery status is unknown.");let s={status:a,installed:Ga(t.installed,"Template Gallery installed state"),complete:Ga(t.complete,"Template Gallery completion state"),repairRequired:Ga(t.repairRequired,"Template Gallery repair state"),installing:Ga(t.installing,"Template Gallery installation state"),...void 0===t.repoId?{}:{repoId:qa(t.repoId,"Template Gallery repository",Pa)},...void 0===t.revision?{}:{revision:qa(t.revision,"Template Gallery revision",Ta)},...void 0===t.assetSetId?{}:{assetSetId:qa(t.assetSetId,"Template Gallery asset set",Aa)},...void 0===t.assetCount?{}:{assetCount:Ba(t.assetCount,"Template Gallery asset count")},...void 0===t.totalBytes?{}:{totalBytes:Ba(t.totalBytes,"Template Gallery byte size")},...void 0===t.code?{}:{code:qa(t.code,"Template Gallery status code")},...void 0===t.message?{}:{message:qa(t.message,"Template Gallery status message")}};if("ready"===s.status&&(!s.installed||!s.complete||s.repairRequired||s.installing)||"missing"===s.status&&(s.installed||s.complete||s.repairRequired)||"repair_required"===s.status&&!s.repairRequired||"installing"===s.status&&!s.installing||"unavailable"!==s.status&&(!s.repoId||!s.revision||!s.assetSetId)||"ready"===s.status&&(void 0===s.assetCount||void 0===s.totalBytes))throw Error("Template Gallery status fields conflict.");return s}function Oa(e){let t=za(e,"Template Gallery plan");if(!1!==t.error||1!==t.schemaVersion)throw Error("Template Gallery plan reports an unsupported contract.");let a={repoId:qa(t.repoId,"Template Gallery repository",Pa),repoType:qa(t.repoType,"Template Gallery repository type"),revision:qa(t.revision,"Template Gallery revision",Ta),assetSetId:qa(t.assetSetId,"Template Gallery asset set",Aa),assetCount:Ba(t.assetCount,"Template Gallery asset count"),totalBytes:Ba(t.totalBytes,"Template Gallery total bytes"),downloadBytes:Ba(t.downloadBytes,"Template Gallery download bytes"),stagingBytes:Ba(t.stagingBytes,"Template Gallery staging bytes"),reservationBytes:Ba(t.reservationBytes,"Template Gallery reservation bytes"),queuedReservationBytes:Ba(t.queuedReservationBytes,"Model queue reservation bytes"),reserveBytes:Ba(t.reserveBytes,"Safety reserve bytes"),cacheFreeBytes:Ba(t.cacheFreeBytes,"Gallery cache free bytes"),destinationFreeBytes:Ba(t.destinationFreeBytes,"Gallery destination free bytes"),sameFilesystem:Ga(t.sameFilesystem,"Template Gallery filesystem identity"),sizeKnown:Ga(t.sizeKnown,"Template Gallery size state"),fitsWithQueue:Ga(t.fitsWithQueue,"Template Gallery fit state"),installed:Ga(t.installed,"Template Gallery installed state"),repairRequired:Ga(t.repairRequired,"Template Gallery repair state"),repairReason:null===t.repairReason||void 0===t.repairReason?null:qa(t.repairReason,"Template Gallery repair reason"),installing:Ga(t.installing,"Template Gallery installation state")};if("dataset"!==a.repoType||a.reservationBytes!==a.downloadBytes+a.stagingBytes||a.installed&&a.repairRequired||a.installed&&(0!==a.downloadBytes||0!==a.stagingBytes||0!==a.reservationBytes))throw Error("Template Gallery plan fields conflict.");return a}function Ea(e){let t=za(e,"Template Gallery install result");if(!1!==t.error||!0!==t.complete||"boolean"!=typeof t.alreadyInstalled)throw Error("Template Gallery install did not complete.");let a=Oa({...za(t.plan,"Template Gallery result plan"),error:!1});if(void 0===t.result){if(!t.alreadyInstalled)throw Error("Template Gallery install result is missing.");return{complete:!0,alreadyInstalled:!0,plan:a}}let s=za(t.result,"Installed Template Gallery receipt");if(!0!==s.installed||!0!==s.complete||!1!==s.repairRequired||s.assetSetId!==a.assetSetId||s.repoId!==a.repoId||s.revision!==a.revision||s.assetCount!==a.assetCount||s.totalBytes!==a.totalBytes)throw Error("Installed Template Gallery receipt does not match its plan.");return{complete:!0,alreadyInstalled:!1,plan:a,result:{installed:!0,complete:!0,repairRequired:!1,assetCount:Ba(s.assetCount,"Installed Template Gallery asset count"),totalBytes:Ba(s.totalBytes,"Installed Template Gallery byte size"),assetSetId:qa(s.assetSetId,"Installed Template Gallery asset set",Aa),repoId:qa(s.repoId,"Installed Template Gallery repository",Pa),revision:qa(s.revision,"Installed Template Gallery revision",Ta),restartRequired:Ga(s.restartRequired,"Template Gallery restart requirement")}}}function La(e){if(!e||e<=0)return"0 B";let t=["B","KiB","MiB","GiB","TiB"],a=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),s=e/1024**a;return`${s.toFixed(s>=10||0===a?0:1)} ${t[a]}`}function Fa(e,t){return t&&!e?"Checking":e?"ready"===e.status?"Ready":"installing"===e.status?"Installing":"repair_required"===e.status?"Repair required":"missing"===e.status?"Not installed":"Unavailable":"Unavailable"}function Ha(){let e=ta(e=>e.setAlertOpener),[t,a]=(0,ka.useState)(null),[s,i]=(0,ka.useState)(!0),[l,n]=(0,ka.useState)(!1),[o,d]=(0,ka.useState)(null),c=(0,ka.useRef)(0),u=(0,ka.useCallback)(async()=>{let e=++c.current;i(!0);try{let t=await Q(`${Gt.serverAddress}/template_gallery/status`,{timeoutMs:12e4,parse:Da});if(e!==c.current)return;a(t),d(null)}catch(t){if(e!==c.current)return;d(De(t,"Could not inspect Template Gallery assets."))}finally{e===c.current&&i(!1)}},[]);(0,ka.useEffect)(()=>{u()},[u]);let m="ready"===t?.status,p="missing"===t?.status||"repair_required"===t?.status;return(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"template-gallery-setup-card",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(r,{size:15,className:"text-hf-yellow"}),(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Template Gallery assets"})]}),(0,Ca.jsx)(Ke,{label:Fa(t,s),tone:m?"success":o||t?.repairRequired?"error":"warning",title:o||t?.message||t?.assetSetId})]}),(0,Ca.jsx)("p",{className:"mt-2 text-xs leading-5 text-modiff-subtle-text",children:"Byte-pinned Gallery previews and default workflow inputs are installed from the app's immutable public Dataset. Model caches are separate and are never removed by this action."}),t?.complete&&(0,Ca.jsxs)("p",{className:"mt-1 text-xs text-modiff-green",children:[t.assetCount??0," files · ",La(t.totalBytes)," · ",t.revision?.slice(0,12)]}),o&&(0,Ca.jsx)("p",{className:"mt-1 break-words text-xs text-modiff-red",children:o}),(0,Ca.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[p&&(0,Ca.jsx)(At,{size:"compact",loading:l||t?.installing,disabled:s||l||t?.installing,onClick:()=>{(async()=>{if(!l){n(!0);try{let t=await Q(`${Gt.serverAddress}/template_gallery/plan`,{timeoutMs:12e4,parse:Oa});if(!t.sizeKnown||!t.fitsWithQueue)throw Error(`The verified ${La(t.reservationBytes)} Gallery reservation does not fit alongside ${La(t.queuedReservationBytes)} of active model reservations and the ${La(t.reserveBytes)} safety reserve.`);e({title:t.repairRequired?"Repair Template Gallery assets?":"Install Template Gallery assets?",message:`Download and hash-verify ${t.assetCount} files (${La(t.totalBytes)}) from ${t.repoId} at immutable revision ${t.revision.slice(0,12)}. Existing model downloads and cached models will not be removed.`,confirmText:t.repairRequired?"Repair":"Install",cancelText:"Cancel",onConfirm:()=>{e(null),(async()=>{try{Fe((await Q(`${Gt.serverAddress}/template_gallery/install`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({}),timeoutMs:864e5,parse:Ea})).result?.restartRequired?"Template Gallery installed. Restart MoDiff after active downloads finish to serve it locally.":"Template Gallery is already installed.",{variant:"success"}),await u()}catch(e){let t=De(e,"Template Gallery installation failed.");d(t),Fe(t,{variant:"error"})}finally{n(!1)}})()},onCancel:()=>{e(null),n(!1)}})}catch(e){let t=De(e,"Could not plan the Template Gallery installation.");d(t),Fe(t,{variant:"error"}),n(!1)}}})()},"data-testid":"template-gallery-install",children:t?.repairRequired?"Check & repair":"Check & install"}),(0,Ca.jsx)(At,{size:"compact",tone:"secondary",icon:(0,Ca.jsx)(q,{size:14}),disabled:s||l,onClick:()=>{u()},"data-testid":"template-gallery-refresh",children:"Refresh"})]})]})}var Ka=(0,ka.lazy)(()=>Ye(()=>import(`./CompositeMigrationCard.js?v=ca6b74e6a02eedb3`).then(e=>({default:e.CompositeMigrationCard})),[]));function Wa(e){if(!e||e<=0)return"0 B";let t=["B","KB","MB","GB","TB"],a=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1),s=e/1024**a;return`${s.toFixed(s>=10||0===a?0:1)} ${t[a]}`}function Va(e){return e&&0!==Object.keys(e).length?Object.entries(e).slice(0,5).map(([e,t])=>`${e}: ${t}`).join(", "):"no files"}function Ua(e){return e?e.details?`${e.message} ${e.details}`:e.message:""}var Qa=["environment","package","backend","model_integrity","model","hardware_fit","asset","user_input","graph"],Ja={environment:"Environment",package:"Packages",backend:"Backend",model_integrity:"Model integrity",model:"Models",hardware_fit:"Hardware fit",asset:"Assets",user_input:"Inputs",graph:"Graph"};function Za(e){return"success"===e?"success":"warning"===e?"warning":"info"===e?"info":"error"}function Xa({children:e,tone:t="muted",testId:a}){return(0,Ca.jsx)("p",{"data-testid":a,className:Me("break-words text-xs leading-5","muted"===t&&"text-modiff-subtle-text","success"===t&&"text-modiff-green","error"===t&&"text-modiff-red","warning"===t&&"text-hf-orange"),children:e})}function Ya({children:e,disabled:t,onClick:a,progress:s,testId:i,title:l,tone:n}){return(0,Ca.jsx)(Ke,{action:"Installing"===("string"==typeof e?e:void 0)?"installing":a?"install":"success"===n?"ready":"warning"===n||"error"===n?"missing":"details",className:"min-h-7 px-2 py-0.5 text-xs",disabled:t,label:e,onClick:a,progress:s,testId:i,title:l,tone:"default"===n?"neutral":n})}function es(){let e=aa(e=>e.hfCache),t=aa(e=>e.localModels),a=aa(e=>e.modelCacheDiagnostics),s=aa(e=>e.studioModelCapabilities),i=aa(e=>e.runtimeStatus),l=aa(e=>e.runtimeError),n=aa(e=>e.hfDownloadProgress),r=aa(e=>e.refreshModelIndexes),o=aa(e=>e.fetchRuntimeStatus),d=aa(e=>e.fetchStudioModelCapabilities),c=aa(e=>e.installHfModel),m=ze(e=>e.form),p=ze(e=>e.activeTemplateId),f=ze(e=>e.graphBinding),h=ze(e=>e.sourceOutputId);be(e=>[e.nodes.map(e=>{let t=Object.entries(e.data.params).filter(([e])=>/repo|model|checkpoint|ckpt|safetensors|lora|vae|controlnet|adapter/i.test(e)).map(([e,t])=>`${e}:${JSON.stringify(t.value??t.default??"")}`).join(",");return`${e.id}:${e.data.module}:${e.data.action}:${e.data.uiState?.disabled?"disabled":"enabled"}:${t}`}).join("|"),e.edges.map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}->${e.target}:${e.targetHandle??""}`).join("|")].join("||"));let x=ze(e=>e.autoResourcePlans),b=ze(e=>e.setAutoResourcePlans),j=ta(e=>e.setModelManagerOpener),v=ta(e=>e.setRightPanelOpen),y=ta(e=>e.setRightPanelTab),w=J(e=>e.showIssues),k=mt(e=>e.sid),C=mt(e=>e.isConnected),I=Object.values(n).filter(jt).length,R=Object.entries(n).filter(([,e])=>jt(e)||Yt(e)||Nt(e)),$=Lt(),M=!!(p||f||h),T=!(!f||!Te(f))||!M&&!f&&($.nodeCount>0||$.blockingIssues.length>0),A=ye(m),P=Z[m.modelType],_=M&&P?[{profile:P,mode:m.mode,status:Ce(P,e,t,a),backendCapability:s.find(e=>e.modelType===P.modelType),autoPlanKey:A,autoPlan:x[A]}]:[],z=M&&P?te({autoResourcePlan:x[A],form:m,hfCache:e,includePipeline:!1,localModels:t,modelCacheDiagnostics:a}):[],B=T?Ze({references:$.modelRefs,hfCache:e,localModels:t,modelCacheDiagnostics:a}).filter(e=>!e.status.runnable):[],G=$.blockingIssues[0]??null,O=function(e){return new Set(e.modelRefs.map(e=>`${e.kind}:${e.value}`)).size}($),E=ea({sid:k,isConnected:C,includeStudio:!T}),L=(0,ka.useMemo)(()=>Qa.map(e=>({category:e,label:Ja[e],issues:E.blockingIssues.filter(t=>t.category===e)})).filter(e=>e.issues.length>0),[E.blockingIssues]),F=async()=>{if(!M)return;let e=await st([m],[A]),t={};e.forEach(e=>{let a=e.planKey??A;a&&(t[a]=e)}),b(t)},H=async()=>{await r(!0,{invalidateAutoPlans:!1}),await F()},K=()=>{v(!0),y("studio")},W=()=>{w(E.issues)},V=e=>"install_model"===e.action&&e.repoId?(0,Ca.jsx)(At,{tone:"primary",icon:(0,Ca.jsx)(D,{size:15}),onClick:()=>{(async e=>{try{await c(e,k),await H()}catch(e){console.error(e)}})(e.repoId)},children:"Install"}):"open_model_manager"===e.action?(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(u,{size:15}),onClick:()=>j({nodeId:null,fieldKey:null}),children:"Models"}):"refresh_cache"===e.action?(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(q,{size:15}),onClick:()=>{H()},children:"Refresh"}):"select_image"===e.action?(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(N,{size:15}),onClick:K,children:"Studio"}):(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(g,{size:15}),onClick:W,children:"Review"});(0,ka.useEffect)(()=>{o(),d()},[o,d]),(0,ka.useEffect)(()=>{if(!M)return;let e=!1;return st([m],[A]).then(t=>{if(e)return;let a={};t.forEach(e=>{let t=e.planKey??A;t&&(a[t]=e)}),b(a)}).catch(e=>{console.error(e)}),()=>{e=!0}},[m,M,e.length,t.length,i?.ready,b,A]);let U=async e=>{try{await c(e.repo,k,{repair:e.repair,revision:e.revision,files:e.files}),await H()}catch(e){console.error(e)}},Q=async e=>{try{await X({modelType:e.modelType}),await F()}catch(e){console.error(e)}};return(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"setup-panel",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("div",{children:(0,Ca.jsx)("h2",{className:"text-base font-bold text-modiff-text",children:"Model Health"})}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(u,{size:15}),"data-testid":"setup-models",onClick:()=>j({nodeId:null,fieldKey:null}),children:"Models"}),(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(q,{size:15}),"data-testid":"setup-refresh",onClick:()=>{H()},children:"Refresh"})]})]}),(0,Ca.jsx)(Sa,{error:l,status:i}),(0,Ca.jsx)(Ma,{}),(0,Ca.jsx)(Ha,{}),L.length>0&&(0,Ca.jsxs)("section",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-current-issues",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,Ca.jsx)("div",{children:(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Current issues"})}),(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(g,{size:15}),onClick:W,children:"Review all"})]}),L.map(e=>(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("h4",{className:"text-xs font-bold uppercase text-modiff-subtle-text",children:[e.label," (",e.issues.length,")"]}),(0,Ca.jsx)("div",{className:"grid gap-2",children:e.issues.map(e=>(0,Ca.jsx)(we,{tone:Za(e.severity),title:e.message,action:V(e),testId:`setup-current-issue-${e.id}`},e.id))})]},e.category))]}),R.length>0&&(0,Ca.jsxs)("section",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-downloads",children:[(0,Ca.jsxs)("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold",children:"Downloads"}),(0,Ca.jsxs)(Ya,{tone:I>0?"default":"warning",title:`${I} active model download${1===I?"":"s"}`,children:[I," active"]})]}),(0,Ca.jsx)("div",{className:"grid gap-2",children:R.map(([e,t])=>(0,Ca.jsx)(Je,{repoId:e,progress:t,testId:`setup-download-${e}`},e))})]}),(0,Ca.jsxs)(Ct,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"setup-advanced-diagnostics",label:(0,Ca.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(S,{size:15,className:"text-hf-yellow"}),"Advanced diagnostics"]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-3",children:[(0,Ca.jsx)(ka.Suspense,{fallback:(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Loading migration tools…"}),children:(0,Ca.jsx)(Ka,{})}),T?(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"setup-workflow-model-health",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Current graph"}),(0,Ca.jsx)(Ya,{tone:"default",title:"Models referenced by the visible canvas graph are shown here.",children:"Contextual"})]}),(0,Ca.jsx)(Bt,{tone:G||B.length>0?"error":"success",title:G?"Graph needs attention":"Graph model checks",meta:Ua(G)||`${$.nodeCount} nodes, ${$.outputPathCount} connected output path${1===$.outputPathCount?"":"s"}.`,testId:"setup-current-graph-health",children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,Ca.jsxs)(Ya,{tone:$.outputPathCount>0?"success":"error",title:`${$.outputPathCount} connected output path${1===$.outputPathCount?"":"s"}.`,children:[$.outputPathCount," outputs"]}),(0,Ca.jsxs)(Ya,{tone:B.length>0?"warning":"success",title:`${O} detected model reference${1===O?"":"s"}.`,children:[O," models"]})]}),B.length>0&&(0,Ca.jsx)("div",{className:"grid gap-2 border-t border-modiff-border pt-2",children:B.map(e=>(0,Ca.jsx)(xa,{activeInstallCount:I,actionTestId:`setup-install-graph-requirement-${e.id}`,installProgress:n,onInstall:e=>U(e),onUseLocal:e=>j({nodeId:null,fieldKey:null,focus:{label:e.label,repo:e.repo,requirementId:e.id,source:"setup"}}),requirement:e,testId:`setup-graph-requirement-${e.id}`},e.id))})]})})]}):M?(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"setup-workflow-model-health",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2",children:[(0,Ca.jsx)("h3",{className:"text-sm font-bold text-modiff-text",children:"Workflow model"}),(0,Ca.jsx)(Ya,{tone:"default",title:"Only models used by the current workflow are shown here.",children:"Contextual"})]}),_.map(({autoPlan:e,backendCapability:t,profile:a,status:s})=>(0,Ca.jsx)(ts,{activeInstallCount:I,autoPlan:e,form:m,backendCapability:t,hfDownloadProgress:n,onInstall:U,onUseLocal:e=>j({nodeId:null,fieldKey:null,focus:{label:e.label,repo:e.repo,requirementId:e.id,source:"setup"}}),onClearHistory:Q,profile:a,requirements:z,status:s},a.modelType))]}):(0,Ca.jsxs)("section",{className:"flex items-center gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3 text-xs text-modiff-subtle-text","data-testid":"setup-workflow-model-empty",children:[(0,Ca.jsx)(g,{size:15,className:"shrink-0 text-modiff-subtle-text"}),(0,Ca.jsx)("span",{children:"Workflow model checks appear after you create, update, or restore a workflow."})]}),a&&(0,Ca.jsxs)(Ct,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-3",label:(0,Ca.jsxs)("span",{className:"flex items-center gap-2",children:[(0,Ca.jsx)(S,{size:15,className:"text-hf-yellow"}),"Diagnostics and scanned locations"]}),buttonClassName:"p-0",panelClassName:"mt-3 grid gap-3",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"Scanned model locations"}),(a.locations||[]).map(e=>{let t=e.repo_count??e.file_count??0,a=void 0===e.repo_count?`${t} files`:`${t} repos`,s=[e.external_package_count?`${e.external_package_count} external packages`:null,e.compatible_hf_repo_count?`${e.compatible_hf_repo_count} HF-compatible repos`:null,e.model_file_bytes?`${Wa(e.model_file_bytes)} model weights`:null].filter(Boolean).join(" | ");return(0,Ca.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2",children:[(0,Ca.jsxs)(Xa,{tone:e.exists?"muted":"warning",children:[e.label,": ",e.path||"default"," | ",e.exists?"exists":"missing"," |"," ",a," | ",!1===e.runnable?"discovered but not runnable":"runnable"]}),s&&(0,Ca.jsxs)(Xa,{children:[s," | ",Va(e.extension_counts)]}),e.reason&&!1===e.runnable&&(0,Ca.jsx)(Xa,{tone:"warning",children:e.reason}),e.error&&(0,Ca.jsx)(Xa,{tone:"error",children:e.error})]},`${e.label}-${e.path}`)})]}),(a.external_model_packages?.length??0)>0&&(0,Ca.jsxs)("section",{"data-testid":"setup-external-models",children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"Detected external packages"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:a.external_model_packages?.slice(0,8).map(e=>(0,Ca.jsxs)(Bt,{tone:e.runnable?"success":"warning",title:e.label,meta:`${e.format} | ${e.file_count??0} files | ${Wa(e.model_file_bytes)}`,children:[(0,Ca.jsx)(Xa,{children:e.path}),(0,Ca.jsx)(Xa,{tone:e.runnable?"success":"warning",children:e.reason})]},`${e.source}-${e.path}`))})]}),(a.hf_compatible_external_repos?.length??0)>0&&(0,Ca.jsxs)("section",{"data-testid":"setup-external-hf-repos",children:[(0,Ca.jsx)("h3",{className:"mb-1 text-sm font-bold",children:"HF-compatible external repos"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:a.hf_compatible_external_repos?.slice(0,8).map(e=>(0,Ca.jsxs)(Bt,{tone:"warning",title:e.repo_id,meta:e.source,children:[(0,Ca.jsx)(Xa,{children:e.path}),(0,Ca.jsx)(Xa,{tone:"warning",children:e.reason})]},`${e.source}-${e.path}`))})]})]})]})]})}function ts({activeInstallCount:e,autoPlan:t,form:a,backendCapability:s,hfDownloadProgress:i,onClearHistory:l,onInstall:n,onUseLocal:r,profile:o,requirements:d,status:c}){let u=oa(t,a),m=Ut(t,a),p=ce(t,a),f=t?p:c.runnable,h=u?.repo??o.defaultRepo,x=i[h],g=jt(x),b=s?.inpaintContract??o.inpaintContract,j=Ve(t,a),v=$e(t,a),y=f?"success":"unsuitable"===v.state?"error":"warning",w=f?"success":"error"===y?"error":"warning",k=m?.resolvedArtifact??m?.artifact??u?.repo??o.defaultRepo,C=f?j:g?"Installing":Yt(x)?"Retry":u?.actionLabel??"Install",N=g||!f&&e>=2;return(0,Ca.jsx)(Bt,{testId:`setup-model-${o.modelType}`,tone:y,title:o.label,meta:k,action:(0,Ca.jsx)(Ya,{tone:w,title:f?j:u?.reason??u?.repo??j,disabled:N,progress:g?Dt(x):null,testId:`setup-install-${o.modelType}`,onClick:!f&&u?()=>{n(u)}:void 0,children:C}),children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,Ca.jsx)(Ya,{tone:c.runnable?"success":"warning",title:c.reason,children:c.runnable?"Cached":"Missing"}),(0,Ca.jsx)(Ya,{tone:f?"success":"error"===y?"error":"warning",title:t?.blockingReason||m?.reason||u?.reason||t?.willNotWorkReason||j,children:"Auto"}),(0,Ca.jsx)(Ya,{tone:s?"success":"warning",title:s?`Backend modes: ${(s.modes||[]).join(", ")}`:"Backend capability metadata not reported for this profile.",children:"Backend"}),(0,Ca.jsx)(Ya,{tone:"success"===v.severity?"success":"error"===v.severity?"error":"info"===v.severity?"default":"warning",title:`${v.summary} ${v.detail}`,children:"Compatibility"}),b&&(0,Ca.jsx)(Ya,{tone:b.available?"success":"warning",title:b.available?"Native mask execution available.":b.reason,children:"Inpaint"})]}),c.matchingExternalPackages.length>0&&(0,Ca.jsx)(Ya,{tone:"warning",title:`Matching external package: ${c.matchingExternalPackages.slice(0,3).join(", ")}`,children:"External package"}),c.matchingExternalRepos.length>0&&(0,Ca.jsx)(Ya,{tone:"warning",title:`Matching HF-compatible external repo: ${c.matchingExternalRepos.slice(0,3).join(", ")}`,children:"External repo"}),x&&(0,Ca.jsx)(Je,{testId:`setup-download-progress-${o.modelType}`,repoId:h,progress:x}),(t?.failureHistory?.length??0)>0&&(0,Ca.jsx)("div",{children:(0,Ca.jsx)(At,{tone:"secondary","data-testid":`setup-clear-auto-history-${o.modelType}`,onClick:()=>{l(o)},children:"Clear Auto history"})}),d.length>0&&(0,Ca.jsx)("div",{className:"grid gap-2 border-t border-modiff-border pt-2",children:d.map(t=>(0,Ca.jsx)(xa,{activeInstallCount:e,actionTestId:`setup-install-requirement-${t.id}`,installProgress:i,onInstall:e=>n(e),onUseLocal:r,requirement:t,testId:`setup-model-requirement-${t.id}`},t.id))})]})})}function as({children:e,disabled:t,icon:a,onClick:s,testId:i}){return(0,Ca.jsx)(At,{tone:"primary",icon:a,"data-testid":i,disabled:t,onClick:s,children:(0,Ca.jsx)("span",{children:e})})}function ss(e){if("number"!=typeof e||!Number.isFinite(e))return"-";if(e<1e3)return`${Math.max(0,Math.round(e))}ms`;let t=e/1e3;return t<60?`${t.toFixed(+(t<10))}s`:`${Math.floor(t/60)}:${Math.round(t%60).toString().padStart(2,"0")}`}function is(e){return"number"==typeof e&&Number.isFinite(e)?ss(1e3*e):null}function ls(e){return"number"==typeof e.durationMs?e.durationMs:e.completedAtMs&&e.startedAtMs?Math.max(0,e.completedAtMs-e.startedAtMs):void 0}function ns({children:e,fallbackStatus:t,focused:a=!1,pending:s=!1,severity:i="default",task:l,taskId:n,testId:r}){if(!l)return null;let o=ie(l,n),d=at(oe(l))||l.error||l.message||`${o} · ${t}`;return(0,Ca.jsx)(et,{content:d,placement:"top",children:c=>(0,Ca.jsx)(At,{...c,align:"left",fullWidth:!0,tone:"secondary",loading:s,"data-testid":r,"aria-label":`Open ${o} run details. ${d}`,onClick:()=>{re(Ge(l,n,t))},className:Me("h-auto! min-w-0 rounded-none p-2","success"===i&&"border-modiff-green/60","error"===i&&"border-modiff-red/70 bg-modiff-red/10 hover:border-modiff-red",a&&"ring-2 ring-hf-yellow"),children:e})})}function rs(){let e=sa(e=>e.currentTask),t=sa(e=>e.queuedTasks),a=sa(e=>e.failedTasks),i=sa(e=>e.sessionRuns),l=sa(e=>e.fetchTasks),n=sa(e=>e.clearCompletedSessionRuns),r=sa(e=>e.focusedTaskId),o=ta(e=>e.runActivityPendingTaskId),d=Object.entries(t),c=Object.entries(a).slice(0,8),u=i.filter(e=>"completed"===e.status||"failed"===e.status||"cancelled"===e.status).slice(0,10);return(0,ka.useEffect)(()=>{l()},[l]),(0,ka.useEffect)(()=>{r&&document.getElementById(`queue-task-${r}`)?.scrollIntoView({block:"nearest",behavior:"smooth"})},[r,e,t,i,a]),(0,Ca.jsxs)("div",{className:"p-3 text-sm text-modiff-text","data-testid":"queue-panel",children:[(0,Ca.jsxs)("div",{className:"mb-2 flex flex-wrap gap-2",children:[(0,Ca.jsx)(as,{icon:(0,Ca.jsx)(q,{size:15}),testId:"queue-refresh",onClick:()=>{l()},children:"Refresh"}),(0,Ca.jsx)(as,{icon:(0,Ca.jsx)(s,{size:15}),testId:"queue-stop",onClick:()=>{(async()=>{try{Fe((await tt()).message||"Stop requested",{variant:"success",autoHideDuration:3e3})}catch(e){Fe(De(e,"Could not stop the current execution."),{variant:"error",autoHideDuration:5e3})}})()},disabled:!e,children:"Stop"})]}),(0,Ca.jsx)("h2",{className:"mb-2 text-sm font-bold",children:"Current run"}),e?(0,Ca.jsx)(ns,{fallbackStatus:"running",focused:r===e.task_id,pending:o===e.task_id,task:e,taskId:e.task_id||"current",testId:"queue-current-run",children:(0,Ca.jsxs)("span",{id:`queue-task-${e.task_id||"current"}`,className:"block min-w-0 flex-1",children:[(0,Ca.jsxs)("span",{className:"flex items-center justify-between gap-2",children:[(0,Ca.jsxs)("span",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:ie(e,e.task_id||"Running task")}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.message||e.task_id||e.sid})]}),(0,Ca.jsx)(I,{size:16,className:"flex-none text-hf-yellow"})]}),(e.current_step||e.eta_seconds||e.average_step_seconds)&&(0,Ca.jsxs)("span",{className:"mt-2 flex flex-wrap gap-x-3 gap-y-1 text-xs text-modiff-subtle-text",children:[e.current_step&&e.total_steps?(0,Ca.jsx)("span",{children:`Step ${e.current_step}/${e.total_steps}`}):null,is(e.eta_seconds)?(0,Ca.jsx)("span",{children:`ETA ${is(e.eta_seconds)}`}):null,is(e.average_step_seconds)?(0,Ca.jsx)("span",{children:`${is(e.average_step_seconds)}/step`}):null]}),(0,Ca.jsx)(Ft,{value:e.progress,className:"mt-2"})]})}):(0,Ca.jsx)("p",{className:"mb-4 text-xs text-modiff-subtle-text",children:"No current run."}),(0,Ca.jsx)("h2",{className:"mb-2 text-sm font-bold",children:"Queued runs"}),0===d.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No queued runs."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:d.map(([e,t])=>(0,Ca.jsxs)("div",{id:`queue-task-${e}`,"data-testid":`queue-run-${e}`,className:Me("flex items-stretch border border-modiff-border bg-modiff-surface",r===e&&"ring-2 ring-hf-yellow"),children:[(0,Ca.jsx)(At,{align:"left",fullWidth:!0,tone:"ghost",loading:o===(t.task_id||e),"aria-label":`Open ${ie(t,e)} run details`,onClick:()=>{re(Ge(t,e,"queued"))},className:"h-auto! min-w-0 flex-1 rounded-none p-2",children:(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:ie(t,e)}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:t.task_id||t.sid})]})}),(0,Ca.jsx)(At,{tone:"ghost",size:"dense",title:"Cancel queued task",onClick:()=>{(async e=>{try{await It(e),Fe("Queued task cancelled",{variant:"success",autoHideDuration:2200}),await l()}catch(e){Fe(De(e,"Could not cancel the queued task."),{variant:"error",autoHideDuration:5e3})}})(e)},icon:(0,Ca.jsx)(R,{size:15}),className:"h-auto! flex-none rounded-none border-l border-modiff-border px-2 text-modiff-subtle-text",children:(0,Ca.jsx)("span",{children:"Cancel"})})]},e))}),(0,Ca.jsxs)("div",{className:"mb-2 mt-4 flex items-center justify-between gap-2",children:[(0,Ca.jsx)("h2",{className:"text-sm font-bold",children:"Session history"}),(0,Ca.jsx)(At,{tone:"ghost",size:"dense",disabled:0===u.length,onClick:n,icon:(0,Ca.jsx)(L,{size:14}),className:"px-2 text-xs",children:"Clear finished"})]}),0===u.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Completed runs will appear here for this browser session."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:u.map(e=>(0,Ca.jsx)(ns,{fallbackStatus:e.status??"completed",focused:r===(e.task_id||e.id),pending:o===(e.task_id||e.id),severity:"failed"===e.status?"error":"completed"===e.status?"success":"default",task:e,taskId:e.task_id||e.id,testId:`queue-session-run-${e.id}`,children:(0,Ca.jsx)("span",{id:`queue-task-${e.task_id||e.id}`,className:"block min-w-0 flex-1",children:(0,Ca.jsxs)("span",{className:"flex items-start gap-2",children:["completed"===e.status?(0,Ca.jsx)(E,{size:16,className:"mt-0.5 flex-none text-modiff-green"}):(0,Ca.jsx)(R,{size:16,className:"mt-0.5 flex-none text-modiff-red"}),(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm",children:ie(e,e.task_id||e.id)}),(0,Ca.jsx)("span",{className:"block truncate text-xs text-modiff-subtle-text",children:e.error||e.message||e.task_id||e.sid})]}),(0,Ca.jsx)("span",{className:"flex-none text-xs font-semibold text-modiff-subtle-text",children:ss(ls(e))})]})})},e.id))}),(0,Ca.jsx)("h2",{className:"mb-2 mt-4 text-sm font-bold",children:"Failed runs"}),0===c.length?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"No failed runs recorded in this session."}):(0,Ca.jsx)("div",{className:"grid gap-2",children:c.map(([e,t])=>(0,Ca.jsx)(ns,{fallbackStatus:"failed",focused:r===e,pending:o===(t.task_id||e),severity:"error",task:t,taskId:e,testId:`queue-failed-run-${e}`,children:(0,Ca.jsxs)("span",{id:`queue-task-${e}`,className:"block min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-sm text-modiff-red",children:ie(t,e)}),(0,Ca.jsx)("span",{className:"block break-all text-xs text-modiff-subtle-text",children:t.task_id||t.sid}),t.error&&(0,Ca.jsx)("span",{className:"block break-words text-xs text-modiff-red",children:t.error})]})},e))})]})}function os(){let e=(0,ka.useRef)(null),[t,a]=(0,ka.useState)(""),[s,i]=(0,ka.useState)(!1),{referenceImages:l,addReferenceImage:r,replaceReferenceImage:o,removeReferenceImage:d,moveReferenceImage:c,setReferenceImages:u,alphaMode:m,updateForm:p}=ze(xe(e=>({referenceImages:e.form.referenceImages,alphaMode:e.form.alphaMode,addReferenceImage:e.addReferenceImage,replaceReferenceImage:e.replaceReferenceImage,removeReferenceImage:e.removeReferenceImage,moveReferenceImage:e.moveReferenceImage,setReferenceImages:e.setReferenceImages,updateForm:e.updateForm})));return(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)(Qe,{title:"Image input workspace",action:(0,Ca.jsx)(pe,{title:"Upload images",onClick:()=>e.current?.click(),disabled:s,children:s?(0,Ca.jsx)(da,{size:18}):(0,Ca.jsx)(N,{size:16})})}),(0,Ca.jsx)(Et,{ref:e,"aria-label":"Upload reference images",accept:ae(["image"]),multiple:!0,hidden:!0,onChange:e=>{(async e=>{if(!e||0===e.length)return;let t=Be();i(!0);try{let a=[];for(let s of Array.from(e))a.push(...await Pt(s,"images")),se(t);u([...ze.getState().form.referenceImages,...a]),ne(t),Ue()}catch(e){if(V(e))return;Fe(De(e,"Could not upload the reference image."),{variant:"error",autoHideDuration:5e3})}finally{i(!1)}})(e.target.files)}}),(0,Ca.jsxs)("div",{className:"mb-2 flex gap-2",children:[(0,Ca.jsx)(ut,{"aria-label":"Reference image path or URL",value:t,onChange:e=>a(e.target.value),placeholder:"Image path or URL",className:"flex-1"}),(0,Ca.jsx)(pe,{title:"Add image",onClick:()=>{r(t),a(""),queueMicrotask(()=>Ue())},disabled:!t.trim(),children:(0,Ca.jsx)(y,{size:17})})]}),(0,Ca.jsx)(Se,{"aria-label":"Reference image alpha handling",value:m,onValueChange:e=>{p({alphaMode:e}),queueMicrotask(()=>Ue())},options:[{value:"ignore",label:"Alpha: ignore"},{value:"add alpha",label:"Alpha: add alpha"},{value:"remove alpha",label:"Alpha: remove alpha"}],className:"mb-2 w-full"}),(0,Ca.jsx)("div",{className:"grid grid-cols-[repeat(auto-fit,minmax(86px,1fr))] gap-2",children:l.map((e,t)=>(0,Ca.jsxs)("div",{className:"border border-modiff-border bg-modiff-bg",children:[(0,Ca.jsx)(U,{src:Tt(e),alt:e,fit:"cover",aspectRatio:"1 / 1",bordered:!1}),(0,Ca.jsx)(ut,{"aria-label":`Reference image ${t+1} path`,value:e,onChange:e=>{o(t,e.target.value),queueMicrotask(()=>Ue())},className:"h-7 w-full border-0 bg-transparent px-1 text-xs"}),(0,Ca.jsxs)("div",{className:"flex justify-between",children:[(0,Ca.jsx)(pe,{title:"Move up",disabled:0===t,onClick:()=>{c(t,-1),queueMicrotask(()=>Ue())},children:(0,Ca.jsx)(n,{size:15})}),(0,Ca.jsx)(pe,{title:"Move down",disabled:t===l.length-1,onClick:()=>{c(t,1),queueMicrotask(()=>Ue())},children:(0,Ca.jsx)(F,{size:15})}),(0,Ca.jsx)(pe,{title:"Remove",onClick:()=>{d(t),queueMicrotask(()=>Ue())},children:(0,Ca.jsx)(L,{size:15})})]})]},`${e}-${t}`))})]})}function ds({isWorking:e,runBlocked:a,expertMode:s=!1,hasManagedForm:i=!0,hasComparePair:l,hasGalleryItems:n,onCompareLatest:o,onExport:d,onInterrupt:c,onRun:p,onUpdateGraph:f,onSavePrompt:h,onOpenGallery:x,onOpenTemplateGallery:g,onOpenSetup:b,onRestoreLatest:j,onRerunLatest:y}){let[w,k]=(0,ka.useState)(!1),[N,S]=(0,ka.useState)(""),I=(0,ka.useMemo)(()=>[{id:"run",label:"Run workflow",detail:"Queue the current Studio graph.",icon:(0,Ca.jsx)(G,{size:15}),disabled:e||a,run:p},...s&&i?[{id:"update",label:"Sync graph",detail:"Reconcile Studio fields with visible graph nodes.",icon:(0,Ca.jsx)(q,{size:15}),disabled:e,run:f}]:[],{id:"interrupt",label:"Interrupt run",detail:"Ask the backend to stop the active or queued execution.",icon:(0,Ca.jsx)(T,{size:15}),run:c},...i?[{id:"save-prompt",label:"Save prompt",detail:"Store the current prompt as a reusable snippet.",icon:(0,Ca.jsx)(C,{size:15}),run:h}]:[],...s?[{id:"export",label:"Export API graph",detail:"Download the current runnable graph JSON.",icon:(0,Ca.jsx)(D,{size:15}),run:d}]:[],{id:"gallery",label:"Open gallery",detail:"Inspect, compare, restore, rerun, and export outputs.",icon:(0,Ca.jsx)(r,{size:15}),run:x},{id:"compare",label:"Compare latest",detail:"Open the latest two Gallery outputs side by side.",icon:(0,Ca.jsx)(v,{size:15}),disabled:!l,run:o},{id:"restore-latest",label:"Restore latest",detail:"Restore the newest Gallery workflow into Studio.",icon:(0,Ca.jsx)(t,{size:15}),disabled:!n,run:j},{id:"rerun-latest",label:"Rerun latest",detail:"Restore and queue the newest Gallery workflow.",icon:(0,Ca.jsx)(G,{size:15}),disabled:!n||e||a,run:y},{id:"templates",label:"Browse templates",detail:"Search categorized workflow templates for the current task.",icon:(0,Ca.jsx)(m,{size:15}),run:g},{id:"setup",label:"Open setup",detail:"Repair missing models and runtime readiness.",icon:(0,Ca.jsx)(u,{size:15}),run:b}],[s,i,l,n,e,o,d,c,x,b,g,j,y,p,h,f,a]),R=(0,ka.useMemo)(()=>{let e=N.trim().toLowerCase();return e?I.filter(t=>`${t.label} ${t.detail}`.toLowerCase().includes(e)):I},[I,N]);return(0,ka.useEffect)(()=>{let t=t=>{let s=t.ctrlKey||t.metaKey;s&&"k"===t.key.toLowerCase()&&(t.preventDefault(),k(!0)),s&&"Enter"===t.key&&!e&&!a&&(t.preventDefault(),p())};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e,p,a]),(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(rt,{tone:"ghost",fullWidth:!0,icon:(0,Ca.jsx)(m,{size:15}),onClick:()=>k(!0),children:"Command palette"}),(0,Ca.jsxs)(ht,{open:w,onClose:()=>{k(!1),S("")},title:"Command palette",panelClassName:"max-w-xl",bodyClassName:"!p-2",children:[(0,Ca.jsx)(Qt,{autoFocus:!0,"aria-label":"Search commands",value:N,onChange:e=>S(e.target.value),onClear:()=>S(""),placeholder:"Search commands",className:"mb-2"}),(0,Ca.jsxs)("div",{className:"grid gap-1",children:[R.map(e=>(0,Ca.jsxs)(rt,{tone:"ghost",align:"left",fullWidth:!0,disabled:e.disabled,onClick:()=>(e=>{e.disabled||(e.run(),k(!1),S(""))})(e),className:"h-auto border border-transparent px-2 py-2 hover:border-hf-yellow hover:bg-modiff-bg",children:[(0,Ca.jsx)("span",{className:"grid size-7 shrink-0 place-items-center text-hf-yellow",children:e.icon}),(0,Ca.jsxs)("span",{className:"min-w-0",children:[(0,Ca.jsx)("span",{className:"block text-sm font-bold text-modiff-text",children:e.label}),(0,Ca.jsx)("span",{className:"block text-xs text-modiff-subtle-text",children:e.detail})]})]},e.id)),0===R.length&&(0,Ca.jsx)("p",{className:"p-2 text-xs text-modiff-subtle-text",children:"No matching commands."})]})]})]})}function cs(e){return"ready"===e?"success":"blocked"===e?"error":"default"}function us(e){return"ready"===e?"Ready":"draft"===e?"Draft":"blocked"===e?"Blocked":"Registry"}function ms({disabled:e=!1,form:t,onChange:a}){let[s,i]=(0,ka.useState)(null),l=aa(e=>e.nodesRegistry),n=Object.keys(l).length>0,r=Z[t.modelType],o=!!l[kt.lora],d=!!l[kt.upscaler],c=!!l[Re],u=async(e,s)=>{let l={...t,...s};i(e);try{a(s),await He(l),Fe("Controlled workflow prepared",{variant:"success",autoHideDuration:1800})}catch(e){Fe(String(e),{variant:"error",autoHideDuration:6500})}finally{i(null)}},m=async(e,t)=>{i(e);try{await t()}catch(e){Fe(String(e),{variant:"error",autoHideDuration:6500})}finally{i(null)}},f=[{id:"control",title:"ControlNet control image",detail:"Qwen Image plus Qwen ControlNet Union.",status:"ready",icon:(0,Ca.jsx)(y,{size:15}),button:"Use control",onClick:()=>u("control",{mode:"control_image",modelType:"QwenImageModularPipeline",controlImage:t.controlImage||t.referenceImages[0]||""})},{id:"lora",title:"LoRA adapter",detail:r.supportsLora?"Adds Lora -> ModelsLoader lora_list.":"Current model metadata does not support LoRA.",status:r.supportsLora?o||!n?"ready":"needs-registry":"blocked",icon:(0,Ca.jsx)(x,{size:15}),button:"Add block",onClick:r.supportsLora?()=>m("lora",()=>wa()):void 0},{id:"upscale",title:"Upscale finish",detail:"Adds Spandrel Upscaler and a second Preview.",status:d||!n?"ready":"needs-registry",icon:(0,Ca.jsx)(p,{size:15}),button:"Add block",onClick:()=>m("upscale",()=>ya())},{id:"inpaint",title:"Inpaint mask draft",detail:"Source image, mask image, Apply Mask, and image encode.",status:"draft",icon:(0,Ca.jsx)(z,{size:15}),button:"Prepare draft",onClick:()=>u("inpaint",{mode:"inpaint",modelType:"QwenImageEditModularPipeline",referenceImages:t.referenceImages,maskImage:t.maskImage})},{id:"strength",title:"Image-to-image strength sweep",detail:"Use edit mode, then run the sweep grid.",status:"ready",icon:(0,Ca.jsx)(w,{size:15}),button:"Edit sweep",onClick:()=>u("strength",{mode:"edit_image",modelType:"QwenImageEditModularPipeline",strength:t.strength||.65,randomSeed:!1})},{id:"multi-reference",title:"Multi-reference edit",detail:"Qwen Edit Plus with multiple source images.",status:"ready",icon:(0,Ca.jsx)(h,{size:15}),button:"Use refs",onClick:()=>u("multi-reference",{mode:"multi_image_reference_edit",modelType:"QwenImageEditPlusModularPipeline",referenceImages:t.referenceImages})},{id:"outpaint",title:"Outpaint canvas",detail:"Expands the source image, generates a boundary mask, and feeds Qwen inpaint.",status:c||!n?"ready":"needs-registry",icon:(0,Ca.jsx)(P,{size:15}),button:"Use outpaint",onClick:()=>u("outpaint",{mode:"outpaint",modelType:"QwenImageEditModularPipeline",referenceImages:t.referenceImages,aspectRatio:"16:9",width:1344,height:768,outpaintLeft:t.outpaintLeft||256,outpaintRight:t.outpaintRight||256,outpaintTop:t.outpaintTop||0,outpaintBottom:t.outpaintBottom||0,outpaintOverlap:t.outpaintOverlap||24,outpaintFeather:t.outpaintFeather||8})}];return(0,Ca.jsxs)("section",{"data-testid":"studio-controlled-workflows",children:[(0,Ca.jsx)(Qe,{title:"Controlled workflows"}),(0,Ca.jsx)("div",{className:"grid gap-2",children:f.map(t=>{let a=s===t.id,i=e||null!==s||"blocked"===t.status||!t.onClick;return(0,Ca.jsx)("article",{className:"border border-modiff-border bg-modiff-bg p-2",children:(0,Ca.jsxs)("div",{className:"flex items-start gap-2",children:[(0,Ca.jsx)("div",{className:"grid size-8 shrink-0 place-items-center rounded-modiff-compact bg-modiff-panel text-hf-yellow",children:t.icon}),(0,Ca.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5",children:[(0,Ca.jsx)("h4",{className:"text-xs font-bold text-modiff-text",children:t.title}),(0,Ca.jsx)(it,{tone:cs(t.status),children:us(t.status)})]}),(0,Ca.jsx)("p",{className:Me("mt-1 text-xs","blocked"===t.status?"text-hf-orange":"text-modiff-subtle-text"),children:t.detail})]}),(0,Ca.jsx)(rt,{tone:"blocked"===t.status?"ghost":"secondary",icon:a?(0,Ca.jsx)(da,{size:14}):t.icon,disabled:i,onClick:()=>{t.onClick?.()},children:t.button})]})},t.id)})})]})}var ps=512,fs={25:"opacity-25",50:"opacity-50",75:"opacity-75",100:"opacity-100"};function hs({sourceImage:e,maskImage:a,onCancel:s,onSave:i}){let n=(0,ka.useRef)(null),r=(0,ka.useRef)(!1),[o,d]=(0,ka.useState)("brush"),[c,u]=(0,ka.useState)(34),[m,p]=(0,ka.useState)(50),[f,h]=(0,ka.useState)([]),[x,g]=(0,ka.useState)([]),j=()=>n.current?.toDataURL("image/png")??"",v=()=>{let e=j();e&&(h(t=>[e,...t].slice(0,20)),g([]))},y=e=>{let t=n.current,a=t?.getContext("2d");if(!t||!a)return;let s=new Image;s.onload=()=>{a.clearRect(0,0,ps,ps),a.fillStyle="black",a.fillRect(0,0,ps,ps),a.drawImage(s,0,0,ps,ps)},s.src=e};(0,ka.useEffect)(()=>{let e=n.current,t=e?.getContext("2d");!e||!t||(t.fillStyle="black",t.fillRect(0,0,ps,ps),a&&y(a))},[a]);let w=e=>{let t=n.current,a=t?.getContext("2d");if(!t||!a)return;let s=t.getBoundingClientRect(),i=(e.clientX-s.left)/s.width*ps,l=(e.clientY-s.top)/s.height*ps;a.beginPath(),a.arc(i,l,c/2,0,2*Math.PI),a.fillStyle="brush"===o?"white":"black",a.fill()},k=e=>{r.current=!1,e.currentTarget.releasePointerCapture(e.pointerId)};return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Mask editor"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"relative aspect-square overflow-hidden border border-modiff-border bg-modiff-bg",children:[e&&(0,Ca.jsx)("img",{src:e,alt:"Source overlay",className:Me("absolute inset-0 h-full w-full object-contain",fs[m])}),(0,Ca.jsx)("canvas",{ref:n,width:ps,height:ps,className:"relative z-10 h-full w-full touch-none mix-blend-screen",onPointerDown:e=>{v(),r.current=!0,e.currentTarget.setPointerCapture(e.pointerId),w(e)},onPointerMove:e=>{r.current&&w(e)},onPointerUp:k,onPointerCancel:k})]}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-1",children:[(0,Ca.jsxs)(it,{active:"brush"===o,onClick:()=>d("brush"),children:[(0,Ca.jsx)(A,{size:13})," Brush"]}),(0,Ca.jsxs)(it,{active:"erase"===o,onClick:()=>d("erase"),children:[(0,Ca.jsx)(B,{size:13})," Erase"]}),(0,Ca.jsx)(it,{onClick:()=>{let e=n.current,t=e?.getContext("2d");if(!e||!t)return;v();let a=t.getImageData(0,0,ps,ps);for(let e=0;e{let e=n.current,t=e?.getContext("2d");!e||!t||(v(),t.fillStyle="black",t.fillRect(0,0,ps,ps))},children:[(0,Ca.jsx)(L,{size:13})," Clear"]}),(0,Ca.jsxs)(it,{onClick:()=>{let e=f[0];if(!e)return;let t=j();g(e=>t?[t,...e].slice(0,20):e),h(e=>e.slice(1)),y(e)},disabled:0===f.length,children:[(0,Ca.jsx)(t,{size:13})," Undo"]}),(0,Ca.jsxs)(it,{onClick:()=>{let e=x[0];if(!e)return;let t=j();h(e=>t?[t,...e].slice(0,20):e),g(e=>e.slice(1)),y(e)},disabled:0===x.length,children:[(0,Ca.jsx)(b,{size:13})," Redo"]})]}),(0,Ca.jsx)(Kt,{label:`Brush size: ${c}`,children:(0,Ca.jsx)(pt,{min:4,max:120,value:c,onChange:u})}),(0,Ca.jsxs)("div",{children:[(0,Ca.jsxs)("p",{className:"mb-1 text-xs text-modiff-subtle-text",children:["Source overlay: ",m,"%"]}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:[25,50,75,100].map(e=>(0,Ca.jsxs)(it,{active:m===e,onClick:()=>p(e),children:[e,"%"]},e))})]}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(rt,{tone:"primary",icon:(0,Ca.jsx)(C,{size:15}),onClick:()=>i(j()),children:"Save mask"}),(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(l,{size:15}),onClick:s,children:"Cancel"})]})]})]})}function xs({form:e}){let t=[["Seed",e.randomSeed?"Random on run, so exact examples cannot be promised.":`Locked to ${e.seed} for reruns.`],["Guidance",`${e.guidanceScale} balances prompt obedience against natural detail.`],["Steps",`${e.steps} sampling steps sets quality/runtime tradeoff.`],["Strength",`${e.strength} controls how much source images can change in edit workflows.`],["Size",`${e.width}x${e.height} changes composition and exactness hash.`],["Dtype",`${e.dtype} affects memory use and can affect reproducibility.`],["Model",ra[e.modelType]]];return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Parameter notes"}),(0,Ca.jsx)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2",children:t.map(([e,t])=>(0,Ca.jsxs)("div",{className:"flex items-start gap-2 text-xs",children:[(0,Ca.jsx)(g,{size:13,className:"mt-0.5 shrink-0 text-modiff-subtle-text"}),(0,Ca.jsxs)("p",{className:"min-w-0 text-modiff-subtle-text",children:[(0,Ca.jsxs)("span",{className:"font-semibold text-modiff-text",children:[e,":"]})," ",t]})]},e))})]})}var gs=["Describe the subject first, then composition, style, lighting, camera, and constraints.","Keep exact text short and put it in quotes when the model needs to render letters."],bs=[["Subject",["one clear subject","premium product","same character identity"]],["Composition",["centered composition","negative space","preserve composition"]],["Style",["cinematic realism","editorial design","minimal studio look"]]],js=[["Subject","subject"],["Environment","environment"],["Preserve","preservation"],["Change","change"],["Composition","composition"],["Texture / materials","materials"],["Style","style"],["Lighting","lighting"],["Camera","camera"],["Motion","motion"],["Continuity","continuity"],["Arrangement","arrangement"],["Mix","mix"],["Parameters","parameters"],["Text","textRendering"]];function vs({form:e,template:t,onChange:a}){let s=t?.promptGuide,i=s?js.map(([e,t])=>[e,s[t]]).filter(e=>Array.isArray(e[1])&&e[1].length>0):bs,l=s?.negative??["low quality","blurry","warped text","distorted anatomy"],n=s?.modelHints??gs,r=t=>{let s=e.prompt.trim();a({prompt:s?`${s}, ${t}`:t})},o=t=>{let s=e.negativePrompt.trim();a({negativePrompt:s?`${s}, ${t}`:t})};return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Prompt composer"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[i.map(([e,t])=>(0,Ca.jsxs)("fieldset",{children:[(0,Ca.jsx)("legend",{className:"mb-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:e}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:t.map(t=>(0,Ca.jsx)(it,{"aria-label":`Add ${e.toLowerCase()} detail: ${t}`,onClick:()=>r(t),children:t},`${e}-${t}`))})]},e)),l.length>0&&(0,Ca.jsxs)("fieldset",{children:[(0,Ca.jsx)("legend",{className:"mb-1 text-xs font-semibold uppercase text-modiff-subtle-text",children:"Avoid"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:l.map(e=>(0,Ca.jsx)(it,{"aria-label":`Add negative prompt detail: ${e}`,onClick:()=>o(e),children:e},`negative-${e}`))})]}),n.length>0&&(0,Ca.jsx)("div",{className:"grid gap-1 border border-modiff-border bg-modiff-bg p-2","aria-label":"Prompt guidance",children:n.map(e=>(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:e},e))}),t&&(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>a({prompt:t.prompt,negativePrompt:t.negativePrompt??e.negativePrompt}),children:"Restore template prompt"})]})]})}function ys(e){return e.match(/\S+/g)||[]}function ws(e,t){let a=ys(e),s=ys(t),i=Array.from({length:a.length+1},()=>Array(s.length+1).fill(0));for(let e=a.length-1;e>=0;--e)for(let t=s.length-1;t>=0;--t){let l=a[e]??"",n=s[t]??"",r=i[e];r&&(r[t]=l===n?(i[e+1]?.[t+1]??0)+1:Math.max(i[e+1]?.[t]??0,r[t+1]??0))}let l=[],n=0,r=0;for(;n=(i[n]?.[r+1]??0)?(l.push({text:e,kind:"removed"}),n+=1):(l.push({text:t,kind:"added"}),r+=1)}for(;n[...a.map((e,t)=>({id:`snippet-${t}`,label:`Snippet ${t+1}`,prompt:e})),...t.map((e,t)=>({id:`history-${t}`,label:`History ${t+1}`,prompt:e}))].filter(t=>t.prompt.trim()&&t.prompt!==e),[e,t,a]),r=n.find(e=>e.id===i)||n[0],o=(0,ka.useMemo)(()=>r?ws(r.prompt,e):[],[e,r]),d=o.filter(e=>"added"===e.kind).length,c=o.filter(e=>"removed"===e.kind).length;return 0===n.length?null:(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)(Qe,{title:"Prompt diff",action:(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(it,{tone:d?"success":"default",children:`+${d}`}),(0,Ca.jsx)(it,{tone:c?"error":"default",children:`-${c}`})]})}),(0,Ca.jsx)(Se,{"aria-label":"Prompt version to compare",value:r?.id||"",onValueChange:l,options:n.map(e=>({value:e.id,label:e.label})),className:"mb-2 w-full"}),(0,Ca.jsx)("div",{className:"max-h-40 overflow-y-auto border border-modiff-border bg-modiff-bg p-2",children:o.map((e,t)=>(0,Ca.jsx)("span",{className:Me("mb-1 mr-1 inline-block rounded-modiff-compact px-1 text-xs","same"===e.kind&&"text-modiff-subtle-text","added"===e.kind&&"bg-modiff-green/10 text-modiff-green","removed"===e.kind&&"bg-modiff-red/10 text-modiff-red line-through"),children:e.text},`${e.text}-${t}`))}),(0,Ca.jsxs)("div",{className:"mt-2 flex gap-2",children:[(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(O,{size:15}),onClick:()=>r&&function(e){navigator.clipboard.writeText(e),Fe("Prompt diff copied",{variant:"success",autoHideDuration:1800})}(function(e,t,a){let s=a.filter(e=>"added"===e.kind).map(e=>e.text).join(" "),i=a.filter(e=>"removed"===e.kind).map(e=>e.text).join(" ");return["Prompt diff","","Base:",e,"","Current:",t,"","Added:",s||"None","","Removed:",i||"None"].join("\n")}(r.prompt,e,o)),children:"Copy diff"}),(0,Ca.jsx)(rt,{tone:"ghost",onClick:()=>r&&s(r.prompt),children:"Use baseline"})]})]})}function Cs(e){return e.split(",").map(e=>e.trim()).filter(Boolean)}function Ns(e,t){let a=new Set(e.map(e=>e.toLowerCase()));return t.forEach(t=>{let s=t.toLowerCase();a.has(s)||(a.add(s),e.push(t))}),e}function Ss(e){return"edit_image"===e.mode?["preserve source identity","match original lighting","localized edit"]:"multi_image_reference_edit"===e.mode?["coherent blend of references","consistent perspective","preserve strongest design details"]:"control_image"===e.mode?["follow the control image structure","clean edges","stable composition"]:"control_edit_image"===e.mode?["preserve source identity","follow the control image structure","stable composition"]:"control_inpaint"===e.mode?["edit only inside the mask","follow the control image structure","preserve unmasked areas"]:"inpaint"===e.mode?["edit only inside the mask","preserve unmasked areas","consistent texture"]:"layer_decomposition"===e.mode?["clean layer boundaries","separated foreground and background","editable alpha"]:["one clear subject","balanced composition","professional finish"]}function Is({form:e,template:t,onApply:s}){let[i,n]=(0,ka.useState)(null),r=(0,ka.useMemo)(()=>i?ws(e.prompt,i.prompt):[],[e.prompt,i]),o=r.filter(e=>"added"===e.kind).length,d=r.filter(e=>"removed"===e.kind).length;return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Prompt enhancer",action:i?(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(it,{tone:o?"success":"default",children:`+${o}`}),(0,Ca.jsx)(it,{tone:d?"error":"default",children:`-${d}`})]}):void 0}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>n(function(e,t){let a=Cs(e.prompt||t?.prompt||""),s=t?.promptGuide,i=[...Ss(e),s?.lighting?.[0],s?.camera?.[0],s?.style?.[0]].filter(e=>!!e);return{prompt:Ns(a.length>0?a:["A polished image"],i).join(", "),negativePrompt:Ns(Cs(e.negativePrompt),s?.negative?.slice(0,3)??["low quality","blurry","artifacts"]).join(", ")}}(e,t)),children:"Suggest"}),i&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(rt,{tone:"primary",icon:(0,Ca.jsx)(a,{size:15}),onClick:()=>{s(i),n(null)},children:"Apply"}),(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(O,{size:15}),onClick:()=>function(e){navigator.clipboard.writeText(e),Fe("Enhanced prompt copied",{variant:"success",autoHideDuration:1800})}(`${i.prompt}\n\nNegative:\n${i.negativePrompt}`),children:"Copy"}),(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(l,{size:15}),onClick:()=>n(null),children:"Dismiss"})]})]}),i&&(0,Ca.jsxs)("div",{className:"grid gap-2 border border-modiff-border bg-modiff-bg p-2","data-testid":"studio-prompt-enhancer-diff",children:[(0,Ca.jsx)("div",{className:"max-h-40 overflow-y-auto",children:r.map((e,t)=>(0,Ca.jsx)("span",{className:Me("mb-1 mr-1 inline-block rounded-modiff-compact px-1 text-xs","same"===e.kind&&"text-modiff-subtle-text","added"===e.kind&&"bg-modiff-green/10 text-modiff-green","removed"===e.kind&&"bg-modiff-red/10 text-modiff-red line-through"),children:e.text},`${e.text}-${t}`))}),(0,Ca.jsxs)("div",{className:"grid gap-1 border-t border-modiff-border pt-2",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:"Negative"}),(0,Ca.jsx)("p",{className:"break-words text-xs text-modiff-subtle-text",children:i.negativePrompt||"None"})]})]})]})]})}function Rs({disabled:e=!1,form:t,template:a,onChange:s,onRunSweep:i}){let l=!!a&&H(a,t),n=me.includes(t.mode),r="edit_image"===t.mode||"multi_image_reference_edit"===t.mode||"inpaint"===t.mode||"control_edit_image"===t.mode||"control_inpaint"===t.mode||"layer_decomposition"===t.mode?[{label:"Lower strength",detail:`Strength ${Math.max(0,Number((t.strength-.1).toFixed(2)))}`,values:{strength:Math.max(0,Number((t.strength-.1).toFixed(2)))}},{label:"Higher strength",detail:`Strength ${Math.min(1,Number((t.strength+.1).toFixed(2)))}`,values:{strength:Math.min(1,Number((t.strength+.1).toFixed(2)))}}]:[],o=n?[{label:"Lower conditioning",detail:`Conditioning ${Math.max(0,Number((t.conditioningScale-.15).toFixed(2)))}`,values:{conditioningScale:Math.max(0,Number((t.conditioningScale-.15).toFixed(2)))}},{label:"Higher conditioning",detail:`Conditioning ${Math.min(2,Number((t.conditioningScale+.15).toFixed(2)))}`,values:{conditioningScale:Math.min(2,Number((t.conditioningScale+.15).toFixed(2)))}},{label:"Shorter clip",detail:`${Math.max(17,t.numFrames-32)} frames`,values:{numFrames:Math.max(17,t.numFrames-32)}},{label:"Quality clip",detail:"50 steps, 81 frames",values:{steps:50,numFrames:81,randomSeed:!1}}]:[],d=[{label:"Next seed",detail:`Seed ${t.seed+1}`,values:{seed:t.seed+1,randomSeed:!1}},{label:"Lower guidance",detail:`Guidance ${Math.max(0,Number((t.guidanceScale-.5).toFixed(1)))}`,values:{guidanceScale:Math.max(0,Number((t.guidanceScale-.5).toFixed(1)))}},{label:"Higher guidance",detail:`Guidance ${Math.min(10,Number((t.guidanceScale+.5).toFixed(1)))}`,values:{guidanceScale:Math.min(10,Number((t.guidanceScale+.5).toFixed(1)))}},{label:"Quality pass",detail:`${Math.min(80,t.steps+12)} steps`,values:{steps:Math.min(80,t.steps+12)}},...r,...o];return(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Variation planner"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:l?"Current settings match the locked template. Any sweep below will become Modified.":"Current settings already differ from the locked template or no active template is selected."}),(0,Ca.jsx)("div",{className:"grid grid-cols-2 gap-2",children:d.map((e,t)=>(0,Ca.jsx)(rt,{tone:"ghost",align:"left",icon:0===t?(0,Ca.jsx)(k,{size:15}):(0,Ca.jsx)(w,{size:15}),onClick:()=>s(e.values),children:(0,Ca.jsxs)("span",{children:[(0,Ca.jsx)("span",{className:"block text-xs font-bold text-modiff-text",children:e.label}),(0,Ca.jsxs)("span",{className:"block text-xs text-hf-orange",children:[e.detail," | Modified"]})]})},e.label))}),(0,Ca.jsx)(rt,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(k,{size:15}),disabled:e,onClick:()=>i(d),children:"Run sweep"})]})]})}function $s({issues:e}){let{installHfModel:t,refreshModelIndexes:a,hfDownloadProgress:s}=aa(xe(e=>({installHfModel:e.installHfModel,refreshModelIndexes:e.refreshModelIndexes,hfDownloadProgress:e.hfDownloadProgress}))),i=mt(e=>e.sid);return e.filter((t,a)=>"install_model"===t.action&&t.repoId&&e.findIndex(e=>"install_model"===e.action&&e.repoId===t.repoId&&JSON.stringify(e.installOptions??{})===JSON.stringify(t.installOptions??{}))===a).map(e=>{let l=e.repoId,n=jt(s[l]);return(0,Ca.jsxs)(rt,{fullWidth:!0,tone:"secondary",disabled:n||!i,"data-testid":`studio-install-graph-model-${l}`,title:`${l}: ${e.message}`,onClick:()=>{(async()=>{try{await t(l,i,e.installOptions),await a(!0)}catch(e){Fe(De(e,`Could not install ${l}.`),{variant:"error"})}})()},children:[n?"Installing":e.installOptions?.repair?"Repair":"Install"," ",l.split("/").pop()]},e.id)})}function Ms({form:e,hfCache:t,localModels:a,modelCacheDiagnostics:s,autoResourcePlan:i,backendCapabilities:l=[],backendCapabilitiesAuthoritative:n=!1}){let r=(0,ka.useMemo)(()=>{let t=Zt(e),a=l.find(t=>t.modelType===e.modelType);return yt(a?{...t,...a}:t,e.mode)},[l,e]),o=(0,ka.useMemo)(()=>n?l.filter(t=>Ee(t).includes(e.mode)).map(e=>e.modelType):Ne(e.mode,{currentModelType:e.modelType}),[l,n,e.mode,e.modelType]),d=(0,ka.useMemo)(()=>{if(!n)return r.modes;let t=l.find(t=>t.modelType===e.modelType);return t?Ee(t):[]},[l,n,r.modes,e.modelType]),c=(0,ka.useMemo)(()=>Ce(r,t,a,s),[r,t,a,s]),u=(0,ka.useMemo)(()=>te({form:e,autoResourcePlan:i,hfCache:t,localModels:a,modelCacheDiagnostics:s,includePipeline:!1}),[i,e,t,a,s]),m=r.modeRequirements?.[e.mode]?.requiredImages??[],p=m.includes("referenceImages"),f=m.includes("maskImage"),h=m.includes("controlImage"),x=m.includes("ipAdapterImage"),g=p||"control_image"===e.mode||"inpaint"===e.mode||"layer_decomposition"===e.mode,b=r.supportsMask,j=r.inpaintContract,v=u.find(e=>!e.status.runnable),y=(0,ka.useMemo)(()=>"auto"===e.resourceMode?oa(i,e):null,[i,e]),w=1===r.revisionCandidates?.length?r.revisionCandidates[0]:void 0;return{capability:r,compatibleModels:o,compatibleModes:d,showImageTray:g,requiresMaskImage:f,requiresControlImage:h,requiresIPAdapterImage:x,supportsMask:b,inpaintContract:j,missingInstallTarget:y??("auto"===e.resourceMode||!1===r.artifactInstallRequired||c.runnable?v?{repo:v.repo,label:v.label}:null:{repo:r.defaultRepo,label:r.label,revision:w,files:r.downloadFiles})}}var Ts=[{label:"1:1",width:1024,height:1024},{label:"4:3",width:1152,height:864},{label:"3:4",width:864,height:1152},{label:"16:9",width:1344,height:768},{label:"9:16",width:768,height:1344}];function As(e,t){let a=Number(e);return Number.isFinite(a)?a:t}function Ps(){let[e,t]=(0,ka.useState)(!1),a=ja(),[s,i]=(0,ka.useState)(!1),l=(0,ka.useRef)(null),[n,r]=(0,ka.useState)(0),o=ta(e=>e.setRightPanelOpen),d=ta(e=>e.setRightPanelTab),c=ta(e=>e.setLightboxOpener),u=ta(e=>e.setTemplateBrowserOpen),p=ta(e=>e.setGalleryLibraryOpen),h=J(e=>e.showIssues),{sid:x,isConnected:b}=mt(xe(e=>({sid:e.sid,isConnected:e.isConnected}))),{hfCache:j,localModels:v,modelCacheDiagnostics:y,runtimeStatus:w,nodesRegistry:k,studioModelCapabilities:N,studioModelCapabilitiesAuthoritative:S,studioExecutionSpecInvalid:I,installHfModel:R}=aa(xe(e=>({hfCache:e.hfCache,localModels:e.localModels,modelCacheDiagnostics:e.modelCacheDiagnostics,runtimeStatus:e.runtimeStatus,nodesRegistry:e.nodesRegistry,studioModelCapabilities:e.studioModelCapabilities,studioModelCapabilitiesAuthoritative:e.studioModelCapabilitiesAuthoritative,studioExecutionSpecInvalid:e.studioExecutionSpecInvalid,installHfModel:e.installHfModel}))),{form:$,autoResourcePlan:M,promptHistory:T,savedSnippets:A,negativePromptPresets:P,activeTemplateId:_,activeWorkflowTabId:z,outputs:q,lastError:B,recentChange:G,pinnedGraphInputIds:D,workflowCanvasHydrated:E,applyPreset:F,addPromptHistory:H,togglePinnedGraphInput:W,saveCurrentPromptAsSnippet:U,removeSnippet:Q,applySnippet:X,applyNegativePreset:Y,detachManagedGraph:te}=ze(xe(e=>({form:e.form,promptHistory:e.promptHistory,savedSnippets:e.savedSnippets,negativePromptPresets:e.negativePromptPresets,autoResourcePlan:e.autoResourcePlan,activeTemplateId:e.activeTemplateId,activeWorkflowTabId:e.activeWorkflowTabId,outputs:e.outputs,lastError:e.lastError,recentChange:e.recentChange,pinnedGraphInputIds:e.pinnedGraphInputIds,workflowCanvasHydrated:e.workflowCanvasHydrated,applyPreset:e.applyPreset,addPromptHistory:e.addPromptHistory,togglePinnedGraphInput:e.togglePinnedGraphInput,saveCurrentPromptAsSnippet:e.saveCurrentPromptAsSnippet,removeSnippet:e.removeSnippet,applySnippet:e.applySnippet,applyNegativePreset:e.applyNegativePreset,detachManagedGraph:e.detachManagedGraph}))),ae=(0,ka.useMemo)(()=>$t.find(e=>e.id===_),[_]),ie=(0,ka.useMemo)(()=>Pe(q,z),[z,q]),le=(0,ka.useMemo)(()=>Ot.filter(e=>{let t=!!e.compatibleModes?.some(e=>me.includes(e)),a=!!e.compatibleModes?.some(e=>de.includes(e));if(me.includes($.mode)&&!t||de.includes($.mode)&&!a)return!1;let s=!e.compatibleModes||e.compatibleModes.includes($.mode),i=!e.compatibleModelTypes||e.compatibleModelTypes.includes($.modelType);return s&&i}),[$.mode,$.modelType]),re=me.includes($.mode),oe=de.includes($.mode),ce="unconditional_image"===$.mode,he="depth_estimation"===$.mode,ge=We.includes($.mode),ye=ot.includes($.mode),Ce=!ce&&!he&&!ge&&!1!==Z[$.modelType].supportsPrompt,Ne=Jt(Z[$.modelType]),Re=xt(Z[$.modelType],$),$e=Ht(Z[$.modelType]),Ae=_e(N,I,$),qe=Ae?.available_expert_quantization_modes??Ae?.expert_quantization_modes??[],Ge=`${Re}. ${Ne} defaults to ${Z[$.modelType].recommendedSteps} steps, ${Z[$.modelType].guidanceLabel.toLowerCase()} ${Z[$.modelType].recommendedGuidance}, ${Z[$.modelType].defaultDtype}. ${$e}`,Oe=ze(e=>e.graphBinding),Ee=ze(e=>e.graphFinalization),Ke=Oe?ke($):null,Ve=Ee??(Ke?{status:"warning",message:Ke}:null),Je=ze(e=>e.canvasTransition),Ze="template_graph_building"===Je?.type&&Je.workflowTabId===z;be(xe(e=>({nodes:e.nodes.map(e=>{let t=Object.entries(e.data.params).filter(([e])=>/repo|model|checkpoint|ckpt|safetensors|lora|vae|controlnet|adapter/i.test(e)).map(([e,t])=>`${e}:${JSON.stringify(t.value??t.default??"")}`).join(",");return`${e.id}:${e.data.module}:${e.data.action}:${e.data.uiState?.disabled?"disabled":"enabled"}:${t}`}).join("|"),edges:e.edges.map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}->${e.target}:${e.targetHandle??""}`).join("|")})));let Xe=Lt(),Ye=E&&!Ze&&Oe?Te(Oe):null,et=Ye?`${Ye.kind}:${Ye.details??Ye.message}`:"",at=E&&!Ze&&(!Oe&&Xe.nodeCount>0||!!Ye),st=Xe.modelRefs.length>0?`${new Set(Xe.modelRefs.map(e=>`${e.kind}:${e.value}`)).size} model refs`:"Graph-defined",nt=ea({sid:x,isConnected:b,includeStudio:!at}),dt=(0,ka.useMemo)(()=>ee(nt.issues),[nt.issues]),ht=nt.blockingIssues.length>0?`${nt.blockingIssues.length} issue${1===nt.blockingIssues.length?"":"s"}`:nt.warningIssues.length>0?`${nt.warningIssues.length} warning${1===nt.warningIssues.length?"":"s"}`:void 0,jt=be(xe(e=>e.nodes)),yt=E&&!Ze&&!_&&0===jt.length,kt=(0,ka.useMemo)(()=>jt.filter(e=>e.selected),[jt]),Nt=(0,ka.useMemo)(()=>ga(jt,D),[jt,!0,D]),St=D.filter(e=>Nt.some(t=>t.id===e)),It=(0,ka.useMemo)(()=>{let e=new Set(St);return Nt.filter(t=>e.has(t.id))},[St,Nt]),{capability:Tt,compatibleModels:At,compatibleModes:Pt,showImageTray:_t,requiresMaskImage:qt,requiresControlImage:Bt,requiresIPAdapterImage:Gt,supportsMask:Dt,inpaintContract:Et,missingInstallTarget:Ft}=Ms({form:$,hfCache:j,localModels:v,modelCacheDiagnostics:y,autoResourcePlan:M,backendCapabilities:N,backendCapabilitiesAuthoritative:S}),Vt=Tt.modeRequirements?.[$.mode]?.requiredVideos??[],Ut=Vt.includes("sourceVideo"),Qt=Vt.includes("referenceVideos"),Zt=Vt.includes("controlVideo"),Yt=nt.blockingIssues[0]?.message??"",sa=!nt.canRun,ia=!at&&!yt,{updateAndSync:oa,handleCreateGraph:da,handleModeChange:ca,handleModelTypeChange:ua,handleRun:ma,handleInstallMissingModel:xa,isInstallingMissingModel:ya,openSetup:wa}=Xt({sid:x,isConnected:b,missingInstallTarget:Ft,installHfModel:R,setIsWorking:t}),Na=(e,t=$)=>{let s=bt(t);a.request("run",s,e)};(0,ka.useEffect)(()=>{!E||Ze||Rt({sid:x,isConnected:b,includeStudio:!0,showDialog:!1})},[x,b,$,Oe,Ee,j,v,y,w,k,Ze,E]),(0,ka.useEffect)(()=>{!Oe||!Ye||"pending"===Ee?.status||"template_graph_building"===Je?.type||te()},[Je?.type,te,Oe,Ye,et,Ee?.status]),(0,ka.useEffect)(()=>{if(!w)return;let e=Wt(w);e===$.device||Mt(w,$.device)||$.device!==ve.device&&!$.device.toLowerCase().startsWith("cuda")||oa({device:e})},[$.device,w,oa]);let Sa=(0,ka.useCallback)(e=>{let t=ze.getState().form,a="low_vram"===e.id?{...e,values:{...e.values,...la(t)}}:e;F(a);let s=ze.getState().form,i=ha(t,s,Object.keys(a.values)),l=t.quantizationMode!==s.quantizationMode||t.resourceMode!==s.resourceMode;queueMicrotask(()=>{l?He(s):Ue(s)}),fa(`${e.label} applied`,i,ze.getState().graphBinding?.managedNodeIds??[]),i.length>0&&Fe(`${e.label} updated ${i.map(e=>e.label).join(", ")}`,{variant:"success",autoHideDuration:2600})},[F]),Ia=(0,ka.useCallback)(()=>{p(!0)},[p]),Ra=(0,ka.useCallback)(()=>{u(!0)},[u]),$a=(0,ka.useCallback)(async()=>{try{let e=await tt();Fe("string"==typeof e.message&&e.message.trim()?e.message:"Interrupt requested",{variant:"success",autoHideDuration:3e3})}catch(e){Fe(De(e,"Could not stop the current execution."),{variant:"error",autoHideDuration:5e3})}},[]),Ma=(0,ka.useCallback)(()=>{if(!x)return void Fe("Connect to the MoDiff server before exporting the API graph.",{variant:"error",autoHideDuration:3e3});let e=vt(be.getState().exportGraph(x)),t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),a=document.createElement("a");a.href=URL.createObjectURL(t),a.download="modiff-api-graph.json",a.click(),URL.revokeObjectURL(a.href)},[x]),Ta=(0,ka.useCallback)(()=>{let e=ze.getState(),t=zt(e.outputs,e.activeWorkflowTabId,{includeUnscopedFallback:!1});t&&(ze.getState().restoreWorkflowFromOutput(t),o(!0),d("studio"),Fe("Latest Gallery workflow restored",{variant:"success",autoHideDuration:2e3}))},[o,d]),Aa=(0,ka.useCallback)(async()=>{let e=ze.getState(),a=zt(e.outputs,e.activeWorkflowTabId,{includeUnscopedFallback:!1});if(a&&x&&b){t(!0);try{ze.getState().restoreWorkflowFromOutput(a);let e=Be();if(!await wt(e))return;await gt({sid:x,studioContext:{forceDeterministic:!a.formSnapshot.randomSeed},workflowContext:e})}catch(e){if(V(e))return;Fe(String(e),{variant:"error",autoHideDuration:6e3})}finally{t(!1)}}else Fe("Connect to the MoDiff server and keep a Gallery output available before rerunning.",{variant:"error",autoHideDuration:4e3})},[b,x]),Pa=(0,ka.useCallback)(()=>{let e=ze.getState(),[t,a]=Pe(e.outputs,e.activeWorkflowTabId);!t||!a||c(na([a.url,t.url],1))},[c]),_a=(0,ka.useCallback)(()=>{h(nt.issues)},[nt.issues,h]),za=(0,ka.useCallback)(async e=>{if(!x||!b)return void Fe("Connect to the MoDiff server before running a sweep.",{variant:"error",autoHideDuration:4e3});if(Yt)return void Fe(Yt,{variant:"error",autoHideDuration:5e3});let a={...ze.getState().form,referenceImages:[...ze.getState().form.referenceImages]},s=Be(),i=`sweep-${Date.now()}`;t(!0),ze.getState().addPromptHistory(a.prompt);try{for(let t of e){se(s);let e={...t.values,randomSeed:!1};ze.getState().updateForm(e),ne(s);let a=ze.getState().form;if(Ue(a),!await wt(s))break;await ue(ze.getState().form,s),se(s);let{response:l}=await gt({sid:x,workflowContext:s,studioContext:{forceDeterministic:!0,variation:{variationGroupId:i,variationLabel:t.label}}});if(se(s),l.error){ze.getState().setLastError(l.message||"MoDiff could not queue this sweep variation.");break}}Fe("Variation sweep queued",{variant:"success",autoHideDuration:2200})}catch(e){if(V(e))return;let t=String(e);ze.getState().setLastError(t),Fe(t,{variant:"error",autoHideDuration:7e3})}finally{Le(s)&&(ze.getState().updateForm(a),ne(s),Ue(a),await He(a,s).catch(e=>{V(e)||console.error("Could not restore the sweep graph",e)})),t(!1)}},[b,Yt,x]);return(0,ka.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let t=()=>{let t=Math.ceil(e.getBoundingClientRect().height);r(e=>e===t?e:t)};if(t(),typeof ResizeObserver>"u")return;let a=0,s=new ResizeObserver(()=>{window.cancelAnimationFrame(a),a=window.requestAnimationFrame(t)});return s.observe(e),()=>{window.cancelAnimationFrame(a),s.disconnect()}},[]),(0,Ca.jsxs)("div",{className:"flex flex-col gap-3 p-3","data-testid":"studio-panel",children:[(0,Ca.jsxs)("div",{ref:l,className:"sticky top-0 z-20 -mx-3 -mt-3 grid gap-2 border-b border-modiff-border bg-modiff-bg p-3 shadow-modiff-node","data-testid":"studio-sticky-header",children:[(0,Ca.jsx)(ds,{isWorking:e,runBlocked:sa,expertMode:!0,hasManagedForm:ia,hasGalleryItems:ie.length>0,hasComparePair:ie.length>1,onRun:()=>{Na(ma)},onInterrupt:()=>{$a()},onUpdateGraph:()=>{da()},onExport:Ma,onSavePrompt:U,onOpenGallery:Ia,onOpenTemplateGallery:Ra,onOpenSetup:wa,onRestoreLatest:Ta,onRerunLatest:()=>{Na(Aa,ie[0]?.formSnapshot)},onCompareLatest:Pa}),Ve&&"complete"!==Ve.status&&"idle"!==Ve.status&&(0,Ca.jsxs)(K,{severity:"error"===Ve.status?"error":"warning"===Ve.status?"warning":"info",testId:"studio-graph-finalization",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold text-modiff-text",children:"pending"===Ve.status?"Finalizing graph...":"warning"===Ve.status?"Graph still finalizing":"Graph finalization failed"}),(0,Ca.jsx)("p",{className:"mt-1 text-xs text-modiff-subtle-text",children:Ve.message||"Preparing dynamic fields and managed links in the background."})]}),B&&(0,Ca.jsx)(K,{severity:"error",children:(0,Ca.jsxs)("div",{className:"flex items-start gap-2",children:[(0,Ca.jsx)(Ct,{className:"min-w-0 flex-1",label:"Last error",buttonClassName:"min-h-0 justify-start p-0 text-xs text-modiff-invalid hover:bg-transparent",panelClassName:"mt-1",children:(0,Ca.jsx)("p",{className:"mt-1 max-h-28 overflow-auto break-words text-xs text-modiff-red",children:B})}),(0,Ca.jsx)(pe,{title:"Copy error",onClick:()=>function(e){navigator.clipboard.writeText(e),Fe("Error copied",{variant:"success",autoHideDuration:1800})}(B),children:(0,Ca.jsx)(O,{size:15})})]})})]}),(0,Ca.jsx)(ft,{id:"task",title:"Task",defaultOpen:!0,children:yt?(0,Ca.jsxs)("div",{className:"grid gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"studio-empty-workflow",children:[(0,Ca.jsxs)("div",{children:[(0,Ca.jsx)("p",{className:"text-sm font-semibold text-modiff-text",children:"No task or model selected"}),(0,Ca.jsx)("p",{className:"mt-1 text-xs leading-5 text-modiff-subtle-text",children:"Choose a task in the canvas, browse templates, or add a node from the Nodes panel to build manually."})]}),(0,Ca.jsx)(rt,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(m,{size:15}),"data-testid":"studio-open-template-browser",onClick:Ra,children:"Browse templates"})]}):(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("div",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3","data-testid":"studio-task-model-summary",children:(0,Ca.jsxs)("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:at?"Current graph":"Current task"}),(0,Ca.jsx)("h2",{className:"truncate text-base font-bold text-modiff-text",children:at?"Custom graph":lt[$.mode]})]}),(0,Ca.jsxs)("div",{className:"min-w-0 text-right",children:[(0,Ca.jsx)("p",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:at?"Graph models":"Selected model"}),(0,Ca.jsxs)("div",{className:"flex items-center justify-end gap-1",children:[(0,Ca.jsx)("h3",{className:"truncate text-base font-bold text-hf-yellow",children:at?st:Ne}),!at&&(0,Ca.jsx)(pe,{title:Ge,children:(0,Ca.jsx)(g,{size:13})})]})]})]})}),ia&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Se,{"aria-label":"Task",value:$.mode,"data-testid":"studio-task-select",onValueChange:e=>{ca(e)},options:Pt.map(e=>({value:e,label:lt[e]}))}),(0,Ca.jsx)(Se,{"aria-label":"Model",value:$.modelType,"data-testid":"studio-model-select",onValueChange:e=>{ua(e)},options:At.map(e=>({value:e,label:ra[e]}))})]}),at?(0,Ca.jsx)($s,{issues:nt.issues}):null,ia&&Ft?(0,Ca.jsx)(rt,{fullWidth:!0,tone:"secondary","data-testid":"studio-install-missing-model",disabled:e||ya,onClick:()=>{xa()},title:`${Ft.label} | ${Ft.repo}`,children:ya?"Installing model...":`${Ft.actionLabel??(Ft.repair?"Repair":"Install")} ${Ft.label}`}):null,Ze?(0,Ca.jsx)(we,{tone:"info",title:"Preparing graph",testId:"studio-run-readiness"}):(0,Ca.jsx)(we,{tone:dt.tone,title:ht?`${dt.title} - ${ht}`:dt.title,meta:nt.primaryIssue?.message,testId:"studio-run-readiness",onClick:nt.issues.length>0?_a:void 0}),jt.length>0?(0,Ca.jsx)(ba,{candidates:Nt,nodes:jt,pinnedInputs:It,pinnedIds:St,selectedNodes:kt,workflowId:z,onTogglePin:W},z):null,0===jt.length?(0,Ca.jsx)(rt,{fullWidth:!0,tone:"secondary",icon:(0,Ca.jsx)(m,{size:15}),"data-testid":"studio-open-template-browser",onClick:Ra,children:"Templates"}):null]})}),ia&&(0,Ca.jsxs)(Ca.Fragment,{children:[Ce&&(0,Ca.jsxs)("div",{className:"relative grid gap-3",children:[(0,Ca.jsxs)(ft,{id:"prompt",title:"Prompt",defaultOpen:!0,testId:"studio-sticky-prompt",className:"sticky z-10 rounded-modiff-panel border border-modiff-border bg-modiff-bg px-2 pb-2 shadow-modiff-node before:absolute before:-inset-x-3 before:-top-3 before:h-3 before:bg-modiff-bg before:content-['']",stickyTop:n+12,children:[(0,Ca.jsx)("div",{"data-testid":"studio-prompt-input",children:(0,Ca.jsx)(Ie,{label:"Prompt",value:$.prompt,multiline:!0,onChange:e=>oa({prompt:e})})}),!1!==Tt.supportsNegativePrompt&&(0,Ca.jsx)("div",{"data-testid":"studio-negative-prompt-input",children:(0,Ca.jsx)(Ie,{label:"Negative prompt",value:$.negativePrompt,multiline:!0,onChange:e=>oa({negativePrompt:e})})}),(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(C,{size:15}),onClick:U,children:"Snippet"}),(0,Ca.jsx)(rt,{tone:"ghost",icon:(0,Ca.jsx)(f,{size:15}),onClick:()=>H($.prompt),children:"History"})]})]}),(0,Ca.jsxs)(ft,{id:"prompt-tools",title:"Prompt tools",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Presets"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1.5",children:le.map(e=>(0,Ca.jsx)(it,{title:e.description,onClick:()=>Sa(e),children:e.label},e.id))}),G&&(0,Ca.jsxs)("div",{className:"mt-2 rounded-modiff-compact border border-hf-yellow/60 bg-modiff-surface p-2 text-xs text-modiff-text","data-testid":"studio-recent-change",children:[(0,Ca.jsx)("p",{className:"font-semibold text-hf-yellow",children:G.label}),(0,Ca.jsx)("div",{className:"mt-1 flex flex-wrap gap-1",children:G.fields.slice(0,6).map(e=>(0,Ca.jsxs)("span",{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg px-1.5 py-0.5 text-modiff-subtle-text",children:[e.label,": ",pa(e.before)," -> ",pa(e.after)]},String(e.key)))})]})]}),(0,Ca.jsx)(ct,{}),(0,Ca.jsx)(vs,{form:$,template:ae,onChange:oa}),(0,Ca.jsx)(ct,{}),(0,Ca.jsx)(Is,{form:$,template:ae,onApply:oa}),(T.length>0||A.length>0||P.length>0)&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(ct,{}),(0,Ca.jsxs)("div",{className:"grid gap-3",children:[A.length>0&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Saved snippets"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:A.slice(0,4).map(e=>(0,Ca.jsxs)("div",{className:"flex gap-1",children:[(0,Ca.jsx)(rt,{fullWidth:!0,tone:"ghost",align:"left",onClick:()=>{X(e),queueMicrotask(()=>Ue())},children:e}),(0,Ca.jsx)(pe,{title:"Remove snippet",onClick:()=>Q(e),children:(0,Ca.jsx)(L,{size:15})})]},e))})]}),T.length>0&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Prompt history"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:T.slice(0,4).map(e=>(0,Ca.jsx)(rt,{tone:"ghost",align:"left",onClick:()=>oa({prompt:e}),children:e},e))})]}),!1!==Tt.supportsNegativePrompt&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Negative presets"}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1",children:P.map(e=>(0,Ca.jsx)(it,{onClick:()=>{Y(e),queueMicrotask(()=>Ue())},children:e},e))})]})]})]}),(0,Ca.jsx)(ct,{}),(0,Ca.jsx)(ks,{currentPrompt:$.prompt,promptHistory:T,savedSnippets:A,onApplyPrompt:e=>oa({prompt:e})})]})]}),(0,Ca.jsxs)(ft,{id:"advanced-generation",title:"Advanced generation",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:re?"Video frame":ye?"Rendered orbit frame":ce?"Native sample size":he?"Prediction map":ge?"Speech recognition":"Image size"}),ce?(0,Ca.jsxs)("p",{className:"text-xs text-modiff-subtle-text","data-testid":"studio-unconditional-native-size",children:["This checkpoint produces fixed ",$.width,"×",$.height," samples."]}):he?(0,Ca.jsxs)("div",{className:"grid gap-2","data-testid":"studio-perception-controls",children:[(0,Ca.jsx)(Ie,{label:"Processing resolution",value:$.processingResolution,onChange:e=>oa({processingResolution:As(e,$.processingResolution)})}),(0,Ca.jsx)(je,{checked:$.matchInputResolution,onChange:e=>oa({matchInputResolution:e}),label:"Match output to source resolution"}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Output is a normalized relative-depth map: near is 0, far is 1. Studio also previews it as grayscale."})]}):ge?(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text","data-testid":"studio-speech-summary",children:"Transcribe local audio into a normalized transcript with bounded chunking and timestamps."}):Tt.layerResolutions?.length?(0,Ca.jsx)(Se,{"aria-label":"Layer resolution","data-testid":"studio-layer-resolution-select",value:String($.width),onValueChange:e=>{let t=As(e,$.width);oa({width:t,height:t,aspectRatio:"1:1"})},options:Tt.layerResolutions.map(e=>({value:String(e),label:`${e} × ${e}`}))}):(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(Se,{"aria-label":"Aspect ratio",value:$.aspectRatio,onValueChange:e=>(e=>{let t=Ts.find(t=>t.label===e);oa(t?{aspectRatio:e,width:t.width,height:t.height}:{aspectRatio:e})})(e),options:[...Ts.map(e=>({value:e.label,label:e.label})),{value:"custom",label:"Custom"}],className:"flex-1"}),(0,Ca.jsx)(ut,{"aria-label":"Width",value:$.width,"data-testid":"studio-width-input",onChange:e=>oa({width:As(e.target.value,$.width),aspectRatio:"custom"}),className:"w-[86px]"}),(0,Ca.jsx)(ut,{"aria-label":"Height",value:$.height,"data-testid":"studio-height-input",onChange:e=>oa({height:As(e.target.value,$.height),aspectRatio:"custom"}),className:"w-[86px]"})]})]}),"outpaint"===$.mode&&(0,Ca.jsxs)("section",{"data-testid":"studio-outpaint-controls",children:[(0,Ca.jsx)(Qe,{title:"Outpaint canvas"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Ie,{label:"Left margin",value:$.outpaintLeft,onChange:e=>oa({outpaintLeft:As(e,$.outpaintLeft)})}),(0,Ca.jsx)(Ie,{label:"Right margin",value:$.outpaintRight,onChange:e=>oa({outpaintRight:As(e,$.outpaintRight)})}),(0,Ca.jsx)(Ie,{label:"Top margin",value:$.outpaintTop,onChange:e=>oa({outpaintTop:As(e,$.outpaintTop)})}),(0,Ca.jsx)(Ie,{label:"Bottom margin",value:$.outpaintBottom,onChange:e=>oa({outpaintBottom:As(e,$.outpaintBottom)})})]}),(0,Ca.jsx)(Kt,{label:`Seam overlap: ${$.outpaintOverlap}`,children:(0,Ca.jsx)(pt,{min:0,max:128,step:4,value:$.outpaintOverlap,onChange:e=>oa({outpaintOverlap:e})})}),(0,Ca.jsx)(Kt,{label:`Mask feather: ${$.outpaintFeather}`,children:(0,Ca.jsx)(pt,{min:0,max:64,step:1,value:$.outpaintFeather,onChange:e=>oa({outpaintFeather:e})})}),(0,Ca.jsx)(Ie,{label:"Fill color",value:$.outpaintFillColor,onChange:e=>oa({outpaintFillColor:e})})]})]}),!ge&&(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Generation"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[(0,Ca.jsx)("div",{"data-testid":"studio-seed-input",children:(0,Ca.jsx)(Ie,{label:"Seed",value:$.seed,onChange:e=>oa({seed:As(e,$.seed)}),disabled:$.randomSeed})}),(0,Ca.jsx)(je,{checked:$.randomSeed,onChange:e=>oa({randomSeed:e}),label:"Randomize seed on export"}),(0,Ca.jsx)(Kt,{label:`Steps: ${$.steps}`,children:(0,Ca.jsx)(pt,{min:1,max:ce?1e3:80,value:$.steps,onChange:e=>oa({steps:e})})}),ce&&(0,Ca.jsx)(Ie,{label:"Batch size",value:$.batchSize,onChange:e=>oa({batchSize:As(e,$.batchSize)})}),"DDIMPipeline"===$.modelType&&(0,Ca.jsx)(Kt,{label:`Eta: ${$.eta}`,children:(0,Ca.jsx)(pt,{min:0,max:1,step:.01,value:$.eta,onChange:e=>oa({eta:e})})}),"ConsistencyModelPipeline"===$.modelType&&(0,Ca.jsx)(Ie,{label:"Class label (-1 is unconditional)",value:$.classLabel,onChange:e=>oa({classLabel:As(e,$.classLabel)})}),Ce&&(0,Ca.jsx)(Kt,{label:`${Tt.guidanceLabel}: ${$.guidanceScale}`,children:(0,Ca.jsx)(pt,{min:0,max:10,step:.1,value:$.guidanceScale,onChange:e=>oa({guidanceScale:e})})}),void 0!==Tt.recommendedPagScale&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Kt,{label:`PAG scale: ${$.pagScale}`,children:(0,Ca.jsx)(pt,{min:0,max:10,step:.1,value:$.pagScale,onChange:e=>oa({pagScale:e})})}),(0,Ca.jsx)(Kt,{label:`PAG adaptive scale: ${$.pagAdaptiveScale}`,children:(0,Ca.jsx)(pt,{min:0,max:10,step:.1,value:$.pagAdaptiveScale,onChange:e=>oa({pagAdaptiveScale:e})})})]}),re&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Ie,{label:"Frames",value:$.numFrames,onChange:e=>oa({numFrames:As(e,$.numFrames)})}),(0,Ca.jsx)(Ie,{label:"FPS",value:$.fps,onChange:e=>oa({fps:As(e,$.fps)})})]}),(0,Ca.jsx)(Kt,{label:`Conditioning: ${$.conditioningScale}`,children:(0,Ca.jsx)(pt,{min:0,max:2,step:.05,value:$.conditioningScale,onChange:e=>oa({conditioningScale:e})})}),(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Kt,{label:`Guidance 2: ${$.guidanceScale2}`,children:(0,Ca.jsx)(pt,{min:0,max:20,step:.1,value:$.guidanceScale2,onChange:e=>oa({guidanceScale2:e})})}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Se,{"aria-label":"Output type",value:$.outputType,onValueChange:e=>oa({outputType:e}),options:[{value:"pil",label:"Output: PIL"},{value:"np",label:"Output: NumPy"},{value:"pt",label:"Output: Torch"}]}),(0,Ca.jsx)(Ie,{label:"Max tokens",value:$.maxSequenceLength,onChange:e=>oa({maxSequenceLength:As(e,$.maxSequenceLength)})})]}),(0,Ca.jsx)(Ie,{label:"Attention kwargs JSON",value:$.attentionKwargsJson,multiline:!0,onChange:e=>oa({attentionKwargsJson:e})})]})]}),Tt.supportsImageInput&&!re&&!he&&(0,Ca.jsx)(Ca.Fragment,{children:(0,Ca.jsx)(Kt,{label:`Strength: ${$.strength}`,children:(0,Ca.jsx)(pt,{min:0,max:1,step:.05,value:$.strength,onChange:e=>oa({strength:e})})})}),(Bt||Zt)&&(0,Ca.jsx)(Kt,{label:`Control conditioning: ${$.conditioningScale}`,children:(0,Ca.jsx)(pt,{min:0,max:2,step:.05,value:$.conditioningScale,onChange:e=>oa({conditioningScale:e})})}),Gt&&(0,Ca.jsx)(Kt,{label:`IP-Adapter scale: ${$.ipAdapterScale}`,children:(0,Ca.jsx)(pt,{min:0,max:2,step:.05,value:$.ipAdapterScale,onChange:e=>oa({ipAdapterScale:e})})}),Tt.supportsLayers&&(0,Ca.jsx)(Ie,{label:Tt.layerCount?`Layers (${Tt.layerCount.min}–${Tt.layerCount.max})`:"Layers",value:$.layers,onChange:e=>{let t=As(e,$.layers);oa({layers:Tt.layerCount?Math.min(Tt.layerCount.max,Math.max(Tt.layerCount.min,t)):t})}})]})]}),Ce&&(0,Ca.jsx)(xs,{form:$}),Ce&&(0,Ca.jsx)(Rs,{form:$,template:ae,onChange:oa,onRunSweep:e=>{Na(()=>za(e))},disabled:e||!!Yt})]}),Ce&&(0,Ca.jsx)(ft,{id:"controlled-workflows",title:"Controlled workflows",children:(0,Ca.jsx)(ms,{form:$,onChange:oa,disabled:e})}),re&&(0,Ca.jsx)(ft,{id:"video-inputs",title:"Video inputs",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:[Ut&&(0,Ca.jsx)(Ie,{label:"Source video path",value:$.sourceVideo,onChange:e=>oa({sourceVideo:e})}),Qt&&(0,Ca.jsx)(Ie,{label:"Source video paths (one per line)",value:$.referenceVideos.join("\n"),onChange:e=>oa({referenceVideos:e.split(/\r?\n/).map(e=>e.trim()).filter(Boolean)}),multiline:!0}),("video_inpaint"===$.mode||"video_outpaint"===$.mode)&&(0,Ca.jsx)(Ie,{label:"Mask video path",value:$.maskVideo,onChange:e=>oa({maskVideo:e})}),Zt&&(0,Ca.jsx)(Ie,{label:"Control video path",value:$.controlVideo,onChange:e=>oa({controlVideo:e})}),"image_to_video"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Use Reference inputs below for the starting image."}),"reference_to_video"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Use Reference inputs below for subject and style images."})]})}),oe&&(0,Ca.jsx)(ft,{id:"audio-inputs",title:"Audio",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2",children:["text_to_audio"!==$.mode&&(0,Ca.jsx)(Ie,{label:"Source audio path",value:$.sourceAudio,onChange:e=>oa({sourceAudio:e})}),"audio_variation"===$.mode&&(0,Ca.jsx)(Ie,{label:"Reference audio path",value:$.referenceAudio,onChange:e=>oa({referenceAudio:e})}),(0,Ca.jsx)(Ie,{label:"Lyrics",value:$.lyrics,onChange:e=>oa({lyrics:e}),multiline:!0}),(0,Ca.jsxs)("div",{className:Me("grid gap-2","grid-cols-2"),children:[(0,Ca.jsx)(Kt,{label:`Duration ${$.audioDuration}s`,children:(0,Ca.jsx)(pt,{value:$.audioDuration,min:1,max:240,step:.5,onChange:e=>oa({audioDuration:e})})}),(0,Ca.jsx)(Kt,{label:`Shift ${$.shift}`,children:(0,Ca.jsx)(pt,{value:$.shift,min:0,max:10,step:.1,onChange:e=>oa({shift:e})})})]}),"audio_continuation"===$.mode&&(0,Ca.jsx)(Kt,{label:`Continuation length ${$.extensionDuration}s`,children:(0,Ca.jsx)(pt,{value:$.extensionDuration,min:1,max:180,step:.5,onChange:e=>oa({extensionDuration:e})})}),"audio_repaint"===$.mode&&(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Kt,{label:`Repaint start ${$.repaintingStart}s`,children:(0,Ca.jsx)(pt,{value:$.repaintingStart,min:0,max:240,step:.1,onChange:e=>oa({repaintingStart:e})})}),(0,Ca.jsx)(Kt,{label:`Repaint end ${$.repaintingEnd}s`,children:(0,Ca.jsx)(pt,{value:$.repaintingEnd,min:0,max:240,step:.1,onChange:e=>oa({repaintingEnd:e})})})]}),"audio_variation"===$.mode&&(0,Ca.jsx)(Kt,{label:`Cover strength ${$.audioCoverStrength}`,children:(0,Ca.jsx)(pt,{value:$.audioCoverStrength,min:0,max:1,step:.01,onChange:e=>oa({audioCoverStrength:e})})}),(0,Ca.jsxs)("div",{className:"grid grid-cols-3 gap-2",children:[(0,Ca.jsx)(ut,{value:$.vocalLanguage,onChange:e=>oa({vocalLanguage:e.target.value}),"aria-label":"Audio language"}),(0,Ca.jsx)(ut,{value:$.keyscale,onChange:e=>oa({keyscale:e.target.value}),"aria-label":"Audio key"}),(0,Ca.jsx)(ut,{value:$.timesignature,onChange:e=>oa({timesignature:e.target.value}),"aria-label":"Audio time signature"})]})]})}),ge&&(0,Ca.jsx)(ft,{id:"speech-inputs",title:"Speech recognition",defaultOpen:!0,children:(0,Ca.jsxs)("div",{className:"grid gap-2","data-testid":"studio-speech-controls",children:[(0,Ca.jsx)(Ie,{label:"Source audio path",value:$.sourceAudio,onChange:e=>oa({sourceAudio:e})}),(0,Ca.jsx)(Ie,{label:"Language hint (optional)",value:$.speechLanguage,onChange:e=>oa({speechLanguage:e})}),(0,Ca.jsx)(Se,{"aria-label":"Speech timestamps",value:$.speechTimestamps,onValueChange:e=>oa({speechTimestamps:e}),options:[{value:"none",label:"No timestamps"},{value:"segment",label:"Segment timestamps"},{value:"word",label:"Word timestamps"}]}),(0,Ca.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,Ca.jsx)(Ie,{label:"Chunk length (seconds)",value:$.speechChunkSeconds,onChange:e=>oa({speechChunkSeconds:As(e,$.speechChunkSeconds)})}),(0,Ca.jsx)(Ie,{label:"Chunk stride (seconds)",value:$.speechStrideSeconds,onChange:e=>oa({speechStrideSeconds:As(e,$.speechStrideSeconds)})})]}),"speech_translation"===$.mode&&(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Translation output is normalized to English."})]})}),(0,Ca.jsx)(ft,{id:"runtime",title:"Runtime",children:(0,Ca.jsxs)("section",{className:"grid gap-2","data-testid":"studio-expert-runtime-controls",children:[(0,Ca.jsx)(Qe,{title:"Custom runtime settings"}),(0,Ca.jsxs)("div",{className:"flex gap-2",children:[(0,Ca.jsx)(Se,{"aria-label":"Data type",value:$.dtype,onValueChange:e=>oa({dtype:e}),options:[{value:"bfloat16",label:"bfloat16"},{value:"float16",label:"float16"},{value:"float32",label:"float32"}],className:"flex-1"}),(0,Ca.jsx)(ut,{"aria-label":"Device",value:$.device,onChange:e=>oa({device:e.target.value}),className:"w-24"})]}),(0,Ca.jsx)(je,{checked:$.autoOffload,onChange:e=>oa({autoOffload:e}),label:"Auto-offload model components"}),(0,Ca.jsxs)("div",{className:Me("grid gap-2",qe.length?"grid-cols-2":"grid-cols-1"),children:[qe.length>0&&(0,Ca.jsx)(Se,{"aria-label":"Quantization","data-testid":"studio-quantization-select",value:$.quantizationMode,onValueChange:e=>{oa({quantizationMode:e})},options:[{value:"none",label:"No quantization"},...qe.map(e=>({value:e,label:"bnb_4bit"===e?"4-bit BnB":"bnb_8bit"===e?"8-bit BnB":"quanto_float8"===e?"Quanto float8":"TorchAO float8"}))]}),(0,Ca.jsx)(Se,{"aria-label":"Offload mode","data-testid":"studio-offload-mode-select",value:$.offloadMode,onValueChange:e=>oa({offloadMode:e}),options:Tt.offloadSupport.modes.map(e=>({value:e,label:fe[e]}))})]})]})}),(_t||"image_to_video"===$.mode||"reference_to_video"===$.mode)&&(0,Ca.jsx)(ft,{id:"reference-inputs",title:he?"Source image":"Reference inputs",defaultOpen:!0,children:(0,Ca.jsx)(os,{})}),(qt||Bt||Gt)&&(0,Ca.jsxs)(ft,{id:"mask-control",title:[qt,Bt,Gt].filter(Boolean).length>1?"Conditioning inputs":qt?"Mask draft":Bt?"Control image":"IP-Adapter image",defaultOpen:!0,children:[qt&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Ie,{label:"Mask image path",value:$.maskImage,onChange:e=>oa({maskImage:e})}),(0,Ca.jsx)("p",{className:Me("text-xs",Dt?"text-modiff-subtle-text":"text-hf-orange"),children:Dt?"The mask limits which source-image region can change.":Et?.reason??"Brush, erase, invert, feather, clear, and fill are frontend draft controls until backend support is confirmed."}),(0,Ca.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,Ca.jsx)(rt,{tone:"ghost",onClick:()=>i(!0),children:"Open mask editor"}),$.maskImage&&(0,Ca.jsx)(rt,{tone:"ghost",onClick:()=>oa({maskImage:""}),children:"Clear saved mask"})]}),s&&(0,Ca.jsx)(hs,{sourceImage:$.referenceImages[0],maskImage:$.maskImage,onSave:e=>{oa({maskImage:e}),i(!1)},onCancel:()=>i(!1)})]}),Bt&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Ie,{label:"Control image path",value:$.controlImage,onChange:e=>oa({controlImage:e})}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"The control image is a separate structural guide declared by the selected task contract."}),$.mode.includes("control_union")&&(0,Ca.jsx)(Ie,{label:"ControlNet Union mode (0–5)",value:$.controlMode,onChange:e=>oa({controlMode:As(e,$.controlMode)})})]}),Gt&&(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsx)(Ie,{label:"IP-Adapter image path",value:$.ipAdapterImage,onChange:e=>oa({ipAdapterImage:e})}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"This reference is encoded by the separately editable IP-Adapter block; it is not the source or ControlNet image."})]})]}),(0,Ca.jsx)("p",{className:"border-t border-modiff-border pt-3 text-xs text-modiff-subtle-text",children:Oe?"Studio is linked to graph nodes. Workflow edits remain visible on the canvas.":"Custom graph mode: add nodes, connect an output, or start from a template."})]}),(0,Ca.jsx)(va,{open:!!a.pending,policies:a.pending?.policies??[],action:"run",onCancel:a.cancel,onConfirm:a.confirm})]})}var _s=[{id:"studio:prompt",kind:"studio-form",label:"Prompt",formKey:"prompt"},{id:"studio:negativePrompt",kind:"studio-form",label:"Negative prompt",formKey:"negativePrompt"},{id:"studio:seed",kind:"studio-form",label:"Seed",formKey:"seed"},{id:"studio:steps",kind:"studio-form",label:"Steps",formKey:"steps"},{id:"studio:guidanceScale",kind:"studio-form",label:"Guidance",formKey:"guidanceScale"},{id:"studio:pagScale",kind:"studio-form",label:"PAG scale",formKey:"pagScale"},{id:"studio:pagAdaptiveScale",kind:"studio-form",label:"PAG adaptive scale",formKey:"pagAdaptiveScale"},{id:"studio:processingResolution",kind:"studio-form",label:"Processing resolution",formKey:"processingResolution"},{id:"studio:matchInputResolution",kind:"studio-form",label:"Match input resolution",formKey:"matchInputResolution"},{id:"studio:strength",kind:"studio-form",label:"Strength",formKey:"strength"},{id:"studio:width",kind:"studio-form",label:"Width",formKey:"width"},{id:"studio:height",kind:"studio-form",label:"Height",formKey:"height"},{id:"studio:referenceImages",kind:"studio-form",label:"Reference images",formKey:"referenceImages"},{id:"studio:controlImage",kind:"studio-form",label:"Control image",formKey:"controlImage"},{id:"studio:maskImage",kind:"studio-form",label:"Mask image",formKey:"maskImage"},{id:"studio:sourceAudio",kind:"studio-form",label:"Source audio",formKey:"sourceAudio"},{id:"studio:speechLanguage",kind:"studio-form",label:"Speech language",formKey:"speechLanguage"},{id:"studio:speechTimestamps",kind:"studio-form",label:"Speech timestamps",formKey:"speechTimestamps"},{id:"studio:speechChunkSeconds",kind:"studio-form",label:"Speech chunk length",formKey:"speechChunkSeconds"},{id:"studio:speechStrideSeconds",kind:"studio-form",label:"Speech chunk stride",formKey:"speechStrideSeconds"}];function zs(e){return!(!e||"object"!=typeof e||!("id"in e)||"string"!=typeof e.id)}function qs(e){return e.filter(zs).flatMap(e=>Object.entries(e.data?.params??{}).filter(([e,t])=>!t.isInput&&!["image","output","images","latents"].includes(e)).slice(0,10).map(([t,a])=>({id:`graph:${e.id}:${t}`,kind:"graph-param",label:`${e.data?.label||e.id} / ${a.label||t}`,nodeId:e.id,paramKey:t})))}function Bs(e){return Array.isArray(e)?e.join("\n"):String(e??"")}function Gs(e,t,a){let s=e[t];return Array.isArray(s)?a.split("\n").map(e=>e.trim()).filter(Boolean):"number"==typeof s?function(e,t){let a=Number(e);return Number.isFinite(a)?a:t}(a,s):"boolean"==typeof s?"true"===a:a}function Ds(e,t){return e.exposedInputs.some(e=>e.id===t.id)}function Os(){let e=ze(e=>e.form),t=ze(e=>e.workflowTabs),a=ze(e=>e.activeWorkflowTabId),s=ze(e=>e.appModeConfigs),i=ze(e=>e.activeAppModeConfigId),l=ze(e=>e.createAppModeConfig),n=ze(e=>e.updateAppModeConfig),r=ze(e=>e.deleteAppModeConfig),o=ze(e=>e.setActiveAppModeConfig),d=ze(e=>e.switchWorkflowTab),c=ze(e=>e.updateForm),u=be(e=>e.nodes),m=mt(e=>e.sid),p=mt(e=>e.isConnected),f=s.find(e=>e.id===i)??s[0]??null,h=t.find(e=>e.id===f?.workflowTabId)??t.find(e=>e.id===a)??null,x=!(!f||f.workflowTabId!==a),g=(0,ka.useMemo)(()=>x?u:h?.snapshot.nodes??[],[x,u,h]),b=(0,ka.useMemo)(()=>[..._s,...qs(g)],[g]),j=(0,ka.useMemo)(()=>function(e){return e.filter(zs).filter(e=>/preview|save|output|video|audio|image/i.test(`${e.data?.label??""} ${e.id}`)).map(e=>({id:`output:${e.id}`,label:e.data?.label||e.id,nodeId:e.id,fieldKey:"output"}))}(g),[g]),v=!!(a&&g.length>0&&j.length>0),y=!!(f&&f.exposedOutputs.length>0&&m&&p),w=(t,a)=>{"studio-form"!==t.kind||!t.formKey||(c({[t.formKey]:Gs(e,t.formKey,a)}),queueMicrotask(()=>Ue()))};return(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"app-mode-panel",children:[(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Run as app",action:(0,Ca.jsx)(rt,{tone:"primary",icon:(0,Ca.jsx)(_,{size:15}),disabled:!v,onClick:()=>{v?l(a)&&Fe("Run as app created for this workflow",{variant:"success",autoHideDuration:2e3}):Fe("Use a graph with at least one output node before creating Run as app.",{variant:"error",autoHideDuration:3500})},"data-testid":"app-mode-create",children:"Create"})}),(0,Ca.jsx)(Y,{children:"Expose selected inputs and outputs from this graph."})]}),s.length>0&&(0,Ca.jsx)(Se,{"aria-label":"Saved app configuration",value:f?.id??"",onValueChange:o,options:s.map(e=>({value:e.id,label:e.name}))}),f?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("section",{className:"grid gap-2 border border-modiff-border bg-modiff-panel p-3",children:[(0,Ca.jsx)(Ie,{label:"App name",value:f.name,onChange:e=>n(f.id,{name:e})}),(0,Ca.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,Ca.jsx)(it,{active:x,children:x?"Workflow open":"Workflow saved"}),(0,Ca.jsx)(it,{children:h?.title??"Missing workflow"}),!x&&(0,Ca.jsx)(rt,{tone:"ghost",onClick:()=>d(f.workflowTabId),children:"Open workflow"}),(0,Ca.jsx)(rt,{tone:"danger",icon:(0,Ca.jsx)(L,{size:15}),onClick:()=>r(f.id),children:"Delete"})]})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Choose inputs"}),(0,Ca.jsx)("div",{className:"grid gap-1",children:b.slice(0,36).map(e=>(0,Ca.jsx)(je,{checked:Ds(f,e),label:e.label,onChange:()=>(e=>{if(!f)return;let t=Ds(f,e)?f.exposedInputs.filter(t=>t.id!==e.id):[...f.exposedInputs,e];n(f.id,{exposedInputs:t})})(e)},e.id))})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Guided inputs"}),(0,Ca.jsxs)("div",{className:"grid gap-2",children:[0===f.exposedInputs.length&&(0,Ca.jsx)(Y,{children:"No inputs exposed yet."}),f.exposedInputs.map(t=>{if("studio-form"===t.kind&&t.formKey){let a=e[t.formKey];return"guidanceScale"===t.formKey||"pagScale"===t.formKey||"pagAdaptiveScale"===t.formKey||"strength"===t.formKey?(0,Ca.jsx)(Kt,{label:`${t.label}: ${String(a)}`,children:(0,Ca.jsx)(pt,{min:0,max:"strength"===t.formKey?1:12,step:.05,value:"number"==typeof a?a:0,onChange:e=>w(t,String(e))})},t.id):(0,Ca.jsx)(Ie,{label:t.label,disabled:!x,multiline:"prompt"===t.formKey||"negativePrompt"===t.formKey||"referenceImages"===t.formKey,value:Bs(a),onChange:e=>w(t,e)},t.id)}return(0,Ca.jsx)(Ie,{label:t.label,disabled:!x,value:String(t.nodeId&&t.paramKey?be.getState().getParam(t.nodeId,t.paramKey,"value")??"":""),onChange:e=>((e,t)=>{"graph-param"!==e.kind||!e.nodeId||!e.paramKey||be.getState().setParamWithHistory(e.nodeId,e.paramKey,t)})(t,e)},t.id)})]})]}),(0,Ca.jsxs)("section",{children:[(0,Ca.jsx)(Qe,{title:"Outputs"}),(0,Ca.jsxs)("div",{className:"grid gap-1",children:[0===j.length&&(0,Ca.jsx)(Y,{children:"No output nodes detected."}),j.map(e=>(0,Ca.jsx)(je,{checked:f.exposedOutputs.some(t=>t.id===e.id),label:e.label,onChange:()=>(e=>{if(!f)return;let t=f.exposedOutputs.some(t=>t.id===e.id)?f.exposedOutputs.filter(t=>t.id!==e.id):[...f.exposedOutputs,e];n(f.id,{exposedOutputs:t})})(e)},e.id))]})]}),(0,Ca.jsx)(rt,{tone:"primary",icon:(0,Ca.jsx)(G,{size:15}),disabled:!y,onClick:()=>{(async()=>{if(!f||!m||!p)return void Fe("Connect to the MoDiff server before running as app.",{variant:"error",autoHideDuration:4e3});if(0===f.exposedOutputs.length)return void Fe("Expose at least one output before running as app.",{variant:"error",autoHideDuration:3500});f.workflowTabId!==a&&d(f.workflowTabId);let e=Be(),t=!!ze.getState().graphBinding;try{if(t&&!await wt(e)||!Rt({sid:m,isConnected:p,includeStudio:t,showDialog:!0}).canRun)return;await gt({sid:m,studioContext:{applyRuntimeMetadata:t},workflowContext:e}),Fe("Run as app queued",{variant:"success",autoHideDuration:2200})}catch(e){if(V(e))return;Fe(String(e),{variant:"error",autoHideDuration:7e3})}})()},"data-testid":"app-mode-run",children:"Run app"})]}):(0,Ca.jsx)("div",{className:"border border-modiff-border bg-modiff-bg p-3 text-xs text-modiff-subtle-text",children:"Create Run as app from the active graph."})]})}function Es(){let e=(0,ka.useMemo)(ge,[]),t=be(t=>e(t.nodes)),a=be(e=>e.edges),s=ze(e=>e.activeWorkflowTabId),[i,l]=(0,ka.useState)(""),[n,r]=(0,ka.useState)(null),[d,c]=(0,ka.useState)(""),[u,m]=(0,ka.useState)(!1),[p,f]=(0,ka.useState)(null),h=(0,ka.useRef)(null),x=(0,ka.useMemo)(()=>{try{return{request:ca(t,a,i||void 0),error:""}}catch(e){return{request:null,error:e instanceof Error?e.message:String(e)}}},[t,a,i]),g=x.request?.key;(0,ka.useEffect)(()=>(h.current?.abort(),m(!1),r(null),c(""),f(null),()=>h.current?.abort()),[g,i,s]);let b=x.request,j=n?.request.key===g?n:null;return(0,Ca.jsxs)("section",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"workflow-resource-assessment",children:[(0,Ca.jsxs)("h2",{className:"flex items-center gap-2 font-semibold",children:[(0,Ca.jsx)(o,{size:17}),"Workflow resources"]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Memory → Automatic chooses supported technical settings. Custom keeps your configured settings. Creator and Developer workspaces can use either memory policy; changing workspace preserves this workflow’s settings."}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"A loader’s Auto Offload controls where its weights reside. Repeat/Loop controls repeated runs. They are separate from Auto resource planning."}),(0,Ca.jsx)(ia,{"aria-label":"Resource assessment scope",value:i,onValueChange:l,options:[{value:"",label:"Whole workflow"},...t.filter(e=>e.data.blockInstanceV2||e.data.blockProjectionContainer).map(e=>({value:e.id,label:`Only ${e.data.label??e.id}`}))]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:i?"Only contained nodes are assessed. Outside suppliers are excluded, as with Run Block.":"Includes connected outside nodes and every enabled Block."}),b?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("p",{className:"text-xs",children:[b.nodeCount," executable nodes · ",b.loaderCount," model loaders · ",b.adapterCount," adapters"]}),(0,Ca.jsx)("p",{className:"rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-auto-reason",children:"Auto can plan custom workflows and multiple Blocks. Each model recipe and the combined memory requirement must pass the backend check."})]}):null,(0,Ca.jsxs)(At,{onClick:()=>{(async()=>{if(!x.request)return;h.current?.abort();let e=new AbortController;h.current=e,m(!0),c(""),r(null);try{let t=await ma(x.request,e.signal);if(!e.signal.aborted&&ze.getState().activeWorkflowTabId===s){let e=be.getState();if(ca(e.nodes,e.edges,i||void 0).key!==t.request.key)throw Error("The workflow changed. Assess its current settings again.");r(t)}}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||m(!1)}})()},disabled:u||!b||!b.nodeCount,"data-testid":"assess-workflow-resources",children:[(0,Ca.jsx)(q,{size:14}),u?"Assessing resources…":"Assess workflow resources"]}),(0,Ca.jsx)(At,{onClick:()=>{(async()=>{h.current?.abort();let e=new AbortController;h.current=e,m(!0),c(""),f(null);try{let t=await(await Ye(async()=>{let{inspectWorkflowAutoPlanV2:e}=await import(`./block-composition-tools.js?v=ca6b74e6a02eedb3`).then(e=>e.t);return{inspectWorkflowAutoPlanV2:e}},[])).inspectWorkflowAutoPlanV2(i||void 0,e.signal);!e.signal.aborted&&ze.getState().activeWorkflowTabId===s&&f(t)}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||m(!1)}})()},disabled:u||!b?.nodeCount,"data-testid":"plan-workflow-auto",children:"Check Auto execution plan"}),p?(0,Ca.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-auto-plan",children:[(0,Ca.jsx)("p",{className:"font-semibold",children:p.canAutoRun?p.requiresPreparation?"Check computed inputs when Run starts":"Ready for Auto execution":"Auto needs attention"}),(0,Ca.jsx)("p",{children:p.message}),(0,Ca.jsxs)("p",{children:[p.requiresPreparation?"Resolved so far: ":"Peak planned resources: ",p.loaders.length," model owners · RAM"," ",Oe(p.requirements.systemRamBytes??null)," · GPU"," ",Oe(p.requirements.vramBytes??null)]}),p.loaders.map(e=>(0,Ca.jsxs)("p",{children:[e.repository," · ",e.consumers.length," consumers"]},e.nodeId)),p.patches.length?(0,Ca.jsxs)("p",{children:["Run will apply ",p.patches.length," resource-setting changes to the visible workflow."]}):null,p.issues.map((e,t)=>(0,Ca.jsx)("p",{className:"break-words text-modiff-subtle-text",children:e},t)),(0,Ca.jsx)("p",{children:"Run checks the current graph and available memory again. Custom preserves your explicit settings."})]}):null,x.error||d?(0,Ca.jsx)("p",{role:"alert",className:"break-words text-xs text-modiff-red",children:x.error||d}):null,j?(0,Ca.jsxs)(Ca.Fragment,{children:[(0,Ca.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-border p-2 text-xs",children:[(0,Ca.jsxs)("p",{children:["Available RAM: ",Oe(j.resources.system.ramAvailableBytes)]}),j.resources.accelerators.map(e=>(0,Ca.jsxs)("p",{children:[e.name,": ",Oe(e.memoryFreeBytes)," free · ",e.memoryKind," memory"]},e.device)),(0,Ca.jsx)("p",{className:"mt-1 text-modiff-subtle-text",children:"Shared GPU memory and RAM overlap; they are not added together."})]}),j.request.items.map(e=>{let t=j.plans[e.id],a=t?Ut(t,e.form??void 0):null;return(0,Ca.jsxs)("div",{className:"grid gap-1 rounded-modiff-compact border border-modiff-border p-2 text-xs","data-testid":"workflow-resource-item",children:[(0,Ca.jsx)("p",{className:"break-words font-semibold",children:e.label}),(0,Ca.jsxs)("p",{children:[e.loaderIds.length," loader",1===e.loaderIds.length?"":"s"," · ",e.consumers," downstream consumers"]}),e.currentSettings.map((t,a)=>(0,Ca.jsxs)("p",{className:"break-words text-modiff-subtle-text",children:["Current: ",t]},e.loaderIds[a])),a?(0,Ca.jsxs)("p",{className:"break-words",children:["Source recipe recommendation: ",a.dtype," · ",a.offloadMode,"."," ",t?.statusLabel??a.reason]}):t?(0,Ca.jsx)("p",{children:t.blockingReason??t.message??"No supported local source recipe was selected."}):null,e.details.map(e=>(0,Ca.jsx)("p",{className:"text-modiff-subtle-text",children:e},e))]},e.id)}),j.request.issues.map(e=>(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:e},e)),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Assessment preserves the graph and current settings. Check Auto execution plan to validate the actual combined graph, connected adapters and available memory before running."})]}):null]})}var Ls=[{value:"recommended",label:"Recommended"},{value:"best_quality",label:"Best quality"},{value:"faster",label:"Faster"},{value:"lowest_memory",label:"Lowest memory"}];function Fs(e){return e.resolvedArtifact||e.artifact||e.modelRepo||""}function Hs(e){let t=e.artifactResolution?.resolved,a=t?.format||e.artifactFormat||e.quantizationMode||"native",s=t?.bits?` ${t.bits}-bit`:"";return`${Fs(e)} · ${a}${s}`}function Ks(e){let t=e.requirements?.minimum||e.requirements?.lowerMemory;if(!t)return[];let a=1024**3,s=[];return"number"==typeof t.vramBytes&&t.vramBytes>0&&s.push(`${Math.ceil(t.vramBytes/a)} GB VRAM`),"number"==typeof t.systemRamBytes&&s.push(`${Math.ceil(t.systemRamBytes/a)} GB RAM`),"number"==typeof t.diskFreeBytes&&s.push(`${Math.ceil(t.diskFreeBytes/a)} GB disk`),s}function Ws(){let[e,t]=(0,ka.useState)(null),a=ta(e=>e.setRightPanelTab),s=ta(e=>e.setRightPanelOpen),l=ta(e=>e.setAlertOpener),n=mt(e=>e.sid),{installHfModel:r}=aa(xe(e=>({installHfModel:e.installHfModel}))),{form:u,graphBinding:m,plan:p,applyAutoResourcePlan:f,createWorkflowTab:h,updateForm:x,setAutoResourcePlan:g}=ze(xe(e=>({form:e.form,graphBinding:e.graphBinding,plan:e.autoResourcePlan,applyAutoResourcePlan:e.applyAutoResourcePlan,createWorkflowTab:e.createWorkflowTab,updateForm:e.updateForm,setAutoResourcePlan:e.setAutoResourcePlan}))),b=Ut(p,u)||null,v=nt(b,m?.controlled?.contractIds),y=(0,ka.useMemo)(()=>(p?.candidates||[]).filter(e=>e.id!==b?.id),[p?.candidates,b?.id]);if(!m)return(0,Ca.jsx)(Es,{});if(!b)return(0,Ca.jsxs)("div",{className:"grid gap-3 p-4 text-sm text-modiff-text","data-testid":"compatibility-panel",children:[(0,Ca.jsxs)("div",{className:"flex items-center gap-2 font-semibold",children:[(0,Ca.jsx)(E,{size:17,className:"text-modiff-green"}),"No model substitution"]}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Select a Studio model to inspect local compatibility."})]});let w=async e=>{let a=Fs(e);if(!a)return;let s=Be();t(a);try{await r(a,n,{repair:!!e.repairRequired}),se(s),Fe(`${a} is ready. Refreshing compatibility.`,{variant:"success"});let t=await he(ze.getState().form);se(s),g(t)}catch(e){if(V(e))return;Fe(e instanceof Error?e.message:`Could not install ${a}.`,{variant:"error"})}finally{t(null)}},k=e=>{let t=Fs(e);l({title:e.repairRequired?"Repair artifact?":"Install artifact?",message:`${t} will be downloaded and managed by MoDiff.`,confirmText:e.repairRequired?"Repair":"Install",cancelText:"Cancel",onConfirm:()=>{l(null),w(e)},onCancel:()=>l(null)})},C=async(e,t="")=>{let a=Be();try{let s={...dt(e,u),confirmedCommunityArtifact:t},i={...u,...s},l=await he(i);se(a);let n=Ut(l,i)??e;f(l,{...dt(n,i),confirmedCommunityArtifact:t}),ne(a),Fe("Next local option selected.",{variant:"info"})}catch(e){if(V(e))return;Fe(String(e),{variant:"error"})}},N=b.compatibilityEvidence,S=v?.message||N?.message||b.reason||b.skipReason||p?.blockingReason||"Compatibility was estimated from the current runtime and model metadata.",I=b.artifactResolution?.base?.repo||b.baseArtifact||Fs(b),R=!!(b.artifactResolution?.substituted||I&&I!==Fs(b));return(0,Ca.jsx)(Ca.Fragment,{children:(0,Ca.jsxs)("div",{className:"grid gap-3 p-3 text-sm text-modiff-text","data-testid":"compatibility-panel",children:[(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Automatic memory selects a supported local resource recipe. Custom keeps your configured technical settings. Switching preserves the workflow’s nodes, connections and creative controls."}),(0,Ca.jsx)("p",{className:"text-xs text-modiff-subtle-text",children:"Auto Offload on a loader controls weight placement. Repeat/Loop controls repeated runs. These are separate from Auto resource planning."}),(0,Ca.jsxs)("div",{className:"flex items-start gap-2 rounded-modiff-compact border border-hf-yellow/50 bg-hf-yellow/10 p-3",children:[(0,Ca.jsx)(j,{size:17,className:"mt-0.5 shrink-0 text-hf-yellow"}),(0,Ca.jsxs)("div",{className:"min-w-0",children:[(0,Ca.jsx)("p",{className:"font-semibold",children:v?.label||N?.label||b.healthBadge||"This should work"}),(0,Ca.jsx)("p",{className:"mt-1 line-clamp-2 text-xs text-modiff-subtle-text",children:S})]})]}),(0,Ca.jsx)(Kt,{label:"Recommendation",children:(0,Ca.jsx)(Se,{value:u.resourcePreference||"recommended",onValueChange:e=>{(async e=>{let t=Be(),a={...u,resourcePreference:e};x({resourcePreference:e}),ne(t);try{let e=await he(a);se(t),g(e)}catch(e){if(V(e))return;Fe(String(e),{variant:"error"})}})(e)},options:Ls.map(e=>({value:e.value,label:e.label})),"data-testid":"compatibility-preference"})}),(0,Ca.jsxs)("section",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border bg-modiff-surface p-3",children:[R?(0,Ca.jsxs)("p",{className:"truncate text-xs text-modiff-subtle-text",title:I,children:["Base: ",I]}):null,(0,Ca.jsx)("p",{className:"break-all font-semibold text-hf-yellow",children:Hs(b)}),(0,Ca.jsx)("div",{className:"flex flex-wrap gap-1.5",children:Ks(b).map(e=>(0,Ca.jsx)("span",{className:"rounded bg-modiff-bg px-2 py-1 text-modiff-label text-modiff-subtle-text",children:e},e))}),!1===b.installed||b.repairRequired?(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(D,{size:15}),onClick:()=>k(b),disabled:e===Fs(b),children:b.repairRequired?"Repair artifact":"Install in app"}):null]}),y.length?(0,Ca.jsxs)("section",{className:"grid gap-2",children:[(0,Ca.jsx)("h3",{className:"text-xs font-semibold uppercase text-modiff-subtle-text",children:"Other options"}),y.map(e=>(0,Ca.jsxs)(At,{tone:"secondary",align:"left",fullWidth:!0,className:"h-auto p-2",onClick:()=>(e=>{if(e.requiresConfirmation&&"manual_only"===e.proof?.status){if(!e.installed||e.repairRequired)return void k(e);let t=Fs(e);return void l({title:"Use community artifact?",message:`${t} is popularity-qualified but not quality-qualified by MoDiff. Use it for this workflow and machine?`,confirmText:"Use artifact",cancelText:"Cancel",onConfirm:()=>{l(null),C(e,t)},onCancel:()=>l(null)})}C(e)})(e),icon:"gguf"===e.artifactFormat?(0,Ca.jsx)(d,{size:15}):(0,Ca.jsx)(o,{size:15}),children:[(0,Ca.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,Ca.jsx)("span",{className:"block truncate text-xs font-semibold",children:Fs(e)}),(0,Ca.jsx)("span",{className:"block truncate text-modiff-label text-modiff-subtle-text",children:e.compatibilityEvidence?.label||e.healthBadge})]}),(0,Ca.jsx)(i,{size:14,className:"text-modiff-subtle-text"})]},e.id))]}):null,(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(c,{size:15}),onClick:()=>a("setup"),children:"Open setup"}),(0,Ca.jsx)(At,{icon:(0,Ca.jsx)(o,{size:15}),onClick:()=>{(async()=>{let e=Be(),t="modules.ModelArtifact.QuantizeDiffusersComponents",a=aa.getState().nodesRegistry;a[t]||(await aa.getState().fetchNodes(),se(e),a=aa.getState().nodesRegistry);let i=Vt(t,a,{x:120,y:100});if(!i)return void Fe("The optimized-artifact node is unavailable in this backend.",{variant:"error"});let l=b.artifactResolution?.base?.repo||b.baseArtifact||Fs(b);h(`Optimize ${l.split("/").pop()||"model"}`),be.getState().addNode(i),be.getState().setParam(i.id,"model_id",{source:"hub",value:l}),be.getState().setParam(i.id,"source_revision",b.artifactResolution?.base?.revision||"main"),b.pipelineClass&&be.getState().setParam(i.id,"pipeline_class",b.pipelineClass),ze.getState().saveActiveWorkflowTab(!0),s(!1),Fe("Optimized-copy workflow created. Review its admission and quality settings before running.",{variant:"success"})})()},children:"Create optimized copy"}),(0,Ca.jsxs)(Ct,{className:"rounded-modiff-compact border border-modiff-border bg-modiff-bg p-2 text-xs",label:"Evidence and requirements",buttonClassName:"min-h-0 p-0 text-xs",panelClassName:"mt-2 grid gap-2 break-words text-modiff-subtle-text",children:[(0,Ca.jsx)("p",{children:S}),b.requirementsMissing?.map(e=>(0,Ca.jsx)("p",{children:e},e)),N?.popularity?(0,Ca.jsxs)("p",{children:["Hub snapshot: ",N.popularity.downloads??0," downloads · ",N.popularity.likes??0," likes. Popularity is not compatibility proof."]}):null]})]})})}var Vs=(0,ka.lazy)(()=>Ye(()=>import(`./block-composition-tools.js?v=ca6b74e6a02eedb3`).then(e=>e.l),[])),Us=(0,ka.lazy)(()=>Ye(()=>import(`./BlockInterfaceDialogContentV2.js?v=ca6b74e6a02eedb3`),[]));function Qs(){let e=St(e=>e.target),t=St(e=>e.close),a=ze(e=>e.activeWorkflowTabId),s=ze(e=>e.workflowCanvasEpoch),i=be(t=>{let a=t.nodes.find(t=>t.id===e?.snapshot.instanceId)?.data.blockInstanceV2;return!(!a||e?.subtreeId&&!a.effectiveGraph.nodes.some(t=>t.nodeId===e.subtreeId))})&&e?.context.workflowTabId===a&&e?.context.canvasEpoch===s;return(0,ka.useEffect)(()=>{e&&!i&&t()},[e,i,t]),e&&i?(0,Ca.jsx)(ka.Suspense,{fallback:(0,Ca.jsx)("p",{className:"p-3 text-sm",role:"status",children:"Loading Block editor…"}),children:"save"===e.mode?(0,Ca.jsx)(Vs,{nodeId:e.nodeId,context:e.context,onClose:t},e.requestId):(0,Ca.jsx)(Us,{...e,onClose:t},e.requestId)}):null}export{rs as a,ua as default,Ps as i,Ws as n,es as o,Os as r,Qs as t}; \ No newline at end of file diff --git a/web/assets/block-composition-tools.js b/web/assets/block-composition-tools.js index 76ebd48..bf3c546 100644 --- a/web/assets/block-composition-tools.js +++ b/web/assets/block-composition-tools.js @@ -1 +1 @@ -import{n as e,r as t}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{Bn as a,Cn as o,En as n,M as i,Ot as d,R as r,Sn as s,X as l,cr as c,dr as u,et as p,kn as f,ln as m,nr as h,ot as g,q as b,tr as x,wt as I,xt as k,z as v}from"./graph-vendor.js?v=cc046c26d6fe7aa4";import{$s as y,Bn as w,Bs as j,Ci as $,Dt as N,Eo as C,Er as S,Fo as _,In as P,Jn as T,Js as O,Ks as M,Ln as E,Mn as H,Mo as R,No as B,Oo as A,Po as V,Sa as z,Si as L,Ti as D,Ts as q,V as F,Vi as G,Vn as W,Vr as U,Xr as K,Xs as Y,Yr as X,Ys as J,_ as Q,_n as Z,_r as ee,_s as te,an as ae,as as oe,br as ne,ca as ie,cn as de,cs as re,ct as se,dn as le,dt as ce,fi as ue,fn as pe,ft as fe,gi as me,gr as he,h as ge,hi as be,hr as xe,in as Ie,is as ke,it as ve,ji as ye,jo as we,ko as je,kr as $e,kt as Ne,m as Ce,mn as Se,oc as _e,os as Pe,p as Te,pi as Oe,q as Me,qo as Ee,rn as He,rs as Re,rt as Be,sa as Ae,ts as Ve,ui as ze,v as Le,vr as De,w as qe,x as Fe,xn as Ge,y as We,yr as Ue}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{t as Ke}from"./EditorPanel.js?v=cc046c26d6fe7aa4";import{a as Ye,i as Xe,n as Je,o as Qe,r as Ze,t as et}from"./BlockInterfaceDialogContentV2.js?v=cc046c26d6fe7aa4";import{t as tt}from"./LegacyUserBlockNode.js?v=cc046c26d6fe7aa4";import{a as at,i as ot,n as nt,o as it,r as dt,t as rt}from"./WorkspacePanel.js?v=cc046c26d6fe7aa4";var st=e({default:()=>ut}),lt=t(u(),1),ct=c();function ut(e){return"composition"===e.mode?(0,ct.jsx)(pt,{...e}):(0,ct.jsx)(Ie,{open:!0,onClose:e.onClose,title:"Switch model route",testId:`switch-block-route-v1-${e.nodeId}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:e.onClose,children:"Cancel"}),(0,ct.jsx)(He,{disabled:e.busy,onClick:()=>e.onSwitch(!0),children:"Save active route and switch"}),(0,ct.jsx)(He,{tone:"primary",disabled:e.busy,onClick:()=>e.onSwitch(!1),children:"Keep draft and switch"})]}),children:(0,ct.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"This route has workflow-local changes. MoDiff can keep its exact values, internal graph, interface, and layout as an inactive workflow draft, then restore them when you switch back. Previews and run authority are not copied between models."})})}function pt({nodeId:e,instance:t,onClose:a}){let o=K(e=>e.library),n=X(e=>e.snapshot),i=K(e=>e.error),d=X(e=>e.error),r=t.effectiveGraph.nodes.some(e=>"upstream_block"===e.modularDiffusers?.kind),s=!r||!(!o||!n),[l,c]=(0,lt.useState)(0),[u,p]=(0,lt.useState)(!1);(0,lt.useEffect)(()=>{if(!r)return;let e=!0;p(!0);let t=K.getState(),a=X.getState();return Promise.all([t.library?Promise.resolve():t.fetchLibrary(),a.snapshot?Promise.resolve():a.fetchSnapshot()]).finally(()=>{e&&p(!1)}),()=>{e=!1}},[r,l]);let[f,m]=(0,lt.useState)(!1),[h,g]=(0,lt.useState)(null),[b,x]=(0,lt.useState)(null),I=(0,lt.useRef)(null),k=(0,lt.useMemo)(()=>{if(!s)return{recipe:null,error:null};try{return{recipe:Le(t,o,n),error:null}}catch(e){return{recipe:null,error:e instanceof Error?e.message:"Could not derive the upstream Modular composition."}}},[t,o,n,s]);return(0,lt.useEffect)(()=>(g(null),x(null),m(!1),()=>I.current?.abort()),[Y(k.recipe)]),(0,ct.jsx)(Ie,{open:!0,onClose:a,title:"Block composition",testId:`user-block-composition-dialog-${e}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:a,children:"Close"}),s?null:(0,ct.jsx)(He,{disabled:u,onClick:()=>c(e=>e+1),children:u?"Loading pinned catalog…":"Retry pinned catalog"}),k.recipe?(0,ct.jsx)(He,{tone:"primary",disabled:f,onClick:()=>{(async()=>{if(!k.recipe||f)return;let e=new AbortController;I.current=e,m(!0),g(null),x(null);try{let t=await Q(k.recipe,e.signal);e.signal.aborted||g(t)}catch(t){e.signal.aborted||x(t instanceof Error?t.message:"The backend could not rebuild this Modular composition.")}finally{e.signal.aborted||m(!1)}})()},children:f?"Rebuilding…":"Validate upstream composition"}):null]}),children:(0,ct.jsxs)("div",{className:"grid gap-2 text-sm text-modiff-subtle-text",children:[s?null:(0,ct.jsx)("p",{role:u?"status":"alert",children:u?"Loading the reviewed block catalog and hierarchy. Your workflow is unchanged.":i??d??"The pinned catalog is unavailable. Retry before validating."}),(0,ct.jsxs)("p",{children:[t.effectiveGraph.nodes.length," ordinary internal nodes and ",t.effectiveGraph.edges.length," ","internal connections are owned by this workflow instance."]}),(0,ct.jsxs)("p",{children:["Source: ",t.definitionSnapshot.source.kind,". Customization state:"," ",t.customization.state.replace(/_/gu," "),"."]}),k.recipe?(0,ct.jsxs)("p",{"data-testid":`block-v2-composition-summary-${e}`,children:["Exact upstream recipe: ",k.recipe.operations.length," structural operation",1===k.recipe.operations.length?"":"s",". Parameter-only changes are stored directly on this workflow instance and do not rebuild sibling blocks."]}):null,k.error?(0,ct.jsx)("p",{className:"text-modiff-warning","data-testid":`block-v2-composition-error-${e}`,children:k.error}):null,h?(0,ct.jsxs)("p",{className:"text-modiff-green","data-testid":`block-v2-composition-receipt-${e}`,children:["Upstream init_pipeline() rebuild passed for ",h.composedPaths.length," paths. Receipt"," ",h.receiptHash.slice(0,20),"…"]}):null,b?(0,ct.jsx)("p",{className:"text-modiff-red",children:b}):null,"edited_unpruned_tree"===h?.inspectionScope?(0,ct.jsx)("p",{children:"This checks the edited tree, including inactive branches. It does not load models or qualify a run. Execution checks each connected step's required components and inputs."}):null]})})}function ft(e,t){return`${e}\0${t}`}function mt(e,t){let a=e.fieldId??e.fieldOrPortId??"",o=t.fieldId??t.fieldOrPortId??"";return e.nodeId===t.nodeId?a===o?0:a=e.length)return[...e];let n=[...e];return[n[t],n[o]]=[n[o],n[t]],n}function gt({entryKey:e,valueType:t,primary:a,mirrors:o,options:n,selected:i,disabled:d=!1,onSelected:r,onAdd:s,onRemove:l}){let c=function(e,t,a,o){let n=new Set([ft(a.nodeId,a.fieldId),...o.map(({nodeId:e,fieldId:t})=>ft(e,t))]);return e.filter(e=>!n.has(e.key)&&M(t,e.valueType))}(n,t,a,o),u=new Map(n.map(e=>[e.key,e.label]));return(0,ct.jsxs)("div",{className:"ml-3 grid gap-2 border-l border-modiff-border-subtle pl-3","data-testid":`interface-mirrors-${e}`,children:[o.map(t=>{let a=ft(t.nodeId,t.fieldId);return(0,ct.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[(0,ct.jsxs)("span",{className:"min-w-0 flex-1 break-words",children:["Additional consumer: ",u.get(a)??`${t.nodeId} / ${t.fieldId}`]}),(0,ct.jsx)(ae,{label:`Remove additional consumer ${u.get(a)??t.fieldId}`,size:"compact",disabled:d,"data-testid":`interface-mirror-remove-${e}-${t.nodeId}-${t.fieldId}`,onClick:()=>l(t),children:(0,ct.jsx)(v,{size:13})})]},a)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Qe,{value:i,disabled:d,onValueChange:r,options:c.map(e=>({value:e.key,label:e.label})),placeholder:"Add another internal consumer","data-testid":`interface-mirror-select-${e}`}),(0,ct.jsx)(ae,{label:"Add additional internal consumer",size:"compact",disabled:d||!i||!c.some(({key:e})=>e===i),"data-testid":`interface-mirror-add-${e}`,onClick:()=>{let e=c.find(({key:e})=>e===i);e&&s(e)},children:(0,ct.jsx)(g,{size:14})})]})]})}function bt(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function xt(e,t,a){let o=new Set([...a.boundary.inputs.map(({portId:e})=>e),...a.boundary.outputs.map(({portId:e})=>e),...a.controls.map(({controlId:e})=>e)]),n=`${e}:${t.nodeId}:${t.fieldId}`.replace(/[^A-Za-z0-9_.:/-]/gu,"-"),i=n,d=2;for(;o.has(i);)i=`${n}-${d++}`;return i}function It({nodeId:e,snapshot:t,subtreeId:a,context:o,onClose:i}){let[d,r]=(0,lt.useState)(()=>Je(t,a)),[s,l]=(0,lt.useState)({input:"",output:"",control:""}),[c,u]=(0,lt.useState)({}),p=(0,lt.useMemo)(()=>Xe(t,a),[t,a]),m=(0,lt.useMemo)(()=>function(e){return e.effectiveGraph.nodes.flatMap(e=>{let t=bt(e.data.params)?e.data.params:{};return Object.entries(t).flatMap(([t,a])=>bt(a)&&"string"==typeof a.type&&a.type?[{key:`${e.nodeId}\0${t}`,nodeId:e.nodeId,fieldId:t,label:`${"string"==typeof e.data.label?e.data.label:e.nodeId} / ${"string"==typeof a.label?a.label:t}`,valueType:a.type,..."string"==typeof a.display?{display:a.display}:{}}]:[])})}(t).filter(({nodeId:e})=>p.has(e)),[t,p]),h=m.filter(({display:e})=>"output"!==e),b=m.filter(({display:e})=>"output"===e),x=h,I=U(e=>e.edges),k=null,y=null;try{d&&(y=Ye(t,t,d,a))}catch(e){k=e instanceof Error?e.message:"Invalid interface draft."}let w=new Set(y?.boundary.inputs.map(({portId:e})=>e)),j=new Set(y?.boundary.outputs.map(({portId:e})=>e)),$=a&&y?Ee(t,a,{schemaVersion:1,...y}):a?[]:I.filter(e=>!((e.target!==t.instanceId||te(e.targetHandle)||e.targetHandle&&w.has(e.targetHandle))&&(e.source!==t.instanceId||te(e.sourceHandle)||e.sourceHandle&&j.has(e.sourceHandle))));return(0,ct.jsx)(Ke,{onClose:()=>i(),title:q(t)&&!a?"Configure node interface":"Configure Block interface",testId:`configure-block-v2-${e}`,footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:()=>i(),children:"Cancel"}),(0,ct.jsx)(He,{tone:"primary",disabled:!d||$.length>0||!!k,onClick:()=>{if(d)try{(function(){D(o,{includeForm:!1});let e=U.getState().nodes.find(e=>e.id===t.instanceId)?.data.blockInstanceV2;if(!e||!d)throw Error("This Block is no longer available. Reopen Configure Interface.");let n=Ye(t,e,d,a);U.getState().configureBlockInterfaceV2(t.instanceId,n,a)})(),i(),R("The workflow instance interface was updated.",{variant:"success",autoHideDuration:3e3})}catch(e){R(e instanceof Error?e.message:"Could not configure this interface.",{variant:"error",autoHideDuration:5200})}},children:"Apply interface"})]}),children:d?(0,ct.jsxs)("div",{className:"grid gap-5",children:[a?(0,ct.jsxs)("p",{className:"rounded-modiff-compact border border-modiff-border-subtle p-3 text-sm text-modiff-subtle-text","data-testid":"block-interface-scope",children:["Editing"," ",String(t.effectiveGraph.nodes.find(e=>e.nodeId===a)?.data.label||a),"'s own ports, controls, and previews. This interface is saved with the workflow and remains available after disconnecting links, collapsing, or reloading. The root Block interface is unchanged. Controls keep their existing values; shared controls continue to update their declared consumers together."]}):null,k?(0,ct.jsx)("p",{role:"alert",className:"text-modiff-red",children:k}):null,$.length?(0,ct.jsxs)("p",{className:"rounded-modiff-compact border border-modiff-warning/50 bg-modiff-warning/10 p-3 text-sm text-modiff-text",children:[$.length," connected edge",1===$.length?"":"s"," would lose a public port. Disconnect ",1===$.length?"it":"them"," before applying."]}):null,[["input","Inputs",h],["output","Outputs",b]].map(([e,t,a])=>{let o=d.boundary["input"===e?"inputs":"outputs"];return(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:t}),o.map((t,i)=>{let d=`${e}:${t.portId}`,s=("input"===e?t.mirrorBindings:void 0)?.map(e=>({nodeId:e.nodeId,fieldId:e.fieldOrPortId}))??[];return(0,ct.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2 [&>input]:col-span-2",children:[(0,ct.jsx)(Se,{"aria-label":`${e} ${t.portId} label`,value:t.label,onChange:a=>{let n=a.currentTarget.value;r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.map(e=>e.portId===t.portId?{...e,label:n}:e)}})}}),(0,ct.jsx)(Qe,{value:ft(t.binding.nodeId,t.binding.fieldOrPortId),onValueChange:n=>{let i=a.find(e=>e.key===n);i&&(r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.map(e=>e.portId===t.portId?(()=>{let t={...e};return delete t.mirrorBindings,{...t,valueType:i.valueType,binding:{nodeId:i.nodeId,fieldOrPortId:i.fieldId}}})():e)}}),u(e=>({...e,[d]:""})))},options:a.map(e=>({value:e.key,label:e.label}))}),(0,ct.jsxs)("div",{className:"flex items-center gap-1",children:[(0,ct.jsx)(ae,{label:`Move ${e} ${t.label} up`,size:"compact",disabled:0===i,onClick:()=>r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:ht(o,i,-1)}}),children:(0,ct.jsx)(n,{size:14})}),(0,ct.jsx)(ae,{label:`Move ${e} ${t.label} down`,size:"compact",disabled:i===o.length-1,onClick:()=>r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:ht(o,i,1)}}),children:(0,ct.jsx)(f,{size:14})}),(0,ct.jsx)(ae,{label:`Remove ${e} ${t.label}`,size:"compact",onClick:()=>r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.filter(e=>e.portId!==t.portId)}}),children:(0,ct.jsx)(v,{size:14})})]})]}),"input"===e?(0,ct.jsx)(gt,{entryKey:d,valueType:t.valueType,primary:{nodeId:t.binding.nodeId,fieldId:t.binding.fieldOrPortId},mirrors:s,options:h,selected:c[d]??"",onSelected:e=>u(t=>({...t,[d]:e})),onAdd:e=>{r(a=>a&&{...a,boundary:{...a.boundary,inputs:a.boundary.inputs.map(a=>a.portId===t.portId?{...a,mirrorBindings:[...a.mirrorBindings??[],{nodeId:e.nodeId,fieldOrPortId:e.fieldId}].sort(mt)}:a)}}),u(e=>({...e,[d]:""}))},onRemove:e=>r(a=>a&&{...a,boundary:{...a.boundary,inputs:a.boundary.inputs.map(a=>{if(a.portId!==t.portId)return a;let o=(a.mirrorBindings??[]).filter(t=>t.nodeId!==e.nodeId||t.fieldOrPortId!==e.fieldId),n={...a};return delete n.mirrorBindings,o.length?{...n,mirrorBindings:o}:n})}})}):null]},t.portId)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Qe,{value:s[e],onValueChange:t=>l(a=>({...a,[e]:t})),options:a.map(e=>({value:e.key,label:e.label})),placeholder:`Choose an internal ${e} field`}),(0,ct.jsx)(ae,{label:`Add public ${e}`,size:"compact",disabled:!s[e],onClick:()=>{let t=a.find(t=>t.key===s[e]);if(!t)return;let n={portId:xt(e,t,d),label:t.label,valueType:t.valueType,required:!1,binding:{nodeId:t.nodeId,fieldOrPortId:t.fieldId}};r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:[...o,n]}}),l(t=>({...t,[e]:""}))},children:(0,ct.jsx)(g,{size:14})})]})]},e)}),a?(0,ct.jsx)(et,{snapshot:t,subtreeId:a,previews:d.previews??[],onChange:e=>r(t=>t&&{...t,previews:e})}):null,(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable controls"}),d.controls.map((e,t)=>{let a=`control:${e.controlId}`,o=e.mirrorBindings??[];return(0,ct.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2 [&>input]:col-span-2",children:[(0,ct.jsx)(Se,{"aria-label":`control ${e.controlId} label`,value:e.label,onChange:t=>{let a=t.currentTarget.value;r(t=>t&&{...t,controls:t.controls.map(t=>t.controlId===e.controlId?{...t,label:a}:t)})}}),(0,ct.jsx)(Qe,{value:ft(e.binding.nodeId,e.binding.fieldId),disabled:!!e.sealed,onValueChange:t=>{let o=x.find(e=>e.key===t);o&&(r(t=>t&&{...t,controls:t.controls.map(t=>t.controlId===e.controlId?(()=>{let e={...t};return delete e.mirrorBindings,{...e,valueType:o.valueType,binding:{nodeId:o.nodeId,fieldId:o.fieldId}}})():t)}),u(e=>({...e,[a]:""})))},options:x.map(e=>({value:e.key,label:e.label}))}),(0,ct.jsxs)("div",{className:"flex items-center gap-1",children:[(0,ct.jsx)(ae,{label:`Move control ${e.label} up`,size:"compact",disabled:0===t,onClick:()=>r(e=>e&&{...e,controls:ht(e.controls,t,-1).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(n,{size:14})}),(0,ct.jsx)(ae,{label:`Move control ${e.label} down`,size:"compact",disabled:t===d.controls.length-1,onClick:()=>r(e=>e&&{...e,controls:ht(e.controls,t,1).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(f,{size:14})}),(0,ct.jsx)(ae,{label:`Remove control ${e.label}`,size:"compact",disabled:!!e.sealed,onClick:()=>r(t=>t&&{...t,controls:t.controls.filter(t=>t.controlId!==e.controlId).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(v,{size:14})})]})]}),(0,ct.jsx)(gt,{entryKey:a,valueType:e.valueType,primary:e.binding,mirrors:o,options:x,selected:c[a]??"",disabled:!!e.sealed,onSelected:e=>u(t=>({...t,[a]:e})),onAdd:t=>{r(a=>a&&{...a,controls:a.controls.map(a=>a.controlId===e.controlId?{...a,mirrorBindings:[...a.mirrorBindings??[],{nodeId:t.nodeId,fieldId:t.fieldId}].sort(mt)}:a)}),u(e=>({...e,[a]:""}))},onRemove:t=>r(a=>a&&{...a,controls:a.controls.map(a=>{if(a.controlId!==e.controlId)return a;let o=(a.mirrorBindings??[]).filter(e=>e.nodeId!==t.nodeId||e.fieldId!==t.fieldId),n={...a};return delete n.mirrorBindings,o.length?{...n,mirrorBindings:o}:n})})})]},e.controlId)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Qe,{value:s.control,onValueChange:e=>l(t=>({...t,control:e})),options:x.map(e=>({value:e.key,label:e.label})),placeholder:"Choose an internal parameter"}),(0,ct.jsx)(ae,{label:"Add editable control",size:"compact",disabled:!s.control,onClick:()=>{let e=x.find(e=>e.key===s.control);if(!e)return;let a=xt("control",e,d),o=Ze(t,e.nodeId,e.fieldId);r(t=>t&&{...t,controls:[...t.controls,{controlId:a,label:e.label,binding:{nodeId:e.nodeId,fieldId:e.fieldId},valueType:e.valueType,...void 0===o?{}:{defaultValue:o},order:t.controls.length}]}),l(e=>({...e,control:""}))},children:(0,ct.jsx)(g,{size:14})})]})]})]}):null})}var kt=e({default:()=>vt});function vt({nodeId:e,onClose:t,context:a}){let[o,n]=(0,lt.useState)(null),i=(0,lt.useRef)(!1),d=U(t=>t.nodes.find(t=>t.id===e)),r=d?.data.blockInstanceV2?e:d?.data.blockProjectionOwnerId,s=U(e=>e.nodes.find(e=>e.id===r)?.data.blockInstanceV2),l=!(!d||d.data.blockInstanceV2),c=!l&&q(s)?"node":"Block",[u,p]=(0,lt.useState)(()=>{let e=ye.getState().workflowTabs.find(e=>e.id===a.workflowTabId)?.title||"Workflow";return Be(d?.data.label||s?.definitionSnapshot.displayName||"Block",e)}),f=!u.trim()||u.trim().length>512,m=s?se(s.definitionSnapshot,s,{editWorkflow:!0,configureInterfaces:!0,createUserDefinitions:!0,updateUserDefinitions:!0}):null;async function h(o){if(!i.current){i.current=!0,n(o);try{if("workflow"!==o&&f)throw Error(`Enter a ${c} name (up to 512 characters).`);let n=await ve({nodeId:e,choice:o,context:a,displayName:u.trim()});R("workflow"===o?"Changes kept only in this workflow.":`${"new"===o?"Saved new":"Updated"} ${c}: ${n.definition?.displayName??c}`,{variant:"success",autoHideDuration:3200}),t()}catch(e){R(e instanceof Error?e.message:`Could not save the ${c} changes.`,{variant:"error",autoHideDuration:6e3})}finally{i.current=!1,n(null)}}}return(0,ct.jsx)(Ke,{onClose:()=>{i.current||t()},title:`Save ${c.toLowerCase()} changes`,testId:`save-user-block-choices-${e}`,footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{disabled:!!o,onClick:t,children:"Cancel"}),(0,ct.jsx)(He,{disabled:!!o||!m?.keepWorkflowOnly,loading:"workflow"===o,onClick:()=>{h("workflow")},children:"Keep only in this workflow"}),m?.saveAsNewUserNode?(0,ct.jsxs)(He,{tone:"primary",disabled:!!o||f,loading:"new"===o,onClick:()=>{h("new")},children:["Save as new ",c]}):null,!l&&m?.updateReusableDefinition?(0,ct.jsxs)(He,{disabled:!!o||f,loading:"update"===o,onClick:()=>{h("update")},children:["Update existing ",c]}):null]}),children:(0,ct.jsxs)("div",{className:"grid gap-2 text-sm text-modiff-subtle-text",children:[(0,ct.jsx)("p",{className:"font-semibold text-modiff-text",children:d?.data.label||"Block"}),(0,ct.jsx)(pe,{label:"node"===c?"Node name":"Block name",required:!0,error:f?"Enter a name.":void 0,children:(0,ct.jsx)(Se,{value:u,onChange:e=>p(e.currentTarget.value),maxLength:512,disabled:!!o,"aria-invalid":f,autoFocus:!0})}),(0,ct.jsx)("p",{children:"Save a reusable copy with these settings and the inputs and outputs you configured."}),(0,ct.jsx)("p",{children:l?"Only this Block and its contents are saved. Outside nodes and their connections stay in this workflow.":`Outside nodes and their connections stay in this workflow. Temporary connected sockets are not added to the saved ${c}.`})]})})}var yt=e({default:()=>wt});function wt({pendingBlock:e,setPendingBlock:t,handleConfirmBlockCreation:a}){return(0,ct.jsx)(Ie,{open:!!e,onClose:()=>t(null),title:"Create block",testId:"create-user-block-dialog",panelClassName:"max-w-xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:()=>t(null),children:"Cancel"}),(0,ct.jsx)(He,{tone:"primary",disabled:!e?.name.trim(),onClick:()=>{a()},"data-testid":"confirm-create-user-block",children:"Create block"})]}),children:e?(0,ct.jsxs)("div",{className:"grid gap-4",children:[(0,ct.jsx)(pe,{label:"Name",required:!0,children:(0,ct.jsx)(Se,{autoFocus:!0,value:e.name,onChange:e=>{let a=e.currentTarget.value;t(e=>e&&{...e,name:a})}})}),e.result.block.inputs.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Inputs"}),e.result.block.inputs.map(a=>(0,ct.jsx)(pe,{label:a.label,children:(0,ct.jsx)(Se,{value:e.inputLabels[a.id]??a.label,onChange:e=>{let o=e.currentTarget.value;t(e=>e&&{...e,inputLabels:{...e.inputLabels,[a.id]:o}})}})},a.id))]}):null,e.result.block.outputs.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Outputs"}),e.result.block.outputs.map(a=>(0,ct.jsx)(pe,{label:a.label,children:(0,ct.jsx)(Se,{value:e.outputLabels[a.id]??a.label,onChange:e=>{let o=e.currentTarget.value;t(e=>e&&{...e,outputLabels:{...e.outputLabels,[a.id]:o}})}})},a.id))]}):null,e.result.block.exposedParams.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable parameters"}),e.result.block.exposedParams.map(a=>(0,ct.jsx)(de,{label:a.label,checked:e.exposedParamIds.has(a.id),onCheckedChange:e=>t(t=>{if(!t)return t;let o=new Set(t.exposedParamIds);return e?o.add(a.id):o.delete(a.id),{...t,exposedParamIds:o}})},a.id))]}):null]}):null})}var jt=e({buildGraphFixPlan:()=>Wt,buildGraphFixPreview:()=>Kt,graphFixHighlightedSockets:()=>Yt,graphNodeIsOutputLike:()=>Ht,graphSocketTypesAreCompatible:()=>_t}),$t=new Set(["image","video","audio"]),Nt=new Set(["bool","float","int","number","str","string","text"]);function Ct(e,t){return e.map(e=>{if(B(e))return e;let a=t[function(e){return`${e.data.module}.${e.data.action}`}(e)];if(!a)return e;let o=Object.fromEntries(Object.entries(e.data.params).map(([e,t])=>{let o=a.params[e];return o?[e,{...t,type:o.type??t.type,required:o.required??t.required}]:[e,t]}));return{...e,data:{...e.data,params:o}}})}function St(e){let t=O(e?.type);return t.length?t:["any"]}function _t(e,t){return J(e?.type,t?.type)}function Pt(e){return Object.entries(_(e)).filter(([,e])=>"input"===e.display||e.isInput)}function Tt(e){return Object.entries(_(e)).filter(([,e])=>"output"===e.display)}function Ot(e){return null!=e&&("string"==typeof e?e.trim().length>0:Array.isArray(e)?e.length>0:"object"!=typeof e||("value"in e?Ot(e.value):Object.keys(e).length>0))}function Mt(e,t,a=!1){if(t.hidden||t.disabled||t.spawn||Ot(t.value??t.default)||!1===t.required)return!1;if(!0===t.required)return!0;if(a)return!1;let o=`${e} ${t.label??""} ${t.description??""}`.toLowerCase();return!/\boptional\b|\bif provided\b|\bwhen supplied\b/.test(o)}function Et(e){return e.filter(e=>"group"!==e.data.type&&"loop"!==e.data.type&&!e.data.uiState?.disabled&&!!e.data.module&&!!e.data.action)}function Ht(e){let t=`${e.data.module} ${e.data.action} ${e.data.label} ${e.data.category}`.toLowerCase();return/\b(preview|export|save|display|output|gallery)\b|viewer\b/.test(t)}function Rt(e){if(!B(e)||!e.data.blockInstanceV2)return!1;let t=e.data.blockInstanceV2.effectiveGraph,a=new Set(t.nodes.filter(({data:e})=>!e.uiState?.disabled).map(({nodeId:e})=>e));return t.nodes.some(e=>a.has(e.nodeId)&&Ht({data:e.data})&&t.edges.some(t=>t.targetNodeId===e.nodeId&&a.has(t.sourceNodeId)))}function Bt(e,t){return V(e,t)?.label||t.replace(/_/g," ")}function At(e){let t=e.split(".");return t[t.length-1]||e}function Vt(e,t,a){let o=new Map;e.forEach(e=>o.set(e.source,[...o.get(e.source)??[],e.target]));let n=[t],i=new Set;for(;n.length;){let e=n.shift();if(e&&!i.has(e)){if(e===a)return!0;i.add(e),n.push(...o.get(e)??[])}}return!1}function zt(...e){return e.filter(Boolean).join(":").replace(/[^a-z0-9:_-]+/gi,"-").toLowerCase()}function Lt(e){let t=St(e);return t.some(e=>$t.has(e))?80:t.some(e=>e.includes("pipeline"))?70:t.some(e=>Nt.has(e))?10:t.includes("any")?0:40}function Dt(e,t){let a=St(e),o=St(t);return a.some(e=>"any"!==e&&o.includes(e))?100:a.includes("any")||o.includes("any")?5:0}function qt(e,t){let a=0;return e.data.module===t.data.module&&(a+=24),e.data.category===t.data.category&&(a+=12),a}function Ft(e,t,a){return"output"===e&&t?{x:t.position.x+340,y:t.position.y}:"producer"===e&&a?{x:a.position.x-340,y:a.position.y}:t&&a?{x:Math.round((t.position.x+a.position.x)/2),y:Math.round((t.position.y+a.position.y)/2+140)}:{x:120,y:100}}function Gt(e,t){return(e.data.blockProjectionOwnerId??null)===(t.data.blockProjectionOwnerId??null)}function Wt(e){e={...e,nodes:Ct(e.nodes,e.registry)};let t=[],a=new Map(e.nodes.map(e=>[e.id,e])),o=new Set;for(let a of e.nodes){if(!B(a)||!a.data.blockInstanceV2)continue;for(let o of ee(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-loop",a.id,o.nodeId,o.fieldId),d=Ce(a.data.blockInstanceV2,o.nodeId,e.modularBlockDefinitions??[]);t.push({id:i,kind:"block_structure",title:"Invalid loop connection",description:o.message,targetNodeId:n,targetHandle:o.fieldId,candidates:d?[{id:zt(i,"restore-one-edge"),issueId:i,title:"Reconnect the missing Loop Members link",description:`Restore only ${d.sourceNodeId} → ${d.targetNodeId}; keep all other edits.`,confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_loop",rootNodeId:a.id,targetNodeId:o.nodeId,graphHash:a.data.blockInstanceV2.effectiveGraph.graphHash}]}]:[]})}for(let o of De(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-state-input",a.id,o.nodeId);t.push({id:i,kind:"missing_input",title:"Missing upstream inputs",description:o.message,targetNodeId:n,candidates:o.reconnectFrom.map(e=>({id:zt(i,e),issueId:i,title:`Reconnect Pipeline State from ${a.data.blockInstanceV2.effectiveGraph.nodes.find(t=>t.nodeId===e)?.data.label??e}`,description:"Reconnect one edge; keep all other edits.",confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_state",rootNodeId:a.id,sourceNodeId:e,targetNodeId:o.nodeId,graphHash:a.data.blockInstanceV2.effectiveGraph.graphHash}]}))})}let o=he(a.data.blockInstanceV2,e.modularBlockDefinitions??[]).filter(e=>e.canRepair);if(o.length){let e=zt("block-derived-control",a.id),n=[...new Set(o.map(({fieldId:e})=>e))].join(", "),i=`Repair ${o.length} bindings (${n}) to inherit derived values. Preserve prompts, requested values, layout and other wires.`;t.push({id:e,kind:"block_derived_control",title:"A mirrored control overwrites an upstream-derived value",description:i,targetNodeId:a.id,candidates:[{id:zt(e,"inherit-derived-state"),issueId:e,title:"Use the upstream-derived values",description:i,confidence:"choice",targetNodeId:a.id,operations:o.map(({nodeId:e,fieldId:t})=>({kind:"repair_block_derived_control",rootNodeId:a.id,sourceNodeId:e,fieldId:t}))}]})}for(let o of Ue(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){if(!o.canRepair)continue;let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-seed",a.id,o.nodeId);t.push({id:i,kind:"block_seed",title:"A saved seed is attached to a step that does not consume it",description:o.reason,targetNodeId:n,candidates:[{id:zt(i,"move-to-generator"),issueId:i,title:"Connect seed to its Generator consumer",description:o.reason,confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_seed",rootNodeId:a.id,sourceNodeId:o.nodeId}]}]})}}e.nodes.forEach(a=>{let o=function(e){if(!B(e))return null;try{return oe([e],[]),null}catch(e){return e instanceof Error?e.message:String(e)}}(a);if(!o)return;let n=function(e,t,a){return a.filter(({data:t})=>t.blockProjectionOwnerId===e.id&&"string"==typeof t.blockProjectionNodeId).sort((e,t)=>String(t.data.blockProjectionNodeId).length-String(e.data.blockProjectionNodeId).length).find(({id:e,data:a})=>{let o=String(a.blockProjectionNodeId);return t.includes(e)||t.includes(`"${o}"`)||t.includes(`'${o}'`)||t.includes(` ${o}:`)||t.includes(` ${o}.`)||t.endsWith(` ${o}`)})?.id??e.id}(a,o,e.nodes),i=zt("block-structure",a.id,o);t.push({id:i,kind:"block_structure",title:`${a.data.label||"Block"} has invalid internal structure`,description:o,targetNodeId:n,candidates:[{id:zt(i,"restore-reviewed"),issueId:i,title:"Restore reviewed internal structure",description:"Restore the registered nodes and links for this workflow instance. Compatible custom additions are retained; incompatible structural edits are removed.",confidence:"choice",targetNodeId:n,operations:[{kind:"restore_block_structure",rootNodeId:a.id}]}]})}),e.edges.forEach(n=>{let i=a.get(n.source),d=a.get(n.target),r=n.sourceHandle??"",s=n.targetHandle??"",l=V(i,r),c=V(d,s);if(!(i&&d&&r&&s&&l&&c)){let e=zt("broken-link",n.id);return void t.push({id:e,kind:"broken_link",title:"Remove a broken connection",description:"One connection points to a node or socket that no longer exists.",targetNodeId:d?.id,targetHandle:s||void 0,candidates:[{id:zt(e,"remove"),issueId:e,title:"Remove broken link",description:"Delete only the invalid connection.",confidence:"safe",targetNodeId:d?.id,targetHandle:s||void 0,operations:[{kind:"remove_edges",edgeIds:[n.id]}]}]})}if(!_t(l,c)||!we(i.data,r,d.data,s)){let a=zt("type-mismatch",n.id),o=function(e,t,a,o,n,i,d,r,s){return a.data.blockProjectionOwnerId||i.data.blockProjectionOwnerId?[]:Object.entries(t.registry).flatMap(([e,t])=>{if("group"===t.type||"loop"===t.type)return[];let s=Pt({data:t}).filter(([e,i])=>_t(n,i)&&we(a.data,o,t,e)).map(([e,t],a)=>({handle:e,param:t,order:a,score:Dt(n,t)})).sort((e,t)=>t.score-e.score).slice(0,3);if(!s.length)return[];let l=Tt({data:t}).filter(([e,a])=>_t(a,r)&&we(t,e,i.data,d)).map(([e,t],a)=>({handle:e,param:t,order:a,score:Dt(t,r)})).sort((e,t)=>t.score-e.score).slice(0,3);return s.sort((e,t)=>e.order-t.order),l.sort((e,t)=>e.order-t.order),s.flatMap(({handle:a,param:o})=>l.map(({handle:n,param:i})=>({key:e,data:t,bridgeInput:a,bridgeInputParam:o,bridgeOutput:n,bridgeOutputParam:i})))}).map(({key:t,data:l,bridgeInput:c,bridgeInputParam:u,bridgeOutput:p,bridgeOutputParam:f})=>{let m=`@${zt(e,t,c,p)}`;return{score:Dt(n,u)+Dt(f,r)+qt({data:l},i),candidate:{id:zt(e,"bridge",t,c,p),issueId:e,title:`Insert ${l.label||At(t)}`,description:`Replace the incompatible link with a typed conversion through ${l.label||"this node"}.`,confidence:"choice",targetNodeId:i.id,targetHandle:d,operations:[{kind:"remove_edges",edgeIds:[s]},{kind:"add_node",ref:m,nodeKey:t,position:Ft("bridge",a,i)},{kind:"connect",source:{nodeId:a.id,handle:o},target:{nodeId:m,handle:c}},{kind:"connect",source:{nodeId:m,handle:p},target:{nodeId:i.id,handle:d}}]}}}).filter(e=>e.score>30).sort((e,t)=>t.score-e.score).slice(0,3).map(e=>e.candidate)}(a,e,i,r,l,d,s,c,n.id);return o.push({id:zt(a,"remove"),issueId:a,title:"Remove incompatible link",description:"Disconnect the mismatched sockets and leave the input highlighted for another fix.",confidence:"safe",targetNodeId:d.id,targetHandle:s,operations:[{kind:"remove_edges",edgeIds:[n.id]}]}),void t.push({id:a,kind:"type_mismatch",title:`${Bt(i,r)} cannot connect to ${Bt(d,s)}`,description:_t(l,c)?"The selected model or component does not satisfy the receiving socket’s declared capabilities.":`The sockets use incompatible types: ${St(l).join(" or ")} and ${St(c).join(" or ")}.`,targetNodeId:d.id,targetHandle:s,candidates:o.slice(0,3)})}o.add(`${d.id}:${s}`)});let n=Et(e.nodes),i=n.filter(Ht),d=i.filter(t=>e.edges.some(e=>e.target===t.id&&a.has(e.source)));if(n.length>0&&0===d.length&&!n.some(Rt)){let a="missing-output",o=function(e,t,a){let o=Et(t.nodes),n=new Set(t.edges.map(e=>`${e.source}:${e.sourceHandle??""}`)),i=o.flatMap(e=>Tt(e).map(([t,a])=>({source:e,sourceHandle:t,sourceParam:a}))).filter(({source:e,sourceHandle:t})=>!n.has(`${e.id}:${t}`)).sort((e,t)=>Lt(t.sourceParam)-Lt(e.sourceParam)),d=a.flatMap(a=>Pt(a).flatMap(([o,n])=>i.filter(({source:e,sourceHandle:i,sourceParam:d})=>e.id!==a.id&&Gt(e,a)&&_t(d,n)&&we(e.data,i,a.data,o)&&!Vt(t.edges,a.id,e.id)).map(({source:t,sourceHandle:i,sourceParam:d})=>({score:Dt(d,n)+Lt(d),candidate:{id:zt(e,"connect-output",t.id,i,a.id,o),issueId:e,title:`Connect ${t.data.label||t.data.action} to ${a.data.label||a.data.action}`,description:`Send ${Bt(t,i)} to the existing output node.`,confidence:"safe",targetNodeId:a.id,targetHandle:o,operations:[{kind:"connect",source:{nodeId:t.id,handle:i},target:{nodeId:a.id,handle:o}}]}}))));return d.length?d.sort((e,t)=>t.score-e.score).slice(0,3).map(e=>e.candidate):Object.entries(t.registry).filter(([,e])=>Ht({data:e})).flatMap(([t,a])=>Pt({data:a}).flatMap(([o,n])=>i.filter(({source:e,sourceHandle:t,sourceParam:i})=>!e.data.blockProjectionOwnerId&&_t(i,n)&&we(e.data,t,a,o)).map(({source:i,sourceHandle:d,sourceParam:r})=>{let s=`@${zt(e,t,i.id)}`;return{score:Dt(r,n)+Lt(r),candidate:{id:zt(e,"add-output",t,i.id,d,o),issueId:e,title:`Add ${a.label||At(t)}`,description:`Create a visible output for ${Bt(i,d)}.`,confidence:"choice",targetNodeId:i.id,targetHandle:d,operations:[{kind:"add_node",ref:s,nodeKey:t,position:Ft("output",i,void 0)},{kind:"connect",source:{nodeId:i.id,handle:d},target:{nodeId:s,handle:o}}]}}}))).sort((e,t)=>t.score-e.score||e.candidate.title.localeCompare(t.candidate.title)).slice(0,3).map(e=>e.candidate)}(a,e,i);o.length&&t.push({id:a,kind:"missing_output",title:i.length?"Connect the graph output":"Add a graph output",description:i.length?"An output node exists, but no generated result reaches it.":"The graph needs a Preview, Save, or Export node to produce a usable result.",targetNodeId:i[0]?.id,candidates:o})}let r=new Set(i.map(e=>e.id));n.forEach(a=>{Pt(a).forEach(([n,i])=>{if(function(e,t){let a=e.data.blockInstanceV2;if(!B(e)||!a)return!1;let o=a.effectiveInterface.boundary.inputs.find(e=>e.portId===t);if(!o)return!1;let n=[o.binding,...o.mirrorBindings??[]];return a.effectiveInterface.controls.some(e=>[e.binding,...e.mirrorBindings??[]].some(e=>n.some(t=>t.nodeId===e.nodeId&&t.fieldOrPortId===e.fieldId)))}(a,n)||!Mt(n,i,!!a.data.skipParamsCheck)||o.has(`${a.id}:${n}`)||r.has(a.id)&&0===d.length)return;let s=zt("missing-input",a.id,n),l=function(e,t,a,o,n){let i=function(e,t,a,o,n){return Et(t.nodes).flatMap(e=>Tt(e).map(([t,a])=>({source:e,sourceHandle:t,sourceParam:a}))).filter(({source:e,sourceHandle:i,sourceParam:d})=>e.id!==a.id&&Gt(e,a)&&_t(d,n)&&we(e.data,i,a.data,o)&&!Vt(t.edges,a.id,e.id)).map(({source:t,sourceHandle:i,sourceParam:d})=>({score:Dt(d,n)+qt(t,a)-Math.min(40,Math.hypot(t.position.x-a.position.x,t.position.y-a.position.y)/50),candidate:{id:zt(e,"connect",t.id,i),issueId:e,title:`Connect ${t.data.label||t.data.action}`,description:`Use its ${Bt(t,i)} output for ${Bt(a,o)}.`,confidence:100===Dt(d,n)?"safe":"choice",targetNodeId:a.id,targetHandle:o,operations:[{kind:"connect",source:{nodeId:t.id,handle:i},target:{nodeId:a.id,handle:o}}]}})).sort((e,t)=>t.score-e.score).map(e=>e.candidate)}(e,t,a,o,n),d=function(e,t,a,o,n){return a.data.blockProjectionOwnerId?[]:Object.entries(t.registry).flatMap(([e,t])=>Tt({data:t}).map(([a,o])=>({key:e,data:t,sourceHandle:a,sourceParam:o}))).filter(({data:e,sourceHandle:t,sourceParam:i})=>!("group"===e.type||"loop"===e.type||!_t(i,n)||!we(e,t,a.data,o)||Ht({data:e}))).map(({key:t,data:i,sourceHandle:d,sourceParam:r})=>{let s=`${t} ${i.label} ${i.category}`.toLowerCase(),l=St(n),c=l.some(e=>e.includes("pipeline"))&&/load|pipeline/.test(s)?50:0,u=l.some(e=>$t.has(e))&&/load|source|import/.test(s)?35:0,p=St(r).includes("any")?45:0,f=`@${zt(e,t)}`;return{score:Dt(r,n)+qt({data:i},a)+c+u-p,candidate:{id:zt(e,"add",t,d),issueId:e,title:`Add ${i.label||At(t)}`,description:`Add this compatible source and connect it to ${Bt(a,o)}.`,confidence:"choice",targetNodeId:a.id,targetHandle:o,operations:[{kind:"add_node",ref:f,nodeKey:t,position:Ft("producer",void 0,a)},{kind:"connect",source:{nodeId:f,handle:d},target:{nodeId:a.id,handle:o}}]}}}).filter(e=>e.score>15).sort((e,t)=>t.score-e.score||e.candidate.title.localeCompare(t.candidate.title)).map(e=>e.candidate)}(e,t,a,o,n);return[...i,...d].slice(0,3)}(s,e,a,n,i);l.length&&t.push({id:s,kind:"missing_input",title:`${a.data.label||a.data.action} needs ${Bt(a,n)}`,description:"Connect an existing compatible value or add a matching source node.",targetNodeId:a.id,targetHandle:n,candidates:l})})});let s=new Set;(e.readinessIssues??[]).forEach(e=>{if("block_media_input_missing"===e.code||"operation_media_input_missing"===e.code){let a=zt(e.code,e.id);return void t.push({id:a,kind:"missing_media",title:e.message,description:e.details??e.message,targetNodeId:e.nodeId,targetHandle:e.fieldId,candidates:[{id:zt(a,"inspect"),issueId:a,title:"Open required input",description:"Select the affected node and its controls. Choose the file yourself; no mask, prompt or connection is changed automatically.",confidence:"safe",targetNodeId:e.nodeId,targetHandle:e.fieldId,operations:[{kind:"external",action:"inspect_node",nodeId:e.nodeId}]}]})}if("modular_component_requirement"!==e.code&&"modular_runtime_failure"!==e.code)if(["environment","package","backend","hardware_fit"].includes(e.category)&&"open_setup"===e.action){let a=`${e.category}:${e.message}`;if(s.has(a))return;s.add(a);let o=zt(e.category,e.message),n="package"===e.category?"Repair backend packages":"backend"===e.category?"Reconnect or update the backend":"hardware_fit"===e.category?"Review hardware compatibility":"Repair the runtime environment";t.push({id:o,kind:"environment",title:n,description:e.message,candidates:[{id:zt(o,"setup"),issueId:o,title:"Open Setup",description:e.details||"Review the detected runtime mismatch and its exact repair command.",confidence:"safe",operations:[{kind:"external",action:"open_setup"}]}]})}else if("model"!==e.category&&"model_integrity"!==e.category||!e.repoId&&!e.modelPath){if("asset"===e.category&&"select_image"===e.action){let a=`missing_media:${e.nodeId??""}:${e.message}`;if(s.has(a))return;s.add(a);let o=zt("missing-media",e.nodeId,e.message);t.push({id:o,kind:"missing_media",title:"Choose the required media",description:e.message,targetNodeId:e.nodeId,candidates:[{id:zt(o,"assets"),issueId:o,title:"Open Gallery",description:"Choose an imported image, video, or audio file without changing the graph automatically.",confidence:"safe",targetNodeId:e.nodeId,operations:[{kind:"external",action:"open_assets",nodeId:e.nodeId}]}]})}}else{let a=`missing_model:${e.nodeId??""}:${e.repoId??e.modelPath}`;if(s.has(a))return;s.add(a);let o=zt("missing-model",e.nodeId,e.repoId,e.modelPath);t.push({id:o,kind:"missing_model",title:"Choose or install the required model",description:e.message,targetNodeId:e.nodeId,candidates:[{id:zt(o,"models"),issueId:o,title:"Open Models",description:"Review compatible installed models or explicitly install the required model.",confidence:"safe",targetNodeId:e.nodeId,operations:[{kind:"external",action:"open_model_manager",nodeId:e.nodeId,repoId:e.repoId}]}]})}else t.push({id:zt(e.code,e.nodeId??"",e.message),kind:"block_structure",title:"modular_runtime_failure"===e.code?"Review the failed Modular block":"Review component compatibility",description:`${e.message} ${e.details??""}`,targetNodeId:e.nodeId,candidates:[]})});let l=t.filter(e=>e.candidates.length>0);return{issues:t,candidateCount:l.reduce((e,t)=>e+t.candidates.length,0),canFix:l.length>0}}function Ut(e,t){return t.get(e)??e}function Kt(e,t){if(!t)return{nodes:[],edges:[]};let a=new Map,o=[];t.operations.forEach(n=>{if("add_node"!==n.kind)return;let i=Me(n.nodeKey,e.registry,n.position);if(!i)return;let d=`graph-fix-preview-${t.id}-${a.size}`,r={...i,id:d,className:"modiff-graph-fix-ghost",draggable:!1,selectable:!1,deletable:!1};r.data.label=`${r.data.label} preview`,a.set(n.ref,d),o.push(r)});let n=[...e.nodes,...o];return{nodes:o,edges:t.operations.flatMap((e,o)=>{if("connect"!==e.kind)return[];let i=Ut(e.source.nodeId,a),d=Ut(e.target.nodeId,a);return n.some(e=>e.id===i)&&n.some(e=>e.id===d)?[{id:`graph-fix-preview-edge-${t.id}-${o}`,source:i,sourceHandle:e.source.handle,target:d,targetHandle:e.target.handle,type:"default",selectable:!1,focusable:!1,className:"modiff-graph-fix-ghost"}]:[]})}}function Yt(e){return e?e.operations.flatMap(e=>"connect"===e.kind?[e.source,e.target]:[]):[]}var Xt=e({default:()=>Qt});function Jt(e,t,a){return e.issues.find(e=>e.id===t)?.candidates.find(e=>e.id===a)}function Qt(){let e=w(e=>e.dialogOpen),t=w(e=>e.closeDialog),a=w(e=>e.setPreviewCandidate),n=w(e=>e.setIssueTargets),{nodes:d,edges:r}=U(W(e=>({nodes:e.nodes,edges:e.edges}))),s=L(e=>e.nodesRegistry),l=K(e=>e.library?.blockDefinitions);(0,lt.useEffect)(()=>{e&&!K.getState().loaded&&K.getState().fetchLibrary()},[e]);let c=z(e=>e.edgeType),u=z(e=>e.setLeftPanelOpen),p=z(e=>e.setLeftPanelTabIndex),f=z(e=>e.setRightPanelOpen),m=z(e=>e.setRightPanelTab),h=z(e=>e.setModelManagerOpener),g=ye(e=>e.saveActiveWorkflowTab),b=ye(e=>e.graphBinding),x=T(e=>e.sid),I=T(e=>e.isConnected),k=qe({sid:x,isConnected:I,includeStudio:!!b}),v=(0,lt.useMemo)(()=>Wt({nodes:d,edges:r,registry:s,modularBlockDefinitions:l,readinessIssues:k.issues}),[r,d,k.issues,s,l]),y=v.issues.map(e=>`${e.id}:${e.candidates.map(e=>e.id).join(",")}`).join("|"),j=(0,lt.useRef)(v);j.current=v;let[$,N]=(0,lt.useState)({}),[C,S]=(0,lt.useState)(!1);(0,lt.useEffect)(()=>{if(!e)return;let t=j.current,o=function(e){let t=e.issues.map(e=>({issue:e,candidate:e.candidates.find(e=>"safe"===e.confidence&&e.operations.length>0&&e.operations.every(e=>"external"===e.kind))})).find(e=>e.candidate);return Object.fromEntries(e.issues.map(e=>[e.id,t?e.id===t.issue.id?t.candidate?.id??"":"":e.candidates.find(e=>"safe"===e.confidence)?.id??""]))}(t);N(o);let i=t.issues[0],d=i?Jt(t,i.id,o[i.id]??""):null;a(d??null),n(t.issues.flatMap(e=>e.targetNodeId?[{nodeId:e.targetNodeId,handle:e.targetHandle}]:[]))},[e,y,n,a]);let _=(e,t={})=>{if("inspect_node"===e){let e=z.getState();f(!0),m("studio");let a=U.getState();if(t.nodeId&&a.nodes.some(e=>e.id===t.nodeId)){a.onNodesChange(a.nodes.map(e=>({id:e.id,type:"select",selected:e.id===t.nodeId})));let o=ye.getState().activeWorkflowTabId;o&&e.setWorkflowFocusRequest({workflowTabId:o,nodeId:t.nodeId,requestId:Date.now(),requestedAt:Date.now()})}return}if("open_setup"===e)return f(!0),void m("setup");u(!0),"open_assets"!==e?(p(3),h({nodeId:t.nodeId??null,fieldKey:null,focus:t.repoId?{repo:t.repoId,source:"graph"}:void 0})):p(2)},P=v.issues.map(e=>Jt(v,e.id,$[e.id]??"")).filter(e=>!!e),O=P.length>0&&P.every(e=>e.operations.every(e=>"external"===e.kind)),M=v.issues.filter(e=>!!$[e.id]).length,E=0===v.candidateCount;return(0,ct.jsx)(Ie,{open:e,onClose:t,title:"Fix graph",description:E?"Review the issue and correct the named node or connection.":"Review proposed repairs before applying them. Graph changes can be undone.",testId:"graph-fix-dialog",panelClassName:"max-w-2xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:t,children:"Cancel"}),!E&&(0,ct.jsx)(He,{tone:"primary",icon:(0,ct.jsx)(i,{size:15}),disabled:0===M||C,loading:C,onClick:()=>{let e=P;if(e.length&&!C){S(!0);try{let a=e.filter(e=>e.operations.some(e=>"external"!==e.kind)),o=v.issues.filter(e=>a.some(t=>t.issueId===e.id)),n=U.getState(),i=Te({nodes:n.nodes,edges:n.edges,registry:s,modularBlockDefinitions:l},e,c),d=a.length>0;d&&(U.getState().replaceGraph({nodes:i.nodes,edges:i.edges},{historyLabel:"Fix graph",clearRemovedCache:!1}),g(!0));let r=xe({sid:x,isConnected:I,includeStudio:!!b,showDialog:!1}),u=U.getState(),p=Wt({nodes:u.nodes,edges:u.edges,registry:s,modularBlockDefinitions:l,readinessIssues:r.issues}),f=d?o.filter(e=>p.issues.some(t=>function(e,t){return e.kind===t.kind&&(e.targetNodeId??null)===(t.targetNodeId??null)&&(e.targetHandle??null)===(t.targetHandle??null)}(e,t))):[];if(d&&f.length>0)throw Error(`The proposed change did not clear ${1===f.length?"the selected issue":`${f.length} selected issues`}. Review the updated graph before retrying.`);if(t(),i.externalActions.forEach(e=>_(e.action,{nodeId:e.nodeId,repoId:e.repoId})),d){let e=r.blocking.length;R(`${1===a.length?"Fix":`${a.length} fixes`} applied and verified.${e>0?` ${e} other blocking ${1===e?"issue remains":"issues remain"}.`:""} Undo is available.`,{variant:"success",autoHideDuration:3600})}}catch(e){R(e instanceof Error?e.message:"The graph changed before the fix could be applied.",{variant:"error",autoHideDuration:4200})}finally{S(!1)}}},"data-testid":"graph-fix-apply",children:O?P[0]?.title:"Apply "+(1===M?"fix":`${M} fixes`)})]}),children:0===v.issues.length?(0,ct.jsx)("div",{className:"rounded-modiff-panel border border-modiff-border bg-modiff-panel p-4 text-sm text-modiff-subtle-text",children:"No deterministic graph repair is currently available."}):(0,ct.jsxs)("div",{className:"grid gap-4",children:[(0,ct.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:E?"No automatic repair is available. Your graph has not been changed.":O?"Review the detected issue and continue to the exact place where it can be resolved.":"Review the proposed connections. MoDiff will apply graph changes together as one undoable action."}),v.issues.map((e,t)=>(0,ct.jsxs)("section",{className:"rounded-modiff-panel border border-modiff-border bg-modiff-panel p-3","data-testid":`graph-fix-issue-${t}`,children:[(0,ct.jsxs)("div",{className:"flex items-start gap-2",children:[(0,ct.jsx)(o,{size:16,className:"mt-0.5 shrink-0 text-modiff-red"}),(0,ct.jsxs)("div",{className:"min-w-0",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:e.title}),(0,ct.jsx)("p",{className:"mt-0.5 text-xs text-modiff-subtle-text",children:e.description})]}),$[e.id]&&(0,ct.jsx)(He,{className:"ml-auto shrink-0","aria-label":`Skip ${e.title}`,onClick:()=>{N(t=>({...t,[e.id]:""})),a(null)},children:"Skip"})]}),0===e.candidates.length?(0,ct.jsx)("p",{className:"mt-3 text-xs text-modiff-subtle-text",children:"Manual correction required. No automatic graph change will be applied for this issue."}):(0,ct.jsx)(Z,{className:"mt-3","aria-label":e.title,value:$[e.id]??"",options:e.candidates.map(e=>({value:e.id,label:e.title,description:e.description,meta:"safe"===e.confidence?"Direct":"Choice"})),onOptionPreview:t=>a(e.candidates.find(e=>e.id===t)??null),onValueChange:t=>{N(a=>({...a,[e.id]:t})),a(e.candidates.find(e=>e.id===t)??null)}})]},e.id))]})})}var Zt=(0,lt.lazy)(()=>$(()=>import(`./OperationOwnerControls.js?v=cc046c26d6fe7aa4`),[])),ea=(0,lt.memo)(e=>{let t=U(t=>t.nodes.find(t=>t.id===e.id)),a=(0,lt.useRef)(null),o=(0,lt.useRef)(null),n=(0,lt.useRef)(null),i=U(t=>Oe(t,e.id)),r=e.data.userBlockSnapshot,s=U(e=>e.toggleUserBlockExpanded),c=U(e=>e.setParamWithHistory),u=U(e=>e.replaceNodeParams),p=U(e=>e.setNodeSize),f=U(e=>e.beginHistoryTransaction),m=U(e=>e.commitHistoryTransaction),g=U(e=>e.setNodeUiState),v=U(e=>e.configureUserBlock),w=ye(e=>e.workflowTabs.find(t=>t.id===e.activeWorkflowTabId)?.title||"Workflow"),j=U(e=>e.fitUserBlockToChildren),$=U(t=>t.nodes.filter(t=>t.data.userBlockInstanceId===e.id).map(e=>`${e.id}:${e.position.x}:${e.position.y}:${e.measured?.width??e.width??0}:${e.measured?.height??e.height??0}`).sort().join("|")),N=h(),C=x(),S=E(e.id,a),_=(0,lt.useMemo)(()=>r?ze(r,{x:0,y:0},e.id):null,[r,e.id]),T=_?.data.userBlockSnapshot??r,O=(0,lt.useMemo)(()=>{let t=_?.data.params;if(!t)return e.data.params;let a={...t};return Object.entries(e.data.params).forEach(([e,o])=>{let n=t[e];a[e]=n?{...n,...o,fieldOptions:{...n.fieldOptions??{},...o.fieldOptions??{}}}:o}),a},[_?.data.params,e.data.params]),M=(0,lt.useMemo)(()=>T?me(T,O):[],[T,O]),B=(0,lt.useMemo)(()=>T?be(T):[],[T]),[A,V]=(0,lt.useState)(null),[z,L]=(0,lt.useState)(!1),[D,q]=(0,lt.useState)(!1),[G,W]=(0,lt.useState)(!1),[Y,X]=(0,lt.useState)(null),[J,Z]=(0,lt.useState)(null),[ee,te]=(0,lt.useState)(null),oe=K(e=>e.library),ne=(0,lt.useMemo)(()=>i?ue(U.getState(),e.id):{valid:!0,issues:[],insertionSuggestions:[]},[U(t=>{if(!i)return"";let a=new Set(t.nodes.filter(t=>t.data.userBlockInstanceId===e.id).map(e=>e.id));return`${t.nodes.filter(e=>a.has(e.id)).map(e=>JSON.stringify([e.id,e.parentId,e.data.type,Object.entries(e.data.params??{}).map(([e,t])=>[e,t.type,t.display,t.isInput,t.hidden,"pipeline_class"===e||"workflow_id"===e?t.value??t.default:void 0])])).sort().join("|")}\n${t.edges.filter(e=>a.has(e.source)||a.has(e.target)).map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}:${e.target}:${e.targetHandle??""}`).sort().join("|")}`}),i,e.id]),ie=U(e=>e.insertNodeInUserBlock),re=(0,lt.useMemo)(()=>We(T,oe),[T,oe]),se=(0,lt.useCallback)((t,a,o)=>c(e.id,t,a,o),[e.id,c]),ce=(0,lt.useCallback)(()=>{s(e.id),ye.getState().saveActiveWorkflowTab(!0)},[e.id,s]),he=(0,lt.useCallback)(async t=>{if(!G){W(!0);try{let a=await tt({instanceId:e.id,choice:t,workflowTitle:w});L(!1),R("update"===t?"Reusable Block updated. Existing workflow instances keep their embedded snapshots.":"new"===t?`Saved as new Block: ${a.name}`:"Changes kept only in this workflow.",{variant:"success",autoHideDuration:3200})}catch(e){R(e instanceof Error?e.message:"Could not save the Block changes.",{variant:"error",autoHideDuration:4200})}finally{W(!1)}}},[e.id,G,w]),xe=(0,lt.useCallback)(()=>{let e=o.current?.offsetHeight??44,t=n.current?.offsetHeight??0;return Math.ceil(e+t+96+4)},[]),ke=(0,lt.useCallback)(()=>{if(i)return;let t=xe(),a=U.getState().nodes.find(t=>t.id===e.id);!a||Oe(U.getState(),e.id)||(a.height??0)>=t||(U.setState(a=>({nodes:a.nodes.map(a=>a.id===e.id?{...a,height:t,data:{...a.data,uiState:{...a.data.uiState,blockCollapsedHeight:t}}}:a)})),N(e.id),S())},[xe,i,e.id,S,N]);(0,lt.useEffect)(()=>{N(e.id)},[i,e.id,N]),(0,lt.useLayoutEffect)(()=>{if(i||(ke(),typeof ResizeObserver>"u"))return;let e=null,t=!0,a=new ResizeObserver(()=>{!t||null!==e||(e=window.requestAnimationFrame(()=>{e=null,t&&ke()}))});return o.current&&a.observe(o.current),n.current&&a.observe(n.current),()=>{t=!1,a.disconnect(),null!==e&&window.cancelAnimationFrame(e)}},[i,ke]),(0,lt.useEffect)(()=>{if(!i||!$)return;let t=window.requestAnimationFrame(()=>{j(e.id),S()});return()=>window.cancelAnimationFrame(t)},[$,i,j,e.id,S]),(0,lt.useEffect)(()=>{y(e.data.params,O)||u(e.id,O)},[O,e.data.params,e.id,u]);let ve=(0,lt.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),f("Resize block");let o=a.current?.clientWidth||e.width||340,n=a.current?.clientHeight||e.height||360,i=t.clientX,d=t.clientY,r=C.getState().transform[2]||1,s=xe(),l=o,c=n,u=t=>{l=Math.min(720,Math.max(280,o+(t.clientX-i)/r)),c=Math.max(s,n+(t.clientY-d)/r),p(e.id,Math.round(l),Math.round(c)),S()},h=()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",h),g(e.id,{blockCollapsedWidth:Math.round(l),blockCollapsedHeight:Math.round(c)}),m(),S()};document.addEventListener("mousemove",u),document.addEventListener("mouseup",h)},[f,xe,m,e.height,e.id,e.width,C,S,p,g]);return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(H,{nodeId:e.id,label:e.data.label||T?.name||"Block",expanded:i,nodeRef:a,headerRef:o,connectorRef:n,onResizeStart:ve,actions:(0,ct.jsxs)(ct.Fragment,{children:[i?(0,ct.jsx)(ae,{className:P("nodrag nowheel",ne.valid?"text-modiff-green":"text-modiff-red"),size:"compact",label:ne.valid?"Inspect Block composition":`Inspect Block composition: ${ne.issues.length} issue${1===ne.issues.length?"":"s"}`,onClick:()=>q(!0),"data-testid":`user-block-composition-${e.id}`,children:(0,ct.jsx)(d,{size:15})}):null,(0,ct.jsx)(ae,{className:"nodrag nowheel",size:"compact",label:"Save Block changes",onClick:()=>L(!0),"data-testid":`user-block-save-choices-${e.id}`,children:(0,ct.jsx)(l,{size:15})}),(0,ct.jsx)(ae,{className:"nodrag nowheel",size:"compact",label:"Configure block instance",onClick:()=>{T&&V({name:T.name,inputLabels:Object.fromEntries(T.inputs.map(e=>[e.id,e.label])),outputLabels:Object.fromEntries(T.outputs.map(e=>[e.id,e.label])),exposedParamIds:new Set(T.exposedParams.map(e=>e.id))})},"data-testid":`user-block-configure-${e.id}`,children:(0,ct.jsx)(b,{size:15})}),(0,ct.jsx)(ae,{className:"nodrag nowheel",size:"compact",label:i?"Collapse block":"Expand block",onClick:ce,"data-testid":`user-block-toggle-${e.id}`,children:i?(0,ct.jsx)(k,{size:16}):(0,ct.jsx)(I,{size:16})})]}),controls:(0,ct.jsxs)("div",{className:"grid gap-2","data-testid":`user-block-disclosures-${e.id}`,children:[(0,ct.jsx)(lt.Suspense,{fallback:(0,ct.jsx)("p",{role:"status",children:"Loading model controls…"}),children:t?(0,ct.jsx)(Zt,{node:t}):null}),M.map(t=>(0,ct.jsxs)("section",{"data-block-source-node":t.id,children:[Object.keys(t.controlParams).length>0?(0,ct.jsx)(le,{label:t.label,"data-testid":`user-block-disclosure-${e.id}-${t.id}`,className:"rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg/60",buttonClassName:"min-h-8 text-xs",panelClassName:"grid gap-2 border-t border-modiff-border-subtle p-2",children:(0,ct.jsx)(fe,{nodeId:e.id,params:t.controlParams,updateStore:se,module:t.module,action:t.action,mode:"controls"})}):null,Object.keys(t.previewParams).length>0?(0,ct.jsxs)("div",{className:"mt-2 overflow-hidden rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg p-2","data-testid":`user-block-preview-${e.id}-${t.id}`,children:[(0,ct.jsx)("div",{className:"mb-2 truncate text-xs font-semibold text-modiff-subtle-text",children:t.label}),(0,ct.jsx)(fe,{nodeId:e.id,params:t.previewParams,updateStore:se,module:t.module,action:t.action,mode:"controls"})]}):null]},t.id))]}),connectors:(0,ct.jsx)(fe,{nodeId:e.id,params:O,updateStore:se,module:e.data.module,action:e.data.action,mode:"connectors"})}),(0,ct.jsx)(Ie,{open:D,onClose:()=>q(!1),title:"Block composition",testId:`user-block-composition-dialog-${e.id}`,panelClassName:"max-w-2xl",footer:(0,ct.jsx)(He,{onClick:()=>q(!1),children:"Close"}),children:(0,ct.jsxs)("div",{className:"grid gap-4 text-sm",children:[(0,ct.jsxs)("section",{className:"grid gap-1",children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Execution contract"}),(0,ct.jsx)("p",{className:"text-modiff-subtle-text",children:"This editable instance executes as an ordinary MoDiff graph. Socket types, container ownership, and sealed Modular workflow-state identity are checked before execution."}),"diffusers"===T?.origin?.provider?(0,ct.jsxs)("p",{className:"text-modiff-subtle-text",children:["Upstream identity: ",T.origin.definitionId||"imported Diffusers definition"," at"," ",T.origin.libraryRevision||T.origin.revision||"its pinned revision",". Ordinary node edits do not claim upstream block-tree parity; reviewed Modular block edits are rebuilt through Diffusers ",(0,ct.jsx)("code",{children:"init_pipeline()"}),"."]}):null]}),(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`user-block-composition-issues-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:ne.valid?"No structural connection issues found":`${ne.issues.length} structural issue${1===ne.issues.length?"":"s"}`}),ne.issues.map(e=>(0,ct.jsx)("div",{className:"rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/10 px-3 py-2 text-modiff-text",children:e.message},e.id))]}),(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`user-block-insertion-suggestions-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Compatible insertion points"}),ne.insertionSuggestions.length?ne.insertionSuggestions.slice(0,12).map(t=>(0,ct.jsxs)("div",{className:"flex items-center justify-between gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg px-3 py-2",children:[(0,ct.jsx)("span",{className:"min-w-0 flex-1 text-modiff-subtle-text",children:t.label}),(0,ct.jsx)(He,{tone:"primary",onClick:()=>{try{ie(e.id,t),ye.getState().saveActiveWorkflowTab(!0),R("The node was inserted into the compatible execution path.",{variant:"success",autoHideDuration:2600})}catch(e){R(e instanceof Error?e.message:"The compatible insertion point is unavailable.",{variant:"error",autoHideDuration:3600})}},children:"Insert"})]},t.id)):(0,ct.jsx)("p",{className:"text-modiff-subtle-text",children:"No disconnected node currently has both an input and output that can safely replace an existing typed connection."})]}),re?(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`reviewed-modular-composition-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Reviewed upstream Modular blocks"}),(0,ct.jsxs)("p",{className:"text-modiff-subtle-text",children:["These actions validate an upstream block-tree modification against the exact pinned Diffusers definition. The backend applies the edit to ",(0,ct.jsx)("code",{children:"sub_blocks"})," and rebuilds its interface through"," ",(0,ct.jsx)("code",{children:"init_pipeline()"}),". The receipt is structural and does not silently replace this ordinary User Node execution graph."]}),(0,ct.jsx)("div",{className:"max-h-52 overflow-y-auto rounded-modiff-compact border border-modiff-border",children:re.definition.blockPlacements.map(e=>{let t=e.path.join(".");return(0,ct.jsxs)("div",{className:"flex items-center justify-between gap-3 border-b border-modiff-border px-3 py-2 last:border-b-0",children:[(0,ct.jsx)("span",{className:"min-w-0 flex-1 truncate text-modiff-subtle-text",children:t}),(0,ct.jsx)(He,{disabled:!!Y,onClick:()=>{X(t),te(null),Q(ge(re,e.path)).then(e=>Z(e)).catch(e=>te(e instanceof Error?e.message:"Could not rebuild the Modular composition.")).finally(()=>X(null))},children:Y===t?"Rebuilding…":"Validate duplicate"})]},t)})}),J?(0,ct.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-green/40 bg-modiff-green/10 px-3 py-2 text-modiff-text","data-testid":`reviewed-modular-composition-receipt-${e.id}`,children:["Upstream ",(0,ct.jsx)("code",{children:"init_pipeline()"})," rebuild passed: ",J.composedPaths.length," ","block paths, ",J.inputs.length," inputs,"," ",J.outputs.length," outputs. Receipt"," ",J.receiptHash.slice(0,20),"…"]}):null,ee?(0,ct.jsx)("div",{className:"rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/10 px-3 py-2 text-modiff-text",children:ee}):null]}):null]})}),(0,ct.jsx)(Ie,{open:z,onClose:()=>{G||L(!1)},title:"Save Block changes",testId:`save-user-block-choices-${e.id}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{disabled:G,onClick:()=>{he("workflow")},children:"Keep only in this workflow"}),(0,ct.jsx)(He,{disabled:G,onClick:()=>{he("new")},children:"Save as new Block"}),(0,ct.jsx)(He,{tone:"primary",disabled:G,onClick:()=>{he("update")},children:"Update existing Block"})]}),children:(0,ct.jsxs)("div",{className:"grid gap-3 text-sm text-modiff-subtle-text",children:[(0,ct.jsx)("p",{children:"The current topology, parameters, exposed ports, and model revision have been captured."}),(0,ct.jsxs)("p",{children:["Updating changes the reusable library definition but does not silently rewrite other workflow instances. Saving as new defaults to"," ",(0,ct.jsx)("strong",{children:F(T?.name||"Block",w)}),"."]})]})}),(0,ct.jsx)(Ie,{open:!!A,onClose:()=>V(null),title:"Configure block instance",testId:`configure-user-block-${e.id}`,panelClassName:"max-w-xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(He,{onClick:()=>V(null),children:"Cancel"}),(0,ct.jsx)(He,{tone:"primary",disabled:!A?.name.trim(),onClick:()=>{A&&(v(e.id,A),V(null))},children:"Apply"})]}),children:A&&T?(0,ct.jsxs)("div",{className:"grid gap-4",children:[(0,ct.jsx)(pe,{label:"Name",required:!0,children:(0,ct.jsx)(Se,{value:A.name,onChange:e=>{let t=e.currentTarget.value;V(e=>e&&{...e,name:t})}})}),T.inputs.map(e=>(0,ct.jsx)(pe,{label:`Input: ${e.label}`,children:(0,ct.jsx)(Se,{value:A.inputLabels[e.id]??e.label,onChange:t=>{let a=t.currentTarget.value;V(t=>t&&{...t,inputLabels:{...t.inputLabels,[e.id]:a}})}})},`input-${e.id}`)),T.outputs.map(e=>(0,ct.jsx)(pe,{label:`Output: ${e.label}`,children:(0,ct.jsx)(Se,{value:A.outputLabels[e.id]??e.label,onChange:t=>{let a=t.currentTarget.value;V(t=>t&&{...t,outputLabels:{...t.outputLabels,[e.id]:a}})}})},`output-${e.id}`)),B.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable parameters"}),B.map(e=>(0,ct.jsx)(de,{label:e.label,checked:A.exposedParamIds.has(e.id),onCheckedChange:t=>V(a=>{if(!a)return a;let o=new Set(a.exposedParamIds);return t?o.add(e.id):o.delete(e.id),{...a,exposedParamIds:o}})},e.id))]}):null]}):null})]})});ea.displayName="UserBlockNode";var ta=/(?:ModelsLoader|LoadPipeline|LoadModel|LoadTokenizer|LoadTextEncoder)$/u;function aa(e,t){let a=e.data.params[t];return void 0===a?.value?a?.default:a.value}function oa(e){let t=aa(e,"repo_id")??aa(e,"model_id");return t&&"object"==typeof t&&"value"in t?"string"==typeof t.value?t.value:"":"string"==typeof t?t:""}function na(e){let t=aa(e,"offload_mode")??(aa(e,"auto_offload")?"Auto Offload enabled":"Auto Offload disabled");return`${oa(e)||e.data.label||e.id} · ${aa(e,"dtype")??"runtime dtype"} · ${aa(e,"device")??"runtime device"} · ${t}`}function ia(e,t,a){let o=e.find(e=>e.id===a);if(a&&!o?.data.blockInstanceV2&&!o?.data.blockProjectionContainer)throw Error("Select a Block to assess its contained graph.");let n=oe(e,t,a),i=je(n.nodes),d=new Set(i.map(e=>e.id)),r=n.edges.filter(e=>d.has(e.source)&&d.has(e.target)),s=Re(e,t).nodes.filter(e=>e.data.blockInstanceV2),l=i.filter(e=>ta.test(e.data.action??"")),c=i.filter(e=>/lora|adapter/iu.test(`${e.data.action} ${e.data.module}`)),u=new Set,p=[],f=[],m=e=>{let t=new Set(e);for(let e=!0;e;){e=!1;for(let a of r)t.has(a.source)&&!t.has(a.target)&&(t.add(a.target),e=!0)}return t.size-e.length};for(let e of s){let t=e.data.blockInstanceV2,a=new Set(t.effectiveGraph.nodes.map(t=>Ve(e.id,t.nodeId))),n=l.filter(e=>a.has(e.id));if(!n.length)continue;n.forEach(e=>u.add(e.id));let d=[],s=Ae(t,"auto")??ie(t),c=s?{...s.form,resourceMode:"auto"}:null;1!==n.length&&(c=null,d.push("This Block has multiple model loaders. Its combined recipe needs a workflow resource contract.")),o?.data.blockProjectionContainer&&(c=null,d.push("This nested scope differs from its full source recipe; the full Block estimate cannot be reused."));let p=n[0];if(c){let e=oa(p),t=aa(p,"model_type");(e&&e!==c.modelRepo||t&&t!==c.modelType)&&(c=null,d.push("The actual loader differs from the source recipe. Its resource plan must be reviewed separately."))}if(c)for(let[e,t]of Object.entries({device:"device",dtype:"dtype",offload_mode:"offloadMode",auto_offload:"autoOffload",quantization_mode:"quantizationMode"})){let a=aa(p,e);void 0!==a&&typeof a==typeof c[t]&&(c[t]=a)}let h=r.filter(e=>a.has(e.target)&&!a.has(e.source));for(let e of h){let t=i.find(t=>t.id===e.source);d.push(`Connected input: ${t?.data.label??e.source} → ${e.targetHandle??"input"}. Its computed value is resolved when the graph runs.`)}"structure_changed"===t.customization.state&&d.push("Internal graph edits are present. The source model estimate does not qualify the edited recipe."),s||d.push("No exact resource planning form is available for this saved or custom Block."),f.push({id:e.id,label:e.data.label??t.definitionSnapshot.displayName,form:c,loaderIds:n.map(e=>e.id),consumers:m(n.map(e=>e.id)),details:[...new Set(d)],currentSettings:n.map(na)})}for(let e of l.filter(e=>!u.has(e.id)))f.push({id:e.id,label:e.data.label??e.id,form:null,loaderIds:[e.id],consumers:m([e.id]),details:["Use Check Auto execution plan for this standalone loader."],currentSettings:[na(e)]});(l.length>1||c.length)&&p.push("Check Auto execution plan for the combined model and adapter memory budget.");let h=ne(e,t,a);return{key:j({target:a??null,owners:s.flatMap(e=>{let t=e.data.blockInstanceV2,a=t.effectiveGraph.nodes.filter(t=>d.has(Ve(e.id,t.nodeId)));return a.length?[{id:e.id,definition:t.definitionRef,members:a}]:[]}),nodes:i.map(e=>({id:e.id,module:e.data.module,action:e.data.action,params:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"!==e.display).map(([e,t])=>[e,{value:void 0===t.value?t.default??null:t.value,type:t.type??null}]))})),edges:r.map(({source:e,target:t,sourceHandle:a,targetHandle:o})=>({source:e,target:t,sourceHandle:a??null,targetHandle:o??null}))}),scopeLabel:o?.data.label??"Whole workflow",items:f,issues:p,autoReason:h.reason,autoEligible:h.eligible,nodeCount:i.length,loaderCount:l.length,adapterCount:c.length}}async function da(e,t){let a=e.items.filter(e=>e.form),[o,n]=await Promise.all([a.length?G(a.map(e=>e.form),a.map(e=>e.id),t):Promise.resolve([]),S(t)]),i={};for(let e of o){let t=a.find(t=>t.id===e.planKey);if(!t||i[t.id])throw Error("Resource assessment returned an unmatched or duplicate Block plan.");i[t.id]=e}if(Object.keys(i).length!==a.length)throw Error("Resource assessment returned an incomplete set of Block plans.");return{request:e,plans:i,resources:n}}var ra=[{value:"studio",label:"Studio",Icon:p},{value:"block",label:"Block",Icon:b},{value:"compatibility",label:"Compatibility",Icon:r},{value:"queue",label:"Queue",Icon:s},{value:"setup",label:"Setup",Icon:b},{value:"app",label:"Run as app",Icon:a}];function sa(){let e=ce(e=>e.target),t=z(e=>e.rightPanelTab),a=z(e=>e.setRightPanelTab),o=ye(e=>e.appModeConfigs),n=U(e=>e.nodes.some(e=>/preview|save|output|video|audio|image/i.test(`${e.data?.label??""} ${e.id}`))),i=ra.filter(a=>"studio"===a.value||"block"===a.value&&!!e||"queue"===a.value||"setup"===a.value||"compatibility"===a.value&&"compatibility"===t),d=ra.filter(e=>"app"===e.value&&(o.length>0||n)),r=d.find(e=>e.value===t),s=r?[...i,r]:i,l=s.some(e=>e.value===t)?t:"studio";return(0,lt.useEffect)(()=>{l!==t&&a(l)},[l,t,a]),(0,ct.jsxs)("div",{className:"flex h-full flex-col","data-testid":"workspace-panel",children:[(0,ct.jsxs)("div",{"aria-label":"Workspace panels",className:"flex min-h-[42px] flex-none overflow-x-auto overflow-y-hidden border-b border-modiff-border bg-modiff-bg",onWheel:Fe,children:[(0,ct.jsx)(Ge,{"aria-label":"Workspace panels",className:"min-w-0 flex-1 flex-nowrap gap-0",value:l,onValueChange:a,options:s.map(e=>{let t=e.Icon;return{value:e.value,id:`workspace-tab-${e.value}`,controls:`workspace-panel-${e.value}`,label:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(t,{size:15}),(0,ct.jsx)("span",{children:e.label})]}),testId:`workspace-tab-${e.value}`,className:"h-[42px] min-w-[72px] flex-none justify-center gap-1.5 rounded-none px-2 text-xs"}})}),d.length>0&&(0,ct.jsx)("div",{className:"flex h-[42px] flex-none items-center px-1","data-testid":"workspace-tabs-more",children:(0,ct.jsx)(N,{label:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(m,{size:16}),(0,ct.jsx)("span",{className:"sr-only",children:"More panels"})]}),children:d.map(e=>{let t=e.Icon;return(0,ct.jsxs)(Ne,{active:l===e.value,onClick:()=>a(e.value),children:[(0,ct.jsx)(t,{size:15}),(0,ct.jsx)("span",{children:e.label})]},e.value)})})})]}),s.filter(e=>e.value!==l).map(e=>(0,ct.jsx)("div",{id:`workspace-panel-${e.value}`,role:"tabpanel","aria-labelledby":`workspace-tab-${e.value}`,hidden:!0},e.value)),(0,ct.jsxs)("div",{id:`workspace-panel-${l}`,role:"tabpanel","aria-labelledby":`workspace-tab-${l}`,className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden",children:["studio"===l&&(0,ct.jsx)(ot,{}),"block"===l&&(0,ct.jsx)(rt,{}),"compatibility"===l&&(0,ct.jsx)(nt,{}),"queue"===l&&(0,ct.jsx)(at,{}),"setup"===l&&(0,ct.jsx)(it,{}),"app"===l&&(0,ct.jsx)(dt,{})]})]})}var la=e({applyRuntimeWorkflowAutoSettingsV2:()=>Ia,applyWorkflowAutoSettingsV2:()=>xa,fetchWorkflowAutoPlanV2:()=>fa,inspectWorkflowAutoPlanV2:()=>ma,parseWorkflowAutoPlanV2:()=>pa,prepareWorkflowAutoExecutionV2:()=>ba}),ca=e=>!(!e||"object"!=typeof e||Array.isArray(e)),ua=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function pa(e){if(!ca(e)||1!==e.schemaVersion||"boolean"!=typeof e.canAutoRun||!ua(e.issues)||"string"!=typeof e.message||![e.graphHash,e.plannedGraphHash].every(e=>"string"==typeof e&&/^sha256:workflow-auto-v1:[a-f0-9]{64}$/u.test(e))||!Array.isArray(e.patches)||!e.patches.every(e=>ca(e)&&"string"==typeof e.nodeId&&("auto_offload"===e.field&&"boolean"==typeof e.value||"offload_mode"===e.field&&"string"==typeof e.value))||!Array.isArray(e.loaders)||!e.loaders.every(e=>ca(e)&&["nodeId","modelType","repository","candidateId"].every(t=>"string"==typeof e[t])&&ua(e.consumers))||!ca(e.requirements)||!Object.values(e.requirements).every(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0)||!ca(e.available)||!Object.values(e.available).every(e=>null===e||"number"==typeof e&&Number.isFinite(e)&&e>=0)||"boolean"!=typeof e.sharedMemory||void 0!==e.requiresPreparation&&"boolean"!=typeof e.requiresPreparation||void 0!==e.preparationNodeIds&&!ua(e.preparationNodeIds)||e.canAutoRun&&e.issues.length||!e.canAutoRun&&e.patches.length)throw Error("The backend returned an invalid workflow Auto plan.");return e}async function fa(e,t){return A(`${_e.serverAddress}/auto_resource/workflow`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaVersion:1,graph:{nodes:e.nodes,paths:e.paths,...e.loops?{loops:e.loops}:{}}}),timeoutMs:12e4,signal:t,parse:pa})}async function ma(e,t){let a=U.getState(),{prepareLegacyGraphForAutoV2:o}=await $(async()=>{let{prepareLegacyGraphForAutoV2:e}=await import(`./studio-templates.js?v=cc046c26d6fe7aa4`).then(e=>e.Gn);return{prepareLegacyGraphForAutoV2:e}},[]),n=o(a.nodes,a.edges,e),i=a.exportGraph("",e?n.remapped.get(e)??e:void 0,{randomizeSeeds:!1,sourceGraph:n});return n.nodes.some(e=>e.data.blockInstanceV2?.effectiveGraph.nodes.some(e=>"upstream_block"===e.modularDiffusers?.kind))?fa((await(await $(async()=>{let{prepareModularCompositionExecutionV2:e}=await import(`./studio-templates.js?v=cc046c26d6fe7aa4`).then(e=>e.g);return{prepareModularCompositionExecutionV2:e}},[])).prepareModularCompositionExecutionV2(a,n.nodes))(i),t):fa(i,t)}function ha(){let e=U.getState().toObject();return j({nodes:e.nodes.map(e=>({id:e.id,data:e.data})),edges:e.edges})}function ga(e){let t=new Map(e.effectiveInterface.controls.map(e=>[e.controlId,[e.binding,...e.mirrorBindings??[]]]));for(let a of e.effectiveInterface.boundary.inputs)t.has(a.portId)||t.set(a.portId,[a.binding,...a.mirrorBindings??[]].map(({nodeId:e,fieldOrPortId:t})=>({nodeId:e,fieldId:t})));return[...t].map(([e,t])=>({logicalId:e,bindings:t}))}async function ba(e,t){let a,o=ye.getState().activeWorkflowTabId,n=ha(),i=()=>o===ye.getState().activeWorkflowTabId&&n===ha()&&"auto"===ye.getState().form.resourceMode;try{if(a=await fa(e),!i())throw Error("The workflow or mode changed while Auto was planning. Run again with the current graph.");if(!a.canAutoRun)throw Error(`Auto cannot run this workflow: ${a.issues.join(" ")}`)}catch(e){throw i()&&$e.getState().showIssues([{id:"workflow-auto-planning",category:"hardware_fit",severity:"error",blocking:!0,message:C(e,"Workflow memory planning failed."),details:"No run was submitted. Review the requirements and model/memory settings, then Run again for a fresh plan."}]),e}let d=xa(e,a.patches,t),r=U.getState().nodes.flatMap(e=>{let t=e.data.blockInstanceV2;return t?ga(t).flatMap(({bindings:t})=>t.length<2||!t.every(e=>"offload_mode"===e.fieldId||"auto_offload"===e.fieldId)?[]:[t.map(t=>({nodeId:Ve(e.id,t.nodeId),field:t.fieldId}))]):[]});return{...d,runtimeHints:{workflowAutoPlan:{schemaVersion:1,graphHash:a.plannedGraphHash,...r.length?{resourceControlGroups:r}:{}},resourceMode:"auto"}}}function xa(e,t,a){let o=structuredClone(e);U.getState().beginHistoryTransaction("Apply workflow Auto resource settings");try{a&&U.setState({nodes:a.nodes,edges:a.edges});let n=new Set;for(let a of t){let i=`${a.nodeId}.${a.field}`,d=o.nodes[a.nodeId]?.params[a.field];if(n.has(i)||!d||d.sourceId)throw Error("The Auto plan targets a missing, connected or repeated resource field.");n.add(i),d.value=a.value;let r=U.getState(),s=r.nodes.find(e=>e.data.blockInstanceV2?.effectiveGraph.nodes.some(t=>Ve(e.id,t.nodeId)===a.nodeId));if(!s?.data.blockInstanceV2){if(!r.nodes.some(e=>e.id===a.nodeId))throw Error("The loader is inside an older Block. Move it into a current Block before applying Auto settings.");r.setParamWithHistory(a.nodeId,a.field,a.value);continue}let l=s.data.blockInstanceV2,c=l.effectiveGraph.nodes.find(e=>Ve(s.id,e.nodeId)===a.nodeId),u=ga(l).filter(e=>e.bindings.some(e=>e.nodeId===c.nodeId&&e.fieldId===a.field));if(u.length){for(let o of u.flatMap(e=>e.bindings)){let n=Ve(s.id,o.nodeId),i=e.nodes[n]?.params[o.fieldId],d=t.find(e=>e.nodeId===n&&e.field===o.fieldId);if(!i||i.sourceId||(d?.value??i.value)!==a.value)throw Error("A shared resource control would change a node outside this Auto plan. Configure that control separately.")}for(let e of u)r.setBlockInstanceValueV2(s.id,e.logicalId,a.value)}else{let e=structuredClone(l.effectiveGraph),t=e.nodes.find(e=>e.nodeId===c.nodeId).data.params;t[a.field]={...t[a.field],value:a.value};let o=Pe(ke(re(l,e),{selected:s.selected}));U.setState({nodes:[...r.nodes.filter(e=>e.id!==s.id&&e.data.blockProjectionOwnerId!==s.id),...o.nodes],edges:[...r.edges.filter(e=>e.data?.blockProjectionOwnerId!==s.id),...o.edges]})}}U.getState().commitHistoryTransaction()}catch(e){throw U.getState().cancelHistoryTransaction(),e}return o}function Ia(e){let t=U.getState().exportGraph("",void 0,{randomizeSeeds:!1});for(let a of e){let e=t.nodes[a.nodeId]?.params[a.field];if(!e||e.sourceId||(e.value??null)!==(a.previousValue??null))throw Error("The run changed resource settings, but your newer workflow edits were preserved. The run details show the settings used.")}xa(t,e)}export{ea as a,yt as c,st as d,ia as i,kt as l,sa as n,Xt as o,da as r,jt as s,la as t,It as u}; \ No newline at end of file +import{n as e,r as t}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Bn as a,Cn as o,En as n,M as i,Ot as d,R as r,Sn as s,X as l,cr as c,dr as u,et as p,kn as f,ln as m,nr as h,ot as g,q as b,tr as x,wt as I,xt as k,z as v}from"./graph-vendor.js?v=ca6b74e6a02eedb3";import{$s as y,Ao as w,Ar as j,At as $,Di as N,Dr as C,Fo as S,Hn as _,Hr as P,Io as O,Ln as T,Lo as H,Ni as M,Nn as R,No as E,Oo as A,Os as B,Ot as V,Po as z,Qs as L,Rn as D,Sn as q,Ti as F,Ui as G,Us as W,V as U,Vn as K,Xo as Y,Xr as X,Yn as Z,Ys as J,Zr as Q,Zs as ee,_ as te,_i as ae,_r as oe,an as ne,at as ie,br as de,bs as re,cs as se,ds as le,fi as ce,fn as ue,ft as pe,gr as fe,h as me,hi as he,hn as ge,in as be,is as xe,it as Ie,jo as ke,la as ve,lc as ye,ln as we,ls as je,lt as $e,m as Ne,mi as Ce,nc as Se,on as _e,os as Pe,p as Oe,pn as Te,pt as He,q as Me,ss as Re,ua as Ee,v as Ae,vi as Be,vn as Ve,vr as ze,w as Le,wa as De,wi as qe,x as Fe,xr as Ge,y as We,yr as Ue}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{t as Ke}from"./EditorPanel.js?v=ca6b74e6a02eedb3";import{a as Ye,i as Xe,n as Ze,o as Je,r as Qe,t as et}from"./BlockInterfaceDialogContentV2.js?v=ca6b74e6a02eedb3";import{t as tt}from"./LegacyUserBlockNode.js?v=ca6b74e6a02eedb3";import{a as at,i as ot,n as nt,o as it,r as dt,t as rt}from"./WorkspacePanel.js?v=ca6b74e6a02eedb3";var st=e({default:()=>ut}),lt=t(u(),1),ct=c();function ut(e){return"composition"===e.mode?(0,ct.jsx)(pt,{...e}):(0,ct.jsx)(ne,{open:!0,onClose:e.onClose,title:"Switch model route",testId:`switch-block-route-v1-${e.nodeId}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:e.onClose,children:"Cancel"}),(0,ct.jsx)(be,{disabled:e.busy,onClick:()=>e.onSwitch(!0),children:"Save active route and switch"}),(0,ct.jsx)(be,{tone:"primary",disabled:e.busy,onClick:()=>e.onSwitch(!1),children:"Keep draft and switch"})]}),children:(0,ct.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:"This route has workflow-local changes. MoDiff can keep its exact values, internal graph, interface, and layout as an inactive workflow draft, then restore them when you switch back. Previews and run authority are not copied between models."})})}function pt({nodeId:e,instance:t,onClose:a}){let o=Q(e=>e.library),n=X(e=>e.snapshot),i=Q(e=>e.error),d=X(e=>e.error),r=t.effectiveGraph.nodes.some(e=>"upstream_block"===e.modularDiffusers?.kind),s=!r||!(!o||!n),[l,c]=(0,lt.useState)(0),[u,p]=(0,lt.useState)(!1);(0,lt.useEffect)(()=>{if(!r)return;let e=!0;p(!0);let t=Q.getState(),a=X.getState();return Promise.all([t.library?Promise.resolve():t.fetchLibrary(),a.snapshot?Promise.resolve():a.fetchSnapshot()]).finally(()=>{e&&p(!1)}),()=>{e=!1}},[r,l]);let[f,m]=(0,lt.useState)(!1),[h,g]=(0,lt.useState)(null),[b,x]=(0,lt.useState)(null),I=(0,lt.useRef)(null),k=(0,lt.useMemo)(()=>{if(!s)return{recipe:null,error:null};try{return{recipe:Ae(t,o,n),error:null}}catch(e){return{recipe:null,error:e instanceof Error?e.message:"Could not derive the upstream Modular composition."}}},[t,o,n,s]);return(0,lt.useEffect)(()=>(g(null),x(null),m(!1),()=>I.current?.abort()),[y(k.recipe)]),(0,ct.jsx)(ne,{open:!0,onClose:a,title:"Block composition",testId:`user-block-composition-dialog-${e}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:a,children:"Close"}),s?null:(0,ct.jsx)(be,{disabled:u,onClick:()=>c(e=>e+1),children:u?"Loading pinned catalog…":"Retry pinned catalog"}),k.recipe?(0,ct.jsx)(be,{tone:"primary",disabled:f,onClick:()=>{(async()=>{if(!k.recipe||f)return;let e=new AbortController;I.current=e,m(!0),g(null),x(null);try{let t=await te(k.recipe,e.signal);e.signal.aborted||g(t)}catch(t){e.signal.aborted||x(t instanceof Error?t.message:"The backend could not rebuild this Modular composition.")}finally{e.signal.aborted||m(!1)}})()},children:f?"Rebuilding…":"Validate upstream composition"}):null]}),children:(0,ct.jsxs)("div",{className:"grid gap-2 text-sm text-modiff-subtle-text",children:[s?null:(0,ct.jsx)("p",{role:u?"status":"alert",children:u?"Loading the reviewed block catalog and hierarchy. Your workflow is unchanged.":i??d??"The pinned catalog is unavailable. Retry before validating."}),(0,ct.jsxs)("p",{children:[t.effectiveGraph.nodes.length," ordinary internal nodes and ",t.effectiveGraph.edges.length," ","internal connections are owned by this workflow instance."]}),(0,ct.jsxs)("p",{children:["Source: ",t.definitionSnapshot.source.kind,". Customization state:"," ",t.customization.state.replace(/_/gu," "),"."]}),k.recipe?(0,ct.jsxs)("p",{"data-testid":`block-v2-composition-summary-${e}`,children:["Exact upstream recipe: ",k.recipe.operations.length," structural operation",1===k.recipe.operations.length?"":"s",". Parameter-only changes are stored directly on this workflow instance and do not rebuild sibling blocks."]}):null,k.error?(0,ct.jsx)("p",{className:"text-modiff-warning","data-testid":`block-v2-composition-error-${e}`,children:k.error}):null,h?(0,ct.jsxs)("p",{className:"text-modiff-green","data-testid":`block-v2-composition-receipt-${e}`,children:["Upstream init_pipeline() rebuild passed for ",h.composedPaths.length," paths. Receipt"," ",h.receiptHash.slice(0,20),"…"]}):null,b?(0,ct.jsx)("p",{className:"text-modiff-red",children:b}):null,"edited_unpruned_tree"===h?.inspectionScope?(0,ct.jsx)("p",{children:"This checks the edited tree, including inactive branches. It does not load models or qualify a run. Execution checks each connected step's required components and inputs."}):null]})})}function ft(e,t){return`${e}\0${t}`}function mt(e,t){let a=e.fieldId??e.fieldOrPortId??"",o=t.fieldId??t.fieldOrPortId??"";return e.nodeId===t.nodeId?a===o?0:a=e.length)return[...e];let n=[...e];return[n[t],n[o]]=[n[o],n[t]],n}function gt({entryKey:e,valueType:t,primary:a,mirrors:o,options:n,selected:i,disabled:d=!1,onSelected:r,onAdd:s,onRemove:l}){let c=function(e,t,a,o){let n=new Set([ft(a.nodeId,a.fieldId),...o.map(({nodeId:e,fieldId:t})=>ft(e,t))]);return e.filter(e=>!n.has(e.key)&&J(t,e.valueType))}(n,t,a,o),u=new Map(n.map(e=>[e.key,e.label]));return(0,ct.jsxs)("div",{className:"ml-3 grid gap-2 border-l border-modiff-border-subtle pl-3","data-testid":`interface-mirrors-${e}`,children:[o.map(t=>{let a=ft(t.nodeId,t.fieldId);return(0,ct.jsxs)("div",{className:"flex min-w-0 items-center gap-2 text-xs text-modiff-subtle-text",children:[(0,ct.jsxs)("span",{className:"min-w-0 flex-1 break-words",children:["Additional consumer: ",u.get(a)??`${t.nodeId} / ${t.fieldId}`]}),(0,ct.jsx)(_e,{label:`Remove additional consumer ${u.get(a)??t.fieldId}`,size:"compact",disabled:d,"data-testid":`interface-mirror-remove-${e}-${t.nodeId}-${t.fieldId}`,onClick:()=>l(t),children:(0,ct.jsx)(v,{size:13})})]},a)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Je,{value:i,disabled:d,onValueChange:r,options:c.map(e=>({value:e.key,label:e.label})),placeholder:"Add another internal consumer","data-testid":`interface-mirror-select-${e}`}),(0,ct.jsx)(_e,{label:"Add additional internal consumer",size:"compact",disabled:d||!i||!c.some(({key:e})=>e===i),"data-testid":`interface-mirror-add-${e}`,onClick:()=>{let e=c.find(({key:e})=>e===i);e&&s(e)},children:(0,ct.jsx)(g,{size:14})})]})]})}function bt(e){return!(!e||"object"!=typeof e||Array.isArray(e))}function xt(e,t,a){let o=new Set([...a.boundary.inputs.map(({portId:e})=>e),...a.boundary.outputs.map(({portId:e})=>e),...a.controls.map(({controlId:e})=>e)]),n=`${e}:${t.nodeId}:${t.fieldId}`.replace(/[^A-Za-z0-9_.:/-]/gu,"-"),i=n,d=2;for(;o.has(i);)i=`${n}-${d++}`;return i}function It({nodeId:e,snapshot:t,subtreeId:a,context:o,onClose:i}){let[d,r]=(0,lt.useState)(()=>Ze(t,a)),[s,l]=(0,lt.useState)({input:"",output:"",control:""}),[c,u]=(0,lt.useState)({}),p=(0,lt.useMemo)(()=>Xe(t,a),[t,a]),m=(0,lt.useMemo)(()=>function(e){return e.effectiveGraph.nodes.flatMap(e=>{let t=bt(e.data.params)?e.data.params:{};return Object.entries(t).flatMap(([t,a])=>bt(a)&&"string"==typeof a.type&&a.type?[{key:`${e.nodeId}\0${t}`,nodeId:e.nodeId,fieldId:t,label:`${"string"==typeof e.data.label?e.data.label:e.nodeId} / ${"string"==typeof a.label?a.label:t}`,valueType:a.type,..."string"==typeof a.display?{display:a.display}:{}}]:[])})}(t).filter(({nodeId:e})=>p.has(e)),[t,p]),h=m.filter(({display:e})=>"output"!==e),b=m.filter(({display:e})=>"output"===e),x=h,I=P(e=>e.edges),k=null,y=null;try{d&&(y=Ye(t,t,d,a))}catch(e){k=e instanceof Error?e.message:"Invalid interface draft."}let w=new Set(y?.boundary.inputs.map(({portId:e})=>e)),j=new Set(y?.boundary.outputs.map(({portId:e})=>e)),$=a&&y?Y(t,a,{schemaVersion:1,...y}):a?[]:I.filter(e=>!((e.target!==t.instanceId||re(e.targetHandle)||e.targetHandle&&w.has(e.targetHandle))&&(e.source!==t.instanceId||re(e.sourceHandle)||e.sourceHandle&&j.has(e.sourceHandle))));return(0,ct.jsx)(Ke,{onClose:()=>i(),title:B(t)&&!a?"Configure node interface":"Configure Block interface",testId:`configure-block-v2-${e}`,footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:()=>i(),children:"Cancel"}),(0,ct.jsx)(be,{tone:"primary",disabled:!d||$.length>0||!!k,onClick:()=>{if(d)try{(function(){N(o,{includeForm:!1});let e=P.getState().nodes.find(e=>e.id===t.instanceId)?.data.blockInstanceV2;if(!e||!d)throw Error("This Block is no longer available. Reopen Configure Interface.");let n=Ye(t,e,d,a);P.getState().configureBlockInterfaceV2(t.instanceId,n,a)})(),i(),z("The workflow instance interface was updated.",{variant:"success",autoHideDuration:3e3})}catch(e){z(e instanceof Error?e.message:"Could not configure this interface.",{variant:"error",autoHideDuration:5200})}},children:"Apply interface"})]}),children:d?(0,ct.jsxs)("div",{className:"grid gap-5",children:[a?(0,ct.jsxs)("p",{className:"rounded-modiff-compact border border-modiff-border-subtle p-3 text-sm text-modiff-subtle-text","data-testid":"block-interface-scope",children:["Editing"," ",String(t.effectiveGraph.nodes.find(e=>e.nodeId===a)?.data.label||a),"'s own ports, controls, and previews. This interface is saved with the workflow and remains available after disconnecting links, collapsing, or reloading. The root Block interface is unchanged. Controls keep their existing values; shared controls continue to update their declared consumers together."]}):null,k?(0,ct.jsx)("p",{role:"alert",className:"text-modiff-red",children:k}):null,$.length?(0,ct.jsxs)("p",{className:"rounded-modiff-compact border border-modiff-warning/50 bg-modiff-warning/10 p-3 text-sm text-modiff-text",children:[$.length," connected edge",1===$.length?"":"s"," would lose a public port. Disconnect ",1===$.length?"it":"them"," before applying."]}):null,[["input","Inputs",h],["output","Outputs",b]].map(([e,t,a])=>{let o=d.boundary["input"===e?"inputs":"outputs"];return(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:t}),o.map((t,i)=>{let d=`${e}:${t.portId}`,s=("input"===e?t.mirrorBindings:void 0)?.map(e=>({nodeId:e.nodeId,fieldId:e.fieldOrPortId}))??[];return(0,ct.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2 [&>input]:col-span-2",children:[(0,ct.jsx)(ge,{"aria-label":`${e} ${t.portId} label`,value:t.label,onChange:a=>{let n=a.currentTarget.value;r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.map(e=>e.portId===t.portId?{...e,label:n}:e)}})}}),(0,ct.jsx)(Je,{value:ft(t.binding.nodeId,t.binding.fieldOrPortId),onValueChange:n=>{let i=a.find(e=>e.key===n);i&&(r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.map(e=>e.portId===t.portId?(()=>{let t={...e};return delete t.mirrorBindings,{...t,valueType:i.valueType,binding:{nodeId:i.nodeId,fieldOrPortId:i.fieldId}}})():e)}}),u(e=>({...e,[d]:""})))},options:a.map(e=>({value:e.key,label:e.label}))}),(0,ct.jsxs)("div",{className:"flex items-center gap-1",children:[(0,ct.jsx)(_e,{label:`Move ${e} ${t.label} up`,size:"compact",disabled:0===i,onClick:()=>r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:ht(o,i,-1)}}),children:(0,ct.jsx)(n,{size:14})}),(0,ct.jsx)(_e,{label:`Move ${e} ${t.label} down`,size:"compact",disabled:i===o.length-1,onClick:()=>r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:ht(o,i,1)}}),children:(0,ct.jsx)(f,{size:14})}),(0,ct.jsx)(_e,{label:`Remove ${e} ${t.label}`,size:"compact",onClick:()=>r(a=>a&&{...a,boundary:{...a.boundary,["input"===e?"inputs":"outputs"]:o.filter(e=>e.portId!==t.portId)}}),children:(0,ct.jsx)(v,{size:14})})]})]}),"input"===e?(0,ct.jsx)(gt,{entryKey:d,valueType:t.valueType,primary:{nodeId:t.binding.nodeId,fieldId:t.binding.fieldOrPortId},mirrors:s,options:h,selected:c[d]??"",onSelected:e=>u(t=>({...t,[d]:e})),onAdd:e=>{r(a=>a&&{...a,boundary:{...a.boundary,inputs:a.boundary.inputs.map(a=>a.portId===t.portId?{...a,mirrorBindings:[...a.mirrorBindings??[],{nodeId:e.nodeId,fieldOrPortId:e.fieldId}].sort(mt)}:a)}}),u(e=>({...e,[d]:""}))},onRemove:e=>r(a=>a&&{...a,boundary:{...a.boundary,inputs:a.boundary.inputs.map(a=>{if(a.portId!==t.portId)return a;let o=(a.mirrorBindings??[]).filter(t=>t.nodeId!==e.nodeId||t.fieldOrPortId!==e.fieldId),n={...a};return delete n.mirrorBindings,o.length?{...n,mirrorBindings:o}:n})}})}):null]},t.portId)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Je,{value:s[e],onValueChange:t=>l(a=>({...a,[e]:t})),options:a.map(e=>({value:e.key,label:e.label})),placeholder:`Choose an internal ${e} field`}),(0,ct.jsx)(_e,{label:`Add public ${e}`,size:"compact",disabled:!s[e],onClick:()=>{let t=a.find(t=>t.key===s[e]);if(!t)return;let n={portId:xt(e,t,d),label:t.label,valueType:t.valueType,required:!1,binding:{nodeId:t.nodeId,fieldOrPortId:t.fieldId}};r(t=>t&&{...t,boundary:{...t.boundary,["input"===e?"inputs":"outputs"]:[...o,n]}}),l(t=>({...t,[e]:""}))},children:(0,ct.jsx)(g,{size:14})})]})]},e)}),a?(0,ct.jsx)(et,{snapshot:t,subtreeId:a,previews:d.previews??[],onChange:e=>r(t=>t&&{...t,previews:e})}):null,(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable controls"}),d.controls.map((e,t)=>{let a=`control:${e.controlId}`,o=e.mirrorBindings??[];return(0,ct.jsxs)("div",{className:"grid gap-2 rounded-modiff-compact border border-modiff-border-subtle p-2",children:[(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2 [&>input]:col-span-2",children:[(0,ct.jsx)(ge,{"aria-label":`control ${e.controlId} label`,value:e.label,onChange:t=>{let a=t.currentTarget.value;r(t=>t&&{...t,controls:t.controls.map(t=>t.controlId===e.controlId?{...t,label:a}:t)})}}),(0,ct.jsx)(Je,{value:ft(e.binding.nodeId,e.binding.fieldId),disabled:!!e.sealed,onValueChange:t=>{let o=x.find(e=>e.key===t);o&&(r(t=>t&&{...t,controls:t.controls.map(t=>t.controlId===e.controlId?(()=>{let e={...t};return delete e.mirrorBindings,{...e,valueType:o.valueType,binding:{nodeId:o.nodeId,fieldId:o.fieldId}}})():t)}),u(e=>({...e,[a]:""})))},options:x.map(e=>({value:e.key,label:e.label}))}),(0,ct.jsxs)("div",{className:"flex items-center gap-1",children:[(0,ct.jsx)(_e,{label:`Move control ${e.label} up`,size:"compact",disabled:0===t,onClick:()=>r(e=>e&&{...e,controls:ht(e.controls,t,-1).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(n,{size:14})}),(0,ct.jsx)(_e,{label:`Move control ${e.label} down`,size:"compact",disabled:t===d.controls.length-1,onClick:()=>r(e=>e&&{...e,controls:ht(e.controls,t,1).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(f,{size:14})}),(0,ct.jsx)(_e,{label:`Remove control ${e.label}`,size:"compact",disabled:!!e.sealed,onClick:()=>r(t=>t&&{...t,controls:t.controls.filter(t=>t.controlId!==e.controlId).map((e,t)=>({...e,order:t}))}),children:(0,ct.jsx)(v,{size:14})})]})]}),(0,ct.jsx)(gt,{entryKey:a,valueType:e.valueType,primary:e.binding,mirrors:o,options:x,selected:c[a]??"",disabled:!!e.sealed,onSelected:e=>u(t=>({...t,[a]:e})),onAdd:t=>{r(a=>a&&{...a,controls:a.controls.map(a=>a.controlId===e.controlId?{...a,mirrorBindings:[...a.mirrorBindings??[],{nodeId:t.nodeId,fieldId:t.fieldId}].sort(mt)}:a)}),u(e=>({...e,[a]:""}))},onRemove:t=>r(a=>a&&{...a,controls:a.controls.map(a=>{if(a.controlId!==e.controlId)return a;let o=(a.mirrorBindings??[]).filter(e=>e.nodeId!==t.nodeId||e.fieldId!==t.fieldId),n={...a};return delete n.mirrorBindings,o.length?{...n,mirrorBindings:o}:n})})})]},e.controlId)}),(0,ct.jsxs)("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[(0,ct.jsx)(Je,{value:s.control,onValueChange:e=>l(t=>({...t,control:e})),options:x.map(e=>({value:e.key,label:e.label})),placeholder:"Choose an internal parameter"}),(0,ct.jsx)(_e,{label:"Add editable control",size:"compact",disabled:!s.control,onClick:()=>{let e=x.find(e=>e.key===s.control);if(!e)return;let a=xt("control",e,d),o=Qe(t,e.nodeId,e.fieldId);r(t=>t&&{...t,controls:[...t.controls,{controlId:a,label:e.label,binding:{nodeId:e.nodeId,fieldId:e.fieldId},valueType:e.valueType,...void 0===o?{}:{defaultValue:o},order:t.controls.length}]}),l(e=>({...e,control:""}))},children:(0,ct.jsx)(g,{size:14})})]})]})]}):null})}var kt=e({default:()=>vt});function vt({nodeId:e,onClose:t,context:a}){let[o,n]=(0,lt.useState)(null),i=(0,lt.useRef)(!1),d=P(t=>t.nodes.find(t=>t.id===e)),r=d?.data.blockInstanceV2?e:d?.data.blockProjectionOwnerId,s=P(e=>e.nodes.find(e=>e.id===r)?.data.blockInstanceV2),l=!(!d||d.data.blockInstanceV2),c=!l&&B(s)?"node":"Block",[u,p]=(0,lt.useState)(()=>{let e=M.getState().workflowTabs.find(e=>e.id===a.workflowTabId)?.title||"Workflow";return Ie(d?.data.label||s?.definitionSnapshot.displayName||"Block",e)}),f=!u.trim()||u.trim().length>512,m=s?$e(s.definitionSnapshot,s,{editWorkflow:!0,configureInterfaces:!0,createUserDefinitions:!0,updateUserDefinitions:!0}):null;async function h(o){if(!i.current){i.current=!0,n(o);try{if("workflow"!==o&&f)throw Error(`Enter a ${c} name (up to 512 characters).`);let n=await ie({nodeId:e,choice:o,context:a,displayName:u.trim()});z("workflow"===o?"Changes kept only in this workflow.":`${"new"===o?"Saved new":"Updated"} ${c}: ${n.definition?.displayName??c}`,{variant:"success",autoHideDuration:3200}),t()}catch(e){z(e instanceof Error?e.message:`Could not save the ${c} changes.`,{variant:"error",autoHideDuration:6e3})}finally{i.current=!1,n(null)}}}return(0,ct.jsx)(Ke,{onClose:()=>{i.current||t()},title:`Save ${c.toLowerCase()} changes`,testId:`save-user-block-choices-${e}`,footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{disabled:!!o,onClick:t,children:"Cancel"}),(0,ct.jsx)(be,{disabled:!!o||!m?.keepWorkflowOnly,loading:"workflow"===o,onClick:()=>{h("workflow")},children:"Keep only in this workflow"}),m?.saveAsNewUserNode?(0,ct.jsxs)(be,{tone:"primary",disabled:!!o||f,loading:"new"===o,onClick:()=>{h("new")},children:["Save as new ",c]}):null,!l&&m?.updateReusableDefinition?(0,ct.jsxs)(be,{disabled:!!o||f,loading:"update"===o,onClick:()=>{h("update")},children:["Update existing ",c]}):null]}),children:(0,ct.jsxs)("div",{className:"grid gap-2 text-sm text-modiff-subtle-text",children:[(0,ct.jsx)("p",{className:"font-semibold text-modiff-text",children:d?.data.label||"Block"}),(0,ct.jsx)(Te,{label:"node"===c?"Node name":"Block name",required:!0,error:f?"Enter a name.":void 0,children:(0,ct.jsx)(ge,{value:u,onChange:e=>p(e.currentTarget.value),maxLength:512,disabled:!!o,"aria-invalid":f,autoFocus:!0})}),(0,ct.jsx)("p",{children:"Save a reusable copy with these settings and the inputs and outputs you configured."}),(0,ct.jsx)("p",{children:l?"Only this Block and its contents are saved. Outside nodes and their connections stay in this workflow.":`Outside nodes and their connections stay in this workflow. Temporary connected sockets are not added to the saved ${c}.`})]})})}var yt=e({default:()=>wt});function wt({pendingBlock:e,setPendingBlock:t,handleConfirmBlockCreation:a}){return(0,ct.jsx)(ne,{open:!!e,onClose:()=>t(null),title:"Create block",testId:"create-user-block-dialog",panelClassName:"max-w-xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:()=>t(null),children:"Cancel"}),(0,ct.jsx)(be,{tone:"primary",disabled:!e?.name.trim(),onClick:()=>{a()},"data-testid":"confirm-create-user-block",children:"Create block"})]}),children:e?(0,ct.jsxs)("div",{className:"grid gap-4",children:[e.error?(0,ct.jsx)("p",{role:"alert",className:"text-sm text-modiff-red",children:e.error}):null,(0,ct.jsx)(Te,{label:"Name",required:!0,children:(0,ct.jsx)(ge,{autoFocus:!0,value:e.name,onChange:e=>{let a=e.currentTarget.value;t(e=>e&&{...e,name:a})}})}),e.result.block.inputs.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Inputs"}),e.result.block.inputs.map(a=>(0,ct.jsx)(Te,{label:a.label,children:(0,ct.jsx)(ge,{value:e.inputLabels[a.id]??a.label,onChange:e=>{let o=e.currentTarget.value;t(e=>e&&{...e,inputLabels:{...e.inputLabels,[a.id]:o}})}})},a.id))]}):null,e.result.block.outputs.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Outputs"}),e.result.block.outputs.map(a=>(0,ct.jsx)(Te,{label:a.label,children:(0,ct.jsx)(ge,{value:e.outputLabels[a.id]??a.label,onChange:e=>{let o=e.currentTarget.value;t(e=>e&&{...e,outputLabels:{...e.outputLabels,[a.id]:o}})}})},a.id))]}):null,e.result.block.exposedParams.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable parameters"}),e.result.block.exposedParams.map(a=>(0,ct.jsx)(we,{label:a.label,checked:e.exposedParamIds.has(a.id),onCheckedChange:e=>t(t=>{if(!t)return t;let o=new Set(t.exposedParamIds);return e?o.add(a.id):o.delete(a.id),{...t,exposedParamIds:o}})},a.id))]}):null]}):null})}var jt=e({buildGraphFixPlan:()=>Wt,buildGraphFixPreview:()=>Kt,graphFixHighlightedSockets:()=>Yt,graphNodeIsOutputLike:()=>Rt,graphSocketTypesAreCompatible:()=>_t}),$t=new Set(["image","video","audio"]),Nt=new Set(["bool","float","int","number","str","string","text"]);function Ct(e,t){return e.map(e=>{if(S(e))return e;let a=t[function(e){return`${e.data.module}.${e.data.action}`}(e)];if(!a)return e;let o=Object.fromEntries(Object.entries(e.data.params).map(([e,t])=>{let o=a.params[e];return o?[e,{...t,type:o.type??t.type,required:o.required??t.required}]:[e,t]}));return{...e,data:{...e.data,params:o}}})}function St(e){let t=ee(e?.type);return t.length?t:["any"]}function _t(e,t){return L(e?.type,t?.type)}function Pt(e){return Object.entries(H(e)).filter(([,e])=>"input"===e.display||e.isInput)}function Ot(e){return Object.entries(H(e)).filter(([,e])=>"output"===e.display)}function Tt(e){return null!=e&&("string"==typeof e?e.trim().length>0:Array.isArray(e)?e.length>0:"object"!=typeof e||("value"in e?Tt(e.value):Object.keys(e).length>0))}function Ht(e,t,a=!1){if(t.hidden||t.disabled||t.spawn||Tt(t.value??t.default)||!1===t.required)return!1;if(!0===t.required)return!0;if(a)return!1;let o=`${e} ${t.label??""} ${t.description??""}`.toLowerCase();return!/\boptional\b|\bif provided\b|\bwhen supplied\b/.test(o)}function Mt(e){return e.filter(e=>"group"!==e.data.type&&"loop"!==e.data.type&&!e.data.uiState?.disabled&&!!e.data.module&&!!e.data.action)}function Rt(e){let t=`${e.data.module} ${e.data.action} ${e.data.label} ${e.data.category}`.toLowerCase();return/\b(preview|export|save|display|output|gallery)\b|viewer\b/.test(t)}function Et(e){if(!S(e)||!e.data.blockInstanceV2)return!1;let t=e.data.blockInstanceV2.effectiveGraph,a=new Set(t.nodes.filter(({data:e})=>!e.uiState?.disabled).map(({nodeId:e})=>e));return t.nodes.some(e=>a.has(e.nodeId)&&Rt({data:e.data})&&t.edges.some(t=>t.targetNodeId===e.nodeId&&a.has(t.sourceNodeId)))}function At(e,t){return O(e,t)?.label||t.replace(/_/g," ")}function Bt(e){let t=e.split(".");return t[t.length-1]||e}function Vt(e,t,a){let o=new Map;e.forEach(e=>o.set(e.source,[...o.get(e.source)??[],e.target]));let n=[t],i=new Set;for(;n.length;){let e=n.shift();if(e&&!i.has(e)){if(e===a)return!0;i.add(e),n.push(...o.get(e)??[])}}return!1}function zt(...e){return e.filter(Boolean).join(":").replace(/[^a-z0-9:_-]+/gi,"-").toLowerCase()}function Lt(e){let t=St(e);return t.some(e=>$t.has(e))?80:t.some(e=>e.includes("pipeline"))?70:t.some(e=>Nt.has(e))?10:t.includes("any")?0:40}function Dt(e,t){let a=St(e),o=St(t);return a.some(e=>"any"!==e&&o.includes(e))?100:a.includes("any")||o.includes("any")?5:0}function qt(e,t){let a=0;return e.data.module===t.data.module&&(a+=24),e.data.category===t.data.category&&(a+=12),a}function Ft(e,t,a){return"output"===e&&t?{x:t.position.x+340,y:t.position.y}:"producer"===e&&a?{x:a.position.x-340,y:a.position.y}:t&&a?{x:Math.round((t.position.x+a.position.x)/2),y:Math.round((t.position.y+a.position.y)/2+140)}:{x:120,y:100}}function Gt(e,t){return(e.data.blockProjectionOwnerId??null)===(t.data.blockProjectionOwnerId??null)}function Wt(e){e={...e,nodes:Ct(e.nodes,e.registry)};let t=[],a=new Map(e.nodes.map(e=>[e.id,e])),o=new Set;for(let a of e.nodes){if(!S(a)||!a.data.blockInstanceV2)continue;for(let o of ze(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-loop",a.id,o.nodeId,o.fieldId),d=Ne(a.data.blockInstanceV2,o.nodeId,e.modularBlockDefinitions??[]);t.push({id:i,kind:"block_structure",title:"Invalid loop connection",description:o.message,targetNodeId:n,targetHandle:o.fieldId,candidates:d?[{id:zt(i,"restore-one-edge"),issueId:i,title:"Reconnect the missing Loop Members link",description:`Restore only ${d.sourceNodeId} → ${d.targetNodeId}; keep all other edits.`,confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_loop",rootNodeId:a.id,targetNodeId:o.nodeId,graphHash:a.data.blockInstanceV2.effectiveGraph.graphHash}]}]:[]})}for(let o of Ue(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-state-input",a.id,o.nodeId);t.push({id:i,kind:"missing_input",title:"Missing upstream inputs",description:o.message,targetNodeId:n,candidates:o.reconnectFrom.map(e=>({id:zt(i,e),issueId:i,title:`Reconnect Pipeline State from ${a.data.blockInstanceV2.effectiveGraph.nodes.find(t=>t.nodeId===e)?.data.label??e}`,description:"Reconnect one edge; keep all other edits.",confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_state",rootNodeId:a.id,sourceNodeId:e,targetNodeId:o.nodeId,graphHash:a.data.blockInstanceV2.effectiveGraph.graphHash}]}))})}let o=oe(a.data.blockInstanceV2,e.modularBlockDefinitions??[]).filter(e=>e.canRepair);if(o.length){let e=zt("block-derived-control",a.id),n=[...new Set(o.map(({fieldId:e})=>e))].join(", "),i=`Repair ${o.length} bindings (${n}) to inherit derived values. Preserve prompts, requested values, layout and other wires.`;t.push({id:e,kind:"block_derived_control",title:"A mirrored control overwrites an upstream-derived value",description:i,targetNodeId:a.id,candidates:[{id:zt(e,"inherit-derived-state"),issueId:e,title:"Use the upstream-derived values",description:i,confidence:"choice",targetNodeId:a.id,operations:o.map(({nodeId:e,fieldId:t})=>({kind:"repair_block_derived_control",rootNodeId:a.id,sourceNodeId:e,fieldId:t}))}]})}for(let o of de(a.data.blockInstanceV2,e.modularBlockDefinitions??[])){if(!o.canRepair)continue;let n=e.nodes.find(({data:e,hidden:t})=>!t&&e.blockProjectionOwnerId===a.id&&e.blockProjectionNodeId===o.nodeId)?.id??a.id,i=zt("block-seed",a.id,o.nodeId);t.push({id:i,kind:"block_seed",title:"A saved seed is attached to a step that does not consume it",description:o.reason,targetNodeId:n,candidates:[{id:zt(i,"move-to-generator"),issueId:i,title:"Connect seed to its Generator consumer",description:o.reason,confidence:"choice",targetNodeId:n,operations:[{kind:"repair_block_seed",rootNodeId:a.id,sourceNodeId:o.nodeId}]}]})}}e.nodes.forEach(a=>{let o=function(e){if(!S(e))return null;try{return se([e],[]),null}catch(e){return e instanceof Error?e.message:String(e)}}(a);if(!o)return;let n=function(e,t,a){return a.filter(({data:t})=>t.blockProjectionOwnerId===e.id&&"string"==typeof t.blockProjectionNodeId).sort((e,t)=>String(t.data.blockProjectionNodeId).length-String(e.data.blockProjectionNodeId).length).find(({id:e,data:a})=>{let o=String(a.blockProjectionNodeId);return t.includes(e)||t.includes(`"${o}"`)||t.includes(`'${o}'`)||t.includes(` ${o}:`)||t.includes(` ${o}.`)||t.endsWith(` ${o}`)})?.id??e.id}(a,o,e.nodes),i=zt("block-structure",a.id,o);t.push({id:i,kind:"block_structure",title:`${a.data.label||"Block"} has invalid internal structure`,description:o,targetNodeId:n,candidates:[{id:zt(i,"restore-reviewed"),issueId:i,title:"Restore reviewed internal structure",description:"Restore the registered nodes and links for this workflow instance. Compatible custom additions are retained; incompatible structural edits are removed.",confidence:"choice",targetNodeId:n,operations:[{kind:"restore_block_structure",rootNodeId:a.id}]}]})}),e.edges.forEach(n=>{let i=a.get(n.source),d=a.get(n.target),r=n.sourceHandle??"",s=n.targetHandle??"",l=O(i,r),c=O(d,s);if(!(i&&d&&r&&s&&l&&c)){let e=zt("broken-link",n.id);return void t.push({id:e,kind:"broken_link",title:"Remove a broken connection",description:"One connection points to a node or socket that no longer exists.",targetNodeId:d?.id,targetHandle:s||void 0,candidates:[{id:zt(e,"remove"),issueId:e,title:"Remove broken link",description:"Delete only the invalid connection.",confidence:"safe",targetNodeId:d?.id,targetHandle:s||void 0,operations:[{kind:"remove_edges",edgeIds:[n.id]}]}]})}if(!_t(l,c)||!E(i.data,r,d.data,s)){let a=zt("type-mismatch",n.id),o=function(e,t,a,o,n,i,d,r,s){return a.data.blockProjectionOwnerId||i.data.blockProjectionOwnerId?[]:Object.entries(t.registry).flatMap(([e,t])=>{if("group"===t.type||"loop"===t.type)return[];let s=Pt({data:t}).filter(([e,i])=>_t(n,i)&&E(a.data,o,t,e)).map(([e,t],a)=>({handle:e,param:t,order:a,score:Dt(n,t)})).sort((e,t)=>t.score-e.score).slice(0,3);if(!s.length)return[];let l=Ot({data:t}).filter(([e,a])=>_t(a,r)&&E(t,e,i.data,d)).map(([e,t],a)=>({handle:e,param:t,order:a,score:Dt(t,r)})).sort((e,t)=>t.score-e.score).slice(0,3);return s.sort((e,t)=>e.order-t.order),l.sort((e,t)=>e.order-t.order),s.flatMap(({handle:a,param:o})=>l.map(({handle:n,param:i})=>({key:e,data:t,bridgeInput:a,bridgeInputParam:o,bridgeOutput:n,bridgeOutputParam:i})))}).map(({key:t,data:l,bridgeInput:c,bridgeInputParam:u,bridgeOutput:p,bridgeOutputParam:f})=>{let m=`@${zt(e,t,c,p)}`;return{score:Dt(n,u)+Dt(f,r)+qt({data:l},i),candidate:{id:zt(e,"bridge",t,c,p),issueId:e,title:`Insert ${l.label||Bt(t)}`,description:`Replace the incompatible link with a typed conversion through ${l.label||"this node"}.`,confidence:"choice",targetNodeId:i.id,targetHandle:d,operations:[{kind:"remove_edges",edgeIds:[s]},{kind:"add_node",ref:m,nodeKey:t,position:Ft("bridge",a,i)},{kind:"connect",source:{nodeId:a.id,handle:o},target:{nodeId:m,handle:c}},{kind:"connect",source:{nodeId:m,handle:p},target:{nodeId:i.id,handle:d}}]}}}).filter(e=>e.score>30).sort((e,t)=>t.score-e.score).slice(0,3).map(e=>e.candidate)}(a,e,i,r,l,d,s,c,n.id);return o.push({id:zt(a,"remove"),issueId:a,title:"Remove incompatible link",description:"Disconnect the mismatched sockets and leave the input highlighted for another fix.",confidence:"safe",targetNodeId:d.id,targetHandle:s,operations:[{kind:"remove_edges",edgeIds:[n.id]}]}),void t.push({id:a,kind:"type_mismatch",title:`${At(i,r)} cannot connect to ${At(d,s)}`,description:_t(l,c)?"The selected model or component does not satisfy the receiving socket’s declared capabilities.":`The sockets use incompatible types: ${St(l).join(" or ")} and ${St(c).join(" or ")}.`,targetNodeId:d.id,targetHandle:s,candidates:o.slice(0,3)})}o.add(`${d.id}:${s}`)});let n=Mt(e.nodes),i=n.filter(Rt),d=i.filter(t=>e.edges.some(e=>e.target===t.id&&a.has(e.source)));if(n.length>0&&0===d.length&&!n.some(Et)){let a="missing-output",o=function(e,t,a){let o=Mt(t.nodes),n=new Set(t.edges.map(e=>`${e.source}:${e.sourceHandle??""}`)),i=o.flatMap(e=>Ot(e).map(([t,a])=>({source:e,sourceHandle:t,sourceParam:a}))).filter(({source:e,sourceHandle:t})=>!n.has(`${e.id}:${t}`)).sort((e,t)=>Lt(t.sourceParam)-Lt(e.sourceParam)),d=a.flatMap(a=>Pt(a).flatMap(([o,n])=>i.filter(({source:e,sourceHandle:i,sourceParam:d})=>e.id!==a.id&&Gt(e,a)&&_t(d,n)&&E(e.data,i,a.data,o)&&!Vt(t.edges,a.id,e.id)).map(({source:t,sourceHandle:i,sourceParam:d})=>({score:Dt(d,n)+Lt(d),candidate:{id:zt(e,"connect-output",t.id,i,a.id,o),issueId:e,title:`Connect ${t.data.label||t.data.action} to ${a.data.label||a.data.action}`,description:`Send ${At(t,i)} to the existing output node.`,confidence:"safe",targetNodeId:a.id,targetHandle:o,operations:[{kind:"connect",source:{nodeId:t.id,handle:i},target:{nodeId:a.id,handle:o}}]}}))));return d.length?d.sort((e,t)=>t.score-e.score).slice(0,3).map(e=>e.candidate):Object.entries(t.registry).filter(([,e])=>Rt({data:e})).flatMap(([t,a])=>Pt({data:a}).flatMap(([o,n])=>i.filter(({source:e,sourceHandle:t,sourceParam:i})=>!e.data.blockProjectionOwnerId&&_t(i,n)&&E(e.data,t,a,o)).map(({source:i,sourceHandle:d,sourceParam:r})=>{let s=`@${zt(e,t,i.id)}`;return{score:Dt(r,n)+Lt(r),candidate:{id:zt(e,"add-output",t,i.id,d,o),issueId:e,title:`Add ${a.label||Bt(t)}`,description:`Create a visible output for ${At(i,d)}.`,confidence:"choice",targetNodeId:i.id,targetHandle:d,operations:[{kind:"add_node",ref:s,nodeKey:t,position:Ft("output",i,void 0)},{kind:"connect",source:{nodeId:i.id,handle:d},target:{nodeId:s,handle:o}}]}}}))).sort((e,t)=>t.score-e.score||e.candidate.title.localeCompare(t.candidate.title)).slice(0,3).map(e=>e.candidate)}(a,e,i);o.length&&t.push({id:a,kind:"missing_output",title:i.length?"Connect the graph output":"Add a graph output",description:i.length?"An output node exists, but no generated result reaches it.":"The graph needs a Preview, Save, or Export node to produce a usable result.",targetNodeId:i[0]?.id,candidates:o})}let r=new Set(i.map(e=>e.id));n.forEach(a=>{Pt(a).forEach(([n,i])=>{if(function(e,t){let a=e.data.blockInstanceV2;if(!S(e)||!a)return!1;let o=a.effectiveInterface.boundary.inputs.find(e=>e.portId===t);if(!o)return!1;let n=[o.binding,...o.mirrorBindings??[]];return a.effectiveInterface.controls.some(e=>[e.binding,...e.mirrorBindings??[]].some(e=>n.some(t=>t.nodeId===e.nodeId&&t.fieldOrPortId===e.fieldId)))}(a,n)||!Ht(n,i,!!a.data.skipParamsCheck)||o.has(`${a.id}:${n}`)||r.has(a.id)&&0===d.length)return;let s=zt("missing-input",a.id,n),l=function(e,t,a,o,n){let i=function(e,t,a,o,n){return Mt(t.nodes).flatMap(e=>Ot(e).map(([t,a])=>({source:e,sourceHandle:t,sourceParam:a}))).filter(({source:e,sourceHandle:i,sourceParam:d})=>e.id!==a.id&&Gt(e,a)&&_t(d,n)&&E(e.data,i,a.data,o)&&!Vt(t.edges,a.id,e.id)).map(({source:t,sourceHandle:i,sourceParam:d})=>({score:Dt(d,n)+qt(t,a)-Math.min(40,Math.hypot(t.position.x-a.position.x,t.position.y-a.position.y)/50),candidate:{id:zt(e,"connect",t.id,i),issueId:e,title:`Connect ${t.data.label||t.data.action}`,description:`Use its ${At(t,i)} output for ${At(a,o)}.`,confidence:100===Dt(d,n)?"safe":"choice",targetNodeId:a.id,targetHandle:o,operations:[{kind:"connect",source:{nodeId:t.id,handle:i},target:{nodeId:a.id,handle:o}}]}})).sort((e,t)=>t.score-e.score).map(e=>e.candidate)}(e,t,a,o,n),d=function(e,t,a,o,n){return a.data.blockProjectionOwnerId?[]:Object.entries(t.registry).flatMap(([e,t])=>Ot({data:t}).map(([a,o])=>({key:e,data:t,sourceHandle:a,sourceParam:o}))).filter(({data:e,sourceHandle:t,sourceParam:i})=>!("group"===e.type||"loop"===e.type||!_t(i,n)||!E(e,t,a.data,o)||Rt({data:e}))).map(({key:t,data:i,sourceHandle:d,sourceParam:r})=>{let s=`${t} ${i.label} ${i.category}`.toLowerCase(),l=St(n),c=l.some(e=>e.includes("pipeline"))&&/load|pipeline/.test(s)?50:0,u=l.some(e=>$t.has(e))&&/load|source|import/.test(s)?35:0,p=St(r).includes("any")?45:0,f=`@${zt(e,t)}`;return{score:Dt(r,n)+qt({data:i},a)+c+u-p,candidate:{id:zt(e,"add",t,d),issueId:e,title:`Add ${i.label||Bt(t)}`,description:`Add this compatible source and connect it to ${At(a,o)}.`,confidence:"choice",targetNodeId:a.id,targetHandle:o,operations:[{kind:"add_node",ref:f,nodeKey:t,position:Ft("producer",void 0,a)},{kind:"connect",source:{nodeId:f,handle:d},target:{nodeId:a.id,handle:o}}]}}}).filter(e=>e.score>15).sort((e,t)=>t.score-e.score||e.candidate.title.localeCompare(t.candidate.title)).map(e=>e.candidate)}(e,t,a,o,n);return[...i,...d].slice(0,3)}(s,e,a,n,i);l.length&&t.push({id:s,kind:"missing_input",title:`${a.data.label||a.data.action} needs ${At(a,n)}`,description:"Connect an existing compatible value or add a matching source node.",targetNodeId:a.id,targetHandle:n,candidates:l})})});let s=new Set;(e.readinessIssues??[]).forEach(e=>{if("block_media_input_missing"===e.code||"operation_media_input_missing"===e.code){let a=zt(e.code,e.id);return void t.push({id:a,kind:"missing_media",title:e.message,description:e.details??e.message,targetNodeId:e.nodeId,targetHandle:e.fieldId,candidates:[{id:zt(a,"inspect"),issueId:a,title:"Open required input",description:"Select the affected node and its controls. Choose the file yourself; no mask, prompt or connection is changed automatically.",confidence:"safe",targetNodeId:e.nodeId,targetHandle:e.fieldId,operations:[{kind:"external",action:"inspect_node",nodeId:e.nodeId}]}]})}if("modular_component_requirement"!==e.code&&"modular_runtime_failure"!==e.code)if(["environment","package","backend","hardware_fit"].includes(e.category)&&"open_setup"===e.action){let a=`${e.category}:${e.message}`;if(s.has(a))return;s.add(a);let o=zt(e.category,e.message),n="package"===e.category?"Repair backend packages":"backend"===e.category?"Reconnect or update the backend":"hardware_fit"===e.category?"Review hardware compatibility":"Repair the runtime environment";t.push({id:o,kind:"environment",title:n,description:e.message,candidates:[{id:zt(o,"setup"),issueId:o,title:"Open Setup",description:e.details||"Review the detected runtime mismatch and its exact repair command.",confidence:"safe",operations:[{kind:"external",action:"open_setup"}]}]})}else if("model"!==e.category&&"model_integrity"!==e.category||!e.repoId&&!e.modelPath){if("asset"===e.category&&"select_image"===e.action){let a=`missing_media:${e.nodeId??""}:${e.message}`;if(s.has(a))return;s.add(a);let o=zt("missing-media",e.nodeId,e.message);t.push({id:o,kind:"missing_media",title:"Choose the required media",description:e.message,targetNodeId:e.nodeId,candidates:[{id:zt(o,"assets"),issueId:o,title:"Open Gallery",description:"Choose an imported image, video, or audio file without changing the graph automatically.",confidence:"safe",targetNodeId:e.nodeId,operations:[{kind:"external",action:"open_assets",nodeId:e.nodeId}]}]})}}else{let a=`missing_model:${e.nodeId??""}:${e.repoId??e.modelPath}`;if(s.has(a))return;s.add(a);let o=zt("missing-model",e.nodeId,e.repoId,e.modelPath);t.push({id:o,kind:"missing_model",title:"Choose or install the required model",description:e.message,targetNodeId:e.nodeId,candidates:[{id:zt(o,"models"),issueId:o,title:"Open Models",description:"Review compatible installed models or explicitly install the required model.",confidence:"safe",targetNodeId:e.nodeId,operations:[{kind:"external",action:"open_model_manager",nodeId:e.nodeId,repoId:e.repoId}]}]})}else t.push({id:zt(e.code,e.nodeId??"",e.message),kind:"block_structure",title:"modular_runtime_failure"===e.code?"Review the failed Modular block":"Review component compatibility",description:`${e.message} ${e.details??""}`,targetNodeId:e.nodeId,candidates:[]})});let l=t.filter(e=>e.candidates.length>0);return{issues:t,candidateCount:l.reduce((e,t)=>e+t.candidates.length,0),canFix:l.length>0}}function Ut(e,t){return t.get(e)??e}function Kt(e,t){if(!t)return{nodes:[],edges:[]};let a=new Map,o=[];t.operations.forEach(n=>{if("add_node"!==n.kind)return;let i=Me(n.nodeKey,e.registry,n.position);if(!i)return;let d=`graph-fix-preview-${t.id}-${a.size}`,r={...i,id:d,className:"modiff-graph-fix-ghost",draggable:!1,selectable:!1,deletable:!1};r.data.label=`${r.data.label} preview`,a.set(n.ref,d),o.push(r)});let n=[...e.nodes,...o];return{nodes:o,edges:t.operations.flatMap((e,o)=>{if("connect"!==e.kind)return[];let i=Ut(e.source.nodeId,a),d=Ut(e.target.nodeId,a);return n.some(e=>e.id===i)&&n.some(e=>e.id===d)?[{id:`graph-fix-preview-edge-${t.id}-${o}`,source:i,sourceHandle:e.source.handle,target:d,targetHandle:e.target.handle,type:"default",selectable:!1,focusable:!1,className:"modiff-graph-fix-ghost"}]:[]})}}function Yt(e){return e?e.operations.flatMap(e=>"connect"===e.kind?[e.source,e.target]:[]):[]}var Xt=e({default:()=>Jt});function Zt(e,t,a){return e.issues.find(e=>e.id===t)?.candidates.find(e=>e.id===a)}function Jt(){let e=K(e=>e.dialogOpen),t=K(e=>e.closeDialog),a=K(e=>e.setPreviewCandidate),n=K(e=>e.setIssueTargets),{nodes:d,edges:r}=P(_(e=>({nodes:e.nodes,edges:e.edges}))),s=qe(e=>e.nodesRegistry),l=Q(e=>e.library?.blockDefinitions);(0,lt.useEffect)(()=>{e&&!Q.getState().loaded&&Q.getState().fetchLibrary()},[e]);let c=De(e=>e.edgeType),u=De(e=>e.setLeftPanelOpen),p=De(e=>e.setLeftPanelTabIndex),f=De(e=>e.setRightPanelOpen),m=De(e=>e.setRightPanelTab),h=De(e=>e.setModelManagerOpener),g=M(e=>e.saveActiveWorkflowTab),b=M(e=>e.graphBinding),x=Z(e=>e.sid),I=Z(e=>e.isConnected),k=Le({sid:x,isConnected:I,includeStudio:!!b}),v=(0,lt.useMemo)(()=>Wt({nodes:d,edges:r,registry:s,modularBlockDefinitions:l,readinessIssues:k.issues}),[r,d,k.issues,s,l]),y=v.issues.map(e=>`${e.id}:${e.candidates.map(e=>e.id).join(",")}`).join("|"),w=(0,lt.useRef)(v);w.current=v;let[j,$]=(0,lt.useState)({}),[N,C]=(0,lt.useState)(!1);(0,lt.useEffect)(()=>{if(!e)return;let t=w.current,o=function(e){let t=e.issues.map(e=>({issue:e,candidate:e.candidates.find(e=>"safe"===e.confidence&&e.operations.length>0&&e.operations.every(e=>"external"===e.kind))})).find(e=>e.candidate);return Object.fromEntries(e.issues.map(e=>[e.id,t?e.id===t.issue.id?t.candidate?.id??"":"":e.candidates.find(e=>"safe"===e.confidence)?.id??""]))}(t);$(o);let i=t.issues[0],d=i?Zt(t,i.id,o[i.id]??""):null;a(d??null),n(t.issues.flatMap(e=>e.targetNodeId?[{nodeId:e.targetNodeId,handle:e.targetHandle}]:[]))},[e,y,n,a]);let S=(e,t={})=>{if("inspect_node"===e){let e=De.getState();f(!0),m("studio");let a=P.getState();if(t.nodeId&&a.nodes.some(e=>e.id===t.nodeId)){a.onNodesChange(a.nodes.map(e=>({id:e.id,type:"select",selected:e.id===t.nodeId})));let o=M.getState().activeWorkflowTabId;o&&e.setWorkflowFocusRequest({workflowTabId:o,nodeId:t.nodeId,requestId:Date.now(),requestedAt:Date.now()})}return}if("open_setup"===e)return f(!0),void m("setup");u(!0),"open_assets"!==e?(p(3),h({nodeId:t.nodeId??null,fieldKey:null,focus:t.repoId?{repo:t.repoId,source:"graph"}:void 0})):p(2)},O=v.issues.map(e=>Zt(v,e.id,j[e.id]??"")).filter(e=>!!e),T=O.length>0&&O.every(e=>e.operations.every(e=>"external"===e.kind)),H=v.issues.filter(e=>!!j[e.id]).length,R=0===v.candidateCount;return(0,ct.jsx)(ne,{open:e,onClose:t,title:"Fix graph",description:R?"Review the issue and correct the named node or connection.":"Review proposed repairs before applying them. Graph changes can be undone.",testId:"graph-fix-dialog",panelClassName:"max-w-2xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:t,children:"Cancel"}),!R&&(0,ct.jsx)(be,{tone:"primary",icon:(0,ct.jsx)(i,{size:15}),disabled:0===H||N,loading:N,onClick:()=>{let e=O;if(e.length&&!N){C(!0);try{let a=e.filter(e=>e.operations.some(e=>"external"!==e.kind)),o=v.issues.filter(e=>a.some(t=>t.issueId===e.id)),n=P.getState(),i=Oe({nodes:n.nodes,edges:n.edges,registry:s,modularBlockDefinitions:l},e,c),d=a.length>0;d&&(P.getState().replaceGraph({nodes:i.nodes,edges:i.edges},{historyLabel:"Fix graph",clearRemovedCache:!1}),g(!0));let r=fe({sid:x,isConnected:I,includeStudio:!!b,showDialog:!1}),u=P.getState(),p=Wt({nodes:u.nodes,edges:u.edges,registry:s,modularBlockDefinitions:l,readinessIssues:r.issues}),f=d?o.filter(e=>p.issues.some(t=>function(e,t){return e.kind===t.kind&&(e.targetNodeId??null)===(t.targetNodeId??null)&&(e.targetHandle??null)===(t.targetHandle??null)}(e,t))):[];if(d&&f.length>0)throw Error(`The proposed change did not clear ${1===f.length?"the selected issue":`${f.length} selected issues`}. Review the updated graph before retrying.`);if(t(),i.externalActions.forEach(e=>S(e.action,{nodeId:e.nodeId,repoId:e.repoId})),d){let e=r.blocking.length;z(`${1===a.length?"Fix":`${a.length} fixes`} applied and verified.${e>0?` ${e} other blocking ${1===e?"issue remains":"issues remain"}.`:""} Undo is available.`,{variant:"success",autoHideDuration:3600})}}catch(e){z(e instanceof Error?e.message:"The graph changed before the fix could be applied.",{variant:"error",autoHideDuration:4200})}finally{C(!1)}}},"data-testid":"graph-fix-apply",children:T?O[0]?.title:"Apply "+(1===H?"fix":`${H} fixes`)})]}),children:0===v.issues.length?(0,ct.jsx)("div",{className:"rounded-modiff-panel border border-modiff-border bg-modiff-panel p-4 text-sm text-modiff-subtle-text",children:"No deterministic graph repair is currently available."}):(0,ct.jsxs)("div",{className:"grid gap-4",children:[(0,ct.jsx)("p",{className:"text-sm text-modiff-subtle-text",children:R?"No automatic repair is available. Your graph has not been changed.":T?"Review the detected issue and continue to the exact place where it can be resolved.":"Review the proposed connections. MoDiff will apply graph changes together as one undoable action."}),v.issues.map((e,t)=>(0,ct.jsxs)("section",{className:"rounded-modiff-panel border border-modiff-border bg-modiff-panel p-3","data-testid":`graph-fix-issue-${t}`,children:[(0,ct.jsxs)("div",{className:"flex items-start gap-2",children:[(0,ct.jsx)(o,{size:16,className:"mt-0.5 shrink-0 text-modiff-red"}),(0,ct.jsxs)("div",{className:"min-w-0",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:e.title}),(0,ct.jsx)("p",{className:"mt-0.5 text-xs text-modiff-subtle-text",children:e.description})]}),j[e.id]&&(0,ct.jsx)(be,{className:"ml-auto shrink-0","aria-label":`Skip ${e.title}`,onClick:()=>{$(t=>({...t,[e.id]:""})),a(null)},children:"Skip"})]}),0===e.candidates.length?(0,ct.jsx)("p",{className:"mt-3 text-xs text-modiff-subtle-text",children:"Manual correction required. No automatic graph change will be applied for this issue."}):(0,ct.jsx)(Ve,{className:"mt-3","aria-label":e.title,value:j[e.id]??"",options:e.candidates.map(e=>({value:e.id,label:e.title,description:e.description,meta:"safe"===e.confidence?"Direct":"Choice"})),onOptionPreview:t=>a(e.candidates.find(e=>e.id===t)??null),onValueChange:t=>{$(a=>({...a,[e.id]:t})),a(e.candidates.find(e=>e.id===t)??null)}})]},e.id))]})})}var Qt=(0,lt.lazy)(()=>F(()=>import(`./OperationOwnerControls.js?v=ca6b74e6a02eedb3`),[])),ea=(0,lt.memo)(e=>{let t=P(t=>t.nodes.find(t=>t.id===e.id)),a=(0,lt.useRef)(null),o=(0,lt.useRef)(null),n=(0,lt.useRef)(null),i=P(t=>he(t,e.id)),r=e.data.userBlockSnapshot,s=P(e=>e.toggleUserBlockExpanded),c=P(e=>e.setParamWithHistory),u=P(e=>e.replaceNodeParams),p=P(e=>e.setNodeSize),f=P(e=>e.beginHistoryTransaction),m=P(e=>e.commitHistoryTransaction),g=P(e=>e.setNodeUiState),v=P(e=>e.configureUserBlock),y=M(e=>e.workflowTabs.find(t=>t.id===e.activeWorkflowTabId)?.title||"Workflow"),w=P(e=>e.fitUserBlockToChildren),j=P(t=>t.nodes.filter(t=>t.data.userBlockInstanceId===e.id).map(e=>`${e.id}:${e.position.x}:${e.position.y}:${e.measured?.width??e.width??0}:${e.measured?.height??e.height??0}`).sort().join("|")),$=h(),N=x(),C=D(e.id,a),S=(0,lt.useMemo)(()=>r?ce(r,{x:0,y:0},e.id):null,[r,e.id]),_=S?.data.userBlockSnapshot??r,O=(0,lt.useMemo)(()=>{let t=S?.data.params;if(!t)return e.data.params;let a={...t};return Object.entries(e.data.params).forEach(([e,o])=>{let n=t[e];a[e]=n?{...n,...o,fieldOptions:{...n.fieldOptions??{},...o.fieldOptions??{}}}:o}),a},[S?.data.params,e.data.params]),H=(0,lt.useMemo)(()=>_?Be(_,O):[],[_,O]),E=(0,lt.useMemo)(()=>_?ae(_):[],[_]),[A,B]=(0,lt.useState)(null),[V,L]=(0,lt.useState)(!1),[q,F]=(0,lt.useState)(!1),[G,W]=(0,lt.useState)(!1),[K,Y]=(0,lt.useState)(null),[X,Z]=(0,lt.useState)(null),[J,ee]=(0,lt.useState)(null),oe=Q(e=>e.library),ie=(0,lt.useMemo)(()=>i?Ce(P.getState(),e.id):{valid:!0,issues:[],insertionSuggestions:[]},[P(t=>{if(!i)return"";let a=new Set(t.nodes.filter(t=>t.data.userBlockInstanceId===e.id).map(e=>e.id));return`${t.nodes.filter(e=>a.has(e.id)).map(e=>JSON.stringify([e.id,e.parentId,e.data.type,Object.entries(e.data.params??{}).map(([e,t])=>[e,t.type,t.display,t.isInput,t.hidden,"pipeline_class"===e||"workflow_id"===e?t.value??t.default:void 0])])).sort().join("|")}\n${t.edges.filter(e=>a.has(e.source)||a.has(e.target)).map(e=>`${e.id}:${e.source}:${e.sourceHandle??""}:${e.target}:${e.targetHandle??""}`).sort().join("|")}`}),i,e.id]),de=P(e=>e.insertNodeInUserBlock),re=(0,lt.useMemo)(()=>We(_,oe),[_,oe]),se=(0,lt.useCallback)((t,a,o)=>c(e.id,t,a,o),[e.id,c]),le=(0,lt.useCallback)(()=>{s(e.id),M.getState().saveActiveWorkflowTab(!0)},[e.id,s]),pe=(0,lt.useCallback)(async t=>{if(!G){W(!0);try{let a=await tt({instanceId:e.id,choice:t,workflowTitle:y});L(!1),z("update"===t?"Reusable Block updated. Existing workflow instances keep their embedded snapshots.":"new"===t?`Saved as new Block: ${a.name}`:"Changes kept only in this workflow.",{variant:"success",autoHideDuration:3200})}catch(e){z(e instanceof Error?e.message:"Could not save the Block changes.",{variant:"error",autoHideDuration:4200})}finally{W(!1)}}},[e.id,G,y]),fe=(0,lt.useCallback)(()=>{let e=o.current?.offsetHeight??44,t=n.current?.offsetHeight??0;return Math.ceil(e+t+96+4)},[]),xe=(0,lt.useCallback)(()=>{if(i)return;let t=fe(),a=P.getState().nodes.find(t=>t.id===e.id);!a||he(P.getState(),e.id)||(a.height??0)>=t||(P.setState(a=>({nodes:a.nodes.map(a=>a.id===e.id?{...a,height:t,data:{...a.data,uiState:{...a.data.uiState,blockCollapsedHeight:t}}}:a)})),$(e.id),C())},[fe,i,e.id,C,$]);(0,lt.useEffect)(()=>{$(e.id)},[i,e.id,$]),(0,lt.useLayoutEffect)(()=>{if(i||(xe(),typeof ResizeObserver>"u"))return;let e=null,t=!0,a=new ResizeObserver(()=>{!t||null!==e||(e=window.requestAnimationFrame(()=>{e=null,t&&xe()}))});return o.current&&a.observe(o.current),n.current&&a.observe(n.current),()=>{t=!1,a.disconnect(),null!==e&&window.cancelAnimationFrame(e)}},[i,xe]),(0,lt.useEffect)(()=>{if(!i||!j)return;let t=window.requestAnimationFrame(()=>{w(e.id),C()});return()=>window.cancelAnimationFrame(t)},[j,i,w,e.id,C]),(0,lt.useEffect)(()=>{Se(e.data.params,O)||u(e.id,O)},[O,e.data.params,e.id,u]);let Ie=(0,lt.useCallback)(t=>{t.preventDefault(),t.stopPropagation(),f("Resize block");let o=a.current?.clientWidth||e.width||340,n=a.current?.clientHeight||e.height||360,i=t.clientX,d=t.clientY,r=N.getState().transform[2]||1,s=fe(),l=o,c=n,u=t=>{l=Math.min(720,Math.max(280,o+(t.clientX-i)/r)),c=Math.max(s,n+(t.clientY-d)/r),p(e.id,Math.round(l),Math.round(c)),C()},h=()=>{document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",h),g(e.id,{blockCollapsedWidth:Math.round(l),blockCollapsedHeight:Math.round(c)}),m(),C()};document.addEventListener("mousemove",u),document.addEventListener("mouseup",h)},[f,fe,m,e.height,e.id,e.width,N,C,p,g]);return(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(R,{nodeId:e.id,label:e.data.label||_?.name||"Block",expanded:i,nodeRef:a,headerRef:o,connectorRef:n,onResizeStart:Ie,actions:(0,ct.jsxs)(ct.Fragment,{children:[i?(0,ct.jsx)(_e,{className:T("nodrag nowheel",ie.valid?"text-modiff-green":"text-modiff-red"),size:"compact",label:ie.valid?"Inspect Block composition":`Inspect Block composition: ${ie.issues.length} issue${1===ie.issues.length?"":"s"}`,onClick:()=>F(!0),"data-testid":`user-block-composition-${e.id}`,children:(0,ct.jsx)(d,{size:15})}):null,(0,ct.jsx)(_e,{className:"nodrag nowheel",size:"compact",label:"Save Block changes",onClick:()=>L(!0),"data-testid":`user-block-save-choices-${e.id}`,children:(0,ct.jsx)(l,{size:15})}),(0,ct.jsx)(_e,{className:"nodrag nowheel",size:"compact",label:"Configure block instance",onClick:()=>{_&&B({name:_.name,inputLabels:Object.fromEntries(_.inputs.map(e=>[e.id,e.label])),outputLabels:Object.fromEntries(_.outputs.map(e=>[e.id,e.label])),exposedParamIds:new Set(_.exposedParams.map(e=>e.id))})},"data-testid":`user-block-configure-${e.id}`,children:(0,ct.jsx)(b,{size:15})}),(0,ct.jsx)(_e,{className:"nodrag nowheel",size:"compact",label:i?"Collapse block":"Expand block",onClick:le,"data-testid":`user-block-toggle-${e.id}`,children:i?(0,ct.jsx)(k,{size:16}):(0,ct.jsx)(I,{size:16})})]}),controls:(0,ct.jsxs)("div",{className:"grid gap-2","data-testid":`user-block-disclosures-${e.id}`,children:[(0,ct.jsx)(lt.Suspense,{fallback:(0,ct.jsx)("p",{role:"status",children:"Loading model controls…"}),children:t?(0,ct.jsx)(Qt,{node:t}):null}),H.map(t=>(0,ct.jsxs)("section",{"data-block-source-node":t.id,children:[Object.keys(t.controlParams).length>0?(0,ct.jsx)(ue,{label:t.label,"data-testid":`user-block-disclosure-${e.id}-${t.id}`,className:"rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg/60",buttonClassName:"min-h-8 text-xs",panelClassName:"grid gap-2 border-t border-modiff-border-subtle p-2",children:(0,ct.jsx)(He,{nodeId:e.id,params:t.controlParams,updateStore:se,module:t.module,action:t.action,mode:"controls"})}):null,Object.keys(t.previewParams).length>0?(0,ct.jsxs)("div",{className:"mt-2 overflow-hidden rounded-modiff-compact border border-modiff-border-subtle bg-modiff-bg p-2","data-testid":`user-block-preview-${e.id}-${t.id}`,children:[(0,ct.jsx)("div",{className:"mb-2 truncate text-xs font-semibold text-modiff-subtle-text",children:t.label}),(0,ct.jsx)(He,{nodeId:e.id,params:t.previewParams,updateStore:se,module:t.module,action:t.action,mode:"controls"})]}):null]},t.id))]}),connectors:(0,ct.jsx)(He,{nodeId:e.id,params:O,updateStore:se,module:e.data.module,action:e.data.action,mode:"connectors"})}),(0,ct.jsx)(ne,{open:q,onClose:()=>F(!1),title:"Block composition",testId:`user-block-composition-dialog-${e.id}`,panelClassName:"max-w-2xl",footer:(0,ct.jsx)(be,{onClick:()=>F(!1),children:"Close"}),children:(0,ct.jsxs)("div",{className:"grid gap-4 text-sm",children:[(0,ct.jsxs)("section",{className:"grid gap-1",children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Execution contract"}),(0,ct.jsx)("p",{className:"text-modiff-subtle-text",children:"This editable instance executes as an ordinary MoDiff graph. Socket types, container ownership, and sealed Modular workflow-state identity are checked before execution."}),"diffusers"===_?.origin?.provider?(0,ct.jsxs)("p",{className:"text-modiff-subtle-text",children:["Upstream identity: ",_.origin.definitionId||"imported Diffusers definition"," at"," ",_.origin.libraryRevision||_.origin.revision||"its pinned revision",". Ordinary node edits do not claim upstream block-tree parity; reviewed Modular block edits are rebuilt through Diffusers ",(0,ct.jsx)("code",{children:"init_pipeline()"}),"."]}):null]}),(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`user-block-composition-issues-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:ie.valid?"No structural connection issues found":`${ie.issues.length} structural issue${1===ie.issues.length?"":"s"}`}),ie.issues.map(e=>(0,ct.jsx)("div",{className:"rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/10 px-3 py-2 text-modiff-text",children:e.message},e.id))]}),(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`user-block-insertion-suggestions-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Compatible insertion points"}),ie.insertionSuggestions.length?ie.insertionSuggestions.slice(0,12).map(t=>(0,ct.jsxs)("div",{className:"flex items-center justify-between gap-3 rounded-modiff-compact border border-modiff-border bg-modiff-bg px-3 py-2",children:[(0,ct.jsx)("span",{className:"min-w-0 flex-1 text-modiff-subtle-text",children:t.label}),(0,ct.jsx)(be,{tone:"primary",onClick:()=>{try{de(e.id,t),M.getState().saveActiveWorkflowTab(!0),z("The node was inserted into the compatible execution path.",{variant:"success",autoHideDuration:2600})}catch(e){z(e instanceof Error?e.message:"The compatible insertion point is unavailable.",{variant:"error",autoHideDuration:3600})}},children:"Insert"})]},t.id)):(0,ct.jsx)("p",{className:"text-modiff-subtle-text",children:"No disconnected node currently has both an input and output that can safely replace an existing typed connection."})]}),re?(0,ct.jsxs)("section",{className:"grid gap-2","data-testid":`reviewed-modular-composition-${e.id}`,children:[(0,ct.jsx)("div",{className:"font-semibold text-modiff-text",children:"Reviewed upstream Modular blocks"}),(0,ct.jsxs)("p",{className:"text-modiff-subtle-text",children:["These actions validate an upstream block-tree modification against the exact pinned Diffusers definition. The backend applies the edit to ",(0,ct.jsx)("code",{children:"sub_blocks"})," and rebuilds its interface through"," ",(0,ct.jsx)("code",{children:"init_pipeline()"}),". The receipt is structural and does not silently replace this ordinary User Node execution graph."]}),(0,ct.jsx)("div",{className:"max-h-52 overflow-y-auto rounded-modiff-compact border border-modiff-border",children:re.definition.blockPlacements.map(e=>{let t=e.path.join(".");return(0,ct.jsxs)("div",{className:"flex items-center justify-between gap-3 border-b border-modiff-border px-3 py-2 last:border-b-0",children:[(0,ct.jsx)("span",{className:"min-w-0 flex-1 truncate text-modiff-subtle-text",children:t}),(0,ct.jsx)(be,{disabled:!!K,onClick:()=>{Y(t),ee(null),te(me(re,e.path)).then(e=>Z(e)).catch(e=>ee(e instanceof Error?e.message:"Could not rebuild the Modular composition.")).finally(()=>Y(null))},children:K===t?"Rebuilding…":"Validate duplicate"})]},t)})}),X?(0,ct.jsxs)("div",{className:"rounded-modiff-compact border border-modiff-green/40 bg-modiff-green/10 px-3 py-2 text-modiff-text","data-testid":`reviewed-modular-composition-receipt-${e.id}`,children:["Upstream ",(0,ct.jsx)("code",{children:"init_pipeline()"})," rebuild passed: ",X.composedPaths.length," ","block paths, ",X.inputs.length," inputs,"," ",X.outputs.length," outputs. Receipt"," ",X.receiptHash.slice(0,20),"…"]}):null,J?(0,ct.jsx)("div",{className:"rounded-modiff-compact border border-modiff-red/40 bg-modiff-red/10 px-3 py-2 text-modiff-text",children:J}):null]}):null]})}),(0,ct.jsx)(ne,{open:V,onClose:()=>{G||L(!1)},title:"Save Block changes",testId:`save-user-block-choices-${e.id}`,panelClassName:"max-w-lg",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{disabled:G,onClick:()=>{pe("workflow")},children:"Keep only in this workflow"}),(0,ct.jsx)(be,{disabled:G,onClick:()=>{pe("new")},children:"Save as new Block"}),(0,ct.jsx)(be,{tone:"primary",disabled:G,onClick:()=>{pe("update")},children:"Update existing Block"})]}),children:(0,ct.jsxs)("div",{className:"grid gap-3 text-sm text-modiff-subtle-text",children:[(0,ct.jsx)("p",{children:"The current topology, parameters, exposed ports, and model revision have been captured."}),(0,ct.jsxs)("p",{children:["Updating changes the reusable library definition but does not silently rewrite other workflow instances. Saving as new defaults to"," ",(0,ct.jsx)("strong",{children:U(_?.name||"Block",y)}),"."]})]})}),(0,ct.jsx)(ne,{open:!!A,onClose:()=>B(null),title:"Configure block instance",testId:`configure-user-block-${e.id}`,panelClassName:"max-w-xl",footer:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(be,{onClick:()=>B(null),children:"Cancel"}),(0,ct.jsx)(be,{tone:"primary",disabled:!A?.name.trim(),onClick:()=>{A&&(v(e.id,A),B(null))},children:"Apply"})]}),children:A&&_?(0,ct.jsxs)("div",{className:"grid gap-4",children:[(0,ct.jsx)(Te,{label:"Name",required:!0,children:(0,ct.jsx)(ge,{value:A.name,onChange:e=>{let t=e.currentTarget.value;B(e=>e&&{...e,name:t})}})}),_.inputs.map(e=>(0,ct.jsx)(Te,{label:`Input: ${e.label}`,children:(0,ct.jsx)(ge,{value:A.inputLabels[e.id]??e.label,onChange:t=>{let a=t.currentTarget.value;B(t=>t&&{...t,inputLabels:{...t.inputLabels,[e.id]:a}})}})},`input-${e.id}`)),_.outputs.map(e=>(0,ct.jsx)(Te,{label:`Output: ${e.label}`,children:(0,ct.jsx)(ge,{value:A.outputLabels[e.id]??e.label,onChange:t=>{let a=t.currentTarget.value;B(t=>t&&{...t,outputLabels:{...t.outputLabels,[e.id]:a}})}})},`output-${e.id}`)),E.length>0?(0,ct.jsxs)("section",{className:"grid gap-2",children:[(0,ct.jsx)("h3",{className:"text-sm font-semibold text-modiff-text",children:"Editable parameters"}),E.map(e=>(0,ct.jsx)(we,{label:e.label,checked:A.exposedParamIds.has(e.id),onCheckedChange:t=>B(a=>{if(!a)return a;let o=new Set(a.exposedParamIds);return t?o.add(e.id):o.delete(e.id),{...a,exposedParamIds:o}})},e.id))]}):null]}):null})]})});ea.displayName="UserBlockNode";var ta=/(?:ModelsLoader|LoadPipeline|LoadModel|LoadTokenizer|LoadTextEncoder)$/u;function aa(e,t){let a=e.data.params[t];return void 0===a?.value?a?.default:a.value}function oa(e){let t=aa(e,"repo_id")??aa(e,"model_id");return t&&"object"==typeof t&&"value"in t?"string"==typeof t.value?t.value:"":"string"==typeof t?t:""}function na(e){let t=aa(e,"offload_mode")??(aa(e,"auto_offload")?"Auto Offload enabled":"Auto Offload disabled");return`${oa(e)||e.data.label||e.id} · ${aa(e,"dtype")??"runtime dtype"} · ${aa(e,"device")??"runtime device"} · ${t}`}function ia(e,t,a){let o=e.find(e=>e.id===a);if(a&&!o?.data.blockInstanceV2&&!o?.data.blockProjectionContainer)throw Error("Select a Block to assess its contained graph.");let n=se(e,t,a),i=ke(n.nodes),d=new Set(i.map(e=>e.id)),r=n.edges.filter(e=>d.has(e.source)&&d.has(e.target)),s=Pe(e,t).nodes.filter(e=>e.data.blockInstanceV2),l=i.filter(e=>ta.test(e.data.action??"")),c=i.filter(e=>/lora|adapter/iu.test(`${e.data.action} ${e.data.module}`)),u=new Set,p=[],f=[],m=e=>{let t=new Set(e);for(let e=!0;e;){e=!1;for(let a of r)t.has(a.source)&&!t.has(a.target)&&(t.add(a.target),e=!0)}return t.size-e.length};for(let e of s){let t=e.data.blockInstanceV2,a=new Set(t.effectiveGraph.nodes.map(t=>xe(e.id,t.nodeId))),n=l.filter(e=>a.has(e.id));if(!n.length)continue;n.forEach(e=>u.add(e.id));let d=[],s=ve(t,"auto")??Ee(t),c=s?{...s.form,resourceMode:"auto"}:null;1!==n.length&&(c=null,d.push("This Block has multiple model loaders. Its combined recipe needs a workflow resource contract.")),o?.data.blockProjectionContainer&&(c=null,d.push("This nested scope differs from its full source recipe; the full Block estimate cannot be reused."));let p=n[0];if(c){let e=oa(p),t=aa(p,"model_type");(e&&e!==c.modelRepo||t&&t!==c.modelType)&&(c=null,d.push("The actual loader differs from the source recipe. Its resource plan must be reviewed separately."))}if(c)for(let[e,t]of Object.entries({device:"device",dtype:"dtype",offload_mode:"offloadMode",auto_offload:"autoOffload",quantization_mode:"quantizationMode"})){let a=aa(p,e);void 0!==a&&typeof a==typeof c[t]&&(c[t]=a)}let h=r.filter(e=>a.has(e.target)&&!a.has(e.source));for(let e of h){let t=i.find(t=>t.id===e.source);d.push(`Connected input: ${t?.data.label??e.source} → ${e.targetHandle??"input"}. Its computed value is resolved when the graph runs.`)}"structure_changed"===t.customization.state&&d.push("Internal graph edits are present. The source model estimate does not qualify the edited recipe."),s||d.push("No exact resource planning form is available for this saved or custom Block."),f.push({id:e.id,label:e.data.label??t.definitionSnapshot.displayName,form:c,loaderIds:n.map(e=>e.id),consumers:m(n.map(e=>e.id)),details:[...new Set(d)],currentSettings:n.map(na)})}for(let e of l.filter(e=>!u.has(e.id)))f.push({id:e.id,label:e.data.label??e.id,form:null,loaderIds:[e.id],consumers:m([e.id]),details:["Use Check Auto execution plan for this standalone loader."],currentSettings:[na(e)]});(l.length>1||c.length)&&p.push("Check Auto execution plan for the combined model and adapter memory budget.");let h=Ge(e,t,a);return{key:W({target:a??null,owners:s.flatMap(e=>{let t=e.data.blockInstanceV2,a=t.effectiveGraph.nodes.filter(t=>d.has(xe(e.id,t.nodeId)));return a.length?[{id:e.id,definition:t.definitionRef,members:a}]:[]}),nodes:i.map(e=>({id:e.id,module:e.data.module,action:e.data.action,params:Object.fromEntries(Object.entries(e.data.params).filter(([,e])=>"output"!==e.display).map(([e,t])=>[e,{value:void 0===t.value?t.default??null:t.value,type:t.type??null}]))})),edges:r.map(({source:e,target:t,sourceHandle:a,targetHandle:o})=>({source:e,target:t,sourceHandle:a??null,targetHandle:o??null}))}),scopeLabel:o?.data.label??"Whole workflow",items:f,issues:p,autoReason:h.reason,autoEligible:h.eligible,nodeCount:i.length,loaderCount:l.length,adapterCount:c.length}}async function da(e,t){let a=e.items.filter(e=>e.form),[o,n]=await Promise.all([a.length?G(a.map(e=>e.form),a.map(e=>e.id),t):Promise.resolve([]),C(t)]),i={};for(let e of o){let t=a.find(t=>t.id===e.planKey);if(!t||i[t.id])throw Error("Resource assessment returned an unmatched or duplicate Block plan.");i[t.id]=e}if(Object.keys(i).length!==a.length)throw Error("Resource assessment returned an incomplete set of Block plans.");return{request:e,plans:i,resources:n}}var ra=[{value:"studio",label:"Studio",Icon:p},{value:"block",label:"Block",Icon:b},{value:"compatibility",label:"Compatibility",Icon:r},{value:"queue",label:"Queue",Icon:s},{value:"setup",label:"Setup",Icon:b},{value:"app",label:"Run as app",Icon:a}];function sa(){let e=pe(e=>e.target),t=De(e=>e.rightPanelTab),a=De(e=>e.setRightPanelTab),o=M(e=>e.appModeConfigs),n=P(e=>e.nodes.some(e=>/preview|save|output|video|audio|image/i.test(`${e.data?.label??""} ${e.id}`))),i=ra.filter(a=>"studio"===a.value||"block"===a.value&&!!e||"queue"===a.value||"setup"===a.value||"compatibility"===a.value&&"compatibility"===t),d=ra.filter(e=>"app"===e.value&&(o.length>0||n)),r=d.find(e=>e.value===t),s=r?[...i,r]:i,l=s.some(e=>e.value===t)?t:"studio";return(0,lt.useEffect)(()=>{l!==t&&a(l)},[l,t,a]),(0,ct.jsxs)("div",{className:"flex h-full flex-col","data-testid":"workspace-panel",children:[(0,ct.jsxs)("div",{"aria-label":"Workspace panels",className:"flex min-h-[42px] flex-none overflow-x-auto overflow-y-hidden border-b border-modiff-border bg-modiff-bg",onWheel:Fe,children:[(0,ct.jsx)(q,{"aria-label":"Workspace panels",className:"min-w-0 flex-1 flex-nowrap gap-0",value:l,onValueChange:a,options:s.map(e=>{let t=e.Icon;return{value:e.value,id:`workspace-tab-${e.value}`,controls:`workspace-panel-${e.value}`,label:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(t,{size:15}),(0,ct.jsx)("span",{children:e.label})]}),testId:`workspace-tab-${e.value}`,className:"h-[42px] min-w-[72px] flex-none justify-center gap-1.5 rounded-none px-2 text-xs"}})}),d.length>0&&(0,ct.jsx)("div",{className:"flex h-[42px] flex-none items-center px-1","data-testid":"workspace-tabs-more",children:(0,ct.jsx)(V,{label:(0,ct.jsxs)(ct.Fragment,{children:[(0,ct.jsx)(m,{size:16}),(0,ct.jsx)("span",{className:"sr-only",children:"More panels"})]}),children:d.map(e=>{let t=e.Icon;return(0,ct.jsxs)($,{active:l===e.value,onClick:()=>a(e.value),children:[(0,ct.jsx)(t,{size:15}),(0,ct.jsx)("span",{children:e.label})]},e.value)})})})]}),s.filter(e=>e.value!==l).map(e=>(0,ct.jsx)("div",{id:`workspace-panel-${e.value}`,role:"tabpanel","aria-labelledby":`workspace-tab-${e.value}`,hidden:!0},e.value)),(0,ct.jsxs)("div",{id:`workspace-panel-${l}`,role:"tabpanel","aria-labelledby":`workspace-tab-${l}`,className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden",children:["studio"===l&&(0,ct.jsx)(ot,{}),"block"===l&&(0,ct.jsx)(rt,{}),"compatibility"===l&&(0,ct.jsx)(nt,{}),"queue"===l&&(0,ct.jsx)(at,{}),"setup"===l&&(0,ct.jsx)(it,{}),"app"===l&&(0,ct.jsx)(dt,{})]})]})}var la=e({applyRuntimeWorkflowAutoSettingsV2:()=>Ia,applyWorkflowAutoSettingsV2:()=>xa,fetchWorkflowAutoPlanV2:()=>fa,inspectWorkflowAutoPlanV2:()=>ma,parseWorkflowAutoPlanV2:()=>pa,prepareWorkflowAutoExecutionV2:()=>ba}),ca=e=>!(!e||"object"!=typeof e||Array.isArray(e)),ua=e=>Array.isArray(e)&&e.every(e=>"string"==typeof e);function pa(e){if(!ca(e)||1!==e.schemaVersion||"boolean"!=typeof e.canAutoRun||!ua(e.issues)||"string"!=typeof e.message||![e.graphHash,e.plannedGraphHash].every(e=>"string"==typeof e&&/^sha256:workflow-auto-v1:[a-f0-9]{64}$/u.test(e))||!Array.isArray(e.patches)||!e.patches.every(e=>ca(e)&&"string"==typeof e.nodeId&&("auto_offload"===e.field&&"boolean"==typeof e.value||"offload_mode"===e.field&&"string"==typeof e.value))||!Array.isArray(e.loaders)||!e.loaders.every(e=>ca(e)&&["nodeId","modelType","repository","candidateId"].every(t=>"string"==typeof e[t])&&ua(e.consumers))||!ca(e.requirements)||!Object.values(e.requirements).every(e=>"number"==typeof e&&Number.isFinite(e)&&e>=0)||!ca(e.available)||!Object.values(e.available).every(e=>null===e||"number"==typeof e&&Number.isFinite(e)&&e>=0)||"boolean"!=typeof e.sharedMemory||void 0!==e.requiresPreparation&&"boolean"!=typeof e.requiresPreparation||void 0!==e.preparationNodeIds&&!ua(e.preparationNodeIds)||e.canAutoRun&&e.issues.length||!e.canAutoRun&&e.patches.length)throw Error("The backend returned an invalid workflow Auto plan.");return e}async function fa(e,t){return w(`${ye.serverAddress}/auto_resource/workflow`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schemaVersion:1,graph:{nodes:e.nodes,paths:e.paths,...e.loops?{loops:e.loops}:{}}}),timeoutMs:12e4,signal:t,parse:pa})}async function ma(e,t){let a=P.getState(),{prepareLegacyGraphForAutoV2:o}=await F(async()=>{let{prepareLegacyGraphForAutoV2:e}=await import(`./studio-templates.js?v=ca6b74e6a02eedb3`).then(e=>e.Kn);return{prepareLegacyGraphForAutoV2:e}},[]),n=o(a.nodes,a.edges,e),i=a.exportGraph("",e?n.remapped.get(e)??e:void 0,{randomizeSeeds:!1,sourceGraph:n});return n.nodes.some(e=>e.data.blockInstanceV2?.effectiveGraph.nodes.some(e=>"upstream_block"===e.modularDiffusers?.kind))?fa((await(await F(async()=>{let{prepareModularCompositionExecutionV2:e}=await import(`./studio-templates.js?v=ca6b74e6a02eedb3`).then(e=>e.g);return{prepareModularCompositionExecutionV2:e}},[])).prepareModularCompositionExecutionV2(a,n.nodes))(i),t):fa(i,t)}function ha(){let e=P.getState().toObject();return W({nodes:e.nodes.map(e=>({id:e.id,data:e.data})),edges:e.edges})}function ga(e){let t=new Map(e.effectiveInterface.controls.map(e=>[e.controlId,[e.binding,...e.mirrorBindings??[]]]));for(let a of e.effectiveInterface.boundary.inputs)t.has(a.portId)||t.set(a.portId,[a.binding,...a.mirrorBindings??[]].map(({nodeId:e,fieldOrPortId:t})=>({nodeId:e,fieldId:t})));return[...t].map(([e,t])=>({logicalId:e,bindings:t}))}async function ba(e,t){let a,o=M.getState().activeWorkflowTabId,n=ha(),i=()=>o===M.getState().activeWorkflowTabId&&n===ha()&&"auto"===M.getState().form.resourceMode;try{if(a=await fa(e),!i())throw Error("The workflow or mode changed while Auto was planning. Run again with the current graph.");if(!a.canAutoRun)throw Error(`Auto cannot run this workflow: ${a.issues.join(" ")}`)}catch(e){throw i()&&j.getState().showIssues([{id:"workflow-auto-planning",category:"hardware_fit",severity:"error",blocking:!0,message:A(e,"Workflow memory planning failed."),details:"No run was submitted. Review the requirements and model/memory settings, then Run again for a fresh plan."}]),e}let d=xa(e,a.patches,t),r=P.getState().nodes.flatMap(e=>{let t=e.data.blockInstanceV2;return t?ga(t).flatMap(({bindings:t})=>t.length<2||!t.every(e=>"offload_mode"===e.fieldId||"auto_offload"===e.fieldId)?[]:[t.map(t=>({nodeId:xe(e.id,t.nodeId),field:t.fieldId}))]):[]});return{...d,runtimeHints:{workflowAutoPlan:{schemaVersion:1,graphHash:a.plannedGraphHash,...r.length?{resourceControlGroups:r}:{}},resourceMode:"auto"}}}function xa(e,t,a){let o=structuredClone(e);P.getState().beginHistoryTransaction("Apply workflow Auto resource settings");try{a&&P.setState({nodes:a.nodes,edges:a.edges});let n=new Set;for(let a of t){let i=`${a.nodeId}.${a.field}`,d=o.nodes[a.nodeId]?.params[a.field];if(n.has(i)||!d||d.sourceId)throw Error("The Auto plan targets a missing, connected or repeated resource field.");n.add(i),d.value=a.value;let r=P.getState(),s=r.nodes.find(e=>e.data.blockInstanceV2?.effectiveGraph.nodes.some(t=>xe(e.id,t.nodeId)===a.nodeId));if(!s?.data.blockInstanceV2){if(!r.nodes.some(e=>e.id===a.nodeId))throw Error("The loader is inside an older Block. Move it into a current Block before applying Auto settings.");r.setParamWithHistory(a.nodeId,a.field,a.value);continue}let l=s.data.blockInstanceV2,c=l.effectiveGraph.nodes.find(e=>xe(s.id,e.nodeId)===a.nodeId),u=ga(l).filter(e=>e.bindings.some(e=>e.nodeId===c.nodeId&&e.fieldId===a.field));if(u.length){for(let o of u.flatMap(e=>e.bindings)){let n=xe(s.id,o.nodeId),i=e.nodes[n]?.params[o.fieldId],d=t.find(e=>e.nodeId===n&&e.field===o.fieldId);if(!i||i.sourceId||(d?.value??i.value)!==a.value)throw Error("A shared resource control would change a node outside this Auto plan. Configure that control separately.")}for(let e of u)r.setBlockInstanceValueV2(s.id,e.logicalId,a.value)}else{let e=structuredClone(l.effectiveGraph),t=e.nodes.find(e=>e.nodeId===c.nodeId).data.params;t[a.field]={...t[a.field],value:a.value};let o=je(Re(le(l,e),{selected:s.selected}));P.setState({nodes:[...r.nodes.filter(e=>e.id!==s.id&&e.data.blockProjectionOwnerId!==s.id),...o.nodes],edges:[...r.edges.filter(e=>e.data?.blockProjectionOwnerId!==s.id),...o.edges]})}}P.getState().commitHistoryTransaction()}catch(e){throw P.getState().cancelHistoryTransaction(),e}return o}function Ia(e){let t=P.getState().exportGraph("",void 0,{randomizeSeeds:!1});for(let a of e){let e=t.nodes[a.nodeId]?.params[a.field];if(!e||e.sourceId||(e.value??null)!==(a.previousValue??null))throw Error("The run changed resource settings, but your newer workflow edits were preserved. The run details show the settings used.")}xa(t,e)}export{ea as a,yt as c,st as d,ia as i,kt as l,sa as n,Xt as o,da as r,jt as s,la as t,It as u}; \ No newline at end of file diff --git a/web/assets/connectEncodingNode.js b/web/assets/connectEncodingNode.js index b2ca536..4479cfc 100644 --- a/web/assets/connectEncodingNode.js +++ b/web/assets/connectEncodingNode.js @@ -1 +1 @@ -import{Ei as e,Io as t,Jo as o,Po as n,Si as r,Ti as i,Vr as a,Wo as d,Ys as s,sc as c}from"./studio-templates.js?v=cc046c26d6fe7aa4";import{n as p,t as l}from"./operationGraphTransaction.js?v=cc046c26d6fe7aa4";import{t as g}from"./operationStarterRequest.js?v=cc046c26d6fe7aa4";import{r as h}from"./operationAuthoring.js?v=cc046c26d6fe7aa4";import{n as u}from"./encodingImageRoute.js?v=cc046c26d6fe7aa4";function f(e,o,n,r){let i=t(o.targetHandle)?o.target:o.source,a=u(e.nodes.find(e=>e.id===i)?.data.blockInstanceV2,n,r);if(!a)throw Error("This model has no unambiguous supported image encoder for this connection. Nothing changed.");let s=d(e,i);if(1!==s.length)throw Error("Connect Encode Inputs to one model loader before connecting its image encoding ports. Nothing changed.");return{encodingId:i,operation:a,owner:s[0]}}function m(e,o,r,i){if(i.pipelineClass!==r.operation.pipelineClass||i.task!==r.operation.task)throw Error("The image encoding route changed. Nothing changed.");let a=h(e,r.owner.id,i,{preserveValues:!0});if(a.review.required)throw Error(`Cannot connect without changing existing work: ${a.review.attention.join(" ")} Nothing changed.`);let d=a.graph;function p(e,o,n){if(!o)throw Error("The connection is missing a socket.");if(!t(o))return{id:a.replacements[e]??e,handle:o};let i=d.nodes.find(t=>t.id===e)?.data.blockInstanceV2,s=o.slice(o.indexOf(":")+1),c=i?.effectiveInterface.boundary["input"===n?"inputs":"outputs"].filter(e=>e.binding.fieldOrPortId===s&&i.effectiveGraph.nodes.some(t=>t.nodeId===e.binding.nodeId&&t.data.operationAuthoring?.operation?.operationId===r.operation.operationId));if(1!==c?.length)throw Error("The prepared encoder does not expose the selected socket. Nothing changed.");return{id:e,handle:c[0].portId}}let l=p(o.source,o.sourceHandle,"output"),g=p(o.target,o.targetHandle,"input"),u=n(d.nodes.find(e=>e.id===l.id),l.handle),f=n(d.nodes.find(e=>e.id===g.id),g.handle);if(!u||!f||"output"!==u.display||"input"!==f.display&&!f.isInput||!s(u.type,f.type))throw Error("These sockets are no longer compatible. Nothing changed.");d.edges=d.edges.filter(e=>e.target!==g.id||e.targetHandle!==g.handle),d.edges.push({id:`edge-${c()}`,source:l.id,sourceHandle:l.handle,target:g.id,targetHandle:g.handle,type:"default"});let m=new Set,w=[g.id];for(;w.length;){let e=w.pop();if(e===l.id)throw Error("That connection would create a cycle. Nothing changed.");if(!m.has(e)){m.add(e);for(let t of d.edges)t.source===e&&w.push(t.target)}}return d}function w(e){let t=e.data.params.execution_profile_id?.value??e.data.params.execution_profile_id?.default;if(!o(e))throw Error("The model loader no longer exists.");return"string"==typeof t&&t?t:void 0}async function I(t,o,n){let d=e(),s=a.getState().toObject(),c=p(s);o&&s.nodes.push(o);let h=r.getState(),u=f(s,t,h.operationContracts,h.pipelineSupport),I=await g(u.operation.pipelineClass,u.operation.task,h.operationContracts,n,w(u.owner));if(!n?.aborted){if(i(d,{includeForm:!1}),p(a.getState().toObject())!==c)throw Error("The workflow changed while preparing this connection. Connect again. Nothing changed.");l(m(s,t,u,I),d,c,"Connect encoding input/output")}}export{I as connectEncodingNode}; \ No newline at end of file +import{Di as e,Hr as t,Io as o,Oi as n,Qs as r,Ro as i,Zo as a,qo as d,uc as s,wi as c}from"./studio-templates.js?v=ca6b74e6a02eedb3";import{n as p,t as l}from"./operationGraphTransaction.js?v=ca6b74e6a02eedb3";import{t as g}from"./operationStarterRequest.js?v=ca6b74e6a02eedb3";import{r as h}from"./operationAuthoring.js?v=ca6b74e6a02eedb3";import{n as u}from"./encodingImageRoute.js?v=ca6b74e6a02eedb3";function f(e,t,o,n){let r=i(t.targetHandle)?t.target:t.source,a=u(e.nodes.find(e=>e.id===r)?.data.blockInstanceV2,o,n);if(!a)throw Error("This model has no unambiguous supported image encoder for this connection. Nothing changed.");let s=d(e,r);if(1!==s.length)throw Error("Connect Encode Inputs to one model loader before connecting its image encoding ports. Nothing changed.");return{encodingId:r,operation:a,owner:s[0]}}function m(e,t,n,a){if(a.pipelineClass!==n.operation.pipelineClass||a.task!==n.operation.task)throw Error("The image encoding route changed. Nothing changed.");let d=h(e,n.owner.id,a,{preserveValues:!0});if(d.review.required)throw Error(`Cannot connect without changing existing work: ${d.review.attention.join(" ")} Nothing changed.`);let c=d.graph;function p(e,t,o){if(!t)throw Error("The connection is missing a socket.");if(!i(t))return{id:d.replacements[e]??e,handle:t};let r=c.nodes.find(t=>t.id===e)?.data.blockInstanceV2,a=t.slice(t.indexOf(":")+1),s=r?.effectiveInterface.boundary["input"===o?"inputs":"outputs"].filter(e=>e.binding.fieldOrPortId===a&&r.effectiveGraph.nodes.some(t=>t.nodeId===e.binding.nodeId&&t.data.operationAuthoring?.operation?.operationId===n.operation.operationId));if(1!==s?.length)throw Error("The prepared encoder does not expose the selected socket. Nothing changed.");return{id:e,handle:s[0].portId}}let l=p(t.source,t.sourceHandle,"output"),g=p(t.target,t.targetHandle,"input"),u=o(c.nodes.find(e=>e.id===l.id),l.handle),f=o(c.nodes.find(e=>e.id===g.id),g.handle);if(!u||!f||"output"!==u.display||"input"!==f.display&&!f.isInput||!r(u.type,f.type))throw Error("These sockets are no longer compatible. Nothing changed.");c.edges=c.edges.filter(e=>e.target!==g.id||e.targetHandle!==g.handle),c.edges.push({id:`edge-${s()}`,source:l.id,sourceHandle:l.handle,target:g.id,targetHandle:g.handle,type:"default"});let m=new Set,w=[g.id];for(;w.length;){let e=w.pop();if(e===l.id)throw Error("That connection would create a cycle. Nothing changed.");if(!m.has(e)){m.add(e);for(let t of c.edges)t.source===e&&w.push(t.target)}}return c}function w(e){let t=e.data.params.execution_profile_id?.value??e.data.params.execution_profile_id?.default;if(!a(e))throw Error("The model loader no longer exists.");return"string"==typeof t&&t?t:void 0}async function I(o,r,i){let a=n(),d=t.getState().toObject(),s=p(d);r&&d.nodes.push(r);let h=c.getState(),u=f(d,o,h.operationContracts,h.pipelineSupport),I=await g(u.operation.pipelineClass,u.operation.task,h.operationContracts,i,w(u.owner));if(!i?.aborted){if(e(a,{includeForm:!1}),p(t.getState().toObject())!==s)throw Error("The workflow changed while preparing this connection. Connect again. Nothing changed.");l(m(d,o,u,I),a,s,"Connect encoding input/output")}}export{I as connectEncodingNode}; \ No newline at end of file diff --git a/web/assets/controlledWorkflows.js b/web/assets/controlledWorkflows.js index ec4b73f..e892fe1 100644 --- a/web/assets/controlledWorkflows.js +++ b/web/assets/controlledWorkflows.js @@ -1 +1 @@ -import{Ar as e,Ei as t,Mo as i,Mr as o,Nr as a,Rr as d,Sa as n,Si as r,Ti as s,Vr as l,ga as u,ji as c,jr as p,sc as g,ua as f,yo as m}from"./studio-templates.js?v=cc046c26d6fe7aa4";var y={source:"hub",value:"nateraw/real-esrgan/RealESRGAN_x2plus.pth",revision:"42efb9c3eeed1f5c0c8a626cf5f7f4481dfbb094",sha256:"49fafd45f8fd7aa8d31ab2a22d14d91b536c34494a5cfe31eb5d89c2fa266abb",byteSize:67061725};function v(e){return JSON.parse(JSON.stringify(e))}function h(e){return`${e.data.module}.${e.data.action}`}function _(e){if(e)return l.getState().nodes.find(t=>t.id===e)}function S(e,t){let i=_(e);if(i)return t.find(e=>i.data.params[e])}function w(e,t,i,o="value"){let a=S(e,t);return!(!e||!a||(l.getState().setParam(e,a,i,o),0))}function x(e,t){w(e,["source_start_seconds"],t.sourceStartSeconds),w(e,["source_duration_seconds"],t.sourceDurationSeconds),w(e,["target_duration_seconds"],t.targetDurationSeconds),w(e,["delay_seconds"],t.delaySeconds??0),w(e,["target_sample_rate"],t.targetSampleRate??48e3),w(e,["fade_in_seconds"],t.fadeInSeconds??0),w(e,["fade_out_seconds"],t.fadeOutSeconds??0)}async function b(e){let t=r.getState(),i=e.filter(e=>!t.nodesRegistry[e]);return(0===Object.keys(t.nodesRegistry).length||i.length>0)&&await t.fetchNodes(),e.filter(e=>!r.getState().nodesRegistry[e])}function q(e,t){return l.getState().nodes.find(i=>h(i)===e&&i.data.studioRole===t)}function k(e){if(0===e.length)return;let t=new Set(e);l.setState(e=>({nodes:e.nodes.filter(e=>!t.has(e.id)),edges:e.edges.filter(e=>!t.has(e.source)&&!t.has(e.target))})),l.getState().updateHandleConnectionStatus()}function V(e,t,i){let o=l.getState().nodes.filter(i=>i.data.studioRole===t&&h(i)!==e).map(e=>e.id);o.length>0&&k(o);let a=q(e,t);if(a)return a.data.studioOwned||l.setState(e=>({nodes:e.nodes.map(e=>e.id===a.id?{...e,data:{...e.data,studioOwned:!0}}:e)})),a.id;let d=r.getState().nodesRegistry[e];if(!d)throw Error(`Missing MoDiff node registry entry: ${e}`);let n=function(e){let t=e.lastIndexOf(".");return{module:e.slice(0,t),action:e.slice(t+1)}}(e),s={id:g(),type:d.type,position:i,data:{...v(d),module:d.module||n.module,action:d.action||n.action,studioRole:t,studioOwned:!0}};return l.getState().addNode(s),s.id}function E(e,t,i,o){if(!e||!i)return!1;let a=S(e,t),d=S(i,o);if(!a||!d)return!1;let r=l.getState();return!!r.edges.some(t=>t.source===e&&t.target===i&&t.sourceHandle===a&&t.targetHandle===d)||(r.onConnect({source:e,sourceHandle:a,target:i,targetHandle:d,edgeType:n.getState().edgeType}),l.getState().edges.some(t=>t.source===e&&t.target===i&&t.sourceHandle===a&&t.targetHandle===d))}function R(e,t,i){let o=_(e);return o?{x:o.position.x+i.x,y:o.position.y+i.y}:t}function C(t,i,a){let d=new Set(l.getState().nodes.map(e=>e.id)),n=p(t,i);try{let e=a();o(n);let t=[...d].filter(e=>!l.getState().nodes.some(t=>t.id===e));return t.length>0&&m(t).catch(e=>console.error("Failed to delete replaced node cache",e)),e}catch(t){throw e(n),t}}async function A(e=c.getState().form,o,n={}){let r=n.workflowContext??t();if(s(r),n.graphPrepared||await a(e,r),s(r),!await d(750,5e3,r))throw Error("The Studio graph schema did not settle before adding the LoRA adapter block.");s(r);let u=c.getState().graphBinding,p=!!u?.nodes.diffusersImagePipeline,g=!!u?.nodes.audioPipeline,m=g?f.audioLora:p?f.directLora:f.lora,y=await b([m]);if(s(r),y.length>0)throw Error(`LoRA block is unavailable because the backend registry is missing ${y.join(", ")}.`);let v=u?.nodes.models,h=u?.nodes.diffusersImagePipeline,_=u?.nodes.diffusersImageInpaint??u?.nodes.diffusersImageControl??u?.nodes.diffusersImageEdit??u?.nodes.diffusersImageGenerate,S=u?.nodes.audioPipeline,x=u?.nodes.audioGenerate;if(!(v||h&&_||S&&x))throw Error("Create a Studio graph before adding a LoRA adapter block.");let q=o?[o,...o.additionalAdapters??[]]:[];if(q.length>1&&!p)throw Error("Multiple LoRA adapters currently require the Diffusers image pipeline.");let A=q.length>0?q:[void 0],P=R(v??h??S,{x:-520,y:180},{x:0,y:270}),L=C(r,g?"lora.diffusers-audio.v1":p?"lora.diffusers-image.v1":"lora.modular.v1",()=>{let e=new Set(A.map((e,t)=>0===t?"loraAdapter":`loraAdapter:${t}`)),t=l.getState().nodes.filter(t=>"string"==typeof t.data.studioRole&&t.data.studioRole.startsWith("loraAdapter:")&&!e.has(t.data.studioRole)).map(e=>e.id);t.length>0&&k(t);let i=A.map((e,t)=>{let i=V(m,0===t?"loraAdapter":`loraAdapter:${t}`,{x:P.x+310*t,y:P.y});return w(i,["scale"],e?.scale??1),w(i,["replace_existing"],0===t),e?.model&&(w(i,["model","adapter_path"],{source:e.model.source,value:e.model.value}),w(i,["revision"],e.model.revision??""),w(i,["expected_sha256"],e.model.sha256??"")),e?.weightName&&w(i,["weight_name"],e.weightName),e?.adapterName&&w(i,["adapter_name"],e.adapterName),i}),a=i[0];g&&o?.baseModel&&(w(S,["model_id","model"],{source:o.baseModel.source,value:o.baseModel.value}),w(S,["revision"],o.baseModel.revision??"")),o?.schedulerClass&&w(a,["scheduler_class"],o.schedulerClass),o?.schedulerConfig&&w(a,["scheduler_config"],JSON.stringify(o.schedulerConfig));let d=!1;if(p||g){let e=l.getState(),t=h??S,o=_??x,a=e.edges.filter(e=>e.source===t&&(e.target===o||i.includes(e.target))||i.includes(e.source)&&(e.target===o||i.includes(e.target))).map(e=>e.id);a.length>0&&e.removeEdges(a),d=E(t,["pipeline"],i[0],["pipeline"]);for(let e=1;e0)throw Error(`Upscale block is unavailable because the backend registry is missing ${r.join(", ")}.`);d.graphPrepared||await a(e,n),s(n);let u=c.getState().graphBinding,p=u?.nodes.decode,g=u?.nodes.diffusersImageGenerate??u?.nodes.diffusersImageEdit??u?.nodes.diffusersImageInpaint??u?.nodes.diffusersImageControl,m=u?.nodes.wanGenerate,y=u?.nodes.videoExport,v=q(f.qualityVideoGenerate,"qualityVideoGenerate"),h=q(f.qualityVideoRetain,"qualityVideoRetain"),_=q(f.videoCompose,"videoCompose")?.id,S=q(f.exportWithAudio,"exportWithAudio")?.id,x=_??v?.id??m;if(!(p||g||v&&h||m&&y))throw Error("Create a Studio graph before adding an Upscale block.");let k=C(n,v?"upscale.quality-loop.v1":y?"upscale.video.v1":"upscale.image.v1",()=>{let t=V(f.upscaler,"upscaler",R(p??g??x,{x:930,y:170},{x:330,y:250}));if(w(t,["device"],e.device),o?.model&&w(t,["model_id"],o.model),void 0!==o?.downscale&&w(t,["downscale"],o.downscale),v&&h){L(v.id,h.id,["video_out"],["video"]);let e=E(v.id,["video_out"],t,["image"]),i=E(t,["output","image"],h.id,["video"]);if(!e||!i)throw Error("Quality-video upscale nodes were created, but their frame handles are not ready yet.");return v.parentId&&l.getState().setNodeLoopParent(t,v.parentId),{nodeId:t,message:"Upscale block added inside the per-shot quality loop"}}if(x&&y){let e=S??y,i=l.getState().edges.filter(t=>(t.source===m||t.source===_)&&t.target===e).map(e=>e.id);i.length>0&&l.getState().removeEdges(i);let o=E(x,_?["video"]:["video_out"],t,["image"]),a=E(t,["output","image"],e,["video"]);if(!o||!a)throw Error("Video upscale nodes were created, but video/image handles are not ready yet.");return{nodeId:t,message:"Upscale block added before the Studio video export"}}let i=V(f.preview,"upscalePreview",R(t,{x:1260,y:170},{x:330,y:0})),a=E(p??g,["images","image","output"],t,["image"]),d=E(t,["output","image"],i,["image"]);if(!a||!d)throw Error("Upscale nodes were created, but image handles are not ready yet. Try Add Upscale again after the registry finishes refreshing.");return{nodeId:t,message:"Upscale block added after Studio image generation"}});return!1!==d.notify&&i(k.message,{variant:"success",autoHideDuration:2200}),k.nodeId}function L(e,t,i,o){if(!e||!t)return;let a=l.getState().edges.filter(i=>i.source===e&&i.target===t).filter(e=>!i||i.includes(e.sourceHandle??"")).filter(e=>!o||o.includes(e.targetHandle??"")).map(e=>e.id);a.length>0&&l.getState().removeEdges(a)}function I(e){if(!e)return;let t=l.getState().edges.filter(t=>t.source===e||t.target===e).map(e=>e.id);t.length>0&&l.getState().removeEdges(t)}function z(e,t,i){w(e,["mode"],"text_to_video"),w(e,["prompts_json"],i),w(e,["negative_prompt"],t.negativePrompt),w(e,["width"],t.width),w(e,["height"],t.height),w(e,["num_frames"],t.numFrames),w(e,["frame_rate"],t.fps),w(e,["num_inference_steps"],t.steps),w(e,["guidance_scale"],t.guidanceScale),w(e,["seed"],t.seed),w(e,["output_type"],t.outputType),w(e,["max_sequence_length"],t.maxSequenceLength)}async function M(e,i,o={}){let d=o.workflowContext??t();s(d);let n=await b([f.videoSequence,f.videoCompose]);if(s(d),n.length>0)throw Error(`Video sequence block is missing ${n.join(", ")}.`);o.graphPrepared||await a(e,d),s(d);let r=c.getState().graphBinding,u=r?.nodes.wanPipeline,p=r?.nodes.wanGenerate,g=r?.nodes.videoExport,m=q(f.upscaler,"upscaler")?.id,y=q(f.exportWithAudio,"exportWithAudio")?.id;if(!u||!g)throw Error("Video sequence requires a Studio video graph.");return C(d,"video-sequence.v1",()=>{let t=V(f.videoSequence,"videoSequence",R(u,{x:-100,y:-80},{x:390,y:0})),o=V(f.videoCompose,"videoCompose",R(t,{x:300,y:-80},{x:390,y:0}));z(t,e,i?.promptsJson??"[]"),p&&l.getState().setNodeUiState(p,{disabled:!0}),w(o,["fps"],e.fps),w(o,["transition_seconds"],i?.transitionSeconds??.35),I(p);let a=y??g;if(!E(u,["pipeline"],t,["pipeline"])||!E(t,["clips"],o,["clip_1"])||!(m?E(o,["video"],m,["image"])&&E(m,["output","image"],a,["video"]):E(o,["video"],a,["video"])))throw Error("Video sequence nodes were created, but their media handles are unavailable.");return o})}async function N(e,i,o={}){let d=o.workflowContext??t();if(s(d),!i)throw Error("Quality video sequence settings are required.");let n=u(e),r="expert"===n.resourceMode?n.quantizationMode:"none",p=await b([f.qualityVideoQuantization,f.qualityVideoRecipe,f.qualityVideoShots,f.qualityVideoJobs,f.qualityVideoLoopItems,f.qualityVideoGenerate,f.qualityVideoRetain,f.qualityVideoLoopResult,f.qualityVideoJoin]);if(s(d),p.length>0)throw Error(`Quality video sequence is missing ${p.join(", ")}.`);o.graphPrepared||await a(n,d),s(d);let g=c.getState().graphBinding,m=g?.nodes.wanPipeline,y=g?.nodes.loadImage,v=g?.nodes.wanGenerate,h=g?.nodes.videoExport,S=i.mode??"image_to_video",x=n.device,k="text_to_video"===S?"none":n.offloadMode;if(!m||"image_to_video"===S&&!y)throw Error("Quality video sequence requires a video pipeline and image-to-video also needs keyframe input.");return C(d,"image_to_video"===S?"quality-video.i2v.v1":"quality-video.t2v.v1",()=>{let t=V(f.qualityVideoQuantization,"qualityVideoQuantization",{x:-930,y:-390}),o=V(f.qualityVideoRecipe,"qualityVideoRecipe",{x:-550,y:-390}),a=V(f.qualityVideoShots,"qualityVideoShots",{x:-930,y:310}),d=V(f.qualityVideoJobs,"qualityVideoJobs",{x:-500,y:310}),n=V(f.qualityVideoLoopItems,"qualityVideoLoopItems",{x:10,y:260}),s=V(f.qualityVideoGenerate,"qualityVideoGenerate",{x:310,y:260}),u=V(f.qualityVideoRetain,"qualityVideoRetain",{x:610,y:260}),c=V(f.qualityVideoLoopResult,"qualityVideoLoopResult",{x:910,y:260}),p=V(f.qualityVideoJoin,"qualityVideoJoin",{x:1270,y:120});w(t,["backend"],r),w(t,["components"],"image_to_video"===S?["transformer","transformer_2"]:["transformer"]),w(t,["dtype"],"bfloat16"),w(o,["device_map"],"none"),w(o,["offload_mode"],k),w(o,["device"],x);let g=x.startsWith("cuda");w(o,["attention_backend"],g?"_native_flash":"auto"),w(o,["attention_components"],g?"text_to_video"===S?"transformer":"transformer,transformer_2":""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(m,["device"],x),w(m,["auto_offload"],"none"!==k),w(m,["offload_mode"],k),w(a,["shots_json"],i.shotsJson),w(a,["maximum_shots"],6),w(d,["mode"],S),w(d,["reference_policy"],"text_to_video"===S?"none":"one_per_shot"),w(d,["base_seed"],e.seed),w(d,["fps"],i.fps??("text_to_video"===S?24:16)),w(d,["minimum_seconds"],5),w(d,["width"],i.width??("text_to_video"===S?1280:832)),w(d,["height"],i.height??("text_to_video"===S?704:480)),w(d,["steps"],i.steps??("text_to_video"===S?50:40)),w(d,["guidance_scale"],i.guidanceScale??("text_to_video"===S?5:3.5)),w(d,["secondary_guidance_scale"],i.secondaryGuidanceScale??3.5),w(d,["conditioning_strength"],i.conditioningStrength??e.strength),w(d,["negative_prompt"],e.negativePrompt),w(u,["quality"],10),w(u,["pin"],!0),w(p,["transition_seconds"],i.transitionSeconds),w(p,["pin"],!0),I(v),I(h),v&&l.getState().setNodeUiState(v,{disabled:!0}),h&&l.getState().setNodeUiState(h,{disabled:!0});let b=q(f.upscaler,"upscaler")?.id;if(!(E(t,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],m,["execution_recipe"])&&E(a,["shots"],d,["shots"])&&("image_to_video"!==S||E(y,["image"],d,["opening_images"]))&&E(d,["jobs"],n,["collection"])&&E(m,["pipeline"],s,["pipeline"])&&E(n,["item"],s,["job"])&&(b?E(s,["video_out"],b,["image"])&&E(b,["output","image"],u,["video"]):E(s,["video_out"],u,["video"]))&&E(s,["fps_out"],u,["fps"])&&E(u,["asset"],c,["value_input"])&&E(c,["collection"],p,["clips"])))throw Error("Quality video sequence nodes were created, but one or more media handles are unavailable.");let R=[n,s,u,c],C=l.getState(),A=C.nodes.find(e=>"qualityVideoLoop"===e.data.studioRole);if(!A){let e=new Set(C.nodes.filter(e=>"loop"===e.data.type).map(e=>e.id));if(C.loopNodes(R),A=l.getState().nodes.find(t=>"loop"===t.data.type&&!e.has(t.id)),A){let e=A.id;l.setState(t=>({nodes:t.nodes.map(t=>t.id===e?{...t,data:{...t.data,studioRole:"qualityVideoLoop",studioOwned:!0}}:t)})),A=_(e)}}if(!A)throw Error("Quality video sequence could not create its visible collection loop.");return R.forEach(e=>l.getState().setNodeLoopParent(e,A.id)),b&&l.getState().setNodeLoopParent(b,A.id),w(A.id,["iteration_mode"],"collection"),w(A.id,["iterations"],6),w(A.id,["max_iterations"],6),w(A.id,["carry"],!1),w(A.id,["collect"],!0),w(A.id,["durable"],!0),w(A.id,["max_retries"],1),p})}async function G(e,i,o={}){let d=o.workflowContext??t();if(s(d),!i)throw Error("Soundtrack settings are required.");let n=u(e),r=await b([f.soundtrackQuantization,f.soundtrackRecipe,f.soundtrackPipeline,f.soundtrackGenerate,f.audioFit,f.exportWithAudio]);if(s(d),r.length>0)throw Error(`Soundtrack block is missing ${r.join(", ")}.`);o.graphPrepared||await a(n,d),s(d);let p=c.getState().graphBinding,g=p?.nodes.wanGenerate,m=p?.nodes.videoExport,y=q(f.upscaler,"upscaler")?.id,v=q(f.videoCompose,"videoCompose")?.id,h=y??v??g;if(!h||!m)throw Error("Soundtrack requires a Studio video graph.");return C(d,"soundtrack.v1",()=>{let t=V(f.soundtrackQuantization,"soundtrackQuantization",{x:-930,y:420}),o=V(f.soundtrackRecipe,"soundtrackRecipe",{x:-550,y:420}),a=V(f.soundtrackPipeline,"soundtrackPipeline",{x:-170,y:420}),d=V(f.soundtrackGenerate,"soundtrackGenerate",{x:220,y:420}),r=V(f.audioFit,"soundtrackAudioFit",{x:620,y:420}),s=V(f.exportWithAudio,"exportWithAudio",{x:1050,y:140});w(t,["backend"],"none"),w(t,["components"],[]),w(t,["dtype"],n.dtype),w(o,["device_map"],"none"),w(o,["offload_mode"],n.offloadMode),w(o,["device"],n.device),w(o,["attention_backend"],"_native_math"),w(o,["attention_components"],""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(a,["model_id"],i.model),i.model.revision&&w(a,["revision"],i.model.revision),w(a,["pipeline_class"],i.pipelineClass),w(a,["mode"],"text_to_audio"),w(a,["dtype"],n.dtype),w(a,["device"],n.device),w(a,["auto_offload"],n.autoOffload),w(a,["offload_mode"],n.offloadMode),w(d,["task_type"],"text2music"),w(d,["prompt"],i.prompt),w(d,["negative_prompt"],i.negativePrompt??""),w(d,["lyrics"],""),w(d,["audio_duration"],i.durationSeconds),w(d,["num_inference_steps"],i.steps),w(d,["guidance_scale"],i.guidanceScale),w(d,["stable_audio_steps"],i.steps),w(d,["stable_audio_guidance"],i.guidanceScale),w(d,["seed"],i.seed),w(d,["bpm"],i.bpm??0),w(d,["keyscale"],i.keyscale??""),w(d,["timesignature"],i.timesignature??"4/4"),x(r,i.audioFit),w(s,["fps"],e.fps),w(s,["quality"],10),L(h,m),l.getState().setNodeUiState(m,{disabled:!0});let u=y?["output","image"]:v?["video"]:["video_out"];if(!(E(t,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],a,["execution_recipe"])&&E(a,["pipeline"],d,["pipeline"])&&E(d,["audio"],r,["audio"])&&E(r,["output"],s,["audio"])&&E(h,u,s,["video"])))throw Error("Soundtrack nodes were created, but their audio/video handles are unavailable.");return s})}async function O(e,i,o={}){let d=o.workflowContext??t();if(s(d),!i)throw Error("Lyric video settings are required.");let n=u(e),r="expert"===n.resourceMode?n.quantizationMode:"none",l=await b([f.lyricVideoQuantization,f.lyricVideoRecipe,f.videoPipeline,f.videoSequence,f.videoCompose,f.upscaler,f.lyricOverlay,f.audioFit,f.exportWithAudio]);if(s(d),l.length>0)throw Error(`Lyric video block is missing ${l.join(", ")}.`);o.graphPrepared||await a(n,d),s(d);let p=c.getState().graphBinding?.nodes.audioGenerate;if(!p)throw Error("Lyric video requires the ACE-Step audio graph.");return C(d,"lyric-video.v1",()=>{let t=V(f.lyricVideoQuantization,"lyricVideoQuantization",{x:-1280,y:340}),o=V(f.lyricVideoRecipe,"lyricVideoRecipe",{x:-900,y:340}),a=V(f.videoPipeline,"lyricVideoPipeline",{x:-500,y:340}),d=V(f.videoSequence,"videoSequence",{x:-100,y:340}),s=V(f.videoCompose,"videoCompose",{x:300,y:340}),l=V(f.upscaler,"upscaler",{x:680,y:340}),u=V(f.lyricOverlay,"lyricOverlay",{x:1060,y:340}),c=V(f.audioFit,"lyricAudioFit",{x:1060,y:720}),g=V(f.exportWithAudio,"exportWithAudio",{x:1440,y:180});if(w(t,["backend"],r),w(t,["components"],["transformer"]),w(t,["dtype"],n.dtype),w(o,["device_map"],"none"),w(o,["offload_mode"],n.offloadMode),w(o,["device"],n.device),w(o,["attention_backend"],"auto"),w(o,["attention_components"],""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(a,["model_id"],i.visualModel),w(a,["pipeline_class"],"LTXConditionPipeline"),w(a,["dtype"],n.dtype),w(a,["device"],n.device),w(a,["auto_offload"],n.autoOffload),w(a,["offload_mode"],n.offloadMode),z(d,{...e,width:768,height:512,numFrames:81,steps:8,guidanceScale:1},i.promptsJson),w(s,["fps"],16),w(s,["transition_seconds"],i.transitionSeconds),w(l,["model_id"],y),w(l,["downscale"],1),w(u,["lrc"],i.lrc),w(u,["fps"],16),w(u,["font_size"],i.fontSize??58),w(u,["bottom_margin"],i.bottomMargin??70),w(p,["task_type"],"text2music"),w(p,["prompt"],i.audio.prompt),w(p,["negative_prompt"],""),w(p,["lyrics"],i.audio.lyrics),w(p,["audio_duration"],i.audio.durationSeconds),w(p,["num_inference_steps"],i.audio.steps),w(p,["guidance_scale"],i.audio.guidanceScale),w(p,["shift"],i.audio.shift??3),w(p,["seed"],i.audio.seed),w(p,["bpm"],i.audio.bpm??0),w(p,["keyscale"],i.audio.keyscale??""),w(p,["timesignature"],i.audio.timesignature??"4"),w(p,["vocal_language"],i.audio.vocalLanguage??"en"),w(p,["sample_rate"],i.audioFit.targetSampleRate??48e3),x(c,i.audioFit),w(g,["fps"],16),!(E(t,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],a,["execution_recipe"])&&E(a,["pipeline"],d,["pipeline"])&&E(d,["clips"],s,["clip_1"])&&E(s,["video"],l,["image"])&&E(l,["output"],u,["video"])&&E(u,["output"],g,["video"])&&E(p,["audio"],c,["audio"])&&E(c,["output"],g,["audio"])))throw Error("Lyric video nodes were created, but their media handles are unavailable.");return g})}export{P as a,G as i,O as n,M as o,N as r,A as t}; \ No newline at end of file +import{Di as e,Hr as t,Mr as i,Ni as o,Nr as a,Oi as d,Po as n,Pr as r,fa as s,jr as l,uc as u,va as c,wa as p,wi as g,xo as f,zr as m}from"./studio-templates.js?v=ca6b74e6a02eedb3";var y={source:"hub",value:"nateraw/real-esrgan/RealESRGAN_x2plus.pth",revision:"42efb9c3eeed1f5c0c8a626cf5f7f4481dfbb094",sha256:"49fafd45f8fd7aa8d31ab2a22d14d91b536c34494a5cfe31eb5d89c2fa266abb",byteSize:67061725};function v(e){return JSON.parse(JSON.stringify(e))}function h(e){return`${e.data.module}.${e.data.action}`}function _(e){if(e)return t.getState().nodes.find(t=>t.id===e)}function S(e,t){let i=_(e);if(i)return t.find(e=>i.data.params[e])}function w(e,i,o,a="value"){let d=S(e,i);return!(!e||!d||(t.getState().setParam(e,d,o,a),0))}function x(e,t){w(e,["source_start_seconds"],t.sourceStartSeconds),w(e,["source_duration_seconds"],t.sourceDurationSeconds),w(e,["target_duration_seconds"],t.targetDurationSeconds),w(e,["delay_seconds"],t.delaySeconds??0),w(e,["target_sample_rate"],t.targetSampleRate??48e3),w(e,["fade_in_seconds"],t.fadeInSeconds??0),w(e,["fade_out_seconds"],t.fadeOutSeconds??0)}async function b(e){let t=g.getState(),i=e.filter(e=>!t.nodesRegistry[e]);return(0===Object.keys(t.nodesRegistry).length||i.length>0)&&await t.fetchNodes(),e.filter(e=>!g.getState().nodesRegistry[e])}function q(e,i){return t.getState().nodes.find(t=>h(t)===e&&t.data.studioRole===i)}function k(e){if(0===e.length)return;let i=new Set(e);t.setState(e=>({nodes:e.nodes.filter(e=>!i.has(e.id)),edges:e.edges.filter(e=>!i.has(e.source)&&!i.has(e.target))})),t.getState().updateHandleConnectionStatus()}function V(e,i,o){let a=t.getState().nodes.filter(t=>t.data.studioRole===i&&h(t)!==e).map(e=>e.id);a.length>0&&k(a);let d=q(e,i);if(d)return d.data.studioOwned||t.setState(e=>({nodes:e.nodes.map(e=>e.id===d.id?{...e,data:{...e.data,studioOwned:!0}}:e)})),d.id;let n=g.getState().nodesRegistry[e];if(!n)throw Error(`Missing MoDiff node registry entry: ${e}`);let r=function(e){let t=e.lastIndexOf(".");return{module:e.slice(0,t),action:e.slice(t+1)}}(e),s={id:u(),type:n.type,position:o,data:{...v(n),module:n.module||r.module,action:n.action||r.action,studioRole:i,studioOwned:!0}};return t.getState().addNode(s),s.id}function E(e,i,o,a){if(!e||!o)return!1;let d=S(e,i),n=S(o,a);if(!d||!n)return!1;let r=t.getState();return!!r.edges.some(t=>t.source===e&&t.target===o&&t.sourceHandle===d&&t.targetHandle===n)||(r.onConnect({source:e,sourceHandle:d,target:o,targetHandle:n,edgeType:p.getState().edgeType}),t.getState().edges.some(t=>t.source===e&&t.target===o&&t.sourceHandle===d&&t.targetHandle===n))}function R(e,t,i){let o=_(e);return o?{x:o.position.x+i.x,y:o.position.y+i.y}:t}function C(e,o,d){let n=new Set(t.getState().nodes.map(e=>e.id)),r=i(e,o);try{let e=d();a(r);let i=[...n].filter(e=>!t.getState().nodes.some(t=>t.id===e));return i.length>0&&f(i).catch(e=>console.error("Failed to delete replaced node cache",e)),e}catch(e){throw l(r),e}}async function P(i=o.getState().form,a,l={}){let u=l.workflowContext??d();if(e(u),l.graphPrepared||await r(i,u),e(u),!await m(750,5e3,u))throw Error("The Studio graph schema did not settle before adding the LoRA adapter block.");e(u);let c=o.getState().graphBinding,p=!!c?.nodes.diffusersImagePipeline,g=!!c?.nodes.audioPipeline,f=g?s.audioLora:p?s.directLora:s.lora,y=await b([f]);if(e(u),y.length>0)throw Error(`LoRA block is unavailable because the backend registry is missing ${y.join(", ")}.`);let v=c?.nodes.models,h=c?.nodes.diffusersImagePipeline,_=c?.nodes.diffusersImageInpaint??c?.nodes.diffusersImageControl??c?.nodes.diffusersImageEdit??c?.nodes.diffusersImageGenerate,S=c?.nodes.audioPipeline,x=c?.nodes.audioGenerate;if(!(v||h&&_||S&&x))throw Error("Create a Studio graph before adding a LoRA adapter block.");let q=a?[a,...a.additionalAdapters??[]]:[];if(q.length>1&&!p)throw Error("Multiple LoRA adapters currently require the Diffusers image pipeline.");let P=q.length>0?q:[void 0],A=R(v??h??S,{x:-520,y:180},{x:0,y:270}),L=C(u,g?"lora.diffusers-audio.v1":p?"lora.diffusers-image.v1":"lora.modular.v1",()=>{let e=new Set(P.map((e,t)=>0===t?"loraAdapter":`loraAdapter:${t}`)),i=t.getState().nodes.filter(t=>"string"==typeof t.data.studioRole&&t.data.studioRole.startsWith("loraAdapter:")&&!e.has(t.data.studioRole)).map(e=>e.id);i.length>0&&k(i);let o=P.map((e,t)=>{let i=V(f,0===t?"loraAdapter":`loraAdapter:${t}`,{x:A.x+310*t,y:A.y});return w(i,["scale"],e?.scale??1),w(i,["replace_existing"],0===t),e?.model&&(w(i,["model","adapter_path"],{source:e.model.source,value:e.model.value}),w(i,["revision"],e.model.revision??""),w(i,["expected_sha256"],e.model.sha256??"")),e?.weightName&&w(i,["weight_name"],e.weightName),e?.adapterName&&w(i,["adapter_name"],e.adapterName),i}),d=o[0];g&&a?.baseModel&&(w(S,["model_id","model"],{source:a.baseModel.source,value:a.baseModel.value}),w(S,["revision"],a.baseModel.revision??"")),a?.schedulerClass&&w(d,["scheduler_class"],a.schedulerClass),a?.schedulerConfig&&w(d,["scheduler_config"],JSON.stringify(a.schedulerConfig));let n=!1;if(p||g){let e=t.getState(),i=h??S,a=_??x,d=e.edges.filter(e=>e.source===i&&(e.target===a||o.includes(e.target))||o.includes(e.source)&&(e.target===a||o.includes(e.target))).map(e=>e.id);d.length>0&&e.removeEdges(d),n=E(i,["pipeline"],o[0],["pipeline"]);for(let e=1;e0)throw Error(`Upscale block is unavailable because the backend registry is missing ${c.join(", ")}.`);l.graphPrepared||await r(i,u),e(u);let p=o.getState().graphBinding,g=p?.nodes.decode,f=p?.nodes.diffusersImageGenerate??p?.nodes.diffusersImageEdit??p?.nodes.diffusersImageInpaint??p?.nodes.diffusersImageControl,m=p?.nodes.wanGenerate,y=p?.nodes.videoExport,v=q(s.qualityVideoGenerate,"qualityVideoGenerate"),h=q(s.qualityVideoRetain,"qualityVideoRetain"),_=q(s.videoCompose,"videoCompose")?.id,S=q(s.exportWithAudio,"exportWithAudio")?.id,x=_??v?.id??m;if(!(g||f||v&&h||m&&y))throw Error("Create a Studio graph before adding an Upscale block.");let k=C(u,v?"upscale.quality-loop.v1":y?"upscale.video.v1":"upscale.image.v1",()=>{let e=V(s.upscaler,"upscaler",R(g??f??x,{x:930,y:170},{x:330,y:250}));if(w(e,["device"],i.device),a?.model&&w(e,["model_id"],a.model),void 0!==a?.downscale&&w(e,["downscale"],a.downscale),v&&h){L(v.id,h.id,["video_out"],["video"]);let i=E(v.id,["video_out"],e,["image"]),o=E(e,["output","image"],h.id,["video"]);if(!i||!o)throw Error("Quality-video upscale nodes were created, but their frame handles are not ready yet.");return v.parentId&&t.getState().setNodeLoopParent(e,v.parentId),{nodeId:e,message:"Upscale block added inside the per-shot quality loop"}}if(x&&y){let i=S??y,o=t.getState().edges.filter(e=>(e.source===m||e.source===_)&&e.target===i).map(e=>e.id);o.length>0&&t.getState().removeEdges(o);let a=E(x,_?["video"]:["video_out"],e,["image"]),d=E(e,["output","image"],i,["video"]);if(!a||!d)throw Error("Video upscale nodes were created, but video/image handles are not ready yet.");return{nodeId:e,message:"Upscale block added before the Studio video export"}}let o=V(s.preview,"upscalePreview",R(e,{x:1260,y:170},{x:330,y:0})),d=E(g??f,["images","image","output"],e,["image"]),n=E(e,["output","image"],o,["image"]);if(!d||!n)throw Error("Upscale nodes were created, but image handles are not ready yet. Try Add Upscale again after the registry finishes refreshing.");return{nodeId:e,message:"Upscale block added after Studio image generation"}});return!1!==l.notify&&n(k.message,{variant:"success",autoHideDuration:2200}),k.nodeId}function L(e,i,o,a){if(!e||!i)return;let d=t.getState().edges.filter(t=>t.source===e&&t.target===i).filter(e=>!o||o.includes(e.sourceHandle??"")).filter(e=>!a||a.includes(e.targetHandle??"")).map(e=>e.id);d.length>0&&t.getState().removeEdges(d)}function I(e){if(!e)return;let i=t.getState().edges.filter(t=>t.source===e||t.target===e).map(e=>e.id);i.length>0&&t.getState().removeEdges(i)}function z(e,t,i){w(e,["mode"],"text_to_video"),w(e,["prompts_json"],i),w(e,["negative_prompt"],t.negativePrompt),w(e,["width"],t.width),w(e,["height"],t.height),w(e,["num_frames"],t.numFrames),w(e,["frame_rate"],t.fps),w(e,["num_inference_steps"],t.steps),w(e,["guidance_scale"],t.guidanceScale),w(e,["seed"],t.seed),w(e,["output_type"],t.outputType),w(e,["max_sequence_length"],t.maxSequenceLength)}async function N(i,a,n={}){let l=n.workflowContext??d();e(l);let u=await b([s.videoSequence,s.videoCompose]);if(e(l),u.length>0)throw Error(`Video sequence block is missing ${u.join(", ")}.`);n.graphPrepared||await r(i,l),e(l);let c=o.getState().graphBinding,p=c?.nodes.wanPipeline,g=c?.nodes.wanGenerate,f=c?.nodes.videoExport,m=q(s.upscaler,"upscaler")?.id,y=q(s.exportWithAudio,"exportWithAudio")?.id;if(!p||!f)throw Error("Video sequence requires a Studio video graph.");return C(l,"video-sequence.v1",()=>{let e=V(s.videoSequence,"videoSequence",R(p,{x:-100,y:-80},{x:390,y:0})),o=V(s.videoCompose,"videoCompose",R(e,{x:300,y:-80},{x:390,y:0}));z(e,i,a?.promptsJson??"[]"),g&&t.getState().setNodeUiState(g,{disabled:!0}),w(o,["fps"],i.fps),w(o,["transition_seconds"],a?.transitionSeconds??.35),I(g);let d=y??f;if(!E(p,["pipeline"],e,["pipeline"])||!E(e,["clips"],o,["clip_1"])||!(m?E(o,["video"],m,["image"])&&E(m,["output","image"],d,["video"]):E(o,["video"],d,["video"])))throw Error("Video sequence nodes were created, but their media handles are unavailable.");return o})}async function M(i,a,n={}){let l=n.workflowContext??d();if(e(l),!a)throw Error("Quality video sequence settings are required.");let u=c(i),p="expert"===u.resourceMode?u.quantizationMode:"none",g=await b([s.qualityVideoQuantization,s.qualityVideoRecipe,s.qualityVideoShots,s.qualityVideoJobs,s.qualityVideoLoopItems,s.qualityVideoGenerate,s.qualityVideoRetain,s.qualityVideoLoopResult,s.qualityVideoJoin]);if(e(l),g.length>0)throw Error(`Quality video sequence is missing ${g.join(", ")}.`);n.graphPrepared||await r(u,l),e(l);let f=o.getState().graphBinding,m=f?.nodes.wanPipeline,y=f?.nodes.loadImage,v=f?.nodes.wanGenerate,h=f?.nodes.videoExport,S=a.mode??"image_to_video",x=u.device,k="text_to_video"===S?"none":u.offloadMode;if(!m||"image_to_video"===S&&!y)throw Error("Quality video sequence requires a video pipeline and image-to-video also needs keyframe input.");return C(l,"image_to_video"===S?"quality-video.i2v.v1":"quality-video.t2v.v1",()=>{let e=V(s.qualityVideoQuantization,"qualityVideoQuantization",{x:-930,y:-390}),o=V(s.qualityVideoRecipe,"qualityVideoRecipe",{x:-550,y:-390}),d=V(s.qualityVideoShots,"qualityVideoShots",{x:-930,y:310}),n=V(s.qualityVideoJobs,"qualityVideoJobs",{x:-500,y:310}),r=V(s.qualityVideoLoopItems,"qualityVideoLoopItems",{x:10,y:260}),l=V(s.qualityVideoGenerate,"qualityVideoGenerate",{x:310,y:260}),u=V(s.qualityVideoRetain,"qualityVideoRetain",{x:610,y:260}),c=V(s.qualityVideoLoopResult,"qualityVideoLoopResult",{x:910,y:260}),g=V(s.qualityVideoJoin,"qualityVideoJoin",{x:1270,y:120});w(e,["backend"],p),w(e,["components"],"image_to_video"===S?["transformer","transformer_2"]:["transformer"]),w(e,["dtype"],"bfloat16"),w(o,["device_map"],"none"),w(o,["offload_mode"],k),w(o,["device"],x);let f=x.startsWith("cuda");w(o,["attention_backend"],f?"_native_flash":"auto"),w(o,["attention_components"],f?"text_to_video"===S?"transformer":"transformer,transformer_2":""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(m,["device"],x),w(m,["auto_offload"],"none"!==k),w(m,["offload_mode"],k),w(d,["shots_json"],a.shotsJson),w(d,["maximum_shots"],6),w(n,["mode"],S),w(n,["reference_policy"],"text_to_video"===S?"none":"one_per_shot"),w(n,["base_seed"],i.seed),w(n,["fps"],a.fps??("text_to_video"===S?24:16)),w(n,["minimum_seconds"],5),w(n,["width"],a.width??("text_to_video"===S?1280:832)),w(n,["height"],a.height??("text_to_video"===S?704:480)),w(n,["steps"],a.steps??("text_to_video"===S?50:40)),w(n,["guidance_scale"],a.guidanceScale??("text_to_video"===S?5:3.5)),w(n,["secondary_guidance_scale"],a.secondaryGuidanceScale??3.5),w(n,["conditioning_strength"],a.conditioningStrength??i.strength),w(n,["negative_prompt"],i.negativePrompt),w(u,["quality"],10),w(u,["pin"],!0),w(g,["transition_seconds"],a.transitionSeconds),w(g,["pin"],!0),I(v),I(h),v&&t.getState().setNodeUiState(v,{disabled:!0}),h&&t.getState().setNodeUiState(h,{disabled:!0});let b=q(s.upscaler,"upscaler")?.id;if(!(E(e,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],m,["execution_recipe"])&&E(d,["shots"],n,["shots"])&&("image_to_video"!==S||E(y,["image"],n,["opening_images"]))&&E(n,["jobs"],r,["collection"])&&E(m,["pipeline"],l,["pipeline"])&&E(r,["item"],l,["job"])&&(b?E(l,["video_out"],b,["image"])&&E(b,["output","image"],u,["video"]):E(l,["video_out"],u,["video"]))&&E(l,["fps_out"],u,["fps"])&&E(u,["asset"],c,["value_input"])&&E(c,["collection"],g,["clips"])))throw Error("Quality video sequence nodes were created, but one or more media handles are unavailable.");let R=[r,l,u,c],C=t.getState(),P=C.nodes.find(e=>"qualityVideoLoop"===e.data.studioRole);if(!P){let e=new Set(C.nodes.filter(e=>"loop"===e.data.type).map(e=>e.id));if(C.loopNodes(R),P=t.getState().nodes.find(t=>"loop"===t.data.type&&!e.has(t.id)),P){let e=P.id;t.setState(t=>({nodes:t.nodes.map(t=>t.id===e?{...t,data:{...t.data,studioRole:"qualityVideoLoop",studioOwned:!0}}:t)})),P=_(e)}}if(!P)throw Error("Quality video sequence could not create its visible collection loop.");return R.forEach(e=>t.getState().setNodeLoopParent(e,P.id)),b&&t.getState().setNodeLoopParent(b,P.id),w(P.id,["iteration_mode"],"collection"),w(P.id,["iterations"],6),w(P.id,["max_iterations"],6),w(P.id,["carry"],!1),w(P.id,["collect"],!0),w(P.id,["durable"],!0),w(P.id,["max_retries"],1),g})}async function G(i,a,n={}){let l=n.workflowContext??d();if(e(l),!a)throw Error("Soundtrack settings are required.");let u=c(i),p=await b([s.soundtrackQuantization,s.soundtrackRecipe,s.soundtrackPipeline,s.soundtrackGenerate,s.audioFit,s.exportWithAudio]);if(e(l),p.length>0)throw Error(`Soundtrack block is missing ${p.join(", ")}.`);n.graphPrepared||await r(u,l),e(l);let g=o.getState().graphBinding,f=g?.nodes.wanGenerate,m=g?.nodes.videoExport,y=q(s.upscaler,"upscaler")?.id,v=q(s.videoCompose,"videoCompose")?.id,h=y??v??f;if(!h||!m)throw Error("Soundtrack requires a Studio video graph.");return C(l,"soundtrack.v1",()=>{let e=V(s.soundtrackQuantization,"soundtrackQuantization",{x:-930,y:420}),o=V(s.soundtrackRecipe,"soundtrackRecipe",{x:-550,y:420}),d=V(s.soundtrackPipeline,"soundtrackPipeline",{x:-170,y:420}),n=V(s.soundtrackGenerate,"soundtrackGenerate",{x:220,y:420}),r=V(s.audioFit,"soundtrackAudioFit",{x:620,y:420}),l=V(s.exportWithAudio,"exportWithAudio",{x:1050,y:140});w(e,["backend"],"none"),w(e,["components"],[]),w(e,["dtype"],u.dtype),w(o,["device_map"],"none"),w(o,["offload_mode"],u.offloadMode),w(o,["device"],u.device),w(o,["attention_backend"],"_native_math"),w(o,["attention_components"],""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(d,["model_id"],a.model),a.model.revision&&w(d,["revision"],a.model.revision),w(d,["pipeline_class"],a.pipelineClass),w(d,["mode"],"text_to_audio"),w(d,["dtype"],u.dtype),w(d,["device"],u.device),w(d,["auto_offload"],u.autoOffload),w(d,["offload_mode"],u.offloadMode),w(n,["task_type"],"text2music"),w(n,["prompt"],a.prompt),w(n,["negative_prompt"],a.negativePrompt??""),w(n,["lyrics"],""),w(n,["audio_duration"],a.durationSeconds),w(n,["num_inference_steps"],a.steps),w(n,["guidance_scale"],a.guidanceScale),w(n,["stable_audio_steps"],a.steps),w(n,["stable_audio_guidance"],a.guidanceScale),w(n,["seed"],a.seed),w(n,["bpm"],a.bpm??0),w(n,["keyscale"],a.keyscale??""),w(n,["timesignature"],a.timesignature??"4/4"),x(r,a.audioFit),w(l,["fps"],i.fps),w(l,["quality"],10),L(h,m),t.getState().setNodeUiState(m,{disabled:!0});let c=y?["output","image"]:v?["video"]:["video_out"];if(!(E(e,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],d,["execution_recipe"])&&E(d,["pipeline"],n,["pipeline"])&&E(n,["audio"],r,["audio"])&&E(r,["output"],l,["audio"])&&E(h,c,l,["video"])))throw Error("Soundtrack nodes were created, but their audio/video handles are unavailable.");return l})}async function O(t,i,a={}){let n=a.workflowContext??d();if(e(n),!i)throw Error("Lyric video settings are required.");let l=c(t),u="expert"===l.resourceMode?l.quantizationMode:"none",p=await b([s.lyricVideoQuantization,s.lyricVideoRecipe,s.videoPipeline,s.videoSequence,s.videoCompose,s.upscaler,s.lyricOverlay,s.audioFit,s.exportWithAudio]);if(e(n),p.length>0)throw Error(`Lyric video block is missing ${p.join(", ")}.`);a.graphPrepared||await r(l,n),e(n);let g=o.getState().graphBinding?.nodes.audioGenerate;if(!g)throw Error("Lyric video requires the ACE-Step audio graph.");return C(n,"lyric-video.v1",()=>{let e=V(s.lyricVideoQuantization,"lyricVideoQuantization",{x:-1280,y:340}),o=V(s.lyricVideoRecipe,"lyricVideoRecipe",{x:-900,y:340}),a=V(s.videoPipeline,"lyricVideoPipeline",{x:-500,y:340}),d=V(s.videoSequence,"videoSequence",{x:-100,y:340}),n=V(s.videoCompose,"videoCompose",{x:300,y:340}),r=V(s.upscaler,"upscaler",{x:680,y:340}),c=V(s.lyricOverlay,"lyricOverlay",{x:1060,y:340}),p=V(s.audioFit,"lyricAudioFit",{x:1060,y:720}),f=V(s.exportWithAudio,"exportWithAudio",{x:1440,y:180});if(w(e,["backend"],u),w(e,["components"],["transformer"]),w(e,["dtype"],l.dtype),w(o,["device_map"],"none"),w(o,["offload_mode"],l.offloadMode),w(o,["device"],l.device),w(o,["attention_backend"],"auto"),w(o,["attention_components"],""),w(o,["vae_slicing"],!0),w(o,["vae_tiling"],!0),w(a,["model_id"],i.visualModel),w(a,["pipeline_class"],"LTXConditionPipeline"),w(a,["dtype"],l.dtype),w(a,["device"],l.device),w(a,["auto_offload"],l.autoOffload),w(a,["offload_mode"],l.offloadMode),z(d,{...t,width:768,height:512,numFrames:81,steps:8,guidanceScale:1},i.promptsJson),w(n,["fps"],16),w(n,["transition_seconds"],i.transitionSeconds),w(r,["model_id"],y),w(r,["downscale"],1),w(c,["lrc"],i.lrc),w(c,["fps"],16),w(c,["font_size"],i.fontSize??58),w(c,["bottom_margin"],i.bottomMargin??70),w(g,["task_type"],"text2music"),w(g,["prompt"],i.audio.prompt),w(g,["negative_prompt"],""),w(g,["lyrics"],i.audio.lyrics),w(g,["audio_duration"],i.audio.durationSeconds),w(g,["num_inference_steps"],i.audio.steps),w(g,["guidance_scale"],i.audio.guidanceScale),w(g,["shift"],i.audio.shift??3),w(g,["seed"],i.audio.seed),w(g,["bpm"],i.audio.bpm??0),w(g,["keyscale"],i.audio.keyscale??""),w(g,["timesignature"],i.audio.timesignature??"4"),w(g,["vocal_language"],i.audio.vocalLanguage??"en"),w(g,["sample_rate"],i.audioFit.targetSampleRate??48e3),x(p,i.audioFit),w(f,["fps"],16),!(E(e,["quantization_config"],o,["quantization_config"])&&E(o,["execution_recipe"],a,["execution_recipe"])&&E(a,["pipeline"],d,["pipeline"])&&E(d,["clips"],n,["clip_1"])&&E(n,["video"],r,["image"])&&E(r,["output"],c,["video"])&&E(c,["output"],f,["video"])&&E(g,["audio"],p,["audio"])&&E(p,["output"],f,["audio"])))throw Error("Lyric video nodes were created, but their media handles are unavailable.");return f})}export{A as a,G as i,O as n,N as o,M as r,P as t}; \ No newline at end of file diff --git a/web/assets/encodingImageRoute.js b/web/assets/encodingImageRoute.js index 173129c..6eea489 100644 --- a/web/assets/encodingImageRoute.js +++ b/web/assets/encodingImageRoute.js @@ -1 +1 @@ -import{n as e}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";import{ws as t}from"./studio-templates.js?v=cc046c26d6fe7aa4";var i=e({optionalEncodingRoute:()=>o});function o(e,i,o){if(!t(e)||!e||e.effectiveInterface.boundary.inputs.some(e=>"image"===e.valueType))return null;let n=e.effectiveGraph.nodes.flatMap(e=>{let t=e.data.operationAuthoring;return t?.operation?[t.operation]:[]}),a=n[0]?.pipelineClass;if(!a||n.some(e=>e.pipelineClass!==a))return null;let s=i.filter(e=>e.pipelineClass===a&&e.task===n[0]?.task),r=i.flatMap(e=>{if(e.pipelineClass!==a||!e.task||e.task.includes("video")||!["vae_encoder","image_encoder"].includes(e.nodeType)||!e.ports.some(e=>"input"===e.direction&&!e.hidden&&"image"===e.semanticName&&e.types.includes("image"))||!o.some(t=>t.pipelineClass===a&&t.tasks.some(t=>t.task===e.task&&"adapter"===t.execution&&t.operationIds.includes(e.operationId))))return[];let t=i.filter(t=>t.pipelineClass===a&&t.task===e.task);return s.some(e=>!t.some(t=>t.operationId===e.operationId))||t.some(e=>e.ports.some(t=>"input"===t.direction&&t.required&&!t.hidden&&t.types.includes("image")&&"image"!==t.semanticName&&!s.some(i=>i.operationId===e.operationId&&i.ports.some(e=>"input"===e.direction&&e.required&&e.semanticName===t.semanticName))))?[]:[{operation:e,cost:t.filter(e=>!s.some(t=>t.operationId===e.operationId)).length}]}),p=Math.min(...r.map(e=>e.cost)),l=r.filter(e=>e.cost===p);return 1===l.length?l[0].operation:null}export{o as n,i as t}; \ No newline at end of file +import{n as e}from"./rolldown-runtime.js?v=ca6b74e6a02eedb3";import{Ds as t}from"./studio-templates.js?v=ca6b74e6a02eedb3";var i=e({optionalEncodingRoute:()=>o});function o(e,i,o){if(!t(e)||!e||e.effectiveInterface.boundary.inputs.some(e=>"image"===e.valueType))return null;let n=e.effectiveGraph.nodes.flatMap(e=>{let t=e.data.operationAuthoring;return t?.operation?[t.operation]:[]}),a=n[0]?.pipelineClass;if(!a||n.some(e=>e.pipelineClass!==a))return null;let s=i.filter(e=>e.pipelineClass===a&&e.task===n[0]?.task),r=i.flatMap(e=>{if(e.pipelineClass!==a||!e.task||e.task.includes("video")||!["vae_encoder","image_encoder"].includes(e.nodeType)||!e.ports.some(e=>"input"===e.direction&&!e.hidden&&"image"===e.semanticName&&e.types.includes("image"))||!o.some(t=>t.pipelineClass===a&&t.tasks.some(t=>t.task===e.task&&"adapter"===t.execution&&t.operationIds.includes(e.operationId))))return[];let t=i.filter(t=>t.pipelineClass===a&&t.task===e.task);return s.some(e=>!t.some(t=>t.operationId===e.operationId))||t.some(e=>e.ports.some(t=>"input"===t.direction&&t.required&&!t.hidden&&t.types.includes("image")&&"image"!==t.semanticName&&!s.some(i=>i.operationId===e.operationId&&i.ports.some(e=>"input"===e.direction&&e.required&&e.semanticName===t.semanticName))))?[]:[{operation:e,cost:t.filter(e=>!s.some(t=>t.operationId===e.operationId)).length}]}),p=Math.min(...r.map(e=>e.cost)),l=r.filter(e=>e.cost===p);return 1===l.length?l[0].operation:null}export{o as n,i as t}; \ No newline at end of file diff --git a/web/assets/graph-vendor.js b/web/assets/graph-vendor.js index 95992be..a3f94d8 100644 --- a/web/assets/graph-vendor.js +++ b/web/assets/graph-vendor.js @@ -1 +1 @@ -import{r as e,t}from"./rolldown-runtime.js?v=cc046c26d6fe7aa4";var n=t(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),l=Symbol.for("react.context"),s=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),c=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.for("react.activity"),p=Symbol.iterator,h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},m=Object.assign,g={};function y(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||h}function v(){}function b(e,t,n){this.props=e,this.context=t,this.refs=g,this.updater=n||h}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if("object"!=typeof e&&"function"!=typeof e&&null!=e)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},v.prototype=y.prototype;var w=b.prototype=new v;w.constructor=b,m(w,y.prototype),w.isPureReactComponent=!0;var x=Array.isArray;function k(){}var S={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function C(e,n,r){var o=r.ref;return{$$typeof:t,type:e,key:n,ref:void 0===o?null:o,props:r}}function M(e){return"object"==typeof e&&!!e&&e.$$typeof===t}var P=/\/+/g;function O(e,t){return"object"==typeof e&&e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+e.replace(/[=:]/g,function(e){return t[e]})}(""+e.key):t.toString(36)}function T(e,r,o,i,a){var l=typeof e;("undefined"===l||"boolean"===l)&&(e=null);var s=!1;if(null===e)s=!0;else switch(l){case"bigint":case"string":case"number":s=!0;break;case"object":switch(e.$$typeof){case t:case n:s=!0;break;case d:return T((s=e._init)(e._payload),r,o,i,a)}}if(s)return a=a(e),s=""===i?"."+O(e,0):i,x(a)?(o="",null!=s&&(o=s.replace(P,"$&/")+"/"),T(a,r,o,"",function(e){return e})):null!=a&&(M(a)&&(a=function(e,t){return C(e.type,t,e.props)}(a,o+(null==a.key||e&&e.key===a.key?"":(""+a.key).replace(P,"$&/")+"/")+s)),r.push(a)),1;s=0;var u=""===i?".":i+":";if(x(e))for(var c=0;c{t.exports=n()}),o=t(e=>{function t(e,t){var n=e.length;e.push(t);e:for(;0>>1,i=e[r];if(!(0>>1;ro(s,n))uo(c,s)?(e[r]=c,e[u]=n,r=u):(e[r]=s,e[l]=n,r=l);else{if(!(uo(c,n)))break e;e[r]=c,e[u]=n,r=u}}}return t}function o(e,t){var n=e.sortIndex-t.sortIndex;return 0===n?e.id-t.id:n}if(e.unstable_now=void 0,"object"==typeof performance&&"function"==typeof performance.now){var i=performance;e.unstable_now=function(){return i.now()}}else{var a=Date,l=a.now();e.unstable_now=function(){return a.now()-l}}var s=[],u=[],c=1,d=null,f=3,p=!1,h=!1,m=!1,g=!1,y="function"==typeof setTimeout?setTimeout:null,v="function"==typeof clearTimeout?clearTimeout:null,b=typeof setImmediate<"u"?setImmediate:null;function w(e){for(var o=n(u);null!==o;){if(null===o.callback)r(u);else{if(!(o.startTime<=e))break;r(u),o.sortIndex=o.expirationTime,t(s,o)}o=n(u)}}function x(e){if(m=!1,w(e),!h)if(null!==n(s))h=!0,S||(S=!0,k());else{var t=n(u);null!==t&&N(x,t.startTime-e)}}var k,S=!1,E=-1,C=5,M=-1;function P(){return!(!g&&e.unstable_now()-Mt&&P());){var a=d.callback;if("function"==typeof a){d.callback=null,f=d.priorityLevel;var l=a(d.expirationTime<=t);if(t=e.unstable_now(),"function"==typeof l){d.callback=l,w(t),o=!0;break t}d===n(s)&&r(s),w(t)}else r(s);d=n(s)}if(null!==d)o=!0;else{var c=n(u);null!==c&&N(x,c.startTime-t),o=!1}}break e}finally{d=null,f=i,p=!1}o=void 0}}finally{o?k():S=!1}}}if("function"==typeof b)k=function(){b(O)};else if(typeof MessageChannel<"u"){var T=new MessageChannel,_=T.port2;T.port1.onmessage=O,k=function(){_.postMessage(null)}}else k=function(){y(O,0)};function N(t,n){E=y(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125a?(r.sortIndex=i,t(u,r),null===n(s)&&r===n(u)&&(m?(v(E),E=-1):m=!0,N(x,i-a))):(r.sortIndex=l,t(s,r),h||p||(h=!0,S||(S=!0,k()))),r},e.unstable_shouldYield=P,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}}),i=t((e,t)=>{t.exports=o()}),a=t(e=>{var t=r();function n(e){var t="https://react.dev/errors/"+e;if(1{(function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||"function"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}})(),t.exports=a()}),s=t(e=>{var t=i(),n=r(),o=l();function a(e){var t="https://react.dev/errors/"+e;if(1F||(e.current=D[F],D[F]=null,F--)}function V(e,t){F++,D[F]=e.current,e.current=t}var $,B,W=j(null),q=j(null),U=j(null),K=j(null);function Y(e,t){switch(V(U,t),V(q,e),V(W,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?yd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)e=vd(t=yd(t),e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}H(W),V(W,e)}function X(){H(W),H(q),H(U)}function Z(e){null!==e.memoizedState&&V(K,e);var t=W.current,n=vd(t,e.type);t!==n&&(V(q,e),V(W,n))}function G(e){q.current===e&&(H(W),H(q)),K.current===e&&(H(K),df._currentValue=A)}function Q(e){if(void 0===$)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);$=t&&t[1]||"",B=-1)":-1--o||s[r]!==u[o]){var c="\n"+s[r].replace(" at new "," at ");return e.displayName&&c.includes("")&&(c=c.replace("",e.displayName)),c}}while(1<=r&&0<=o);break}}}finally{J=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:"")?Q(n):""}function te(e,t){switch(e.tag){case 26:case 27:case 5:return Q(e.type);case 16:return Q("Lazy");case 13:return e.child!==t&&null!==t?Q("Suspense Fallback"):Q("Suspense");case 19:return Q("SuspenseList");case 0:case 15:return ee(e.type,!1);case 11:return ee(e.type.render,!1);case 1:return ee(e.type,!0);case 31:return Q("Activity");default:return""}}function ne(e){try{var t="",n=null;do{t+=te(e,n),n=e,e=e.return}while(e);return t}catch(e){return"\nError generating stack: "+e.message+"\n"+e.stack}}var re=Object.prototype.hasOwnProperty,oe=t.unstable_scheduleCallback,ie=t.unstable_cancelCallback,ae=t.unstable_shouldYield,le=t.unstable_requestPaint,se=t.unstable_now,ue=t.unstable_getCurrentPriorityLevel,ce=t.unstable_ImmediatePriority,de=t.unstable_UserBlockingPriority,fe=t.unstable_NormalPriority,pe=t.unstable_LowPriority,he=t.unstable_IdlePriority,me=t.log,ge=t.unstable_setDisableYieldValue,ye=null,ve=null;function be(e){if("function"==typeof me&&ge(e),ve&&"function"==typeof ve.setStrictMode)try{ve.setStrictMode(ye,e)}catch{}}var we=Math.clz32?Math.clz32:function(e){return 0==(e>>>=0)?32:31-(xe(e)/ke|0)|0},xe=Math.log,ke=Math.LN2,Se=256,Ee=262144,Ce=4194304;function Me(e){var t=42&e;if(0!==t)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return 261888&e;case 262144:case 524288:case 1048576:case 2097152:return 3932160&e;case 4194304:case 8388608:case 16777216:case 33554432:return 62914560&e;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function Pe(e,t,n){var r=e.pendingLanes;if(0===r)return 0;var o=0,i=e.suspendedLanes,a=e.pingedLanes;e=e.warmLanes;var l=134217727&r;return 0===l?0===(l=r&~i)?0===a?n||0!==(n=r&~e)&&(o=Me(n)):o=Me(a):o=Me(l):0===(r=l&~i)?0===(a&=l)?n||0!==(n=l&~e)&&(o=Me(n)):o=Me(a):o=Me(r),0===o?0:0!==t&&t!==o&&0===(t&i)&&((i=o&-o)>=(n=t&-t)||32===i&&4194048&n)?t:o}function Oe(e,t){return 0===(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)}function Te(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;default:return-1}}function _e(){var e=Ce;return!(62914560&(Ce<<=1))&&(Ce=4194304),e}function Ne(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ie(e,t){e.pendingLanes|=t,268435456!==t&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function ze(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-we(t);e.entangledLanes|=t,e.entanglements[r]=1073741824|e.entanglements[r]|261930&n}function Re(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-we(n),o=1<"u"||void 0===window.document||void 0===window.document.createElement),$t=!1;if(Vt)try{var Bt={};Object.defineProperty(Bt,"passive",{get:function(){$t=!0}}),window.addEventListener("test",Bt,Bt),window.removeEventListener("test",Bt,Bt)}catch{$t=!1}var Wt=null,qt=null,Ut=null;function Kt(){if(Ut)return Ut;var e,t,n=qt,r=n.length,o="value"in Wt?Wt.value:Wt.textContent,i=o.length;for(e=0;e=Mn),Tn=" ",_n=!1;function Nn(e,t){switch(e){case"keyup":return-1!==En.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function In(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var zn=!1,Rn={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Ln(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Rn[e.type]:"textarea"===t}function An(e,t,n,r){Lt?At?At.push(r):At=[r]:Lt=r,0<(t=rd(t,"onChange")).length&&(n=new nn("onChange","change",null,n,r),e.push({event:n,listeners:t}))}var Dn=null,Fn=null;function jn(e){Xc(e,0)}function Hn(e){if(ht(Qe(e)))return e}function Vn(e,t){if("change"===e)return t}var $n=!1;if(Vt){var Bn;if(Vt){var Wn="oninput"in document;if(!Wn){var qn=document.createElement("div");qn.setAttribute("oninput","return;"),Wn="function"==typeof qn.oninput}Bn=Wn}else Bn=!1;$n=Bn&&(!document.documentMode||9=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=er(r)}}function nr(e,t){return!(!e||!t)&&(e===t||(!e||3!==e.nodeType)&&(t&&3===t.nodeType?nr(e,t.parentNode):"contains"in e?e.contains(t):!!e.compareDocumentPosition&&!!(16&e.compareDocumentPosition(t))))}function rr(e){for(var t=mt((e=null!=e&&null!=e.ownerDocument&&null!=e.ownerDocument.defaultView?e.ownerDocument.defaultView:window).document);t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch{n=!1}if(!n)break;t=mt((e=t.contentWindow).document)}return t}function or(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}var ir=Vt&&"documentMode"in document&&11>=document.documentMode,ar=null,lr=null,sr=null,ur=!1;function cr(e,t,n){var r=n.window===n?n.document:9===n.nodeType?n:n.ownerDocument;ur||null==ar||ar!==mt(r)||(r="selectionStart"in(r=ar)&&or(r)?{start:r.selectionStart,end:r.selectionEnd}:{anchorNode:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset},sr&&Jn(sr,r)||(sr=r,0<(r=rd(lr,"onSelect")).length&&(t=new nn("onSelect","select",null,t,n),e.push({event:t,listeners:r}),t.target=ar)))}function dr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var fr={animationend:dr("Animation","AnimationEnd"),animationiteration:dr("Animation","AnimationIteration"),animationstart:dr("Animation","AnimationStart"),transitionrun:dr("Transition","TransitionRun"),transitionstart:dr("Transition","TransitionStart"),transitioncancel:dr("Transition","TransitionCancel"),transitionend:dr("Transition","TransitionEnd")},pr={},hr={};function mr(e){if(pr[e])return pr[e];if(!fr[e])return e;var t,n=fr[e];for(t in n)if(n.hasOwnProperty(t)&&t in hr)return pr[e]=n[t];return e}Vt&&(hr=document.createElement("div").style,"AnimationEvent"in window||(delete fr.animationend.animation,delete fr.animationiteration.animation,delete fr.animationstart.animation),"TransitionEvent"in window||delete fr.transitionend.transition);var gr=mr("animationend"),yr=mr("animationiteration"),vr=mr("animationstart"),br=mr("transitionrun"),wr=mr("transitionstart"),xr=mr("transitioncancel"),kr=mr("transitionend"),Sr=new Map,Er="abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Cr(e,t){Sr.set(e,t),rt(t,[e])}Er.push("scrollEnd");var Mr="function"==typeof reportError?reportError:function(e){if("object"==typeof window&&"function"==typeof window.ErrorEvent){var t=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:"object"==typeof e&&e&&"string"==typeof e.message?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if("object"==typeof process&&"function"==typeof process.emit)return void process.emit("uncaughtException",e);console.error(e)},Pr=[],Or=0,Tr=0;function _r(){for(var e=Or,t=Tr=Or=0;t>=a,o-=a,no=1<<32-we(t)+o|n<m?(g=d,d=null):g=d.sibling;var y=p(o,d,l[m],s);if(null===y){null===d&&(d=g);break}e&&d&&null===y.alternate&&t(o,d),a=i(y,a,m),null===c?u=y:c.sibling=y,c=y,d=g}if(m===l.length)return n(o,d),fo&&oo(o,m),u;if(null===d){for(;mg?(y=m,m=null):y=m.sibling;var b=p(o,m,v.value,u);if(null===b){null===m&&(m=y);break}e&&m&&null===b.alternate&&t(o,m),l=i(b,l,g),null===d?c=b:d.sibling=b,d=b,m=y}if(v.done)return n(o,m),fo&&oo(o,g),c;if(null===m){for(;!v.done;g++,v=s.next())null!==(v=f(o,v.value,u))&&(l=i(v,l,g),null===d?c=v:d.sibling=v,d=v);return fo&&oo(o,g),c}for(m=r(m);!v.done;g++,v=s.next())null!==(v=h(m,o,g,v.value,u))&&(e&&null!==v.alternate&&m.delete(null===v.key?g:v.key),l=i(v,l,g),null===d?c=v:d.sibling=v,d=v);return e&&m.forEach(function(e){return t(o,e)}),fo&&oo(o,g),c}function w(e,r,i,s){if("object"==typeof i&&i&&i.type===y&&null===i.key&&(i=i.props.children),"object"==typeof i&&i){switch(i.$$typeof){case m:e:{for(var u=i.key;null!==r;){if(r.key===u){if((u=i.type)===y){if(7===r.tag){n(e,r.sibling),(s=o(r,i.props.children)).return=e,e=s;break e}}else if(r.elementType===u||"object"==typeof u&&u&&u.$$typeof===M&&oi(u)===r.type){n(e,r.sibling),di(s=o(r,i.props),i),s.return=e,e=s;break e}n(e,r);break}t(e,r),r=r.sibling}i.type===y?((s=Br(i.props.children,e.mode,s,i.key)).return=e,e=s):(di(s=$r(i.type,i.key,i.props,null,e.mode,s),i),s.return=e,e=s)}return l(e);case g:e:{for(u=i.key;null!==r;){if(r.key===u){if(4===r.tag&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),(s=o(r,i.children||[])).return=e,e=s;break e}n(e,r);break}t(e,r),r=r.sibling}(s=Ur(i,e.mode,s)).return=e,e=s}return l(e);case M:return w(e,r,i=oi(i),s)}if(z(i))return v(e,r,i,s);if(_(i)){if("function"!=typeof(u=_(i)))throw Error(a(150));return b(e,r,i=u.call(i),s)}if("function"==typeof i.then)return w(e,r,ci(i),s);if(i.$$typeof===x)return w(e,r,Ro(e,i),s);fi(e,i)}return"string"==typeof i&&""!==i||"number"==typeof i||"bigint"==typeof i?(i=""+i,null!==r&&6===r.tag?(n(e,r.sibling),(s=o(r,i)).return=e,e=s):(n(e,r),(s=Wr(i,e.mode,s)).return=e,e=s),l(e)):n(e,r)}return function(e,t,n,r){try{ui=0;var o=w(e,t,n,r);return si=null,o}catch(t){if(t===Qo||t===ei)throw t;var i=Fr(29,t,null,e.mode);return i.lanes=r,i.return=e,i}}}var hi=pi(!0),mi=pi(!1),gi=!1;function yi(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function vi(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function bi(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function wi(e,t,n){var r=e.updateQueue;if(null===r)return null;if(r=r.shared,2&pu){var o=r.pending;return null===o?t.next=t:(t.next=o.next,o.next=t),r.pending=t,t=Lr(e),Rr(e,null,n),t}return Nr(e,r,t,n),Lr(e)}function xi(e,t,n){if(null!==(t=t.updateQueue)&&(t=t.shared,4194048&n)){var r=t.lanes;n|=r&=e.pendingLanes,t.lanes=n,Re(e,n)}}function ki(e,t){var n=e.updateQueue,r=e.alternate;if(null!==r&&n===(r=r.updateQueue)){var o=null,i=null;if(null!==(n=n.firstBaseUpdate)){do{var a={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};null===i?o=i=a:i=i.next=a,n=n.next}while(null!==n);null===i?o=i=t:i=i.next=t}else o=i=t;return n={baseState:r.baseState,firstBaseUpdate:o,lastBaseUpdate:i,shared:r.shared,callbacks:r.callbacks},void(e.updateQueue=n)}null===(e=n.lastBaseUpdate)?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Si=!1;function Ei(){if(Si&&null!==qo)throw qo}function Ci(e,t,n,r){Si=!1;var o=e.updateQueue;gi=!1;var i=o.firstBaseUpdate,a=o.lastBaseUpdate,l=o.shared.pending;if(null!==l){o.shared.pending=null;var s=l,u=s.next;s.next=null,null===a?i=u:a.next=u,a=s;var c=e.alternate;null!==c&&(l=(c=c.updateQueue).lastBaseUpdate)!==a&&(null===l?c.firstBaseUpdate=u:l.next=u,c.lastBaseUpdate=s)}if(null!==i){var d=o.baseState;for(a=0,c=u=s=null,l=i;;){var f=-536870913&l.lane,h=f!==l.lane;if(h?(gu&f)===f:(r&f)===f){0!==f&&f===Wo&&(Si=!0),null!==c&&(c=c.next={lane:0,tag:l.tag,payload:l.payload,callback:null,next:null});e:{var m=e,g=l;f=t;var y=n;switch(g.tag){case 1:if("function"==typeof(m=g.payload)){d=m.call(y,d,f);break e}d=m;break e;case 3:m.flags=-65537&m.flags|128;case 0:if(null==(f="function"==typeof(m=g.payload)?m.call(y,d,f):m))break e;d=p({},d,f);break e;case 2:gi=!0}}null!==(f=l.callback)&&(e.flags|=64,h&&(e.flags|=8192),null===(h=o.callbacks)?o.callbacks=[f]:h.push(f))}else h={lane:f,tag:l.tag,payload:l.payload,callback:l.callback,next:null},null===c?(u=c=h,s=d):c=c.next=h,a|=f;if(null===(l=l.next)){if(null===(l=o.shared.pending))break;l=(h=l).next,h.next=null,o.lastBaseUpdate=h,o.shared.pending=null}}null===c&&(s=d),o.baseState=s,o.firstBaseUpdate=u,o.lastBaseUpdate=c,null===i&&(o.shared.lanes=0),Eu|=a,e.lanes=a,e.memoizedState=d}}function Mi(e,t){if("function"!=typeof e)throw Error(a(191,e));e.call(t)}function Pi(e,t){var n=e.callbacks;if(null!==n)for(e.callbacks=null,e=0;ei?i:8;var a=R.T,l={};R.T=l,dl(e,!1,t,n);try{var s=o(),u=R.S;null!==u&&u(l,s),"object"==typeof s&&s&&"function"==typeof s.then?cl(e,t,function(e,t){var n=[],r={status:"pending",value:null,reason:null,then:function(e){n.push(e)}};return e.then(function(){r.status="fulfilled",r.value=t;for(var e=0;e<\/script>",i=i.removeChild(i.firstChild);break;case"select":i="string"==typeof r.is?l.createElement("select",{is:r.is}):l.createElement("select"),r.multiple?i.multiple=!0:r.size&&(i.size=r.size);break;default:i="string"==typeof r.is?l.createElement(o,{is:r.is}):l.createElement(o)}}i[Ve]=t,i[$e]=r;e:for(l=t.child;null!==l;){if(5===l.tag||6===l.tag)i.appendChild(l.stateNode);else if(4!==l.tag&&27!==l.tag&&null!==l.child){l.child.return=l,l=l.child;continue}if(l===t)break e;for(;null===l.sibling;){if(null===l.return||l.return===t)break e;l=l.return}l.sibling.return=l.return,l=l.sibling}t.stateNode=i;e:switch(fd(i,o,r),o){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}r&&ls(t)}}return fs(t),ss(t,t.type,null===e||e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&null!=t.stateNode)e.memoizedProps!==r&&ls(t);else{if("string"!=typeof r&&null===t.stateNode)throw Error(a(166));if(e=U.current,bo(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,null!==(o=uo))switch(o.tag){case 27:case 5:r=o.memoizedProps}e[Ve]=t,(e=!!(e.nodeValue===n||null!==r&&!0===r.suppressHydrationWarning||ud(e.nodeValue,n)))||go(t,!0)}else(e=gd(e).createTextNode(r))[Ve]=t,t.stateNode=e}return fs(t),null;case 31:if(n=t.memoizedState,null===e||null!==e.memoizedState){if(r=bo(t),null!==n){if(null===e){if(!r)throw Error(a(318));if(!(e=null===(e=t.memoizedState)?null:e.dehydrated))throw Error(a(557));e[Ve]=t}else wo(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;fs(t),e=!1}else n=xo(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return 256&t.flags?(ji(t),t):(ji(t),null);if(128&t.flags)throw Error(a(558))}return fs(t),null;case 13:if(r=t.memoizedState,null===e||null!==e.memoizedState&&null!==e.memoizedState.dehydrated){if(o=bo(t),null!==r&&null!==r.dehydrated){if(null===e){if(!o)throw Error(a(318));if(!(o=null===(o=t.memoizedState)?null:o.dehydrated))throw Error(a(317));o[Ve]=t}else wo(),!(128&t.flags)&&(t.memoizedState=null),t.flags|=4;fs(t),o=!1}else o=xo(),null!==e&&null!==e.memoizedState&&(e.memoizedState.hydrationErrors=o),o=!0;if(!o)return 256&t.flags?(ji(t),t):(ji(t),null)}return ji(t),128&t.flags?(t.lanes=n,t):(n=null!==r,e=null!==e&&null!==e.memoizedState,n&&(o=null,null!==(r=t.child).alternate&&null!==r.alternate.memoizedState&&null!==r.alternate.memoizedState.cachePool&&(o=r.alternate.memoizedState.cachePool.pool),i=null,null!==r.memoizedState&&null!==r.memoizedState.cachePool&&(i=r.memoizedState.cachePool.pool),i!==o&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),cs(t,t.updateQueue),fs(t),null);case 4:return X(),null===e&&Jc(t.stateNode.containerInfo),fs(t),null;case 10:return Po(t.type),fs(t),null;case 19:if(H(Hi),null===(r=t.memoizedState))return fs(t),null;if(o=!!(128&t.flags),null===(i=r.rendering))if(o)ds(r,!1);else{if(0!==Su||null!==e&&128&e.flags)for(e=t.child;null!==e;){if(null!==(i=Vi(e))){for(t.flags|=128,ds(r,!1),e=i.updateQueue,t.updateQueue=e,cs(t,e),t.subtreeFlags=0,e=n,n=t.child;null!==n;)Vr(n,e),n=n.sibling;return V(Hi,1&Hi.current|2),fo&&oo(t,r.treeForkCount),t.child}e=e.sibling}null!==r.tail&&se()>Ru&&(t.flags|=128,o=!0,ds(r,!1),t.lanes=4194304)}else{if(!o)if(null!==(e=Vi(i))){if(t.flags|=128,o=!0,e=e.updateQueue,t.updateQueue=e,cs(t,e),ds(r,!0),null===r.tail&&"hidden"===r.tailMode&&!i.alternate&&!fo)return fs(t),null}else 2*se()-r.renderingStartTime>Ru&&536870912!==n&&(t.flags|=128,o=!0,ds(r,!1),t.lanes=4194304);r.isBackwards?(i.sibling=t.child,t.child=i):(null===(e=r.last)?t.child=i:e.sibling=i,r.last=i)}return null===r.tail?(fs(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=se(),e.sibling=null,n=Hi.current,V(Hi,o?1&n|2:1&n),fo&&oo(t,r.treeForkCount),e);case 22:case 23:return ji(t),Ii(),r=null!==t.memoizedState,null===e?r&&(t.flags|=8192):null!==e.memoizedState!==r&&(t.flags|=8192),r?536870912&n&&!(128&t.flags)&&(fs(t),6&t.subtreeFlags&&(t.flags|=8192)):fs(t),null!==(n=t.updateQueue)&&cs(t,n.retryQueue),n=null,null!==e&&null!==e.memoizedState&&null!==e.memoizedState.cachePool&&(n=e.memoizedState.cachePool.pool),r=null,null!==t.memoizedState&&null!==t.memoizedState.cachePool&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),null!==e&&H(Yo),null;case 24:return n=null,null!==e&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Po(jo),fs(t),null;case 25:case 30:return null}throw Error(a(156,t.tag))}function hs(e,t){switch(lo(t),t.tag){case 1:return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 3:return Po(jo),X(),65536&(e=t.flags)&&!(128&e)?(t.flags=-65537&e|128,t):null;case 26:case 27:case 5:return G(t),null;case 31:if(null!==t.memoizedState){if(ji(t),null===t.alternate)throw Error(a(340));wo()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 13:if(ji(t),null!==(e=t.memoizedState)&&null!==e.dehydrated){if(null===t.alternate)throw Error(a(340));wo()}return 65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 19:return H(Hi),null;case 4:return X(),null;case 10:return Po(t.type),null;case 22:case 23:return ji(t),Ii(),null!==e&&H(Yo),65536&(e=t.flags)?(t.flags=-65537&e|128,t):null;case 24:return Po(jo),null;default:return null}}function ms(e,t){switch(lo(t),t.tag){case 3:Po(jo),X();break;case 26:case 27:case 5:G(t);break;case 4:X();break;case 31:null!==t.memoizedState&&ji(t);break;case 13:ji(t);break;case 19:H(Hi);break;case 10:Po(t.type);break;case 22:case 23:ji(t),Ii(),null!==e&&H(Yo);break;case 24:Po(jo)}}function gs(e,t){try{var n=t.updateQueue,r=null===n?null:n.lastEffect;if(null!==r){var o=r.next;n=o;do{if((n.tag&e)===e){r=void 0;var i=n.create,a=n.inst;r=i(),a.destroy=r}n=n.next}while(n!==o)}}catch(e){Sc(t,t.return,e)}}function ys(e,t,n){try{var r=t.updateQueue,o=null===r?null:r.lastEffect;if(null!==o){var i=o.next;r=i;do{if((r.tag&e)===e){var a=r.inst,l=a.destroy;if(void 0!==l){a.destroy=void 0,o=t;var s=n,u=l;try{u()}catch(e){Sc(o,s,e)}}}r=r.next}while(r!==i)}}catch(e){Sc(t,t.return,e)}}function vs(e){var t=e.updateQueue;if(null!==t){var n=e.stateNode;try{Pi(t,n)}catch(t){Sc(e,e.return,t)}}}function bs(e,t,n){n.props=Sl(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Sc(e,t,n)}}function ws(e,t){try{var n=e.ref;if(null!==n){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;default:r=e.stateNode}"function"==typeof n?e.refCleanup=n(r):n.current=r}}catch(n){Sc(e,t,n)}}function xs(e,t){var n=e.ref,r=e.refCleanup;if(null!==n)if("function"==typeof r)try{r()}catch(n){Sc(e,t,n)}finally{e.refCleanup=null,null!=(e=e.alternate)&&(e.refCleanup=null)}else if("function"==typeof n)try{n(null)}catch(n){Sc(e,t,n)}else n.current=null}function ks(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":n.autoFocus&&r.focus();break e;case"img":n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Sc(e,e.return,t)}}function Ss(e,t,n){try{var r=e.stateNode;(function(e,t,n,r){switch(t){case"div":case"span":case"svg":case"path":case"a":case"g":case"p":case"li":break;case"input":var o=null,i=null,l=null,s=null,u=null,c=null,d=null;for(h in n){var f=n[h];if(n.hasOwnProperty(h)&&null!=f)switch(h){case"checked":case"value":break;case"defaultValue":u=f;default:r.hasOwnProperty(h)||cd(e,t,h,null,r,f)}}for(var p in r){var h=r[p];if(f=n[p],r.hasOwnProperty(p)&&(null!=h||null!=f))switch(p){case"type":i=h;break;case"name":o=h;break;case"checked":c=h;break;case"defaultChecked":d=h;break;case"value":l=h;break;case"defaultValue":s=h;break;case"children":case"dangerouslySetInnerHTML":if(null!=h)throw Error(a(137,t));break;default:h!==f&&cd(e,t,p,h,r,f)}}return void vt(e,l,s,u,c,d,i,o);case"select":for(i in h=l=s=p=null,n)if(u=n[i],n.hasOwnProperty(i)&&null!=u)switch(i){case"value":break;case"multiple":h=u;default:r.hasOwnProperty(i)||cd(e,t,i,null,r,u)}for(o in r)if(i=r[o],u=n[o],r.hasOwnProperty(o)&&(null!=i||null!=u))switch(o){case"value":p=i;break;case"defaultValue":s=i;break;case"multiple":l=i;default:i!==u&&cd(e,t,o,i,r,u)}return t=s,n=l,r=h,void(null==p?!!r!=!!n&&(null==t?xt(e,!!n,n?[]:"",!1):xt(e,!!n,t,!0)):xt(e,!!n,p,!1));case"textarea":for(s in h=p=null,n)if(o=n[s],n.hasOwnProperty(s)&&null!=o&&!r.hasOwnProperty(s))switch(s){case"value":case"children":break;default:cd(e,t,s,null,r,o)}for(l in r)if(o=r[l],i=n[l],r.hasOwnProperty(l)&&(null!=o||null!=i))switch(l){case"value":p=o;break;case"defaultValue":h=o;break;case"children":break;case"dangerouslySetInnerHTML":if(null!=o)throw Error(a(91));break;default:o!==i&&cd(e,t,l,o,r,i)}return void kt(e,p,h);case"option":for(var m in n)p=n[m],n.hasOwnProperty(m)&&null!=p&&!r.hasOwnProperty(m)&&("selected"===m?e.selected=!1:cd(e,t,m,null,r,p));for(u in r)p=r[u],h=n[u],!r.hasOwnProperty(u)||p===h||null==p&&null==h||("selected"===u?e.selected=p&&"function"!=typeof p&&"symbol"!=typeof p:cd(e,t,u,p,r,h));return;case"img":case"link":case"area":case"base":case"br":case"col":case"embed":case"hr":case"keygen":case"meta":case"param":case"source":case"track":case"wbr":case"menuitem":for(var g in n)p=n[g],n.hasOwnProperty(g)&&null!=p&&!r.hasOwnProperty(g)&&cd(e,t,g,null,r,p);for(c in r)if(p=r[c],h=n[c],r.hasOwnProperty(c)&&p!==h&&(null!=p||null!=h))switch(c){case"children":case"dangerouslySetInnerHTML":if(null!=p)throw Error(a(137,t));break;default:cd(e,t,c,p,r,h)}return;default:if(Ot(t)){for(var y in n)p=n[y],n.hasOwnProperty(y)&&void 0!==p&&!r.hasOwnProperty(y)&&dd(e,t,y,void 0,r,p);for(d in r)p=r[d],h=n[d],!r.hasOwnProperty(d)||p===h||void 0===p&&void 0===h||dd(e,t,d,p,r,h);return}}for(var v in n)p=n[v],n.hasOwnProperty(v)&&null!=p&&!r.hasOwnProperty(v)&&cd(e,t,v,null,r,p);for(f in r)p=r[f],h=n[f],!r.hasOwnProperty(f)||p===h||null==p&&null==h||cd(e,t,f,p,r,h)})(r,e.type,n,t),r[$e]=t}catch(t){Sc(e,e.return,t)}}function Es(e){return 5===e.tag||3===e.tag||26===e.tag||27===e.tag&&Md(e.type)||4===e.tag}function Cs(e){e:for(;;){for(;null===e.sibling;){if(null===e.return||Es(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;5!==e.tag&&6!==e.tag&&18!==e.tag;){if(27===e.tag&&Md(e.type)||2&e.flags||null===e.child||4===e.tag)continue e;e.child.return=e,e=e.child}if(!(2&e.flags))return e.stateNode}}function Ms(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?(9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).insertBefore(e,t):((t=9===n.nodeType?n.body:"HTML"===n.nodeName?n.ownerDocument.body:n).appendChild(e),null!=(n=n._reactRootContainer)||null!==t.onclick||(t.onclick=It));else if(4!==r&&(27===r&&Md(e.type)&&(n=e.stateNode,t=null),null!==(e=e.child)))for(Ms(e,t,n),e=e.sibling;null!==e;)Ms(e,t,n),e=e.sibling}function Ps(e,t,n){var r=e.tag;if(5===r||6===r)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(4!==r&&(27===r&&Md(e.type)&&(n=e.stateNode),null!==(e=e.child)))for(Ps(e,t,n),e=e.sibling;null!==e;)Ps(e,t,n),e=e.sibling}function Os(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,o=t.attributes;o.length;)t.removeAttributeNode(o[0]);fd(t,r,n),t[Ve]=e,t[$e]=n}catch(t){Sc(e,e.return,t)}}var Ts=!1,_s=!1,Ns=!1,Is="function"==typeof WeakSet?WeakSet:Set,zs=null;function Rs(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:Ys(e,n),4&r&&gs(5,n);break;case 1:if(Ys(e,n),4&r)if(e=n.stateNode,null===t)try{e.componentDidMount()}catch(e){Sc(n,n.return,e)}else{var o=Sl(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(o,t,e.__reactInternalSnapshotBeforeUpdate)}catch(e){Sc(n,n.return,e)}}64&r&&vs(n),512&r&&ws(n,n.return);break;case 3:if(Ys(e,n),64&r&&null!==(e=n.updateQueue)){if(t=null,null!==n.child)switch(n.child.tag){case 27:case 5:case 1:t=n.child.stateNode}try{Pi(e,t)}catch(e){Sc(n,n.return,e)}}break;case 27:null===t&&4&r&&Os(n);case 26:case 5:Ys(e,n),null===t&&4&r&&ks(n),512&r&&ws(n,n.return);break;case 12:Ys(e,n);break;case 31:Ys(e,n),4&r&&Hs(e,n);break;case 13:Ys(e,n),4&r&&Vs(e,n),64&r&&null!==(e=n.memoizedState)&&null!==(e=e.dehydrated)&&function(e,t){var n=e.ownerDocument;if("$~"===e.data)e._reactRetry=t;else if("$?"!==e.data||"loading"!==n.readyState)t();else{var r=function(){t(),n.removeEventListener("DOMContentLoaded",r)};n.addEventListener("DOMContentLoaded",r),e._reactRetry=r}}(e,n=Pc.bind(null,n));break;case 22:if(!(r=null!==n.memoizedState||Ts)){t=null!==t&&null!==t.memoizedState||_s,o=Ts;var i=_s;Ts=r,(_s=t)&&!i?Zs(e,n,!!(8772&n.subtreeFlags)):Ys(e,n),Ts=o,_s=i}break;case 30:break;default:Ys(e,n)}}function Ls(e){var t=e.alternate;null!==t&&(e.alternate=null,Ls(t)),e.child=null,e.deletions=null,e.sibling=null,5===e.tag&&null!==(t=e.stateNode)&&Xe(t),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var As=null,Ds=!1;function Fs(e,t,n){for(n=n.child;null!==n;)js(e,t,n),n=n.sibling}function js(e,t,n){if(ve&&"function"==typeof ve.onCommitFiberUnmount)try{ve.onCommitFiberUnmount(ye,n)}catch{}switch(n.tag){case 26:_s||xs(n,t),Fs(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode).parentNode.removeChild(n);break;case 27:_s||xs(n,t);var r=As,o=Ds;Md(n.type)&&(As=n.stateNode,Ds=!1),Fs(e,t,n),Fd(n.stateNode),As=r,Ds=o;break;case 5:_s||xs(n,t);case 6:if(r=As,o=Ds,As=null,Fs(e,t,n),Ds=o,null!==(As=r))if(Ds)try{(9===As.nodeType?As.body:"HTML"===As.nodeName?As.ownerDocument.body:As).removeChild(n.stateNode)}catch(e){Sc(n,t,e)}else try{As.removeChild(n.stateNode)}catch(e){Sc(n,t,e)}break;case 18:null!==As&&(Ds?(Pd(9===(e=As).nodeType?e.body:"HTML"===e.nodeName?e.ownerDocument.body:e,n.stateNode),Bf(e)):Pd(As,n.stateNode));break;case 4:r=As,o=Ds,As=n.stateNode.containerInfo,Ds=!0,Fs(e,t,n),As=r,Ds=o;break;case 0:case 11:case 14:case 15:ys(2,n,t),_s||ys(4,n,t),Fs(e,t,n);break;case 1:_s||(xs(n,t),"function"==typeof(r=n.stateNode).componentWillUnmount&&bs(n,t,r)),Fs(e,t,n);break;case 21:Fs(e,t,n);break;case 22:_s=(r=_s)||null!==n.memoizedState,Fs(e,t,n),_s=r;break;default:Fs(e,t,n)}}function Hs(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)){e=e.dehydrated;try{Bf(e)}catch(e){Sc(t,t.return,e)}}}function Vs(e,t){if(null===t.memoizedState&&null!==(e=t.alternate)&&null!==(e=e.memoizedState)&&null!==(e=e.dehydrated))try{Bf(e)}catch(e){Sc(t,t.return,e)}}function $s(e,t){var n=function(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return null===t&&(t=e.stateNode=new Is),t;case 22:return null===(t=(e=e.stateNode)._retryCache)&&(t=e._retryCache=new Is),t;default:throw Error(a(435,e.tag))}}(e);t.forEach(function(t){if(!n.has(t)){n.add(t);var r=Oc.bind(null,e,t);t.then(r,r)}})}function Bs(e,t){var n=t.deletions;if(null!==n)for(var r=0;r title"))),fd(i,r,n),i[Ve]=e,et(i),r=i;break e;case"link":var l=nf("link","href",o).get(r+(n.href||""));if(l)for(var s=0;sl)break;var c=s.transferSize,d=s.initiatorType;c&&pd(d)&&(a+=c*((s=s.responseEnd)af?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(o)}}:null}(d,h),null!==h)return Hu=i,e.cancelPendingCommit=h(mc.bind(null,e,t,i,n,r,o,a,l,s,c,d,null,f,p)),void Qu(e,i,a,!u)}mc(e,t,i,n,r,o,a,l,s)}function Gu(e){for(var t=e;;){var n=t.tag;if((0===n||11===n||15===n)&&16384&t.flags&&null!==(n=t.updateQueue)&&null!==(n=n.stores))for(var r=0;rg&&(a=g,g=m,m=a);var y=tr(l,m),v=tr(l,g);if(y&&v&&(1!==p.rangeCount||p.anchorNode!==y.node||p.anchorOffset!==y.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var b=d.createRange();b.setStart(y.node,y.offset),p.removeAllRanges(),m>g?(p.addRange(b),p.extend(v.node,v.offset)):(b.setEnd(v.node,v.offset),p.addRange(b))}}}}for(d=[],p=l;p=p.parentNode;)1===p.nodeType&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for("function"==typeof l.focus&&l.focus(),l=0;ln?32:n,R.T=null,n=$u,$u=null;var i=Fu,l=Hu;if(Du=0,ju=Fu=null,Hu=0,6&pu)throw Error(a(331));var s=pu;if(pu|=4,su(i.current),eu(i,i.current,l,n),pu=s,Ac(0,!1),ve&&"function"==typeof ve.onPostCommitFiberRoot)try{ve.onPostCommitFiberRoot(ye,i)}catch{}return!0}finally{L.p=o,R.T=r,bc(e,t)}}function kc(e,t,n){t=Yr(n,t),null!==(e=wi(e,t=Tl(e.stateNode,t,2),2))&&(Ie(e,2),Lc(e))}function Sc(e,t,n){if(3===e.tag)kc(e,e,n);else for(;null!==t;){if(3===t.tag){kc(t,e,n);break}if(1===t.tag){var r=t.stateNode;if("function"==typeof t.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===Au||!Au.has(r))){e=Yr(n,e),null!==(r=wi(t,n=_l(2),2))&&(Nl(n,r,t,e),Ie(r,2),Lc(r));break}}t=t.return}}function Ec(e,t,n){var r=e.pingCache;if(null===r){r=e.pingCache=new fu;var o=new Set;r.set(t,o)}else void 0===(o=r.get(t))&&(o=new Set,r.set(t,o));o.has(n)||(xu=!0,o.add(n),e=Cc.bind(null,e,t,n),t.then(e,e))}function Cc(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,hu===e&&(gu&n)===n&&(4===Su||3===Su&&(62914560&gu)===gu&&300>se()-Iu?!(2&pu)&&tc(e,0):Mu|=n,Ou===gu&&(Ou=0)),Lc(e)}function Mc(e,t){0===t&&(t=_e()),null!==(e=zr(e,t))&&(Ie(e,t),Lc(e))}function Pc(e){var t=e.memoizedState,n=0;null!==t&&(n=t.retryLane),Mc(e,n)}function Oc(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,o=e.memoizedState;null!==o&&(n=o.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}null!==r&&r.delete(t),Mc(e,n)}var Tc=null,_c=null,Nc=!1,Ic=!1,zc=!1,Rc=0;function Lc(e){e!==_c&&null===e.next&&(null===_c?Tc=_c=e:_c=_c.next=e),Ic=!0,Nc||(Nc=!0,Ed(function(){6&pu?oe(ce,Dc):Fc()}))}function Ac(e,t){if(!zc&&Ic){zc=!0;do{for(var n=!1,r=Tc;null!==r;){if(!t)if(0!==e){var o=r.pendingLanes;if(0===o)var i=0;else{var a=r.suspendedLanes,l=r.pingedLanes;i=(1<<31-we(42|e)+1)-1,i=201326741&(i&=o&~(a&~l))?201326741&i|1:i?2|i:0}0!==i&&(n=!0,Vc(r,i))}else i=gu,!(3&(i=Pe(r,r===hu?i:0,null!==r.cancelPendingCommit||-1!==r.timeoutHandle)))||Oe(r,i)||(n=!0,Vc(r,i));r=r.next}}while(n);zc=!1}}function Dc(){Fc()}function Fc(){Ic=Nc=!1;var e=0;0!==Rc&&function(){var e=window.event;return e&&"popstate"===e.type?e!==wd&&(wd=e,!0):(wd=null,!1)}()&&(e=Rc);for(var t=se(),n=null,r=Tc;null!==r;){var o=r.next,i=jc(r,t);0===i?(r.next=null,null===n?Tc=o:n.next=o,null===o&&(_c=n)):(n=r,(0!==e||3&i)&&(Ic=!0)),r=o}0!==Du&&5!==Du||Ac(e,!1),0!==Rc&&(Rc=0)}function jc(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,o=e.expirationTimes,i=-62914561&e.pendingLanes;0"u"?null:document;function Wd(e,t,n){var r=Bd;if(r&&"string"==typeof t&&t){var o=yt(t);o='link[rel="'+e+'"][href="'+o+'"]',"string"==typeof n&&(o+='[crossorigin="'+n+'"]'),Hd.has(o)||(Hd.add(o),e={rel:e,crossOrigin:n,href:t},null===r.querySelector(o)&&(fd(t=r.createElement("link"),"link",e),et(t),r.head.appendChild(t)))}}function qd(e,t,n,r){var o=(o=U.current)?Vd(o):null;if(!o)throw Error(a(446));switch(e){case"meta":case"title":return null;case"style":return"string"==typeof n.precedence&&"string"==typeof n.href?(t=Ud(n.href),(r=(n=Je(o).hoistableStyles).get(t))||(r={type:"style",instance:null,count:0,state:null},n.set(t,r)),r):{type:"void",instance:null,count:0,state:null};case"link":if("stylesheet"===n.rel&&"string"==typeof n.href&&"string"==typeof n.precedence){e=Ud(n.href);var i=Je(o).hoistableStyles,l=i.get(e);if(l||(o=o.ownerDocument||o,l={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},i.set(e,l),(i=o.querySelector(Kd(e)))&&!i._p&&(l.instance=i,l.state.loading=5),jd.has(e)||(n={rel:"preload",as:"style",href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},jd.set(e,n),i||function(e,t,n,r){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?r.loading=1:(t=e.createElement("link"),r.preload=t,t.addEventListener("load",function(){return r.loading|=1}),t.addEventListener("error",function(){return r.loading|=2}),fd(t,"link",n),et(t),e.head.appendChild(t))}(o,e,n,l.state))),t&&null===r)throw Error(a(528,""));return l}if(t&&null!==r)throw Error(a(529,""));return null;case"script":return t=n.async,"string"==typeof(n=n.src)&&t&&"function"!=typeof t&&"symbol"!=typeof t?(t=Xd(n),(r=(n=Je(o).hoistableScripts).get(t))||(r={type:"script",instance:null,count:0,state:null},n.set(t,r)),r):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,e))}}function Ud(e){return'href="'+yt(e)+'"'}function Kd(e){return'link[rel="stylesheet"]['+e+"]"}function Yd(e){return p({},e,{"data-precedence":e.precedence,precedence:null})}function Xd(e){return'[src="'+yt(e)+'"]'}function Zd(e){return"script[async]"+e}function Gd(e,t,n){if(t.count++,null===t.instance)switch(t.type){case"style":var r=e.querySelector('style[data-href~="'+yt(n.href)+'"]');if(r)return t.instance=r,et(r),r;var o=p({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return et(r=(e.ownerDocument||e).createElement("style")),fd(r,"style",o),Qd(r,n.precedence,e),t.instance=r;case"stylesheet":o=Ud(n.href);var i=e.querySelector(Kd(o));if(i)return t.state.loading|=4,t.instance=i,et(i),i;r=Yd(n),(o=jd.get(o))&&Jd(r,o),et(i=(e.ownerDocument||e).createElement("link"));var l=i;return l._p=new Promise(function(e,t){l.onload=e,l.onerror=t}),fd(i,"link",r),t.state.loading|=4,Qd(i,n.precedence,e),t.instance=i;case"script":return i=Xd(n.src),(o=e.querySelector(Zd(i)))?(t.instance=o,et(o),o):(r=n,(o=jd.get(i))&&ef(r=p({},n),o),et(o=(e=e.ownerDocument||e).createElement("script")),fd(o,"link",r),e.head.appendChild(o),t.instance=o);case"void":return null;default:throw Error(a(443,t.type))}else"stylesheet"===t.type&&!(4&t.state.loading)&&(r=t.instance,t.state.loading|=4,Qd(r,n.precedence,e));return t.instance}function Qd(e,t,n){for(var r=n.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),o=r.length?r[r.length-1]:null,i=o,a=0;a title"):null)}function of(e){return!("stylesheet"===e.type&&!(3&e.state.loading))}var af=0;function lf(){if(this.count--,0===this.count&&(0===this.imgCount||!this.waitingForImages))if(this.stylesheets)uf(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}var sf=null;function uf(e,t){e.stylesheets=null,null!==e.unsuspend&&(e.count++,sf=new Map,t.forEach(cf,e),sf=null,lf.call(e))}function cf(e,t){if(!(4&t.state.loading)){var n=sf.get(e);if(n)var r=n.get(null);else{n=new Map,sf.set(e,n);for(var o=e.querySelectorAll("link[data-precedence],style[data-precedence]"),i=0;i{(function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||"function"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}})(),t.exports=s()}),c=t(e=>{var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.fragment");function r(e,n,r){var o=null;if(void 0!==r&&(o=""+r),void 0!==n.key&&(o=""+n.key),"key"in n)for(var i in r={},n)"key"!==i&&(r[i]=n[i]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:o,ref:void 0===n?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r}),d=t((e,t)=>{t.exports=c()}),f=e(r(),1),p=d();function h(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let n,r=0;r{}};function g(){for(var e,t=0,n=arguments.length,r={};t=0&&(n=e.slice(r+1),e=e.slice(0,r)),e&&!t.hasOwnProperty(e))throw Error("unknown type: "+e);return{type:e,name:n}})}(e+"",r),i=-1,a=o.length;if(!(arguments.length<2)){if(null!=t&&"function"!=typeof t)throw Error("invalid callback: "+t);for(;++i0)for(var n,r,o=Array(n),i=0;i=0&&"xmlns"!==(t=e.slice(0,n))&&(e=e.slice(n+1)),w.hasOwnProperty(t)?{space:w[t],local:e}:e}function k(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return"http://www.w3.org/1999/xhtml"===n&&"http://www.w3.org/1999/xhtml"===t.documentElement.namespaceURI?t.createElement(e):t.createElementNS(n,e)}}function S(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function E(e){var t=x(e);return(t.local?S:k)(t)}function C(){}function M(e){return null==e?C:function(){return this.querySelector(e)}}function P(){return[]}function O(e){return null==e?P:function(){return this.querySelectorAll(e)}}function T(e){return function(){return this.matches(e)}}function _(e){return function(t){return t.matches(e)}}var N=Array.prototype.find;function I(){return this.firstElementChild}var z=Array.prototype.filter;function R(){return Array.from(this.children)}function L(e){return Array(e.length)}function A(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}function D(e,t,n,r,o,i){for(var a,l=0,s=t.length,u=i.length;lt?1:e>=t?0:NaN}function $(e){return function(){this.removeAttribute(e)}}function B(e){return function(){this.removeAttributeNS(e.space,e.local)}}function W(e,t){return function(){this.setAttribute(e,t)}}function q(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function U(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttribute(e):this.setAttribute(e,n)}}function K(e,t){return function(){var n=t.apply(this,arguments);null==n?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function Y(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function X(e){return function(){this.style.removeProperty(e)}}function Z(e,t,n){return function(){this.style.setProperty(e,t,n)}}function G(e,t,n){return function(){var r=t.apply(this,arguments);null==r?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function Q(e,t){return e.style.getPropertyValue(t)||Y(e).getComputedStyle(e,null).getPropertyValue(t)}function J(e){return function(){delete this[e]}}function ee(e,t){return function(){this[e]=t}}function te(e,t){return function(){var n=t.apply(this,arguments);null==n?delete this[e]:this[e]=n}}function ne(e){return e.trim().split(/^|\s+/)}function re(e){return e.classList||new oe(e)}function oe(e){this._node=e,this._names=ne(e.getAttribute("class")||"")}function ie(e,t){for(var n=re(e),r=-1,o=t.length;++r=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var Pe=[null];function Oe(e,t){this._groups=e,this._parents=t}function Te(){return new Oe([[document.documentElement]],Pe)}function _e(e){return"string"==typeof e?new Oe([[document.querySelector(e)]],[document.documentElement]):new Oe([[e]],Pe)}function Ne(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,[(r=r.matrixTransform(t.getScreenCTM().inverse())).x,r.y]}if(t.getBoundingClientRect){var o=t.getBoundingClientRect();return[e.clientX-o.left-t.clientLeft,e.clientY-o.top-t.clientTop]}}return[e.pageX,e.pageY]}Oe.prototype=Te.prototype={constructor:Oe,select:function(e){"function"!=typeof e&&(e=M(e));for(var t=this._groups,n=t.length,r=Array(n),o=0;o=w&&(w=b+1);!(v=g[w])&&++w=0;)(r=o[i])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(e){function t(t,n){return t&&n?e(t.__data__,n.__data__):!t-!n}e||=V;for(var n=this._groups,r=n.length,o=Array(r),i=0;i1?this.each((null==t?X:"function"==typeof t?G:Z)(e,t,n??"")):Q(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?J:"function"==typeof t?te:ee)(e,t)):this.node()[e]},classed:function(e,t){var n=ne(e+"");if(arguments.length<2){for(var r=re(this.node()),o=-1,i=n.length;++o=0&&(t=e.slice(n+1),e=e.slice(0,n)),{type:e,name:t}})}(e+""),a=i.length;if(!(arguments.length<2)){for(l=t?Se:ke,r=0;r()=>e;function je(e,{sourceEvent:t,subject:n,target:r,identifier:o,active:i,x:a,y:l,dx:s,dy:u,dispatch:c}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:o,enumerable:!0,configurable:!0},active:{value:i,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:s,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:c}})}function He(e){return!e.ctrlKey&&!e.button}function Ve(){return this.parentNode}function $e(e,t){return t??{x:e.x,y:e.y}}function Be(){return navigator.maxTouchPoints||"ontouchstart"in this}function We(){var e,t,n,r,o=He,i=Ve,a=$e,l=Be,s={},u=g("start","drag","end"),c=0,d=0;function f(e){e.on("mousedown.drag",p).filter(l).on("touchstart.drag",y).on("touchmove.drag",v,Ie).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(a,l){if(!r&&o.call(this,a,l)){var s=w(this,i.call(this,a,l),a,l,"mouse");s&&(_e(a.view).on("mousemove.drag",h,ze).on("mouseup.drag",m,ze),Ae(a.view),Re(a),n=!1,e=a.clientX,t=a.clientY,s("start",a))}}function h(r){if(Le(r),!n){var o=r.clientX-e,i=r.clientY-t;n=o*o+i*i>d}s.mouse("drag",r)}function m(e){_e(e.view).on("mousemove.drag mouseup.drag",null),De(e.view,n),Le(e),s.mouse("end",e)}function y(e,t){if(o.call(this,e,t)){var n,r,a=e.changedTouches,l=i.call(this,e,t),s=a.length;for(n=0;n>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===n?dt(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===n?dt(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=et.exec(e))?new pt(t[1],t[2],t[3],1):(t=tt.exec(e))?new pt(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=nt.exec(e))?dt(t[1],t[2],t[3],t[4]):(t=rt.exec(e))?dt(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=ot.exec(e))?bt(t[1],t[2]/100,t[3]/100,1):(t=it.exec(e))?bt(t[1],t[2]/100,t[3]/100,t[4]):at.hasOwnProperty(e)?ct(at[e]):"transparent"===e?new pt(NaN,NaN,NaN,0):null}function ct(e){return new pt(e>>16&255,e>>8&255,255&e,1)}function dt(e,t,n,r){return r<=0&&(e=t=n=NaN),new pt(e,t,n,r)}function ft(e,t,n,r){return 1===arguments.length?function(e){return e instanceof Ke||(e=ut(e)),e?new pt((e=e.rgb()).r,e.g,e.b,e.opacity):new pt}(e):new pt(e,t,n,r??1)}function pt(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}function ht(){return`#${vt(this.r)}${vt(this.g)}${vt(this.b)}`}function mt(){let e=gt(this.opacity);return`${1===e?"rgb(":"rgba("}${yt(this.r)}, ${yt(this.g)}, ${yt(this.b)}${1===e?")":`, ${e})`}`}function gt(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function yt(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function vt(e){return((e=yt(e))<16?"0":"")+e.toString(16)}function bt(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new xt(e,t,n,r)}function wt(e){if(e instanceof xt)return new xt(e.h,e.s,e.l,e.opacity);if(e instanceof Ke||(e=ut(e)),!e)return new xt;if(e instanceof xt)return e;var t=(e=e.rgb()).r/255,n=e.g/255,r=e.b/255,o=Math.min(t,n,r),i=Math.max(t,n,r),a=NaN,l=i-o,s=(i+o)/2;return l?(a=t===i?(n-r)/l+6*(n0&&s<1?0:a,new xt(a,l,s,e.opacity)}function xt(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}function kt(e){return(e=(e||0)%360)<0?e+360:e}function St(e){return Math.max(0,Math.min(1,e||0))}function Et(e,t,n){return 255*(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)}qe(Ke,ut,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:lt,formatHex:lt,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return wt(this).formatHsl()},formatRgb:st,toString:st}),qe(pt,ft,Ue(Ke,{brighter(e){return e=null==e?Xe:Xe**+e,new pt(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?Ye:Ye**+e,new pt(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new pt(yt(this.r),yt(this.g),yt(this.b),gt(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:ht,formatHex:ht,formatHex8:function(){return`#${vt(this.r)}${vt(this.g)}${vt(this.b)}${vt(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:mt,toString:mt})),qe(xt,function(e,t,n,r){return 1===arguments.length?wt(e):new xt(e,t,n,r??1)},Ue(Ke,{brighter(e){return e=null==e?Xe:Xe**+e,new xt(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?Ye:Ye**+e,new xt(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+360*(this.h<0),t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,o=2*n-r;return new pt(Et(e>=240?e-240:e+120,o,r),Et(e,o,r),Et(e<120?e+240:e-120,o,r),this.opacity)},clamp(){return new xt(kt(this.h),St(this.s),St(this.l),gt(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=gt(this.opacity);return`${1===e?"hsl(":"hsla("}${kt(this.h)}, ${100*St(this.s)}%, ${100*St(this.l)}%${1===e?")":`, ${e})`}`}}));var Ct=e=>()=>e;function Mt(e,t){var n=t-e;return n?function(e,t){return function(n){return e+n*t}}(e,n):Ct(isNaN(e)?t:e)}var Pt=function e(t){var n=function(e){return 1==(e=+e)?Mt:function(t,n){return n-t?function(e,t,n){return t=t**+n-(e**=+n),n=1/n,function(r){return(e+r*t)**+n}}(t,n,e):Ct(isNaN(t)?n:t)}}(t);function r(e,t){var r=n((e=ft(e)).r,(t=ft(t)).r),o=n(e.g,t.g),i=n(e.b,t.b),a=Mt(e.opacity,t.opacity);return function(t){return e.r=r(t),e.g=o(t),e.b=i(t),e.opacity=a(t),e+""}}return r.gamma=e,r}(1);function Ot(e,t){t||=[];var n,r=e?Math.min(t.length,e.length):0,o=t.slice();return function(i){for(n=0;ni&&(o=t.slice(i,o),l[a]?l[a]+=o:l[++a]=o),(n=n[0])===(r=r[0])?l[a]?l[a]+=r:l[++a]=r:(l[++a]=null,s.push({i:a,x:Nt(n,r)})),i=Rt.lastIndex;return i180?t+=360:t-e>180&&(e+=360),i.push({i:n.push(o(n)+"rotate(",null,r)-2,x:Nt(e,t)}))}function l(e,t,n,i){e===t?t&&n.push(o(n)+"skewX("+t+r):i.push({i:n.push(o(n)+"skewX(",null,r)-2,x:Nt(e,t)})}function s(e,t,n,r,i,a){if(e!==n||t!==r){var l=i.push(o(i)+"scale(",null,",",null,")");a.push({i:l-4,x:Nt(e,n)},{i:l-2,x:Nt(t,r)})}else(1!==n||1!==r)&&i.push(o(i)+"scale("+n+","+r+")")}return function(t,n){var r=[],o=[];return t=e(t),n=e(n),i(t.translateX,t.translateY,n.translateX,n.translateY,r,o),a(t.rotate,n.rotate,r,o),l(t.skewX,n.skewX,r,o),s(t.scaleX,t.scaleY,n.scaleX,n.scaleY,r,o),t=n=null,function(e){for(var t,n=-1,i=o.length;++n=0&&t._call.call(void 0,e),t=t._next;--Yt}()}finally{Yt=0,function(){for(var e,t,n=qt,r=1/0;n;)n._call?(r>n._time&&(r=n._time),e=n,n=n._next):(t=n._next,n._next=null,n=e?e._next=t:qt=t);Ut=e,un(r)}(),Qt=0}}function sn(){var e=en.now(),t=e-Gt;t>1e3&&(Jt-=t,Gt=e)}function un(e){Yt||(Xt&&=clearTimeout(Xt),e-Qt>24?(e<1/0&&(Xt=setTimeout(ln,e-en.now()-Jt)),Zt&&=clearInterval(Zt)):(Zt||=(Gt=en.now(),setInterval(sn,1e3)),Yt=1,tn(ln)))}function cn(e,t,n){var r=new on;return t=null==t?0:+t,r.restart(n=>{r.stop(),e(n+t)},t,n),r}on.prototype=an.prototype={constructor:on,restart:function(e,t,n){if("function"!=typeof e)throw TypeError("callback is not a function");n=(null==n?nn():+n)+(null==t?0:+t),!this._next&&Ut!==this&&(Ut?Ut._next=this:qt=this,Ut=this),this._call=e,this._time=n,un()},stop:function(){this._call&&(this._call=null,this._time=1/0,un())}};var dn=g("start","end","cancel","interrupt"),fn=[];function pn(e,t,n,r,o,i){var a=e.__transition;if(a){if(n in a)return}else e.__transition={};!function(e,t,n){var r,o=e.__transition;function i(s){var u,c,d,f;if(1!==n.state)return l();for(u in o)if((f=o[u]).name===n.name){if(3===f.state)return cn(i);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",e,e.__data__,f.index,f.group),delete o[u]):+u0)throw Error("too late; already scheduled");return n}function mn(e,t){var n=gn(e,t);if(n.state>3)throw Error("too late; already running");return n}function gn(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw Error("transition not found");return n}function yn(e,t){var n,r,o,i=e.__transition,a=!0;if(i){for(o in t=null==t?null:t+"",i)(n=i[o]).name===t?(r=n.state>2&&n.state<5,n.state=6,n.timer.stop(),n.on.call(r?"interrupt":"cancel",e,e.__data__,n.index,n.group),delete i[o]):a=!1;a&&delete e.__transition}}function vn(e,t){var n,r;return function(){var o=mn(this,e),i=o.tween;if(i!==n)for(var a=0,l=(r=n=i).length;a=0&&(e=e.slice(0,t)),!e||"start"===e})}(t)?hn:mn;return function(){var a=i(this,e),l=a.on;l!==r&&(o=(r=l).copy()).on(t,n),a.on=o}}(n,e,t))},attr:function(e,t){var n=x(e),r="transform"===n?Bt:xn;return this.attrTween(e,"function"==typeof t?(n.local?Pn:Mn)(n,r,wn(this,"attr."+e,t)):null==t?(n.local?Sn:kn)(n):(n.local?Cn:En)(n,r,t))},attrTween:function(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw Error();var r=x(e);return this.tween(n,(r.local?On:Tn)(r,t))},style:function(e,t,n){var r="transform"==(e+="")?$t:xn;return null==t?this.styleTween(e,function(e,t){var n,r,o;return function(){var i=Q(this,e),a=(this.style.removeProperty(e),Q(this,e));return i===a?null:i===n&&a===r?o:o=t(n=i,r=a)}}(e,r)).on("end.style."+e,Ln(e)):"function"==typeof t?this.styleTween(e,function(e,t,n){var r,o,i;return function(){var a=Q(this,e),l=n(this),s=l+"";return l??(this.style.removeProperty(e),s=l=Q(this,e)),a===s?null:a===r&&s===o?i:(o=s,i=t(r=a,l))}}(e,r,wn(this,"style."+e,t))).each(function(e,t){var n,r,o,i,a="style."+t,l="end."+a;return function(){var s=mn(this,e),u=s.on,c=null==s.value[a]?i||=Ln(t):void 0;(u!==n||o!==c)&&(r=(n=u).copy()).on(l,o=c),s.on=r}}(this._id,e)):this.styleTween(e,function(e,t,n){var r,o,i=n+"";return function(){var a=Q(this,e);return a===i?null:a===r?o:o=t(r=a,n)}}(e,r,t),n).on("end.style."+e,null)},styleTween:function(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==t)return this.tween(r,null);if("function"!=typeof t)throw Error();return this.tween(r,function(e,t,n){var r,o;function i(){var i=t.apply(this,arguments);return i!==o&&(r=(o=i)&&function(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}(e,i,n)),r}return i._value=t,i}(e,t,n??""))},text:function(e){return this.tween("text","function"==typeof e?function(e){return function(){var t=e(this);this.textContent=t??""}}(wn(this,"text",e)):function(e){return function(){this.textContent=e}}(null==e?"":e+""))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw Error();return this.tween(t,function(e){var t,n;function r(){var r=e.apply(this,arguments);return r!==n&&(t=(n=r)&&function(e){return function(t){this.textContent=e.call(this,t)}}(r)),t}return r._value=e,r}(e))},remove:function(){return this.on("end.remove",function(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}(this._id))},tween:function(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r,o=gn(this.node(),n).tween,i=0,a=o.length;i()=>e;function Bn(e,{sourceEvent:t,target:n,transform:r,dispatch:o}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:o}})}function Wn(e,t,n){this.k=e,this.x=t,this.y=n}Wn.prototype={constructor:Wn,scale:function(e){return 1===e?this:new Wn(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new Wn(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var qn=new Wn(1,0,0);function Un(e){for(;!e.__zoom;)if(!(e=e.parentNode))return qn;return e.__zoom}function Kn(e){e.stopImmediatePropagation()}function Yn(e){e.preventDefault(),e.stopImmediatePropagation()}function Xn(e){return!(e.ctrlKey&&"wheel"!==e.type||e.button)}function Zn(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function Gn(){return this.__zoom||qn}function Qn(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Jn(){return navigator.maxTouchPoints||"ontouchstart"in this}function er(e,t,n){var r=e.invertX(t[0][0])-n[0][0],o=e.invertX(t[1][0])-n[1][0],i=e.invertY(t[0][1])-n[0][1],a=e.invertY(t[1][1])-n[1][1];return e.translate(o>r?(r+o)/2:Math.min(0,r)||Math.max(0,o),a>i?(i+a)/2:Math.min(0,i)||Math.max(0,a))}function tr(){var e,t,n,r=Xn,o=Zn,i=er,a=Qn,l=Jn,s=[0,1/0],u=[[-1/0,-1/0],[1/0,1/0]],c=250,d=Kt,f=g("start","zoom","end"),p=0,h=10;function m(e){e.property("__zoom",Gn).on("wheel.zoom",S,{passive:!1}).on("mousedown.zoom",E).on("dblclick.zoom",C).filter(l).on("touchstart.zoom",M).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",O).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function y(e,t){return(t=Math.max(s[0],Math.min(s[1],t)))===e.k?e:new Wn(t,e.x,e.y)}function v(e,t,n){var r=t[0]-n[0]*e.k,o=t[1]-n[1]*e.k;return r===e.x&&o===e.y?e:new Wn(e.k,r,o)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function w(e,t,n,r){e.on("start.zoom",function(){x(this,arguments).event(r).start()}).on("interrupt.zoom end.zoom",function(){x(this,arguments).event(r).end()}).tween("zoom",function(){var e=this,i=arguments,a=x(e,i).event(r),l=o.apply(e,i),s=null==n?b(l):"function"==typeof n?n.apply(e,i):n,u=Math.max(l[1][0]-l[0][0],l[1][1]-l[0][1]),c=e.__zoom,f="function"==typeof t?t.apply(e,i):t,p=d(c.invert(s).concat(u/c.k),f.invert(s).concat(u/f.k));return function(e){if(1===e)e=f;else{var t=p(e),n=u/t[2];e=new Wn(n,s[0]-t[0]*n,s[1]-t[1]*n)}a.zoom(null,e)}})}function x(e,t,n){return!n&&e.__zooming||new k(e,t)}function k(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=o.apply(e,t),this.taps=0}function S(e,...t){if(r.apply(this,arguments)){var n=x(this,t).event(e),o=this.__zoom,l=Math.max(s[0],Math.min(s[1],o.k*2**a.apply(this,arguments))),c=Ne(e);if(n.wheel)(n.mouse[0][0]!==c[0]||n.mouse[0][1]!==c[1])&&(n.mouse[1]=o.invert(n.mouse[0]=c)),clearTimeout(n.wheel);else{if(o.k===l)return;n.mouse=[c,o.invert(c)],yn(this),n.start()}Yn(e),n.wheel=setTimeout(function(){n.wheel=null,n.end()},150),n.zoom("mouse",i(v(y(o,l),n.mouse[0],n.mouse[1]),n.extent,u))}}function E(e,...t){if(!n&&r.apply(this,arguments)){var o=e.currentTarget,a=x(this,t,!0).event(e),l=_e(e.view).on("mousemove.zoom",function(e){if(Yn(e),!a.moved){var t=e.clientX-c,n=e.clientY-d;a.moved=t*t+n*n>p}a.event(e).zoom("mouse",i(v(a.that.__zoom,a.mouse[0]=Ne(e,o),a.mouse[1]),a.extent,u))},!0).on("mouseup.zoom",function(e){l.on("mousemove.zoom mouseup.zoom",null),De(e.view,a.moved),Yn(e),a.event(e).end()},!0),s=Ne(e,o),c=e.clientX,d=e.clientY;Ae(e.view),Kn(e),a.mouse=[s,this.__zoom.invert(s)],yn(this),a.start()}}function C(e,...t){if(r.apply(this,arguments)){var n=this.__zoom,a=Ne(e.changedTouches?e.changedTouches[0]:e,this),l=n.invert(a),s=n.k*(e.shiftKey?.5:2),d=i(v(y(n,s),a,l),o.apply(this,t),u);Yn(e),c>0?_e(this).transition().duration(c).call(w,d,a,e):_e(this).call(m.transform,d,a,e)}}function M(n,...o){if(r.apply(this,arguments)){var i,a,l,s,u=n.touches,c=u.length,d=x(this,o,n.changedTouches.length===c).event(n);for(Kn(n),a=0;a`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};!function(e){e.Strict="strict",e.Loose="loose"}(nr||={}),function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"}(rr||={}),function(e){e.Partial="partial",e.Full="full"}(or||={});var sr,ur,cr,dr={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};!function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"}(sr||={}),function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"}(ur||={}),function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"}(cr||={});var fr={[cr.Left]:cr.Right,[cr.Right]:cr.Left,[cr.Top]:cr.Bottom,[cr.Bottom]:cr.Top};function pr(e){return null===e?null:e?"valid":"invalid"}var hr=e=>"id"in e&&"source"in e&&"target"in e,mr=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),gr=(e,t,n)=>{if(!e.id)return[];let r=new Set;return n.forEach(t=>{t.source===e.id&&r.add(t.target)}),t.filter(e=>r.has(e.id))},yr=(e,t,n)=>{if(!e.id)return[];let r=new Set;return n.forEach(t=>{t.target===e.id&&r.add(t.source)}),t.filter(e=>r.has(e.id))},vr=(e,t=[0,0])=>{let{width:n,height:r}=Br(e),o=e.origin??t,i=n*o[0],a=r*o[1];return{x:e.position.x-i,y:e.position.y-a}},br=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(e=>{(void 0===t.filter||t.filter(e))&&(n=Pr(n,Nr(e)),r=!0)}),r?Tr(n):{x:0,y:0,width:0,height:0}},wr=(e,t,[n,r,o]=[0,0,1],i=!1,a=!1)=>{let l={...Dr(t,[n,r,o]),width:t.width/o,height:t.height/o},s=[];for(let t of e.values()){let{measured:e,selectable:n=!0,hidden:r=!1}=t;if(a&&!n||r)continue;let o=e.width??t.width??t.initialWidth??null,u=e.height??t.height??t.initialHeight??null,c=zr(l,_r(t)),d=(o??0)*(u??0),f=i&&c>0;(!t.internals.handleBounds||f||c>=d||t.dragging)&&s.push(t)}return s};function xr({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:o,onError:i}){let a=n.get(e),l=a.parentId?n.get(a.parentId):void 0,{x:s,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},c=a.origin??r,d=a.extent||o;if("parent"!==a.extent||a.expandParent)l&&$r(a.extent)&&(d=[[a.extent[0][0]+s,a.extent[0][1]+u],[a.extent[1][0]+s,a.extent[1][1]+u]]);else if(l){let e=l.measured.width,t=l.measured.height;e&&t&&(d=[[s,u],[s+e,u+t]])}else i?.("005","Only child nodes can use a parent extent.");let f=$r(d)?Sr(t,d,a.measured):t;return(void 0===a.measured.width||void 0===a.measured.height)&&i?.("015","It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."),{position:{x:f.x-s+(a.measured.width??0)*c[0],y:f.y-u+(a.measured.height??0)*c[1]},positionAbsolute:f}}var kr=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),Sr=(e={x:0,y:0},t,n)=>({x:kr(e.x,t[0][0],t[1][0]-(n?.width??0)),y:kr(e.y,t[0][1],t[1][1]-(n?.height??0))});function Er(e,t,n){let{width:r,height:o}=Br(n),{x:i,y:a}=n.internals.positionAbsolute;return Sr(e,[[i,a],[i+r,a+o]],t)}var Cr=(e,t,n)=>en?-kr(Math.abs(e-n),1,t)/t:0,Mr=(e,t,n=15,r=40)=>[Cr(e.x,r,t.width-r)*n,Cr(e.y,r,t.height-r)*n],Pr=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),Or=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),Tr=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),_r=(e,t=[0,0])=>{let{x:n,y:r}=mr(e)?e.internals.positionAbsolute:vr(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},Nr=(e,t=[0,0])=>{let{x:n,y:r}=mr(e)?e.internals.positionAbsolute:vr(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},Ir=(e,t)=>Tr(Pr(Or(e),Or(t))),zr=(e,t)=>{let n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},Rr=e=>Lr(e.width)&&Lr(e.height)&&Lr(e.x)&&Lr(e.y),Lr=e=>!isNaN(e)&&isFinite(e),Ar=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Dr=({x:e,y:t},[n,r,o],i=!1,a=[1,1])=>{let l={x:(e-n)/o,y:(t-r)/o};return i?Ar(l,a):l},Fr=({x:e,y:t},[n,r,o])=>({x:e*o+n,y:t*o+r});function jr(e,t){if("number"==typeof e)return Math.floor(.5*(t-t/(1+e)));if("string"==typeof e&&e.endsWith("px")){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if("string"==typeof e&&e.endsWith("%")){let n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}var Hr=(e,t,n,r,o,i)=>{let a=function(e,t,n){if("string"==typeof e||"number"==typeof e){let r=jr(e,n),o=jr(e,t);return{top:r,right:o,bottom:r,left:o,x:2*o,y:2*r}}if("object"==typeof e){let r=jr(e.top??e.y??0,n),o=jr(e.bottom??e.y??0,n),i=jr(e.left??e.x??0,t),a=jr(e.right??e.x??0,t);return{top:r,right:a,bottom:o,left:i,x:i+a,y:r+o}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}(i,t,n),l=(t-a.x)/e.width,s=(n-a.y)/e.height,u=kr(Math.min(l,s),r,o),c=t/2-(e.x+e.width/2)*u,d=n/2-(e.y+e.height/2)*u,f=function(e,t,n,r,o,i){let{x:a,y:l}=Fr(e,[t,n,r]),{x:s,y:u}=Fr({x:e.x+e.width,y:e.y+e.height},[t,n,r]),c=o-s,d=i-u;return{left:Math.floor(a),top:Math.floor(l),right:Math.floor(c),bottom:Math.floor(d)}}(e,c,d,u,t,n),p=Math.min(f.left-a.left,0),h=Math.min(f.top-a.top,0);return{x:c-p+Math.min(f.right-a.right,0),y:d-h+Math.min(f.bottom-a.bottom,0),zoom:u}},Vr=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function $r(e){return null!=e&&"parent"!==e}function Br(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function Wr(e){return void 0!==(e.measured?.width??e.width??e.initialWidth)&&void 0!==(e.measured?.height??e.height??e.initialHeight)}function qr(e,t={width:0,height:0},n,r,o){let i={...e},a=r.get(n);if(a){let e=a.origin||o;i.x+=a.internals.positionAbsolute.x-(t.width??0)*e[0],i.y+=a.internals.positionAbsolute.y-(t.height??0)*e[1]}return i}function Ur(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Kr(e){return{...lr,...e||{}}}function Yr(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:o}){let{x:i,y:a}=eo(e),l=Dr({x:i-(o?.left??0),y:a-(o?.top??0)},r),{x:s,y:u}=n?Ar(l,t):l;return{xSnapped:s,ySnapped:u,...l}}var Xr=e=>({width:e.offsetWidth,height:e.offsetHeight}),Zr=e=>e?.getRootNode?.()||window?.document,Gr=["INPUT","SELECT","TEXTAREA"];function Qr(e){let t=e.composedPath?.()?.[0]||e.target;return 1===t?.nodeType&&(Gr.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey"))}var Jr=e=>"clientX"in e,eo=(e,t)=>{let n=Jr(e),r=n?e.clientX:e.touches?.[0].clientX,o=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:o-(t?.top??0)}},to=(e,t,n,r,o)=>{let i=t.querySelectorAll(`.${e}`);return i&&i.length?Array.from(i).map(t=>{let i=t.getBoundingClientRect();return{id:t.getAttribute("data-handleid"),type:e,nodeId:o,position:t.getAttribute("data-handlepos"),x:(i.left-n.left)/r,y:(i.top-n.top)/r,...Xr(t)}}):null};function no({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:o,sourceControlY:i,targetControlX:a,targetControlY:l}){let s=.125*e+.375*o+.375*a+.125*n,u=.125*t+.375*i+.375*l+.125*r;return[s,u,Math.abs(s-e),Math.abs(u-t)]}function ro(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function oo({pos:e,x1:t,y1:n,x2:r,y2:o,c:i}){switch(e){case cr.Left:return[t-ro(t-r,i),n];case cr.Right:return[t+ro(r-t,i),n];case cr.Top:return[t,n-ro(n-o,i)];case cr.Bottom:return[t,n+ro(o-n,i)]}}function io({sourceX:e,sourceY:t,sourcePosition:n=cr.Bottom,targetX:r,targetY:o,targetPosition:i=cr.Top,curvature:a=.25}){let[l,s]=oo({pos:n,x1:e,y1:t,x2:r,y2:o,c:a}),[u,c]=oo({pos:i,x1:r,y1:o,x2:e,y2:t,c:a}),[d,f,p,h]=no({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:l,sourceControlY:s,targetControlX:u,targetControlY:c});return[`M${e},${t} C${l},${s} ${u},${c} ${r},${o}`,d,f,p,h]}function ao({sourceX:e,sourceY:t,targetX:n,targetY:r}){let o=Math.abs(n-e)/2,i=n0}var uo=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`;function co({sourceX:e,sourceY:t,targetX:n,targetY:r}){let[o,i,a,l]=ao({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,o,i,a,l]}var fo={[cr.Left]:{x:-1,y:0},[cr.Right]:{x:1,y:0},[cr.Top]:{x:0,y:-1},[cr.Bottom]:{x:0,y:1}},po=(e,t)=>Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2);function ho(e,t,n,r){let o=Math.min(po(e,t)/2,po(t,n)/2,r),{x:i,y:a}=t;if(e.x===i&&i===n.x||e.y===a&&a===n.y)return`L${i} ${a}`;if(e.y===a)return`L ${i+o*(e.xt===cr.Left||t===cr.Right?e.xe[h]?-1:1)*r:v[h]=(f[h]>n[h]?-1:1)*r}}if(t!==r){let e="x"===h?"y":"x",t=u[h]===c[e],n=d[e]>f[e],r=d[e]=Math.max(Math.abs(p.y-g[0].y),Math.abs(b.y-g[0].y))?(l=(p.x+b.x)/2,s=g[0].y):(l=g[0].x,s=(p.y+b.y)/2)}let x={x:d.x+y.x,y:d.y+y.y},k={x:f.x+v.x,y:f.y+v.y};return[[e,...x.x!==g[0].x||x.y!==g[0].y?[x]:[],...g,...k.x!==g[g.length-1].x||k.y!==g[g.length-1].y?[k]:[],n],l,s,b,w]}({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:o},targetPosition:i,center:{x:l,y:s},offset:u,stepPosition:c}),g=`M${d[0].x} ${d[0].y}`;for(let e=1;ee.id===t):e[0])||null}function wo(e,t){return e?"string"==typeof e?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("&")}`:""}var xo={nodeOrigin:[0,0],nodeExtent:ir,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},ko={...xo,checkEquality:!0};function So(e,t){let n={...e};for(let e in t)void 0!==t[e]&&(n[e]=t[e]);return n}function Eo(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let n=[],r=[];for(let t of e.handles){let o={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};"source"===t.type?n.push(o):"target"===t.type&&r.push(o)}return{source:n,target:r}}function Co(e){return"manual"===e}function Mo(e,t,n,r={}){let o=So(ko,r),i={i:0},a=new Map(t),l=o?.elevateNodesOnSelect&&!Co(o.zIndexMode)?1e3:0,s=e.length>0,u=!1;t.clear(),n.clear();for(let c of e){let e=a.get(c.id);if(o.checkEquality&&c===e?.internals.userNode)t.set(c.id,e);else{let n=Sr(vr(c,o.nodeOrigin),$r(c.extent)?c.extent:o.nodeExtent,Br(c));e={...o.defaults,...c,measured:{width:c.measured?.width,height:c.measured?.height},internals:{positionAbsolute:n,handleBounds:Eo(c,e),z:Oo(c,l,o.zIndexMode),userNode:c}},t.set(c.id,e)}(void 0===e.measured||void 0===e.measured.width||void 0===e.measured.height)&&!e.hidden&&(s=!1),c.parentId&&Po(e,t,n,r,i),u||=c.selected??!1}return{nodesInitialized:s,hasSelectedNodes:u}}function Po(e,t,n,r,o){let{elevateNodesOnSelect:i,nodeOrigin:a,nodeExtent:l,zIndexMode:s}=So(xo,r),u=e.parentId,c=t.get(u);if(!c)return;(function(e,t){if(!e.parentId)return;let n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))})(e,n),o&&!c.parentId&&void 0===c.internals.rootParentIndex&&"auto"===s&&(c.internals.rootParentIndex=++o.i,c.internals.z=c.internals.z+10*o.i),o&&void 0!==c.internals.rootParentIndex&&(o.i=c.internals.rootParentIndex);let{x:d,y:f,z:p}=function(e,t,n,r,o,i){let{x:a,y:l}=t.internals.positionAbsolute,s=Br(e),u=vr(e,n),c=$r(e.extent)?Sr(u,e.extent,s):u,d=Sr({x:a+c.x,y:l+c.y},r,s);"parent"===e.extent&&(d=Er(d,s,t));let f=Oo(e,o,i),p=t.internals.z??0;return{x:d.x,y:d.y,z:p>=f?p+1:f}}(e,c,a,l,i&&!Co(s)?1e3:0,s),{positionAbsolute:h}=e.internals,m=d!==h.x||f!==h.y;(m||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:m?{x:d,y:f}:h,z:p}})}function Oo(e,t,n){let r=Lr(e.zIndex)?e.zIndex:0;return Co(n)?r:r+(e.selected?t:0)}function To(e,t,n,r=[0,0]){let o=[],i=new Map;for(let n of e){let e=t.get(n.parentId);if(!e)continue;let r=Ir(i.get(n.parentId)?.expandedRect??_r(e),n.rect);i.set(n.parentId,{expandedRect:r,parent:e})}return i.size>0&&i.forEach(({expandedRect:t,parent:i},a)=>{let l=i.internals.positionAbsolute,s=Br(i),u=i.origin??r,c=t.x0||d>0||h||m)&&(o.push({id:a,type:"position",position:{x:i.position.x-c+h,y:i.position.y-d+m}}),n.get(a)?.forEach(t=>{e.some(e=>e.id===t.id)||o.push({id:t.id,type:"position",position:{x:t.position.x+c,y:t.position.y+d}})})),(s.widthe.id===n):l?.[0])??null;return s&&i?{...s,...vo(a,s,s.position,!0)}:s}function Ao(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}var Do=()=>!0;function Fo(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:o,fromType:i,doc:a,lib:l,flowId:s,isValidConnection:u=Do,nodeLookup:c}){let d="target"===i,f=t?a.querySelector(`.${l}-flow__handle[data-id="${s}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:h}=eo(e),m=a.elementFromPoint(p,h),g=m?.classList.contains(`${l}-flow__handle`)?m:f,y={handleDomNode:g,isValid:!1,connection:null,toHandle:null};if(g){let e=Ao(void 0,g),t=g.getAttribute("data-nodeid"),i=g.getAttribute("data-handleid"),a=g.classList.contains("connectable"),l=g.classList.contains("connectableend");if(!t||!e)return y;let s={source:d?t:r,sourceHandle:d?i:o,target:d?r:t,targetHandle:d?o:i};y.connection=s,y.isValid=a&&l&&(n===nr.Strict?d&&"source"===e||!d&&"target"===e:t!==r||i!==o)&&u(s),y.toHandle=Lo(t,e,i,c,n,!0)}return y}var jo,Ho={onPointerDown:function(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:o,edgeUpdaterType:i,isTarget:a,domNode:l,nodeLookup:s,lib:u,autoPanOnConnect:c,flowId:d,panBy:f,cancelConnection:p,onConnectStart:h,onConnect:m,onConnectEnd:g,isValidConnection:y=Do,onReconnectEnd:v,updateConnection:b,getTransform:w,getFromHandle:x,autoPanSpeed:k,dragThreshold:S=1,handleDomNode:E}){let C,M=Zr(e.target),P=0,{x:O,y:T}=eo(e),_=Ao(i,E),N=l?.getBoundingClientRect(),I=!1;if(!N||!_)return;let z=Lo(o,_,r,s,t);if(!z)return;let R=eo(e,N),L=!1,A=null,D=!1,F=null;function j(){if(!c||!N)return;let[e,t]=Mr(R,N,k);f({x:e,y:t}),P=requestAnimationFrame(j)}let H={...z,nodeId:o,type:_,position:z.position},V=s.get(o),$={inProgress:!0,isValid:null,from:vo(V,H,cr.Left,!0),fromHandle:H,fromPosition:H.position,fromNode:V,to:R,toHandle:null,toPosition:fr[H.position],toNode:null,pointer:R};function B(){I=!0,b($),h?.(e,{nodeId:o,handleId:r,handleType:_})}function W(e){if(!I){let{x:t,y:n}=eo(e),r=t-O,o=n-T;if(!(r*r+o*o>S*S))return;B()}if(!x()||!H)return void q(e);let i=w();R=eo(e,N),C=function(e,t,n,r){let o=[],i=1/0,a=function(e,t,n){let r=[],o={x:e.x-n,y:e.y-n,width:2*n,height:2*n};for(let e of t.values())zr(o,_r(e))>0&&r.push(e);return r}(e,n,t+250);for(let n of a){let a=[...n.internals.handleBounds?.source??[],...n.internals.handleBounds?.target??[]];for(let l of a){if(r.nodeId===l.nodeId&&r.type===l.type&&r.id===l.id)continue;let{x:a,y:s}=vo(n,l,l.position,!0),u=Math.sqrt((a-e.x)**2+(s-e.y)**2);u>t||(u1){let e="source"===r.type?"target":"source";return o.find(t=>t.type===e)??o[0]}return o[0]}(Dr(R,i,!1,[1,1]),n,s,H),L||=(j(),!0);let l=Fo(e,{handle:C,connectionMode:t,fromNodeId:o,fromHandleId:r,fromType:a?"target":"source",isValidConnection:y,doc:M,lib:u,flowId:d,nodeLookup:s});F=l.handleDomNode,A=l.connection,D=function(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}(!!C,l.isValid);let c=s.get(o),f=c?vo(c,H,cr.Left,!0):$.from,p={...$,from:f,isValid:D,to:l.toHandle&&D?Fr({x:l.toHandle.x,y:l.toHandle.y},i):R,toHandle:l.toHandle,toPosition:D&&l.toHandle?l.toHandle.position:fr[H.position],toNode:l.toHandle?s.get(l.toHandle.nodeId):null,pointer:R};b(p),$=p}function q(e){if(!("touches"in e&&e.touches.length>0)){if(I){(C||F)&&A&&D&&m?.(A);let{inProgress:t,...n}=$,r={...n,toPosition:$.toHandle?$.toPosition:null};g?.(e,r),i&&v?.(e,r)}p(),cancelAnimationFrame(P),L=!1,D=!1,A=null,F=null,M.removeEventListener("mousemove",W),M.removeEventListener("mouseup",q),M.removeEventListener("touchmove",W),M.removeEventListener("touchend",q)}}0===S&&B(),M.addEventListener("mousemove",W),M.addEventListener("mouseup",q),M.addEventListener("touchmove",W),M.addEventListener("touchend",q)},isValid:Fo},Vo=e=>({x:e.x,y:e.y,zoom:e.k}),$o=({x:e,y:t,zoom:n})=>qn.translate(e,t).scale(n),Bo=(e,t)=>e.target.closest(`.${t}`),Wo=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),qo=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Uo=(e,t=0,n=qo,r=()=>{})=>{let o="number"==typeof t&&t>0;return o||r(),o?e.transition().duration(t).ease(n).on("end",r):e},Ko=e=>{let t=e.ctrlKey&&Vr()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t};function Yo(e){return{isHorizontal:e.includes("right")||e.includes("left"),isVertical:e.includes("bottom")||e.includes("top"),affectsX:e.includes("left"),affectsY:e.includes("top")}}function Xo(e,t){return Math.max(0,t-e)}function Zo(e,t){return Math.max(0,e-t)}function Go(e,t,n){return Math.max(0,t-e,e-n)}function Qo(e,t){return e?!t:t}!function(e){e.Line="line",e.Handle="handle"}(jo||={});var Jo={width:0,height:0,x:0,y:0},ei={...Jo,pointerX:0,pointerY:0,aspectRatio:1};function ti(e,t,n){let r=t.position.x+e.position.x,o=t.position.y+e.position.y,i=e.measured.width??0,a=e.measured.height??0,l=n[0]*i,s=n[1]*a;return[[r-l,o-s],[r+i-l,o+a-s]]}var ni=t(e=>{var t=r(),n="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},o=t.useState,i=t.useEffect,a=t.useLayoutEffect,l=t.useDebugValue;function s(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!n(e,r)}catch{return!0}}var u=typeof window>"u"||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var n=t(),r=o({inst:{value:n,getSnapshot:t}}),u=r[0].inst,c=r[1];return a(function(){u.value=n,u.getSnapshot=t,s(u)&&c({inst:u})},[e,n,t]),i(function(){return s(u)&&c({inst:u}),e(function(){s(u)&&c({inst:u})})},[e]),l(n),n};e.useSyncExternalStore=void 0===t.useSyncExternalStore?u:t.useSyncExternalStore}),ri=t((e,t)=>{t.exports=ni()}),oi=t(e=>{var t=r(),n=ri(),o="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},i=n.useSyncExternalStore,a=t.useRef,l=t.useEffect,s=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,c){var d=a(null);if(null===d.current){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=s(function(){function e(e){if(!l){if(l=!0,i=e,e=r(e),void 0!==c&&f.hasValue){var t=f.value;if(c(t,e))return a=t}return a=e}if(t=a,o(i,e))return t;var n=r(e);return void 0!==c&&c(t,n)?(i=e,t):(i=e,a=n)}var i,a,l=!1,s=void 0===n?null:n;return[function(){return e(t())},null===s?void 0:function(){return e(s())}]},[t,n,r,c]);var p=i(e,d[0],d[1]);return l(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}}),ii=e(t((e,t)=>{t.exports=oi()})(),1),ai=e=>{let t,n=new Set,r=(e,r)=>{let o="function"==typeof e?e(t):e;if(!Object.is(o,t)){let e=t;t=r??("object"!=typeof o||!o)?o:Object.assign({},t,o),n.forEach(n=>n(t,e))}},o=()=>t,i={setState:r,getState:o,getInitialState:()=>a,subscribe:e=>(n.add(e),()=>n.delete(e)),destroy:()=>{n.clear()}},a=t=e(r,o,i);return i},{useDebugValue:li}=f.default,{useSyncExternalStoreWithSelector:si}=ii.default,ui=e=>e;function ci(e,t=ui,n){let r=si(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return li(r),r}var di=(e,t)=>{let n=(e=>e?ai(e):ai)(e),r=(e,r=t)=>ci(n,e,r);return Object.assign(r,n),r};function fi(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}let n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(let r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}var pi=e(l()),hi=(0,f.createContext)(null),mi=hi.Provider,gi=((e="react")=>`Seems like you have not used zustand provider as an ancestor. Help: https://${e}flow.dev/error#001`)("react");function yi(e,t){let n=(0,f.useContext)(hi);if(null===n)throw Error(gi);return ci(n,e,t)}function vi(){let e=(0,f.useContext)(hi);if(null===e)throw Error(gi);return(0,f.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}var bi={display:"none"},wi={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},xi="react-flow__node-desc",ki="react-flow__edge-desc",Si=e=>e.ariaLiveMessage,Ei=e=>e.ariaLabelConfig;function Ci({rfId:e}){let t=yi(Si);return(0,p.jsx)("div",{id:`react-flow__aria-live-${e}`,"aria-live":"assertive","aria-atomic":"true",style:wi,children:t})}function Mi({rfId:e,disableKeyboardA11y:t}){let n=yi(Ei);return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)("div",{id:`${xi}-${e}`,style:bi,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),(0,p.jsx)("div",{id:`${ki}-${e}`,style:bi,children:n["edge.a11yDescription.default"]}),!t&&(0,p.jsx)(Ci,{rfId:e})]})}var Pi=(0,f.forwardRef)(({position:e="top-left",children:t,className:n,style:r,...o},i)=>(0,p.jsx)("div",{className:h(["react-flow__panel",n,...`${e}`.split("-")]),style:r,ref:i,...o,children:t}));function Oi({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:(0,p.jsx)(Pi,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:(0,p.jsx)("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}Pi.displayName="Panel";var Ti=e=>{let t=[],n=[];for(let[,n]of e.nodeLookup)n.selected&&t.push(n.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&n.push(t);return{selectedNodes:t,selectedEdges:n}},_i=e=>e.id;function Ni(e,t){return fi(e.selectedNodes.map(_i),t.selectedNodes.map(_i))&&fi(e.selectedEdges.map(_i),t.selectedEdges.map(_i))}function Ii({onSelectionChange:e}){let t=vi(),{selectedNodes:n,selectedEdges:r}=yi(Ti,Ni);return(0,f.useEffect)(()=>{let o={nodes:n,edges:r};e?.(o),t.getState().onSelectionChangeHandlers.forEach(e=>e(o))},[n,r,e]),null}var zi=e=>!!e.onSelectionChangeHandlers;function Ri({onSelectionChange:e}){let t=yi(zi);return e||t?(0,p.jsx)(Ii,{onSelectionChange:e}):null}var Li=[0,0],Ai={x:0,y:0,zoom:1},Di=[..."nodes.edges.defaultNodes.defaultEdges.onConnect.onConnectStart.onConnectEnd.onClickConnectStart.onClickConnectEnd.nodesDraggable.autoPanOnNodeFocus.nodesConnectable.nodesFocusable.edgesFocusable.edgesReconnectable.elevateNodesOnSelect.elevateEdgesOnSelect.minZoom.maxZoom.nodeExtent.onNodesChange.onEdgesChange.elementsSelectable.connectionMode.snapGrid.snapToGrid.translateExtent.connectOnClick.defaultEdgeOptions.fitView.fitViewOptions.onNodesDelete.onEdgesDelete.onDelete.onNodeDrag.onNodeDragStart.onNodeDragStop.onSelectionDrag.onSelectionDragStart.onSelectionDragStop.onMoveStart.onMove.onMoveEnd.noPanClassName.nodeOrigin.autoPanOnConnect.autoPanOnNodeDrag.onError.connectionRadius.isValidConnection.selectNodesOnDrag.nodeDragThreshold.connectionDragThreshold.onBeforeDelete.debug.autoPanSpeed.ariaLabelConfig.zIndexMode".split("."),"rfId"],Fi=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),ji={translateExtent:ir,nodeOrigin:Li,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function Hi(e){let{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:o,setTranslateExtent:i,setNodeExtent:a,reset:l,setDefaultNodesAndEdges:s}=yi(Fi,fi),u=vi();(0,f.useEffect)(()=>(s(e.defaultNodes,e.defaultEdges),()=>{c.current=ji,l()}),[]);let c=(0,f.useRef)(ji);return(0,f.useEffect)(()=>{for(let l of Di){let s=e[l];s!==c.current[l]&&void 0!==e[l]&&("nodes"===l?t(s):"edges"===l?n(s):"minZoom"===l?r(s):"maxZoom"===l?o(s):"translateExtent"===l?i(s):"nodeExtent"===l?a(s):"ariaLabelConfig"===l?u.setState({ariaLabelConfig:Kr(s)}):"fitView"===l?u.setState({fitViewQueued:s}):"fitViewOptions"===l?u.setState({fitViewOptions:s}):u.setState({[l]:s}))}c.current=e},Di.map(t=>e[t])),null}function Vi(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}var $i=typeof document<"u"?document:null;function Bi(e=null,t={target:$i,actInsideInputWithModifier:!0}){let[n,r]=(0,f.useState)(!1),o=(0,f.useRef)(!1),i=(0,f.useRef)(new Set([])),[a,l]=(0,f.useMemo)(()=>{if(null!==e){let t=(Array.isArray(e)?e:[e]).filter(e=>"string"==typeof e).map(e=>e.replace("+","\n").replace("\n\n","\n+").split("\n"));return[t,t.reduce((e,t)=>e.concat(...t),[])]}return[[],[]]},[e]);return(0,f.useEffect)(()=>{let n=t?.target??$i,s=t?.actInsideInputWithModifier??!0;if(null!==e){let e=e=>{if(o.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!o.current||o.current&&!s)&&Qr(e))return!1;let n=qi(e.code,l);if(i.current.add(e[n]),Wi(a,i.current,!1)){let n=e.composedPath?.()?.[0]||e.target,i="BUTTON"===n?.nodeName||"A"===n?.nodeName;!1!==t.preventDefault&&(o.current||!i)&&e.preventDefault(),r(!0)}},u=e=>{let t=qi(e.code,l);Wi(a,i.current,!0)?(r(!1),i.current.clear()):i.current.delete(e[t]),"Meta"===e.key&&i.current.clear(),o.current=!1},c=()=>{i.current.clear(),r(!1)};return n?.addEventListener("keydown",e),n?.addEventListener("keyup",u),window.addEventListener("blur",c),window.addEventListener("contextmenu",c),()=>{n?.removeEventListener("keydown",e),n?.removeEventListener("keyup",u),window.removeEventListener("blur",c),window.removeEventListener("contextmenu",c)}}},[e,r]),n}function Wi(e,t,n){return e.filter(e=>n||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function qi(e,t){return t.includes(e)?"code":"key"}function Ui(e,t){let n=[],r=new Map,o=[];for(let t of e)if("add"!==t.type)if("remove"===t.type||"replace"===t.type)r.set(t.id,[t]);else{let e=r.get(t.id);e?e.push(t):r.set(t.id,[t])}else o.push(t);for(let e of t){let t=r.get(e.id);if(!t){n.push(e);continue}if("remove"===t[0].type)continue;if("replace"===t[0].type){n.push({...t[0].item});continue}let o={...e};for(let e of t)Ki(e,o);n.push(o)}return o.length&&o.forEach(e=>{void 0===e.index?n.push({...e.item}):n.splice(e.index,0,{...e.item})}),n}function Ki(e,t){switch(e.type){case"select":t.selected=e.selected;break;case"position":void 0!==e.position&&(t.position=e.position),void 0!==e.dragging&&(t.dragging=e.dragging);break;case"dimensions":void 0!==e.dimensions&&(t.measured={...e.dimensions},e.setAttributes&&((!0===e.setAttributes||"width"===e.setAttributes)&&(t.width=e.dimensions.width),(!0===e.setAttributes||"height"===e.setAttributes)&&(t.height=e.dimensions.height))),"boolean"==typeof e.resizing&&(t.resizing=e.resizing)}}function Yi(e,t){return Ui(e,t)}function Xi(e,t){return Ui(e,t)}function Zi(e,t){return{id:e,type:"select",selected:t}}function Gi(e,t=new Set,n=!1){let r=[];for(let[o,i]of e){let e=t.has(o);(void 0!==i.selected||e)&&i.selected!==e&&(n&&(i.selected=e),r.push(Zi(i.id,e)))}return r}function Qi({items:e=[],lookup:t}){let n=[],r=new Map(e.map(e=>[e.id,e]));for(let[r,o]of e.entries()){let e=t.get(o.id),i=e?.internals?.userNode??e;void 0!==i&&i!==o&&n.push({id:o.id,item:o,type:"replace"}),void 0===i&&n.push({item:o,type:"add",index:r})}for(let[e]of t)void 0===r.get(e)&&n.push({id:e,type:"remove"});return n}function Ji(e){return{id:e.id,type:"remove"}}var ea=(e,t)=>{},ta=e=>(e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e))(e);function na(e){return(0,f.forwardRef)(e)}var ra=typeof window<"u"?f.useLayoutEffect:f.useEffect;function oa(e){let[t,n]=(0,f.useState)(BigInt(0)),[r]=(0,f.useState)(()=>function(e){let t=[];return{get:()=>t,reset:()=>{t=[]},push:n=>{t.push(n),e()}}}(()=>n(e=>e+BigInt(1))));return ra(()=>{let t=r.get();t.length&&(e(t),r.reset())},[t]),r}var ia=(0,f.createContext)(null);function aa({children:e}){let t=vi(),n=oa((0,f.useCallback)(e=>{let{nodes:n=[],setNodes:r,hasDefaultNodes:o,onNodesChange:i,nodeLookup:a,fitViewQueued:l,onNodesChangeMiddlewareMap:s}=t.getState(),u=n;for(let t of e)u="function"==typeof t?t(u):t;let c=Qi({items:u,lookup:a});for(let e of s.values())c=e(c);o&&r(u),c.length>0?i?.(c):l&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:n,setNodes:r}=t.getState();e&&r(n)})},[])),r=oa((0,f.useCallback)(e=>{let{edges:n=[],setEdges:r,hasDefaultEdges:o,onEdgesChange:i,edgeLookup:a}=t.getState(),l=n;for(let t of e)l="function"==typeof t?t(l):t;o?r(l):i&&i(Qi({items:l,lookup:a}))},[])),o=(0,f.useMemo)(()=>({nodeQueue:n,edgeQueue:r}),[]);return(0,p.jsx)(ia.Provider,{value:o,children:e})}var la=e=>!!e.panZoom;function sa(){let e=(()=>{let e=vi();return(0,f.useMemo)(()=>({zoomIn:async t=>{let{panZoom:n}=e.getState();return!!n&&n.scaleBy(1.2,t)},zoomOut:async t=>{let{panZoom:n}=e.getState();return!!n&&n.scaleBy(1/1.2,t)},zoomTo:async(t,n)=>{let{panZoom:r}=e.getState();return!!r&&r.scaleTo(t,n)},getZoom:()=>e.getState().transform[2],setViewport:async(t,n)=>{let{transform:[r,o,i],panZoom:a}=e.getState();return!!a&&(await a.setViewport({x:t.x??r,y:t.y??o,zoom:t.zoom??i},n),!0)},getViewport:()=>{let[t,n,r]=e.getState().transform;return{x:t,y:n,zoom:r}},setCenter:async(t,n,r)=>e.getState().setCenter(t,n,r),fitBounds:async(t,n)=>{let{width:r,height:o,minZoom:i,maxZoom:a,panZoom:l}=e.getState(),s=Hr(t,r,o,i,a,n?.padding??.1);return!!l&&(await l.setViewport(s,{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0)},screenToFlowPosition:(t,n={})=>{let{transform:r,snapGrid:o,snapToGrid:i,domNode:a}=e.getState();if(!a)return t;let{x:l,y:s}=a.getBoundingClientRect(),u={x:t.x-l,y:t.y-s},c=n.snapGrid??o;return Dr(u,r,n.snapToGrid??i,c)},flowToScreenPosition:t=>{let{transform:n,domNode:r}=e.getState();if(!r)return t;let{x:o,y:i}=r.getBoundingClientRect(),a=Fr(t,n);return{x:a.x+o,y:a.y+i}}}),[])})(),t=vi(),n=function(){let e=(0,f.useContext)(ia);if(!e)throw Error("useBatchContext must be used within a BatchProvider");return e}(),r=yi(la),o=(0,f.useMemo)(()=>{let e=e=>t.getState().nodeLookup.get(e),r=e=>{n.nodeQueue.push(e)},o=e=>{n.edgeQueue.push(e)},i=e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState(),o=ta(e)?e:n.get(e.id),i=o.parentId?qr(o.position,o.measured,o.parentId,n,r):o.position;return _r({...o,position:i,width:o.measured?.width??o.width,height:o.measured?.height??o.height})},a=(e,t,n={replace:!1})=>{r(r=>r.map(r=>{if(r.id===e){let e="function"==typeof t?t(r):t;return n.replace&&ta(e)?e:{...r,...e}}return r}))},l=(e,t,n={replace:!1})=>{o(r=>r.map(r=>{if(r.id===e){let e="function"==typeof t?t(r):t;return n.replace&&(e=>hr(e))(e)?e:{...r,...e}}return r}))};return{getNodes:()=>t.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=t.getState();return e.map(e=>({...e}))},getEdge:e=>t.getState().edgeLookup.get(e),setNodes:r,setEdges:o,addNodes:e=>{let t=Array.isArray(e)?e:[e];n.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];n.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:n=[],transform:r}=t.getState(),[o,i,a]=r;return{nodes:e.map(e=>({...e})),edges:n.map(e=>({...e})),viewport:{x:o,y:i,zoom:a}}},deleteElements:async({nodes:e=[],edges:n=[]})=>{let{nodes:r,edges:o,onNodesDelete:i,onEdgesDelete:a,triggerNodeChanges:l,triggerEdgeChanges:s,onDelete:u,onBeforeDelete:c}=t.getState(),{nodes:d,edges:f}=await async function({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:o}){let i=new Set(e.map(e=>e.id)),a=[];for(let e of n){if(!1===e.deletable)continue;let t=i.has(e.id),n=!t&&e.parentId&&a.find(t=>t.id===e.parentId);(t||n)&&a.push(e)}let l=new Set(t.map(e=>e.id)),s=r.filter(e=>!1!==e.deletable),u=((e,t)=>{let n=new Set;return e.forEach(e=>{n.add(e.id)}),t.filter(e=>n.has(e.source)||n.has(e.target))})(a,s);for(let e of s)l.has(e.id)&&!u.find(t=>t.id===e.id)&&u.push(e);if(!o)return{edges:u,nodes:a};let c=await o({nodes:a,edges:u});return"boolean"==typeof c?c?{edges:u,nodes:a}:{edges:[],nodes:[]}:c}({nodesToRemove:e,edgesToRemove:n,nodes:r,edges:o,onBeforeDelete:c}),p=f.length>0,h=d.length>0;if(p){let e=f.map(Ji);a?.(f),s(e)}if(h){let e=d.map(Ji);i?.(d),l(e)}return(h||p)&&u?.({nodes:d,edges:f}),{deletedNodes:d,deletedEdges:f}},getIntersectingNodes:(e,n=!0,r)=>{let o=Rr(e),a=o?e:i(e),l=void 0!==r;return a?(r||t.getState().nodes).filter(r=>{let i=t.getState().nodeLookup.get(r.id);if(i&&!o&&(r.id===e.id||!i.internals.positionAbsolute))return!1;let s=_r(l?r:i),u=zr(s,a);return n&&u>0||u>=s.width*s.height||u>=a.width*a.height}):[]},isNodeIntersecting:(e,t,n=!0)=>{let r=Rr(e)?e:i(e);if(!r)return!1;let o=zr(r,t);return n&&o>0||o>=t.width*t.height||o>=r.width*r.height},updateNode:a,updateNodeData:(e,t,n={replace:!1})=>{a(e,e=>{let r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},updateEdge:l,updateEdgeData:(e,t,n={replace:!1})=>{l(e,e=>{let r="function"==typeof t?t(e):t;return n.replace?{...e,data:r}:{...e,data:{...e.data,...r}}},n)},getNodesBounds:e=>{let{nodeLookup:n,nodeOrigin:r}=t.getState();return((e,t={nodeOrigin:[0,0]})=>0===e.length?{x:0,y:0,width:0,height:0}:Tr(e.reduce((e,n)=>{let r="string"==typeof n,o=t.nodeLookup||r?void 0:n;return t.nodeLookup&&(o=r?t.nodeLookup.get(n):mr(n)?n:t.nodeLookup.get(n.id)),Pr(e,o?Nr(o,t.nodeOrigin):{x:0,y:0,x2:0,y2:0})},{x:1/0,y:1/0,x2:-1/0,y2:-1/0})))(e,{nodeLookup:n,nodeOrigin:r})},getHandleConnections:({type:e,id:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}-${e}${n?`-${n}`:""}`)?.values()??[]),getNodeConnections:({type:e,handleId:n,nodeId:r})=>Array.from(t.getState().connectionLookup.get(`${r}${e?n?`-${e}-${n}`:`-${e}`:""}`)?.values()??[]),fitView:async e=>{let r=t.getState().fitViewResolver??function(){let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}();return t.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:r}),n.nodeQueue.push(e=>[...e]),r.promise}}},[]);return(0,f.useMemo)(()=>({...o,...e,viewportInitialized:r}),[r])}var ua=e=>e.selected,ca=typeof window<"u"?window:void 0;function da({deleteKeyCode:e,multiSelectionKeyCode:t}){let n=vi(),{deleteElements:r}=sa(),o=Bi(e,{actInsideInputWithModifier:!1}),i=Bi(t,{target:ca});(0,f.useEffect)(()=>{if(o){let{edges:e,nodes:t}=n.getState();r({nodes:t.filter(ua),edges:e.filter(ua)}),n.setState({nodesSelectionActive:!1})}},[o]),(0,f.useEffect)(()=>{n.setState({multiSelectionActive:i})},[i])}var fa={position:"absolute",width:"100%",height:"100%",top:0,left:0},pa=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function ha({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:n=!0,panOnScroll:r=!1,panOnScrollSpeed:o=.5,panOnScrollMode:i=rr.Free,zoomOnDoubleClick:a=!0,panOnDrag:l=!0,defaultViewport:s,translateExtent:u,minZoom:c,maxZoom:d,zoomActivationKeyCode:h,preventScrolling:m=!0,children:g,noWheelClassName:y,noPanClassName:v,onViewportChange:b,isControlledViewport:w,paneClickDistance:x,selectionOnDrag:k}){let S=vi(),E=(0,f.useRef)(null),{userSelectionActive:C,lib:M,connectionInProgress:P}=yi(pa,fi),O=Bi(h),T=(0,f.useRef)();!function(e){let t=vi();(0,f.useEffect)(()=>{let n=()=>{if(!e.current||!(e.current.checkVisibility?.()??1))return!1;let n=Xr(e.current);(0===n.height||0===n.width)&&t.getState().onError?.("004","The parent container needs a width and a height to render the graph."),t.setState({width:n.width||500,height:n.height||500})};if(e.current){n(),window.addEventListener("resize",n);let t=new ResizeObserver(()=>n());return t.observe(e.current),()=>{window.removeEventListener("resize",n),t&&e.current&&t.unobserve(e.current)}}},[])}(E);let _=(0,f.useCallback)(e=>{b?.({x:e[0],y:e[1],zoom:e[2]}),w||S.setState({transform:e})},[b,w]);return(0,f.useEffect)(()=>{if(E.current){T.current=function({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:o,onPanZoom:i,onPanZoomStart:a,onPanZoomEnd:l,onDraggingChange:s}){let u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},c=e.getBoundingClientRect(),d=tr().scaleExtent([t,n]).translateExtent(r),f=_e(e).call(d);y({x:o.x,y:o.y,zoom:kr(o.zoom,t,n)},[[0,0],[c.width,c.height]],r);let p=f.on("wheel.zoom"),h=f.on("dblclick.zoom");async function m(e,t){return!!f&&new Promise(n=>{d?.interpolate("linear"===t?.interpolate?At:Kt).transform(Uo(f,t?.duration,t?.ease,()=>n(!0)),e)})}function g(){d.on("zoom",null)}async function y(e,t,n){let r=$o(e),o=d?.constrain()(r,t,n);return o&&await m(o),o}return d.wheelDelta(Ko),{update:function({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:n,userSelectionActive:r,panOnScroll:o,panOnDrag:c,panOnScrollMode:m,panOnScrollSpeed:y,preventScrolling:v,zoomOnPinch:b,zoomOnScroll:w,zoomOnDoubleClick:x,zoomActivationKeyPressed:k,lib:S,onTransformChange:E,connectionInProgress:C,paneClickDistance:M,selectionOnDrag:P}){r&&!u.isZoomingOrPanning&&g();let O=o&&!k&&!r;d.clickDistance(P?1/0:!Lr(M)||M<0?0:M);let T=O?function({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:o,panOnScrollSpeed:i,zoomOnPinch:a,onPanZoomStart:l,onPanZoom:s,onPanZoomEnd:u}){return c=>{if(Bo(c,t))return c.ctrlKey&&c.preventDefault(),!1;c.preventDefault(),c.stopImmediatePropagation();let d=n.property("__zoom").k||1;if(c.ctrlKey&&a){let e=Ne(c),t=d*2**Ko(c);return void r.scaleTo(n,t,e,c)}let f=1===c.deltaMode?20:1,p=o===rr.Vertical?0:c.deltaX*f,h=o===rr.Horizontal?0:c.deltaY*f;!Vr()&&c.shiftKey&&o!==rr.Vertical&&(p=c.deltaY*f,h=0),r.translateBy(n,-p/d*i,-h/d*i,{internal:!0});let m=Vo(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(s?.(c,m),e.panScrollTimeout=setTimeout(()=>{u?.(c,m),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(c,m))}}({zoomPanValues:u,noWheelClassName:e,d3Selection:f,d3Zoom:d,panOnScrollMode:m,panOnScrollSpeed:y,zoomOnPinch:b,onPanZoomStart:a,onPanZoom:i,onPanZoomEnd:l}):function({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,o){let i="wheel"===r.type,a=!t&&i&&!r.ctrlKey,l=Bo(r,e);if(r.ctrlKey&&i&&l&&r.preventDefault(),a||l)return null;r.preventDefault(),n.call(this,r,o)}}({noWheelClassName:e,preventScrolling:v,d3ZoomHandler:p});f.on("wheel.zoom",T,{passive:!1});let _=function({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;let o=Vo(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=o,"mousedown"===r.sourceEvent?.type&&t(!0),n&&n?.(r.sourceEvent,o)}}({zoomPanValues:u,onDraggingChange:s,onPanZoomStart:a});d.on("start",_);let N=function({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:o}){return i=>{e.usedRightMouseButton=!(!n||!Wo(t,e.mouseButton??0)),i.sourceEvent?.sync||r([i.transform.x,i.transform.y,i.transform.k]),o&&!i.sourceEvent?.internal&&o?.(i.sourceEvent,Vo(i.transform))}}({zoomPanValues:u,panOnDrag:c,onPaneContextMenu:!!n,onPanZoom:i,onTransformChange:E});d.on("zoom",N);let I=function({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:o,onPaneContextMenu:i}){return a=>{if(!a.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,i&&Wo(t,e.mouseButton??0)&&!e.usedRightMouseButton&&a.sourceEvent&&i(a.sourceEvent),e.usedRightMouseButton=!1,r(!1),o)){let t=Vo(a.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{o?.(a.sourceEvent,t)},n?150:0)}}}({zoomPanValues:u,panOnDrag:c,panOnScroll:o,onPaneContextMenu:n,onPanZoomEnd:l,onDraggingChange:s});d.on("end",I);let z=function({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:o,zoomOnDoubleClick:i,userSelectionActive:a,noWheelClassName:l,noPanClassName:s,lib:u,connectionInProgress:c}){return d=>{let f=e||t,p=n&&d.ctrlKey,h="wheel"===d.type;if(1===d.button&&"mousedown"===d.type&&(Bo(d,`${u}-flow__node`)||Bo(d,`${u}-flow__edge`)))return!0;if(!r&&!f&&!o&&!i&&!n||a||c&&!h||Bo(d,l)&&h||Bo(d,s)&&(!h||o&&h&&!e)||!n&&d.ctrlKey&&h)return!1;if(!n&&"touchstart"===d.type&&d.touches?.length>1)return d.preventDefault(),!1;if(!f&&!o&&!p&&h||!r&&("mousedown"===d.type||"touchstart"===d.type)||Array.isArray(r)&&!r.includes(d.button)&&"mousedown"===d.type)return!1;let m=Array.isArray(r)&&r.includes(d.button)||!d.button||d.button<=1;return(!d.ctrlKey||h)&&m}}({zoomActivationKeyPressed:k,panOnDrag:c,zoomOnScroll:w,panOnScroll:o,zoomOnDoubleClick:x,zoomOnPinch:b,userSelectionActive:r,noPanClassName:t,noWheelClassName:e,lib:S,connectionInProgress:C});d.filter(z),x?f.on("dblclick.zoom",h):f.on("dblclick.zoom",null)},destroy:g,setViewport:async function(e,t){let n=$o(e);return await m(n,t),n},setViewportConstrained:y,getViewport:function(){let e=f?Un(f.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}},scaleTo:async function(e,t){return!!f&&new Promise(n=>{d?.interpolate("linear"===t?.interpolate?At:Kt).scaleTo(Uo(f,t?.duration,t?.ease,()=>n(!0)),e)})},scaleBy:async function(e,t){return!!f&&new Promise(n=>{d?.interpolate("linear"===t?.interpolate?At:Kt).scaleBy(Uo(f,t?.duration,t?.ease,()=>n(!0)),e)})},setScaleExtent:function(e){d?.scaleExtent(e)},setTranslateExtent:function(e){d?.translateExtent(e)},syncViewport:function(e){if(f){let t=$o(e),n=f.property("__zoom");(n.k!==e.zoom||n.x!==e.x||n.y!==e.y)&&d?.transform(f,t,null,{sync:!0})}},setClickDistance:function(e){let t=!Lr(e)||e<0?0:e;d?.clickDistance(t)}}}({domNode:E.current,minZoom:c,maxZoom:d,translateExtent:u,viewport:s,onDraggingChange:e=>S.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:n,onMoveStart:r}=S.getState();r?.(e,t),n?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:n,onMove:r}=S.getState();r?.(e,t),n?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:n,onMoveEnd:r}=S.getState();r?.(e,t),n?.(t)}});let{x:e,y:t,zoom:n}=T.current.getViewport();return S.setState({panZoom:T.current,transform:[e,t,n],domNode:E.current.closest(".react-flow")}),()=>{T.current?.destroy()}}},[]),(0,f.useEffect)(()=>{T.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:n,panOnScroll:r,panOnScrollSpeed:o,panOnScrollMode:i,zoomOnDoubleClick:a,panOnDrag:l,zoomActivationKeyPressed:O,preventScrolling:m,noPanClassName:v,userSelectionActive:C,noWheelClassName:y,lib:M,onTransformChange:_,connectionInProgress:P,selectionOnDrag:k,paneClickDistance:x})},[e,t,n,r,o,i,a,l,O,m,v,C,y,M,_,P,k,x]),(0,p.jsx)("div",{className:"react-flow__renderer",ref:E,style:fa,children:g})}var ma=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ga(){let{userSelectionActive:e,userSelectionRect:t}=yi(ma,fi);return e&&t?(0,p.jsx)("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}var ya=(e,t)=>n=>{n.target===t.current&&e?.(n)},va=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function ba({isSelecting:e,selectionKeyPressed:t,selectionMode:n=or.Full,panOnDrag:r,autoPanOnSelection:o,paneClickDistance:i,selectionOnDrag:a,onSelectionStart:l,onSelectionEnd:s,onPaneClick:u,onPaneContextMenu:c,onPaneScroll:d,onPaneMouseEnter:m,onPaneMouseMove:g,onPaneMouseLeave:y,children:v}){let b=(0,f.useRef)(0),w=vi(),{userSelectionActive:x,elementsSelectable:k,dragging:S,connectionInProgress:E,panBy:C,autoPanSpeed:M}=yi(va,fi),P=k&&(e||x),O=(0,f.useRef)(null),T=(0,f.useRef)(),_=(0,f.useRef)(new Set),N=(0,f.useRef)(new Set),I=(0,f.useRef)(!1),z=(0,f.useRef)({x:0,y:0}),R=(0,f.useRef)(!1),L=e=>{I.current||E?I.current=!1:(u?.(e),w.getState().resetSelectedElements(),w.setState({nodesSelectionActive:!1}))},A=d?e=>d(e):void 0;function D(e,t){let{userSelectionRect:r}=w.getState();if(!r)return;let{transform:o,nodeLookup:i,edgeLookup:a,connectionLookup:l,triggerNodeChanges:s,triggerEdgeChanges:u,defaultEdgeOptions:c}=w.getState(),d={x:r.startX,y:r.startY},{x:f,y:p}=Fr(d,o),h={startX:d.x,startY:d.y,x:ee.id)),N.current=new Set;let y=c?.selectable??!0;for(let e of _.current){let t=l.get(e);if(t)for(let{edgeId:e}of t.values()){let t=a.get(e);t&&(t.selectable??y)&&N.current.add(e)}}Ur(m,_.current)||s(Gi(i,_.current,!0)),Ur(g,N.current)||u(Gi(a,N.current)),w.setState({userSelectionRect:h,userSelectionActive:!0,nodesSelectionActive:!1})}function F(){if(!o||!T.current)return;let[e,t]=Mr(z.current,T.current,M);C({x:e,y:t}).then(e=>{if(!I.current||!e)return void(b.current=requestAnimationFrame(F));let{x:t,y:n}=z.current;D(t,n),b.current=requestAnimationFrame(F)})}let j=()=>{cancelAnimationFrame(b.current),b.current=0,R.current=!1};return(0,f.useEffect)(()=>()=>j(),[]),(0,p.jsxs)("div",{className:h(["react-flow__pane",{draggable:!0===r||Array.isArray(r)&&r.includes(0),dragging:S,selection:e}]),onClick:P?void 0:ya(L,O),onContextMenu:ya(e=>{Array.isArray(r)&&r?.includes(2)?e.preventDefault():c?.(e)},O),onWheel:ya(A,O),onPointerEnter:P?void 0:m,onPointerMove:P?e=>{let{userSelectionRect:n,transform:r,resetSelectedElements:o}=w.getState();if(!T.current||!n)return;let{x:a,y:s}=eo(e.nativeEvent,T.current);z.current={x:a,y:s};let u=Fr({x:n.startX,y:n.startY},r);if(!I.current){let n=t?0:i;if(Math.hypot(a-u.x,s-u.y)<=n)return;o(),l?.(e)}I.current=!0,R.current||=(F(),!0),D(a,s)}:g,onPointerUp:P?e=>{0===e.button&&(e.target?.releasePointerCapture?.(e.pointerId),!x&&e.target===O.current&&w.getState().userSelectionRect&&L?.(e),w.setState({userSelectionActive:!1,userSelectionRect:null}),I.current&&(s?.(e),w.setState({nodesSelectionActive:_.current.size>0})),j())}:void 0,onPointerCancel:P?e=>{e.target?.releasePointerCapture?.(e.pointerId),j()}:void 0,onPointerDownCapture:P?n=>{let{domNode:r,transform:o}=w.getState();if(T.current=r?.getBoundingClientRect(),!T.current)return;let i=n.target===O.current;if(!i&&n.target.closest(".nokey")||!e||!(a&&i||t)||0!==n.button||!n.isPrimary)return;n.target?.setPointerCapture?.(n.pointerId),I.current=!1;let{x:l,y:s}=eo(n.nativeEvent,T.current),u=Dr({x:l,y:s},o);w.setState({userSelectionRect:{width:0,height:0,startX:u.x,startY:u.y,x:l,y:s}}),i||(n.stopPropagation(),n.preventDefault())}:void 0,onClickCapture:P?e=>{I.current&&=(e.stopPropagation(),!1)}:void 0,onPointerLeave:y,ref:O,style:fa,children:[v,(0,p.jsx)(ga,{})]})}function wa({id:e,store:t,unselect:n=!1,nodeRef:r}){let{addSelectedNodes:o,unselectNodesAndEdges:i,multiSelectionActive:a,nodeLookup:l,onError:s}=t.getState(),u=l.get(e);u?(t.setState({nodesSelectionActive:!1}),u.selected?(n||u.selected&&a)&&(i({nodes:[u],edges:[]}),requestAnimationFrame(()=>r?.current?.blur())):o([e])):s?.("012",(e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`)(e))}function xa({nodeRef:e,disabled:t=!1,noDragClassName:n,handleSelector:r,nodeId:o,isSelectable:i,nodeClickDistance:a}){let l=vi(),[s,u]=(0,f.useState)(!1),c=(0,f.useRef)();return(0,f.useEffect)(()=>{c.current=function({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:o}){let i={x:null,y:null},a=0,l=new Map,s=!1,u={x:0,y:0},c=null,d=!1,f=null,p=!1,h=!1,m=null;return{update:function({noDragClassName:g,handleSelector:y,domNode:v,isSelectable:b,nodeId:w,nodeClickDistance:x=0}){function k({x:e,y:n}){let{nodeLookup:o,nodeExtent:a,snapGrid:s,snapToGrid:u,nodeOrigin:c,onNodeDrag:d,onSelectionDrag:f,onError:p,updateNodePositions:g}=t();i={x:e,y:n};let y=!1,v=l.size>1,b=v&&a?Or(br(l)):null,x=v&&u?function({dragItems:e,snapGrid:t,x:n,y:r}){let o=e.values().next().value;if(!o)return null;let i={x:n-o.distance.x,y:r-o.distance.y},a=Ar(i,t);return{x:a.x-i.x,y:a.y-i.y}}({dragItems:l,snapGrid:s,x:e,y:n}):null;for(let[t,r]of l){if(!o.has(t))continue;let i={x:e-r.distance.x,y:n-r.distance.y};u&&(i=x?{x:Math.round(i.x+x.x),y:Math.round(i.y+x.y)}:Ar(i,s));let l=null;if(v&&a&&!r.extent&&b){let{positionAbsolute:e}=r.internals,t=e.x-b.x+a[0][0],n=e.x+r.measured.width-b.x2+a[1][0];l=[[t,e.y-b.y+a[0][1]],[n,e.y+r.measured.height-b.y2+a[1][1]]]}let{position:d,positionAbsolute:f}=xr({nodeId:t,nextPosition:i,nodeLookup:o,nodeExtent:l||a,nodeOrigin:c,onError:p});y=y||r.position.x!==d.x||r.position.y!==d.y,r.position=d,r.internals.positionAbsolute=f}if(h||=y,y&&(g(l,!0),m&&(r||d||!w&&f))){let[e,t]=Ro({nodeId:w,dragItems:l,nodeLookup:o});r?.(m,l,e,t),d?.(m,e,t),w||f?.(m,t)}}async function S(){if(!c)return;let{transform:e,panBy:n,autoPanSpeed:r,autoPanOnNodeDrag:o}=t();if(!o)return s=!1,void cancelAnimationFrame(a);let[l,d]=Mr(u,c,r);(0!==l||0!==d)&&(i.x=(i.x??0)-l/e[2],i.y=(i.y??0)-d/e[2],await n({x:l,y:d})&&k(i)),a=requestAnimationFrame(S)}function E(r){let{nodeLookup:o,multiSelectionActive:a,nodesDraggable:s,transform:u,snapGrid:f,snapToGrid:p,selectNodesOnDrag:h,onNodeDragStart:m,onSelectionDragStart:g,unselectNodesAndEdges:y}=t();d=!0,(!h||!b)&&!a&&w&&(o.get(w)?.selected||y()),b&&h&&w&&e?.(w);let v=Yr(r.sourceEvent,{transform:u,snapGrid:f,snapToGrid:p,containerBounds:c});if(i=v,l=function(e,t,n,r){let o=new Map;for(let[i,a]of e)if((a.selected||a.id===r)&&(!a.parentId||!Io(a,e))&&(a.draggable||t&&void 0===a.draggable)){let t=e.get(i);t&&o.set(i,{id:i,position:t.position||{x:0,y:0},distance:{x:n.x-t.internals.positionAbsolute.x,y:n.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return o}(o,s,v,w),l.size>0&&(n||m||!w&&g)){let[e,t]=Ro({nodeId:w,dragItems:l,nodeLookup:o});n?.(r.sourceEvent,l,e,t),m?.(r.sourceEvent,e,t),w||g?.(r.sourceEvent,t)}}f=_e(v);let C=We().clickDistance(x).on("start",e=>{let{domNode:n,nodeDragThreshold:r,transform:o,snapGrid:a,snapToGrid:l}=t();c=n?.getBoundingClientRect()||null,p=!1,h=!1,m=e.sourceEvent,0===r&&E(e),i=Yr(e.sourceEvent,{transform:o,snapGrid:a,snapToGrid:l,containerBounds:c}),u=eo(e.sourceEvent,c)}).on("drag",e=>{let{autoPanOnNodeDrag:n,transform:r,snapGrid:o,snapToGrid:a,nodeDragThreshold:f,nodeLookup:h}=t(),g=Yr(e.sourceEvent,{transform:r,snapGrid:o,snapToGrid:a,containerBounds:c});if(m=e.sourceEvent,("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1||w&&!h.has(w))&&(p=!0),!p){if(!s&&n&&d&&(s=!0,S()),!d){let t=eo(e.sourceEvent,c),n=t.x-u.x,r=t.y-u.y;Math.sqrt(n*n+r*r)>f&&E(e)}(i.x!==g.xSnapped||i.y!==g.ySnapped)&&l&&d&&(u=eo(e.sourceEvent,c),k(g))}}).on("end",e=>{if(d&&!p){if(s=!1,d=!1,cancelAnimationFrame(a),l.size>0){let{nodeLookup:n,updateNodePositions:r,onNodeDragStop:i,onSelectionDragStop:a}=t();if(h&&=(r(l,!1),!1),o||i||!w&&a){let[t,r]=Ro({nodeId:w,dragItems:l,nodeLookup:n,dragging:!1});o?.(e.sourceEvent,l,t,r),i?.(e.sourceEvent,t,r),w||a?.(e.sourceEvent,r)}}}else p&&l.size>0&&t().updateNodePositions(l,!1)}).filter(e=>{let t=e.target;return!e.button&&(!g||!zo(t,`.${g}`,v))&&(!y||zo(t,y,v))});f.call(C)},destroy:function(){f?.on(".drag",null)}}}({getStoreItems:()=>l.getState(),onNodeMouseDown:t=>{wa({id:t,store:l,nodeRef:e})},onDragStart:()=>{u(!0)},onDragStop:()=>{u(!1)}})},[]),(0,f.useEffect)(()=>{if(!t&&e.current&&c.current)return c.current.update({noDragClassName:n,handleSelector:r,domNode:e.current,isSelectable:i,nodeId:o,nodeClickDistance:a}),()=>{c.current?.destroy()}},[n,r,t,i,e,o,a]),s}function ka(){let e=vi();return(0,f.useCallback)(t=>{let{nodeExtent:n,snapToGrid:r,snapGrid:o,nodesDraggable:i,onError:a,updateNodePositions:l,nodeLookup:s,nodeOrigin:u}=e.getState(),c=new Map,d=(e=>t=>t.selected&&(t.draggable||e&&void 0===t.draggable))(i),f=r?o[0]:5,p=r?o[1]:5,h=t.direction.x*f*t.factor,m=t.direction.y*p*t.factor;for(let[,e]of s){if(!d(e))continue;let t={x:e.internals.positionAbsolute.x+h,y:e.internals.positionAbsolute.y+m};r&&(t=Ar(t,o));let{position:i,positionAbsolute:l}=xr({nodeId:e.id,nextPosition:t,nodeLookup:s,nodeExtent:n,nodeOrigin:u,onError:a});e.position=i,e.internals.positionAbsolute=l,c.set(e.id,e)}l(c)},[])}var Sa=(0,f.createContext)(null),Ea=Sa.Provider;Sa.Consumer;var Ca=()=>(0,f.useContext)(Sa),Ma=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),Pa=(0,f.memo)(na(function({type:e="source",position:t=cr.Top,isValidConnection:n,isConnectable:r=!0,isConnectableStart:o=!0,isConnectableEnd:i=!0,id:a,onConnect:l,children:s,className:u,onMouseDown:c,onTouchStart:d,...f},m){let g=a||null,y="target"===e,v=vi(),b=Ca(),{connectOnClick:w,noPanClassName:x,rfId:k}=yi(Ma,fi),{connectingFrom:S,connectingTo:E,clickConnecting:C,isPossibleEndHandle:M,connectionInProcess:P,clickConnectionInProcess:O,valid:T}=yi(((e,t,n)=>r=>{let{connectionClickStartHandle:o,connectionMode:i,connection:a}=r,{fromHandle:l,toHandle:s,isValid:u}=a,c=s?.nodeId===e&&s?.id===t&&s?.type===n;return{connectingFrom:l?.nodeId===e&&l?.id===t&&l?.type===n,connectingTo:c,clickConnecting:o?.nodeId===e&&o?.id===t&&o?.type===n,isPossibleEndHandle:i===nr.Strict?l?.type!==n:e!==l?.nodeId||t!==l?.id,connectionInProcess:!!l,clickConnectionInProcess:!!o,valid:c&&u}})(b,g,e),fi);b||v.getState().onError?.("010","Handle: No node id found. Make sure to only use a Handle inside a custom Node.");let _=e=>{let{defaultEdgeOptions:t,onConnect:n,hasDefaultEdges:r}=v.getState(),o={...t,...e};if(r){let{edges:e,setEdges:t,onError:n}=v.getState();t(function(e,t,n={}){return((e,t,n={})=>{if(!e.source||!e.target)return n.onError?.("006","Can't create edge. An edge needs a source and a target."),t;let r,o=n.getEdgeId||uo;return r=hr(e)?{...e}:{...e,id:o(e)},((e,t)=>t.some(t=>!(t.source!==e.source||t.target!==e.target||t.sourceHandle!==e.sourceHandle&&(t.sourceHandle||e.sourceHandle)||t.targetHandle!==e.targetHandle&&(t.targetHandle||e.targetHandle))))(r,t)?t:(null===r.sourceHandle&&delete r.sourceHandle,null===r.targetHandle&&delete r.targetHandle,t.concat(r))})(e,t,{...n,onError:n.onError??ea})}(o,e,{onError:n}))}n?.(o),l?.(o)},N=e=>{if(!b)return;let t=Jr(e.nativeEvent);if(o&&(t&&0===e.button||!t)){let t=v.getState();Ho.onPointerDown(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:y,handleId:g,nodeId:b,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>v.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:_,isValidConnection:n||((...e)=>v.getState().isValidConnection?.(...e)??!0),getTransform:()=>v.getState().transform,getFromHandle:()=>v.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?c?.(e):d?.(e)};return(0,p.jsx)("div",{"data-handleid":g,"data-nodeid":b,"data-handlepos":t,"data-id":`${k}-${b}-${g}-${e}`,className:h(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",x,u,{source:!y,target:y,connectable:r,connectablestart:o,connectableend:i,clickconnecting:C,connectingfrom:S,connectingto:E,valid:T,connectionindicator:r&&(!P||M)&&(P||O?i:o)}]),onMouseDown:N,onTouchStart:N,onClick:w?t=>{let{onClickConnectStart:r,onClickConnectEnd:i,connectionClickStartHandle:a,connectionMode:l,isValidConnection:s,lib:u,rfId:c,nodeLookup:d,connection:f}=v.getState();if(!b||!a&&!o)return;if(!a)return r?.(t.nativeEvent,{nodeId:b,handleId:g,handleType:e}),void v.setState({connectionClickStartHandle:{nodeId:b,type:e,id:g}});let p=Zr(t.target),h=n||s,{connection:m,isValid:y}=Ho.isValid(t.nativeEvent,{handle:{nodeId:b,id:g,type:e},connectionMode:l,fromNodeId:a.nodeId,fromHandleId:a.id||null,fromType:a.type,isValidConnection:h,flowId:c,doc:p,lib:u,nodeLookup:d});y&&m&&_(m);let w=structuredClone(f);delete w.inProgress,w.toPosition=w.toHandle?w.toHandle.position:null,i?.(t,w),v.setState({connectionClickStartHandle:null})}:void 0,ref:m,...f,children:s})})),Oa={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},Ta={input:function({data:e,isConnectable:t,sourcePosition:n=cr.Bottom}){return(0,p.jsxs)(p.Fragment,{children:[e?.label,(0,p.jsx)(Pa,{type:"source",position:n,isConnectable:t})]})},default:function({data:e,isConnectable:t,targetPosition:n=cr.Top,sourcePosition:r=cr.Bottom}){return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(Pa,{type:"target",position:n,isConnectable:t}),e?.label,(0,p.jsx)(Pa,{type:"source",position:r,isConnectable:t})]})},output:function({data:e,isConnectable:t,targetPosition:n=cr.Top}){return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(Pa,{type:"target",position:n,isConnectable:t}),e?.label]})},group:function(){return null}},_a=e=>{let{width:t,height:n,x:r,y:o}=br(e.nodeLookup,{filter:e=>!!e.selected});return{width:Lr(t)?t:null,height:Lr(n)?n:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${r}px,${o}px)`}};function Na({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:n}){let r=vi(),{width:o,height:i,transformString:a,userSelectionActive:l}=yi(_a,fi),s=ka(),u=(0,f.useRef)(null);(0,f.useEffect)(()=>{n||u.current?.focus({preventScroll:!0})},[n]);let c=!l&&null!==o&&null!==i;if(xa({nodeRef:u,disabled:!c}),!c)return null;let d=e?t=>{e(t,r.getState().nodes.filter(e=>e.selected))}:void 0;return(0,p.jsx)("div",{className:h(["react-flow__nodesselection","react-flow__container",t]),style:{transform:a},children:(0,p.jsx)("div",{ref:u,className:"react-flow__nodesselection-rect",onContextMenu:d,tabIndex:n?void 0:-1,onKeyDown:n?void 0:e=>{Object.prototype.hasOwnProperty.call(Oa,e.key)&&(e.preventDefault(),s({direction:Oa[e.key],factor:e.shiftKey?4:1}))},style:{width:o,height:i}})})}var Ia=typeof window<"u"?window:void 0,za=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function Ra({children:e,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:i,onPaneScroll:a,paneClickDistance:l,deleteKeyCode:s,selectionKeyCode:u,selectionOnDrag:c,selectionMode:d,onSelectionStart:f,onSelectionEnd:h,multiSelectionKeyCode:m,panActivationKeyCode:g,zoomActivationKeyCode:y,elementsSelectable:v,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:x,panOnScrollSpeed:k,panOnScrollMode:S,zoomOnDoubleClick:E,panOnDrag:C,autoPanOnSelection:M,defaultViewport:P,translateExtent:O,minZoom:T,maxZoom:_,preventScrolling:N,onSelectionContextMenu:I,noWheelClassName:z,noPanClassName:R,disableKeyboardA11y:L,onViewportChange:A,isControlledViewport:D}){let{nodesSelectionActive:F,userSelectionActive:j}=yi(za,fi),H=Bi(u,{target:Ia}),V=Bi(g,{target:Ia}),$=V||C,B=V||x,W=c&&!0!==$,q=H||j||W;return da({deleteKeyCode:s,multiSelectionKeyCode:m}),(0,p.jsx)(ha,{onPaneContextMenu:i,elementsSelectable:v,zoomOnScroll:b,zoomOnPinch:w,panOnScroll:B,panOnScrollSpeed:k,panOnScrollMode:S,zoomOnDoubleClick:E,panOnDrag:!H&&$,defaultViewport:P,translateExtent:O,minZoom:T,maxZoom:_,zoomActivationKeyCode:y,preventScrolling:N,noWheelClassName:z,noPanClassName:R,onViewportChange:A,isControlledViewport:D,paneClickDistance:l,selectionOnDrag:W,children:(0,p.jsxs)(ba,{onSelectionStart:f,onSelectionEnd:h,onPaneClick:t,onPaneMouseEnter:n,onPaneMouseMove:r,onPaneMouseLeave:o,onPaneContextMenu:i,onPaneScroll:a,panOnDrag:$,autoPanOnSelection:M,isSelecting:!!q,selectionMode:d,selectionKeyPressed:H,paneClickDistance:l,selectionOnDrag:W,children:[e,F&&(0,p.jsx)(Na,{onSelectionContextMenu:I,noPanClassName:R,disableKeyboardA11y:L})]})})}Ra.displayName="FlowRenderer";var La=(0,f.memo)(Ra),Aa=e=>e.updateNodeInternals;function Da({node:e,nodeType:t,hasDimensions:n,resizeObserver:r}){let o=vi(),i=(0,f.useRef)(null),a=(0,f.useRef)(null),l=(0,f.useRef)(e.sourcePosition),s=(0,f.useRef)(e.targetPosition),u=(0,f.useRef)(t),c=n&&!!e.internals.handleBounds;return(0,f.useEffect)(()=>{i.current&&!e.hidden&&(!c||a.current!==i.current)&&(a.current&&r?.unobserve(a.current),r?.observe(i.current),a.current=i.current)},[c,e.hidden]),(0,f.useEffect)(()=>()=>{a.current&&=(r?.unobserve(a.current),null)},[]),(0,f.useEffect)(()=>{if(i.current){let n=u.current!==t,r=l.current!==e.sourcePosition,a=s.current!==e.targetPosition;(n||r||a)&&(u.current=t,l.current=e.sourcePosition,s.current=e.targetPosition,o.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:i.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),i}var Fa=(0,f.memo)(function({id:e,onClick:t,onMouseEnter:n,onMouseMove:r,onMouseLeave:o,onContextMenu:i,onDoubleClick:a,nodesDraggable:l,elementsSelectable:s,nodesConnectable:u,nodesFocusable:c,resizeObserver:d,noDragClassName:f,noPanClassName:m,disableKeyboardA11y:g,rfId:y,nodeTypes:v,nodeClickDistance:b,onError:w}){let{node:x,internals:k,isParent:S}=yi(t=>{let n=t.nodeLookup.get(e),r=t.parentLookup.has(e);return{node:n,internals:n.internals,isParent:r}},fi),E=x.type||"default",C=v?.[E]||Ta[E];void 0===C&&(w?.("003",(e=>`Node type "${e}" not found. Using fallback type "default".`)(E)),E="default",C=v?.default||Ta.default);let M=!!(x.draggable||l&&void 0===x.draggable),P=!!(x.selectable||s&&void 0===x.selectable),O=!!(x.connectable||u&&void 0===x.connectable),T=!!(x.focusable||c&&void 0===x.focusable),_=vi(),N=Wr(x),I=Da({node:x,nodeType:E,hasDimensions:N,resizeObserver:d}),z=xa({nodeRef:I,disabled:x.hidden||!M,noDragClassName:f,handleSelector:x.dragHandle,nodeId:e,isSelectable:P,nodeClickDistance:b}),R=ka();if(x.hidden)return null;let L=Br(x),A=function(e){return void 0===e.internals.handleBounds?{width:e.width??e.initialWidth??e.style?.width,height:e.height??e.initialHeight??e.style?.height}:{width:e.width??e.style?.width,height:e.height??e.style?.height}}(x),D=P||M||t||n||r||o,F=n?e=>n(e,{...k.userNode}):void 0,j=r?e=>r(e,{...k.userNode}):void 0,H=o?e=>o(e,{...k.userNode}):void 0,V=i?e=>i(e,{...k.userNode}):void 0,$=a?e=>a(e,{...k.userNode}):void 0;return(0,p.jsx)("div",{className:h(["react-flow__node",`react-flow__node-${E}`,{[m]:M},x.className,{selected:x.selected,selectable:P,parent:S,draggable:M,dragging:z}]),ref:I,style:{zIndex:k.z,transform:`translate(${k.positionAbsolute.x}px,${k.positionAbsolute.y}px)`,pointerEvents:D?"all":"none",visibility:N?"visible":"hidden",...x.style,...A},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:F,onMouseMove:j,onMouseLeave:H,onContextMenu:V,onClick:n=>{let{selectNodesOnDrag:r,nodeDragThreshold:o}=_.getState();P&&(!r||!M||o>0)&&wa({id:e,store:_,nodeRef:I}),t&&t(n,{...k.userNode})},onDoubleClick:$,onKeyDown:T?t=>{if(!Qr(t.nativeEvent)&&!g)if(ar.includes(t.key)&&P){let n="Escape"===t.key;wa({id:e,store:_,unselect:n,nodeRef:I})}else if(M&&x.selected&&Object.prototype.hasOwnProperty.call(Oa,t.key)){t.preventDefault();let{ariaLabelConfig:e}=_.getState();_.setState({ariaLiveMessage:e["node.a11yDescription.ariaLiveMessage"]({direction:t.key.replace("Arrow","").toLowerCase(),x:~~k.positionAbsolute.x,y:~~k.positionAbsolute.y})}),R({direction:Oa[t.key],factor:t.shiftKey?4:1})}}:void 0,tabIndex:T?0:void 0,onFocus:T?()=>{if(g||!I.current?.matches(":focus-visible"))return;let{transform:t,width:n,height:r,autoPanOnNodeFocus:o,setCenter:i}=_.getState();o&&(wr(new Map([[e,x]]),{x:0,y:0,width:n,height:r},t,!0).length>0||i(x.position.x+L.width/2,x.position.y+L.height/2,{zoom:t[2]}))}:void 0,role:x.ariaRole??(T?"group":void 0),"aria-roledescription":"node","aria-describedby":g?void 0:`${xi}-${y}`,"aria-label":x.ariaLabel,...x.domAttributes,children:(0,p.jsx)(Ea,{value:e,children:(0,p.jsx)(C,{id:e,data:x.data,type:E,positionAbsoluteX:k.positionAbsolute.x,positionAbsoluteY:k.positionAbsolute.y,selected:x.selected??!1,selectable:P,draggable:M,deletable:x.deletable??!0,isConnectable:O,sourcePosition:x.sourcePosition,targetPosition:x.targetPosition,dragging:z,dragHandle:x.dragHandle,zIndex:k.z,parentId:x.parentId,...L})})})}),ja=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function Ha(e){let{nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,onError:i}=yi(ja,fi),a=function(e){return yi((0,f.useCallback)((e=>t=>e?wr(t.nodeLookup,{x:0,y:0,width:t.width,height:t.height},t.transform,!0).map(e=>e.id):Array.from(t.nodeLookup.keys()))(e),[e]),fi)}(e.onlyRenderVisibleElements),l=function(){let e=yi(Aa),[t]=(0,f.useState)(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(t=>{let n=new Map;t.forEach(e=>{let t=e.target.getAttribute("data-id");n.set(t,{id:t,nodeElement:e.target,force:!0})}),e(n)}));return(0,f.useEffect)(()=>()=>{t?.disconnect()},[t]),t}();return(0,p.jsx)("div",{className:"react-flow__nodes",style:fa,children:a.map(a=>(0,p.jsx)(Fa,{id:a,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:l,nodesDraggable:t,nodesConnectable:n,nodesFocusable:r,elementsSelectable:o,nodeClickDistance:e.nodeClickDistance,onError:i},a))})}Ha.displayName="NodeRenderer";var Va=(0,f.memo)(Ha);function $a(e){return yi((0,f.useCallback)(t=>{if(!e)return t.edges.map(e=>e.id);let n=[];if(t.width&&t.height)for(let e of t.edges){let r=t.nodeLookup.get(e.source),o=t.nodeLookup.get(e.target);r&&o&&so({sourceNode:r,targetNode:o,width:t.width,height:t.height,transform:t.transform})&&n.push(e.id)}return n},[e]),fi)}var Ba={[ur.Arrow]:({color:e="none",strokeWidth:t=1})=>(0,p.jsx)("polyline",{className:"arrow",style:{strokeWidth:t,...e&&{stroke:e}},strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"}),[ur.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>(0,p.jsx)("polyline",{className:"arrowclosed",style:{strokeWidth:t,...e&&{stroke:e,fill:e}},strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},Wa=({id:e,type:t,color:n,width:r=12.5,height:o=12.5,markerUnits:i="strokeWidth",strokeWidth:a,orient:l="auto-start-reverse"})=>{let s=function(e){let t=vi();return(0,f.useMemo)(()=>Object.prototype.hasOwnProperty.call(Ba,e)?Ba[e]:(t.getState().onError?.("009",(e=>`Marker type "${e}" doesn't exist.`)(e)),null),[e])}(t);return s?(0,p.jsx)("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${r}`,markerHeight:`${o}`,viewBox:"-10 -10 20 20",markerUnits:i,orient:l,refX:"0",refY:"0",children:(0,p.jsx)(s,{color:n,strokeWidth:a})}):null},qa=({defaultColor:e,rfId:t})=>{let n=yi(e=>e.edges),r=yi(e=>e.defaultEdgeOptions),o=(0,f.useMemo)(()=>function(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:o}){let i=new Set;return e.reduce((e,a)=>([a.markerStart||r,a.markerEnd||o].forEach(r=>{if(r&&"object"==typeof r){let o=wo(r,t);i.has(o)||(e.push({id:o,color:r.color||n,...r}),i.add(o))}}),e),[]).sort((e,t)=>e.id.localeCompare(t.id))}(n,{id:t,defaultColor:e,defaultMarkerStart:r?.markerStart,defaultMarkerEnd:r?.markerEnd}),[n,r,t,e]);return o.length?(0,p.jsx)("svg",{className:"react-flow__marker","aria-hidden":"true",children:(0,p.jsx)("defs",{children:o.map(e=>(0,p.jsx)(Wa,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};qa.displayName="MarkerDefinitions";var Ua=(0,f.memo)(qa);function Ka({x:e,y:t,label:n,labelStyle:r,labelShowBg:o=!0,labelBgStyle:i,labelBgPadding:a=[2,4],labelBgBorderRadius:l=2,children:s,className:u,...c}){let[d,m]=(0,f.useState)({x:1,y:0,width:0,height:0}),g=h(["react-flow__edge-textwrapper",u]),y=(0,f.useRef)(null);return(0,f.useEffect)(()=>{if(y.current){let e=y.current.getBBox();m({x:e.x,y:e.y,width:e.width,height:e.height})}},[n]),n?(0,p.jsxs)("g",{transform:`translate(${e-d.width/2} ${t-d.height/2})`,className:g,visibility:d.width?"visible":"hidden",...c,children:[o&&(0,p.jsx)("rect",{width:d.width+2*a[0],x:-a[0],y:-a[1],height:d.height+2*a[1],className:"react-flow__edge-textbg",style:i,rx:l,ry:l}),(0,p.jsx)("text",{className:"react-flow__edge-text",y:d.height/2,dy:"0.3em",ref:y,style:r,children:n}),s]}):null}Ka.displayName="EdgeText";var Ya=(0,f.memo)(Ka);function Xa({path:e,labelX:t,labelY:n,label:r,labelStyle:o,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:s,interactionWidth:u=20,...c}){return(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)("path",{...c,d:e,fill:"none",className:h(["react-flow__edge-path",c.className])}),u?(0,p.jsx)("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:u,className:"react-flow__edge-interaction"}):null,r&&Lr(t)&&Lr(n)?(0,p.jsx)(Ya,{x:t,y:n,label:r,labelStyle:o,labelShowBg:i,labelBgStyle:a,labelBgPadding:l,labelBgBorderRadius:s}):null]})}function Za({pos:e,x1:t,y1:n,x2:r,y2:o}){return e===cr.Left||e===cr.Right?[.5*(t+r),n]:[t,.5*(n+o)]}function Ga({sourceX:e,sourceY:t,sourcePosition:n=cr.Bottom,targetX:r,targetY:o,targetPosition:i=cr.Top}){let[a,l]=Za({pos:n,x1:e,y1:t,x2:r,y2:o}),[s,u]=Za({pos:i,x1:r,y1:o,x2:e,y2:t}),[c,d,f,p]=no({sourceX:e,sourceY:t,targetX:r,targetY:o,sourceControlX:a,sourceControlY:l,targetControlX:s,targetControlY:u});return[`M${e},${t} C${a},${l} ${s},${u} ${r},${o}`,c,d,f,p]}function Qa(e){return(0,f.memo)(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,sourcePosition:a,targetPosition:l,label:s,labelStyle:u,labelShowBg:c,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:v})=>{let[b,w,x]=Ga({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:i,targetPosition:l});return(0,p.jsx)(Xa,{id:e.isInternal?void 0:t,path:b,labelX:w,labelY:x,label:s,labelStyle:u,labelShowBg:c,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:v})})}var Ja=Qa({isInternal:!1}),el=Qa({isInternal:!0});function tl(e){return(0,f.memo)(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,label:a,labelStyle:l,labelShowBg:s,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,sourcePosition:h=cr.Bottom,targetPosition:m=cr.Top,markerEnd:g,markerStart:y,pathOptions:v,interactionWidth:b})=>{let[w,x,k]=mo({sourceX:n,sourceY:r,sourcePosition:h,targetX:o,targetY:i,targetPosition:m,borderRadius:v?.borderRadius,offset:v?.offset,stepPosition:v?.stepPosition});return(0,p.jsx)(Xa,{id:e.isInternal?void 0:t,path:w,labelX:x,labelY:k,label:a,labelStyle:l,labelShowBg:s,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:g,markerStart:y,interactionWidth:b})})}Ja.displayName="SimpleBezierEdge",el.displayName="SimpleBezierEdgeInternal";var nl=tl({isInternal:!1}),rl=tl({isInternal:!0});function ol(e){return(0,f.memo)(({id:t,...n})=>{let r=e.isInternal?void 0:t;return(0,p.jsx)(nl,{...n,id:r,pathOptions:(0,f.useMemo)(()=>({borderRadius:0,offset:n.pathOptions?.offset}),[n.pathOptions?.offset])})})}nl.displayName="SmoothStepEdge",rl.displayName="SmoothStepEdgeInternal";var il=ol({isInternal:!1}),al=ol({isInternal:!0});function ll(e){return(0,f.memo)(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,label:a,labelStyle:l,labelShowBg:s,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:m,interactionWidth:g})=>{let[y,v,b]=co({sourceX:n,sourceY:r,targetX:o,targetY:i});return(0,p.jsx)(Xa,{id:e.isInternal?void 0:t,path:y,labelX:v,labelY:b,label:a,labelStyle:l,labelShowBg:s,labelBgStyle:u,labelBgPadding:c,labelBgBorderRadius:d,style:f,markerEnd:h,markerStart:m,interactionWidth:g})})}il.displayName="StepEdge",al.displayName="StepEdgeInternal";var sl=ll({isInternal:!1}),ul=ll({isInternal:!0});function cl(e){return(0,f.memo)(({id:t,sourceX:n,sourceY:r,targetX:o,targetY:i,sourcePosition:a=cr.Bottom,targetPosition:l=cr.Top,label:s,labelStyle:u,labelShowBg:c,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,pathOptions:v,interactionWidth:b})=>{let[w,x,k]=io({sourceX:n,sourceY:r,sourcePosition:a,targetX:o,targetY:i,targetPosition:l,curvature:v?.curvature});return(0,p.jsx)(Xa,{id:e.isInternal?void 0:t,path:w,labelX:x,labelY:k,label:s,labelStyle:u,labelShowBg:c,labelBgStyle:d,labelBgPadding:f,labelBgBorderRadius:h,style:m,markerEnd:g,markerStart:y,interactionWidth:b})})}sl.displayName="StraightEdge",ul.displayName="StraightEdgeInternal";var dl=cl({isInternal:!1}),fl=cl({isInternal:!0});dl.displayName="BezierEdge",fl.displayName="BezierEdgeInternal";var pl={default:fl,straight:ul,step:al,smoothstep:rl,simplebezier:el},hl={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},ml=(e,t,n)=>n===cr.Left?e-t:n===cr.Right?e+t:e,gl=(e,t,n)=>n===cr.Top?e-t:n===cr.Bottom?e+t:e,yl="react-flow__edgeupdater";function vl({position:e,centerX:t,centerY:n,radius:r=10,onMouseDown:o,onMouseEnter:i,onMouseOut:a,type:l}){return(0,p.jsx)("circle",{onMouseDown:o,onMouseEnter:i,onMouseOut:a,className:h([yl,`${yl}-${l}`]),cx:ml(t,r,e),cy:gl(n,r,e),r,stroke:"transparent",fill:"transparent"})}function bl({isReconnectable:e,reconnectRadius:t,edge:n,sourceX:r,sourceY:o,targetX:i,targetY:a,sourcePosition:l,targetPosition:s,onReconnect:u,onReconnectStart:c,onReconnectEnd:d,setReconnecting:f,setUpdateHover:h}){let m=vi(),g=(e,t)=>{if(0!==e.button)return;let{autoPanOnConnect:r,domNode:o,connectionMode:i,connectionRadius:a,lib:l,onConnectStart:s,cancelConnection:p,nodeLookup:h,rfId:g,panBy:y,updateConnection:v}=m.getState(),b="target"===t.type;Ho.onPointerDown(e.nativeEvent,{autoPanOnConnect:r,connectionMode:i,connectionRadius:a,domNode:o,handleId:t.id,nodeId:t.nodeId,nodeLookup:h,isTarget:b,edgeUpdaterType:t.type,lib:l,flowId:g,cancelConnection:p,panBy:y,isValidConnection:(...e)=>m.getState().isValidConnection?.(...e)??!0,onConnect:e=>u?.(n,e),onConnectStart:(r,o)=>{f(!0),c?.(e,n,t.type),s?.(r,o)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,r)=>{f(!1),d?.(e,n,t.type,r)},updateConnection:v,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},y=()=>h(!0),v=()=>h(!1);return(0,p.jsxs)(p.Fragment,{children:[(!0===e||"source"===e)&&(0,p.jsx)(vl,{position:l,centerX:r,centerY:o,radius:t,onMouseDown:e=>g(e,{nodeId:n.target,id:n.targetHandle??null,type:"target"}),onMouseEnter:y,onMouseOut:v,type:"source"}),(!0===e||"target"===e)&&(0,p.jsx)(vl,{position:s,centerX:i,centerY:a,radius:t,onMouseDown:e=>g(e,{nodeId:n.source,id:n.sourceHandle??null,type:"source"}),onMouseEnter:y,onMouseOut:v,type:"target"})]})}var wl=(0,f.memo)(function({id:e,edgesFocusable:t,edgesReconnectable:n,elementsSelectable:r,onClick:o,onDoubleClick:i,onContextMenu:a,onMouseEnter:l,onMouseMove:s,onMouseLeave:u,reconnectRadius:c,onReconnect:d,onReconnectStart:m,onReconnectEnd:g,rfId:y,edgeTypes:v,noPanClassName:b,onError:w,disableKeyboardA11y:x}){let k=yi(t=>t.edgeLookup.get(e)),S=yi(e=>e.defaultEdgeOptions);k=S?{...S,...k}:k;let E=k.type||"default",C=v?.[E]||pl[E];void 0===C&&(w?.("011",(e=>`Edge type "${e}" not found. Using fallback type "default".`)(E)),E="default",C=v?.default||pl.default);let M=!!(k.focusable||t&&void 0===k.focusable),P=void 0!==d&&(k.reconnectable||n&&void 0===k.reconnectable),O=!!(k.selectable||r&&void 0===k.selectable),T=(0,f.useRef)(null),[_,N]=(0,f.useState)(!1),[I,z]=(0,f.useState)(!1),R=vi(),{zIndex:L,sourceX:A,sourceY:D,targetX:F,targetY:j,sourcePosition:H,targetPosition:V}=yi((0,f.useCallback)(t=>{let n=t.nodeLookup.get(k.source),r=t.nodeLookup.get(k.target);if(!n||!r)return{zIndex:k.zIndex,...hl};let o=function(e){let{sourceNode:t,targetNode:n}=e;if(!go(t)||!go(n))return null;let r=t.internals.handleBounds||yo(t.handles),o=n.internals.handleBounds||yo(n.handles),i=bo(r?.source??[],e.sourceHandle),a=bo(e.connectionMode===nr.Strict?o?.target??[]:(o?.target??[]).concat(o?.source??[]),e.targetHandle);if(!i||!a)return e.onError?.("008",((e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${"source"===e?n:r}", edge id: ${t}.`)(i?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;let l=i?.position||cr.Bottom,s=a?.position||cr.Top,u=vo(t,i,l),c=vo(n,a,s);return{sourceX:u.x,sourceY:u.y,targetX:c.x,targetY:c.y,sourcePosition:l,targetPosition:s}}({id:e,sourceNode:n,targetNode:r,sourceHandle:k.sourceHandle||null,targetHandle:k.targetHandle||null,connectionMode:t.connectionMode,onError:w});return{zIndex:lo({selected:k.selected,zIndex:k.zIndex,sourceNode:n,targetNode:r,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode}),...o||hl}},[k.source,k.target,k.sourceHandle,k.targetHandle,k.selected,k.zIndex]),fi),$=(0,f.useMemo)(()=>k.markerStart?`url('#${wo(k.markerStart,y)}')`:void 0,[k.markerStart,y]),B=(0,f.useMemo)(()=>k.markerEnd?`url('#${wo(k.markerEnd,y)}')`:void 0,[k.markerEnd,y]);if(k.hidden||null===A||null===D||null===F||null===j)return null;let W=i?e=>{i(e,{...k})}:void 0,q=a?e=>{a(e,{...k})}:void 0,U=l?e=>{l(e,{...k})}:void 0,K=s?e=>{s(e,{...k})}:void 0,Y=u?e=>{u(e,{...k})}:void 0;return(0,p.jsx)("svg",{style:{zIndex:L},children:(0,p.jsxs)("g",{className:h(["react-flow__edge",`react-flow__edge-${E}`,k.className,b,{selected:k.selected,animated:k.animated,inactive:!O&&!o,updating:_,selectable:O}]),onClick:t=>{let{addSelectedEdges:n,unselectNodesAndEdges:r,multiSelectionActive:i}=R.getState();O&&(R.setState({nodesSelectionActive:!1}),k.selected&&i?(r({nodes:[],edges:[k]}),T.current?.blur()):n([e])),o&&o(t,k)},onDoubleClick:W,onContextMenu:q,onMouseEnter:U,onMouseMove:K,onMouseLeave:Y,onKeyDown:M?t=>{if(!x&&ar.includes(t.key)&&O){let{unselectNodesAndEdges:n,addSelectedEdges:r}=R.getState();"Escape"===t.key?(T.current?.blur(),n({edges:[k]})):r([e])}}:void 0,tabIndex:M?0:void 0,role:k.ariaRole??(M?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":null===k.ariaLabel?void 0:k.ariaLabel||`Edge from ${k.source} to ${k.target}`,"aria-describedby":M?`${ki}-${y}`:void 0,ref:T,...k.domAttributes,children:[!I&&(0,p.jsx)(C,{id:e,source:k.source,target:k.target,type:k.type,selected:k.selected,animated:k.animated,selectable:O,deletable:k.deletable??!0,label:k.label,labelStyle:k.labelStyle,labelShowBg:k.labelShowBg,labelBgStyle:k.labelBgStyle,labelBgPadding:k.labelBgPadding,labelBgBorderRadius:k.labelBgBorderRadius,sourceX:A,sourceY:D,targetX:F,targetY:j,sourcePosition:H,targetPosition:V,data:k.data,style:k.style,sourceHandleId:k.sourceHandle,targetHandleId:k.targetHandle,markerStart:$,markerEnd:B,pathOptions:"pathOptions"in k?k.pathOptions:void 0,interactionWidth:k.interactionWidth}),P&&(0,p.jsx)(bl,{edge:k,isReconnectable:P,reconnectRadius:c,onReconnect:d,onReconnectStart:m,onReconnectEnd:g,sourceX:A,sourceY:D,targetX:F,targetY:j,sourcePosition:H,targetPosition:V,setUpdateHover:N,setReconnecting:z})]})})}),xl=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function kl({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:n,edgeTypes:r,noPanClassName:o,onReconnect:i,onEdgeContextMenu:a,onEdgeMouseEnter:l,onEdgeMouseMove:s,onEdgeMouseLeave:u,onEdgeClick:c,reconnectRadius:d,onEdgeDoubleClick:f,onReconnectStart:h,onReconnectEnd:m,disableKeyboardA11y:g}){let{edgesFocusable:y,edgesReconnectable:v,elementsSelectable:b,onError:w}=yi(xl,fi),x=$a(t);return(0,p.jsxs)("div",{className:"react-flow__edges",children:[(0,p.jsx)(Ua,{defaultColor:e,rfId:n}),x.map(e=>(0,p.jsx)(wl,{id:e,edgesFocusable:y,edgesReconnectable:v,elementsSelectable:b,noPanClassName:o,onReconnect:i,onContextMenu:a,onMouseEnter:l,onMouseMove:s,onMouseLeave:u,onClick:c,reconnectRadius:d,onDoubleClick:f,onReconnectStart:h,onReconnectEnd:m,rfId:n,onError:w,edgeTypes:r,disableKeyboardA11y:g},e))]})}kl.displayName="EdgeRenderer";var Sl=(0,f.memo)(kl),El=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function Cl({children:e}){return(0,p.jsx)("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:yi(El)},children:e})}function Ml(e){let t=sa(),n=(0,f.useRef)(!1);(0,f.useEffect)(()=>{!n.current&&t.viewportInitialized&&e&&(setTimeout(()=>e(t),1),n.current=!0)},[e,t.viewportInitialized])}var Pl=e=>e.panZoom?.syncViewport;function Ol(e){let t=yi(Pl),n=vi();return(0,f.useEffect)(()=>{e&&(t?.(e),n.setState({transform:[e.x,e.y,e.zoom]}))},[e,t]),null}function Tl(e){return e.connection.inProgress?{...e.connection,to:Dr(e.connection.to,e.transform)}:{...e.connection}}function _l(e){return yi(function(e){return e?t=>e(Tl(t)):Tl}(e),fi)}var Nl=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function Il({containerStyle:e,style:t,type:n,component:r}){let{nodesConnectable:o,width:i,height:a,isValid:l,inProgress:s}=yi(Nl,fi);return i&&o&&s?(0,p.jsx)("svg",{style:e,width:i,height:a,className:"react-flow__connectionline react-flow__container",children:(0,p.jsx)("g",{className:h(["react-flow__connection",pr(l)]),children:(0,p.jsx)(zl,{style:t,type:n,CustomComponent:r,isValid:l})})}):null}var zl=({style:e,type:t=sr.Bezier,CustomComponent:n,isValid:r})=>{let{inProgress:o,from:i,fromNode:a,fromHandle:l,fromPosition:s,to:u,toNode:c,toHandle:d,toPosition:f,pointer:h}=_l();if(!o)return;if(n)return(0,p.jsx)(n,{connectionLineType:t,connectionLineStyle:e,fromNode:a,fromHandle:l,fromX:i.x,fromY:i.y,toX:u.x,toY:u.y,fromPosition:s,toPosition:f,connectionStatus:pr(r),toNode:c,toHandle:d,pointer:h});let m="",g={sourceX:i.x,sourceY:i.y,sourcePosition:s,targetX:u.x,targetY:u.y,targetPosition:f};switch(t){case sr.Bezier:[m]=io(g);break;case sr.SimpleBezier:[m]=Ga(g);break;case sr.Step:[m]=mo({...g,borderRadius:0});break;case sr.SmoothStep:[m]=mo(g);break;default:[m]=co(g)}return(0,p.jsx)("path",{d:m,fill:"none",className:"react-flow__connection-path",style:e})};zl.displayName="ConnectionLine";var Rl={};function Ll(e=Rl){(0,f.useRef)(e),vi(),(0,f.useEffect)(()=>{},[e])}function Al(){vi(),(0,f.useRef)(!1),(0,f.useEffect)(()=>{},[])}function Dl({nodeTypes:e,edgeTypes:t,onInit:n,onNodeClick:r,onEdgeClick:o,onNodeDoubleClick:i,onEdgeDoubleClick:a,onNodeMouseEnter:l,onNodeMouseMove:s,onNodeMouseLeave:u,onNodeContextMenu:c,onSelectionContextMenu:d,onSelectionStart:f,onSelectionEnd:h,connectionLineType:m,connectionLineStyle:g,connectionLineComponent:y,connectionLineContainerStyle:v,selectionKeyCode:b,selectionOnDrag:w,selectionMode:x,multiSelectionKeyCode:k,panActivationKeyCode:S,zoomActivationKeyCode:E,deleteKeyCode:C,onlyRenderVisibleElements:M,elementsSelectable:P,defaultViewport:O,translateExtent:T,minZoom:_,maxZoom:N,preventScrolling:I,defaultMarkerColor:z,zoomOnScroll:R,zoomOnPinch:L,panOnScroll:A,panOnScrollSpeed:D,panOnScrollMode:F,zoomOnDoubleClick:j,panOnDrag:H,autoPanOnSelection:V,onPaneClick:$,onPaneMouseEnter:B,onPaneMouseMove:W,onPaneMouseLeave:q,onPaneScroll:U,onPaneContextMenu:K,paneClickDistance:Y,nodeClickDistance:X,onEdgeContextMenu:Z,onEdgeMouseEnter:G,onEdgeMouseMove:Q,onEdgeMouseLeave:J,reconnectRadius:ee,onReconnect:te,onReconnectStart:ne,onReconnectEnd:re,noDragClassName:oe,noWheelClassName:ie,noPanClassName:ae,disableKeyboardA11y:le,nodeExtent:se,rfId:ue,viewport:ce,onViewportChange:de}){return Ll(e),Ll(t),Al(),Ml(n),Ol(ce),(0,p.jsx)(La,{onPaneClick:$,onPaneMouseEnter:B,onPaneMouseMove:W,onPaneMouseLeave:q,onPaneContextMenu:K,onPaneScroll:U,paneClickDistance:Y,deleteKeyCode:C,selectionKeyCode:b,selectionOnDrag:w,selectionMode:x,onSelectionStart:f,onSelectionEnd:h,multiSelectionKeyCode:k,panActivationKeyCode:S,zoomActivationKeyCode:E,elementsSelectable:P,zoomOnScroll:R,zoomOnPinch:L,zoomOnDoubleClick:j,panOnScroll:A,panOnScrollSpeed:D,panOnScrollMode:F,panOnDrag:H,autoPanOnSelection:V,defaultViewport:O,translateExtent:T,minZoom:_,maxZoom:N,onSelectionContextMenu:d,preventScrolling:I,noDragClassName:oe,noWheelClassName:ie,noPanClassName:ae,disableKeyboardA11y:le,onViewportChange:de,isControlledViewport:!!ce,children:(0,p.jsxs)(Cl,{children:[(0,p.jsx)(Sl,{edgeTypes:t,onEdgeClick:o,onEdgeDoubleClick:a,onReconnect:te,onReconnectStart:ne,onReconnectEnd:re,onlyRenderVisibleElements:M,onEdgeContextMenu:Z,onEdgeMouseEnter:G,onEdgeMouseMove:Q,onEdgeMouseLeave:J,reconnectRadius:ee,defaultMarkerColor:z,noPanClassName:ae,disableKeyboardA11y:le,rfId:ue}),(0,p.jsx)(Il,{style:g,type:m,component:y,containerStyle:v}),(0,p.jsx)("div",{className:"react-flow__edgelabel-renderer"}),(0,p.jsx)(Va,{nodeTypes:e,onNodeClick:r,onNodeDoubleClick:i,onNodeMouseEnter:l,onNodeMouseMove:s,onNodeMouseLeave:u,onNodeContextMenu:c,nodeClickDistance:X,onlyRenderVisibleElements:M,noPanClassName:ae,noDragClassName:oe,disableKeyboardA11y:le,nodeExtent:se,rfId:ue}),(0,p.jsx)("div",{className:"react-flow__viewport-portal"})]})})}Dl.displayName="GraphView";var Fl=(0,f.memo)(Dl),jl=(e,t)=>{},Hl=({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:s=.5,maxZoom:u=2,nodeOrigin:c,nodeExtent:d,zIndexMode:f="basic"}={})=>{let p=new Map,h=new Map,m=new Map,g=new Map,y=r??t??[],v=n??e??[],b=c??[0,0],w=d??ir;No(m,g,y);let{nodesInitialized:x}=Mo(v,p,h,{nodeOrigin:b,nodeExtent:w,zIndexMode:f}),k=[0,0,1];if(a&&o&&i){let{x:e,y:t,zoom:n}=Hr(br(p,{filter:e=>!(!e.width&&!e.initialWidth||!e.height&&!e.initialHeight)}),o,i,s,u,l?.padding??.1);k=[e,t,n]}return{rfId:"1",width:o??0,height:i??0,transform:k,nodes:v,nodesInitialized:x,nodeLookup:p,parentLookup:h,edges:y,edgeLookup:g,connectionLookup:m,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:void 0!==n,hasDefaultEdges:void 0!==r,panZoom:null,minZoom:s,maxZoom:u,translateExtent:ir,nodeExtent:w,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:nr.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:b,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:a??!1,fitViewOptions:l,fitViewResolver:null,connection:{...dr},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:jl,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:lr,zIndexMode:f,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}};function Vl({initialNodes:e,initialEdges:t,defaultNodes:n,defaultEdges:r,initialWidth:o,initialHeight:i,initialMinZoom:a,initialMaxZoom:l,initialFitViewOptions:s,fitView:u,nodeOrigin:c,nodeExtent:d,zIndexMode:h,children:m}){let[g]=(0,f.useState)(()=>(({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:s,maxZoom:u,nodeOrigin:c,nodeExtent:d,zIndexMode:f})=>((e,t)=>e?di(e,t):di)((p,h)=>{async function m(){let{nodeLookup:e,panZoom:t,fitViewOptions:n,fitViewResolver:r,width:o,height:i,minZoom:a,maxZoom:l}=h();t&&(await async function({nodes:e,width:t,height:n,panZoom:r,minZoom:o,maxZoom:i},a){if(0===e.size)return!0;let l=Hr(br(function(e,t){let n=new Map,r=t?.nodes?new Set(t.nodes.map(e=>e.id)):null;return e.forEach(e=>{e.measured.width&&e.measured.height&&(t?.includeHiddenNodes||!e.hidden)&&(!r||r.has(e.id))&&n.set(e.id,e)}),n}(e,a)),t,n,a?.minZoom??o,a?.maxZoom??i,a?.padding??.1);return await r.setViewport(l,{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),!0}({nodes:e,width:o,height:i,panZoom:t,minZoom:a,maxZoom:l},n),r?.resolve(!0),p({fitViewResolver:null}))}return{...Hl({nodes:e,edges:t,width:o,height:i,fitView:a,fitViewOptions:l,minZoom:s,maxZoom:u,nodeOrigin:c,nodeExtent:d,defaultNodes:n,defaultEdges:r,zIndexMode:f}),setNodes:e=>{let{nodeLookup:t,parentLookup:n,nodeOrigin:r,elevateNodesOnSelect:o,fitViewQueued:i,zIndexMode:a,nodesSelectionActive:l}=h(),{nodesInitialized:s,hasSelectedNodes:u}=Mo(e,t,n,{nodeOrigin:r,nodeExtent:d,elevateNodesOnSelect:o,checkEquality:!0,zIndexMode:a}),c=l&&u;i&&s?(m(),p({nodes:e,nodesInitialized:s,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:c})):p({nodes:e,nodesInitialized:s,nodesSelectionActive:c})},setEdges:e=>{let{connectionLookup:t,edgeLookup:n}=h();No(t,n,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=h();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=h();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:n,parentLookup:r,domNode:o,nodeOrigin:i,nodeExtent:a,debug:l,fitViewQueued:s,zIndexMode:u}=h(),{changes:c,updatedInternals:d}=function(e,t,n,r,o,i,a){let l=r?.querySelector(".xyflow__viewport"),s=!1;if(!l)return{changes:[],updatedInternals:s};let u=[],c=window.getComputedStyle(l),{m22:d}=new window.DOMMatrixReadOnly(c.transform),f=[];for(let r of e.values()){let e=t.get(r.id);if(!e)continue;if(e.hidden){t.set(e.id,{...e,internals:{...e.internals,handleBounds:void 0}}),s=!0;continue}let l=Xr(r.nodeElement),c=e.measured.width!==l.width||e.measured.height!==l.height;if(l.width&&l.height&&(c||!e.internals.handleBounds||r.force)){let p=r.nodeElement.getBoundingClientRect(),h=$r(e.extent)?e.extent:i,{positionAbsolute:m}=e.internals;e.parentId&&"parent"===e.extent?m=Er(m,l,t.get(e.parentId)):h&&(m=Sr(m,h,l));let g={...e,measured:l,internals:{...e.internals,positionAbsolute:m,handleBounds:{source:to("source",r.nodeElement,p,d,e.id),target:to("target",r.nodeElement,p,d,e.id)}}};t.set(e.id,g),e.parentId&&Po(g,t,n,{nodeOrigin:o,zIndexMode:a}),s=!0,c&&(u.push({id:e.id,type:"dimensions",dimensions:l}),e.expandParent&&e.parentId&&f.push({id:e.id,parentId:e.parentId,rect:_r(g,o)}))}}if(f.length>0){let e=To(f,t,n,o);u.push(...e)}return{changes:u,updatedInternals:s}}(e,n,r,o,i,a,u);d&&(function(e,t,n){let r=So(xo,n);for(let n of e.values())if(n.parentId)Po(n,e,t,r);else{let e=Sr(vr(n,r.nodeOrigin),$r(n.extent)?n.extent:r.nodeExtent,Br(n));n.internals.positionAbsolute=e}}(n,r,{nodeOrigin:i,nodeExtent:a,zIndexMode:u}),s?(m(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),c?.length>0&&(l&&console.log("React Flow: trigger node changes",c),t?.(c)))},updateNodePositions:(e,t=!1)=>{let n=[],r=[],{nodeLookup:o,triggerNodeChanges:i,connection:a,updateConnection:l,onNodesChangeMiddlewareMap:s}=h();for(let[i,s]of e){let e=o.get(i),u=!!(e?.expandParent&&e?.parentId&&s?.position),c={id:i,type:"position",position:u?{x:Math.max(0,s.position.x),y:Math.max(0,s.position.y)}:s.position,dragging:t};if(e&&a.inProgress&&a.fromNode.id===e.id){let t=vo(e,a.fromHandle,cr.Left,!0);l({...a,from:t})}u&&e.parentId&&n.push({id:i,parentId:e.parentId,rect:{...s.internals.positionAbsolute,width:s.measured.width??0,height:s.measured.height??0}}),r.push(c)}if(n.length>0){let{parentLookup:e,nodeOrigin:t}=h(),i=To(n,o,e,t);r.push(...i)}for(let e of s.values())r=e(r);i(r)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:n,nodes:r,hasDefaultNodes:o,debug:i}=h();e?.length&&(o&&n(Yi(e,r)),i&&console.log("React Flow: trigger node changes",e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:n,edges:r,hasDefaultEdges:o,debug:i}=h();e?.length&&(o&&n(Xi(e,r)),i&&console.log("React Flow: trigger edge changes",e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:o,triggerEdgeChanges:i}=h();t?o(e.map(e=>Zi(e,!0))):(o(Gi(r,new Set([...e]),!0)),i(Gi(n)))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:n,nodeLookup:r,triggerNodeChanges:o,triggerEdgeChanges:i}=h();t?i(e.map(e=>Zi(e,!0))):(i(Gi(n,new Set([...e]))),o(Gi(r,new Set,!0)))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:n,nodes:r,nodeLookup:o,triggerNodeChanges:i,triggerEdgeChanges:a}=h(),l=e||r,s=t||n,u=[];for(let e of l){if(!e.selected)continue;let t=o.get(e.id);t&&(t.selected=!1),u.push(Zi(e.id,!1))}let c=[];for(let e of s)e.selected&&c.push(Zi(e.id,!1));i(u),a(c)},setMinZoom:e=>{let{panZoom:t,maxZoom:n}=h();t?.setScaleExtent([e,n]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:n}=h();t?.setScaleExtent([n,e]),p({maxZoom:e})},setTranslateExtent:e=>{h().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:n,triggerEdgeChanges:r,elementsSelectable:o}=h();if(!o)return;let i=t.reduce((e,t)=>t.selected?[...e,Zi(t.id,!1)]:e,[]),a=e.reduce((e,t)=>t.selected?[...e,Zi(t.id,!1)]:e,[]);n(i),r(a)},setNodeExtent:e=>{let{nodes:t,nodeLookup:n,parentLookup:r,nodeOrigin:o,elevateNodesOnSelect:i,nodeExtent:a,zIndexMode:l}=h();e[0][0]===a[0][0]&&e[0][1]===a[0][1]&&e[1][0]===a[1][0]&&e[1][1]===a[1][1]||(Mo(t,n,r,{nodeOrigin:o,nodeExtent:e,elevateNodesOnSelect:i,checkEquality:!1,zIndexMode:l}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:n,height:r,panZoom:o,translateExtent:i}=h();return async function({delta:e,panZoom:t,transform:n,translateExtent:r,width:o,height:i}){if(!t||!e.x&&!e.y)return!1;let a=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[o,i]],r);return!!a&&(a.x!==n[0]||a.y!==n[1]||a.k!==n[2])}({delta:e,panZoom:o,transform:t,translateExtent:i,width:n,height:r})},setCenter:async(e,t,n)=>{let{width:r,height:o,maxZoom:i,panZoom:a}=h();if(!a)return!1;let l=void 0===n?.zoom?i:n.zoom;return await a.setViewport({x:r/2-e*l,y:o/2-t*l,zoom:l},{duration:n?.duration,ease:n?.ease,interpolate:n?.interpolate}),!0},cancelConnection:()=>{p({connection:{...dr}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...Hl()})}},Object.is))({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,width:o,height:i,fitView:u,minZoom:a,maxZoom:l,fitViewOptions:s,nodeOrigin:c,nodeExtent:d,zIndexMode:h}));return(0,p.jsx)(mi,{value:g,children:(0,p.jsx)(aa,{children:m})})}function $l({children:e,nodes:t,edges:n,defaultNodes:r,defaultEdges:o,width:i,height:a,fitView:l,fitViewOptions:s,minZoom:u,maxZoom:c,nodeOrigin:d,nodeExtent:h,zIndexMode:m}){return(0,f.useContext)(hi)?(0,p.jsx)(p.Fragment,{children:e}):(0,p.jsx)(Vl,{initialNodes:t,initialEdges:n,defaultNodes:r,defaultEdges:o,initialWidth:i,initialHeight:a,fitView:l,initialFitViewOptions:s,initialMinZoom:u,initialMaxZoom:c,nodeOrigin:d,nodeExtent:h,zIndexMode:m,children:e})}var Bl={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0},Wl=na(function({nodes:e,edges:t,defaultNodes:n,defaultEdges:r,className:o,nodeTypes:i,edgeTypes:a,onNodeClick:l,onEdgeClick:s,onInit:u,onMove:c,onMoveStart:d,onMoveEnd:m,onConnect:g,onConnectStart:y,onConnectEnd:v,onClickConnectStart:b,onClickConnectEnd:w,onNodeMouseEnter:x,onNodeMouseMove:k,onNodeMouseLeave:S,onNodeContextMenu:E,onNodeDoubleClick:C,onNodeDragStart:M,onNodeDrag:P,onNodeDragStop:O,onNodesDelete:T,onEdgesDelete:_,onDelete:N,onSelectionChange:I,onSelectionDragStart:z,onSelectionDrag:R,onSelectionDragStop:L,onSelectionContextMenu:A,onSelectionStart:D,onSelectionEnd:F,onBeforeDelete:j,connectionMode:H,connectionLineType:V=sr.Bezier,connectionLineStyle:$,connectionLineComponent:B,connectionLineContainerStyle:W,deleteKeyCode:q="Backspace",selectionKeyCode:U="Shift",selectionOnDrag:K=!1,selectionMode:Y=or.Full,panActivationKeyCode:X="Space",multiSelectionKeyCode:Z=(Vr()?"Meta":"Control"),zoomActivationKeyCode:G=(Vr()?"Meta":"Control"),snapToGrid:Q,snapGrid:J,onlyRenderVisibleElements:ee=!1,selectNodesOnDrag:te,nodesDraggable:ne,autoPanOnNodeFocus:re,nodesConnectable:oe,nodesFocusable:ie,nodeOrigin:ae=Li,edgesFocusable:le,edgesReconnectable:se,elementsSelectable:ue=!0,defaultViewport:ce=Ai,minZoom:de=.5,maxZoom:fe=2,translateExtent:pe=ir,preventScrolling:he=!0,nodeExtent:me,defaultMarkerColor:ge="#b1b1b7",zoomOnScroll:ye=!0,zoomOnPinch:ve=!0,panOnScroll:be=!1,panOnScrollSpeed:we=.5,panOnScrollMode:xe=rr.Free,zoomOnDoubleClick:ke=!0,panOnDrag:Se=!0,onPaneClick:Ee,onPaneMouseEnter:Ce,onPaneMouseMove:Me,onPaneMouseLeave:Pe,onPaneScroll:Oe,onPaneContextMenu:Te,paneClickDistance:_e=1,nodeClickDistance:Ne=0,children:Ie,onReconnect:ze,onReconnectStart:Re,onReconnectEnd:Le,onEdgeContextMenu:Ae,onEdgeDoubleClick:De,onEdgeMouseEnter:Fe,onEdgeMouseMove:je,onEdgeMouseLeave:He,reconnectRadius:Ve=10,onNodesChange:$e,onEdgesChange:Be,noDragClassName:We="nodrag",noWheelClassName:qe="nowheel",noPanClassName:Ue="nopan",fitView:Ke,fitViewOptions:Ye,connectOnClick:Xe,attributionPosition:Ze,proOptions:Ge,defaultEdgeOptions:Qe,elevateNodesOnSelect:Je=!0,elevateEdgesOnSelect:et=!1,disableKeyboardA11y:tt=!1,autoPanOnConnect:nt,autoPanOnNodeDrag:rt,autoPanOnSelection:ot=!0,autoPanSpeed:it,connectionRadius:at,isValidConnection:lt,onError:st,style:ut,id:ct,nodeDragThreshold:dt,connectionDragThreshold:ft,viewport:pt,onViewportChange:ht,width:mt,height:gt,colorMode:yt="light",debug:vt,onScroll:bt,ariaLabelConfig:wt,zIndexMode:xt="basic",...kt},St){let Et=ct||"1",Ct=function(e){let[t,n]=(0,f.useState)("system"===e?null:e);return(0,f.useEffect)(()=>{if("system"!==e)return void n(e);let t=Vi(),r=()=>n(t?.matches?"dark":"light");return r(),t?.addEventListener("change",r),()=>{t?.removeEventListener("change",r)}},[e]),null===t?Vi()?.matches?"dark":"light":t}(yt),Mt=(0,f.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),bt?.(e)},[bt]);return(0,p.jsx)("div",{"data-testid":"rf__wrapper",...kt,onScroll:Mt,style:{...ut,...Bl},ref:St,className:h(["react-flow",o,Ct]),id:ct,role:"application",children:(0,p.jsxs)($l,{nodes:e,edges:t,width:mt,height:gt,fitView:Ke,fitViewOptions:Ye,minZoom:de,maxZoom:fe,nodeOrigin:ae,nodeExtent:me,zIndexMode:xt,children:[(0,p.jsx)(Hi,{nodes:e,edges:t,defaultNodes:n,defaultEdges:r,onConnect:g,onConnectStart:y,onConnectEnd:v,onClickConnectStart:b,onClickConnectEnd:w,nodesDraggable:ne,autoPanOnNodeFocus:re,nodesConnectable:oe,nodesFocusable:ie,edgesFocusable:le,edgesReconnectable:se,elementsSelectable:ue,elevateNodesOnSelect:Je,elevateEdgesOnSelect:et,minZoom:de,maxZoom:fe,nodeExtent:me,onNodesChange:$e,onEdgesChange:Be,snapToGrid:Q,snapGrid:J,connectionMode:H,translateExtent:pe,connectOnClick:Xe,defaultEdgeOptions:Qe,fitView:Ke,fitViewOptions:Ye,onNodesDelete:T,onEdgesDelete:_,onDelete:N,onNodeDragStart:M,onNodeDrag:P,onNodeDragStop:O,onSelectionDrag:R,onSelectionDragStart:z,onSelectionDragStop:L,onMove:c,onMoveStart:d,onMoveEnd:m,noPanClassName:Ue,nodeOrigin:ae,rfId:Et,autoPanOnConnect:nt,autoPanOnNodeDrag:rt,autoPanSpeed:it,onError:st,connectionRadius:at,isValidConnection:lt,selectNodesOnDrag:te,nodeDragThreshold:dt,connectionDragThreshold:ft,onBeforeDelete:j,debug:vt,ariaLabelConfig:wt,zIndexMode:xt}),(0,p.jsx)(Fl,{onInit:u,onNodeClick:l,onEdgeClick:s,onNodeMouseEnter:x,onNodeMouseMove:k,onNodeMouseLeave:S,onNodeContextMenu:E,onNodeDoubleClick:C,nodeTypes:i,edgeTypes:a,connectionLineType:V,connectionLineStyle:$,connectionLineComponent:B,connectionLineContainerStyle:W,selectionKeyCode:U,selectionOnDrag:K,selectionMode:Y,deleteKeyCode:q,multiSelectionKeyCode:Z,panActivationKeyCode:X,zoomActivationKeyCode:G,onlyRenderVisibleElements:ee,defaultViewport:ce,translateExtent:pe,minZoom:de,maxZoom:fe,preventScrolling:he,zoomOnScroll:ye,zoomOnPinch:ve,zoomOnDoubleClick:ke,panOnScroll:be,panOnScrollSpeed:we,panOnScrollMode:xe,panOnDrag:Se,autoPanOnSelection:ot,onPaneClick:Ee,onPaneMouseEnter:Ce,onPaneMouseMove:Me,onPaneMouseLeave:Pe,onPaneScroll:Oe,onPaneContextMenu:Te,paneClickDistance:_e,nodeClickDistance:Ne,onSelectionContextMenu:A,onSelectionStart:D,onSelectionEnd:F,onReconnect:ze,onReconnectStart:Re,onReconnectEnd:Le,onEdgeContextMenu:Ae,onEdgeDoubleClick:De,onEdgeMouseEnter:Fe,onEdgeMouseMove:je,onEdgeMouseLeave:He,reconnectRadius:Ve,defaultMarkerColor:ge,noDragClassName:We,noWheelClassName:qe,noPanClassName:Ue,rfId:Et,disableKeyboardA11y:tt,nodeExtent:me,viewport:pt,onViewportChange:ht}),(0,p.jsx)(Ri,{onSelectionChange:I}),Ie,(0,p.jsx)(Oi,{proOptions:Ge,position:Ze}),(0,p.jsx)(Mi,{rfId:Et,disableKeyboardA11y:tt})]})})});function ql(){let e=vi();return(0,f.useCallback)(t=>{let{domNode:n,updateNodeInternals:r}=e.getState(),o=Array.isArray(t)?t:[t],i=new Map;o.forEach(e=>{let t=n?.querySelector(`.react-flow__node[data-id="${e}"]`);t&&i.set(e,{id:e,nodeElement:t,force:!0})}),requestAnimationFrame(()=>r(i,{triggerFitView:!1}))},[])}var Ul,Kl=e=>({x:e.transform[0],y:e.transform[1],zoom:e.transform[2]});function Yl(){return yi(Kl,fi)}function Xl({dimensions:e,lineWidth:t,variant:n,className:r}){return(0,p.jsx)("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:h(["react-flow__background-pattern",n,r])})}function Zl({radius:e,className:t}){return(0,p.jsx)("circle",{cx:e,cy:e,r:e,className:h(["react-flow__background-pattern","dots",t])})}!function(e){e.Lines="lines",e.Dots="dots",e.Cross="cross"}(Ul||={});var Gl={[Ul.Dots]:1,[Ul.Lines]:1,[Ul.Cross]:6},Ql=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function Jl({id:e,variant:t=Ul.Dots,gap:n=20,size:r,lineWidth:o=1,offset:i=0,color:a,bgColor:l,style:s,className:u,patternClassName:c}){let d=(0,f.useRef)(null),{transform:m,patternId:g}=yi(Ql,fi),y=r||Gl[t],v=t===Ul.Dots,b=t===Ul.Cross,w=Array.isArray(n)?n:[n,n],x=[w[0]*m[2]||1,w[1]*m[2]||1],k=y*m[2],S=Array.isArray(i)?i:[i,i],E=b?[k,k]:x,C=[S[0]*m[2]||1+E[0]/2,S[1]*m[2]||1+E[1]/2],M=`${g}${e||""}`;return(0,p.jsxs)("svg",{className:h(["react-flow__background",u]),style:{...s,...fa,"--xy-background-color-props":l,"--xy-background-pattern-color-props":a},ref:d,"data-testid":"rf__background",children:[(0,p.jsx)("pattern",{id:M,x:m[0]%x[0],y:m[1]%x[1],width:x[0],height:x[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${C[0]},-${C[1]})`,children:v?(0,p.jsx)(Zl,{radius:k/2,className:c}):(0,p.jsx)(Xl,{dimensions:E,lineWidth:o,variant:t,className:c})}),(0,p.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${M})`})]})}Jl.displayName="Background";var es=(0,f.memo)(Jl);function ts(){return(0,p.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:(0,p.jsx)("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function ns(){return(0,p.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:(0,p.jsx)("path",{d:"M0 0h32v4.2H0z"})})}function rs(){return(0,p.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:(0,p.jsx)("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function os(){return(0,p.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,p.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function is(){return(0,p.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,p.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function as({children:e,className:t,...n}){return(0,p.jsx)("button",{type:"button",className:h(["react-flow__controls-button",t]),...n,children:e})}var ls=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function ss({style:e,showZoom:t=!0,showFitView:n=!0,showInteractive:r=!0,fitViewOptions:o,onZoomIn:i,onZoomOut:a,onFitView:l,onInteractiveChange:s,className:u,children:c,position:d="bottom-left",orientation:f="vertical","aria-label":m}){let g=vi(),{isInteractive:y,minZoomReached:v,maxZoomReached:b,ariaLabelConfig:w}=yi(ls,fi),{zoomIn:x,zoomOut:k,fitView:S}=sa();return(0,p.jsxs)(Pi,{className:h(["react-flow__controls","horizontal"===f?"horizontal":"vertical",u]),position:d,style:e,"data-testid":"rf__controls","aria-label":m??w["controls.ariaLabel"],children:[t&&(0,p.jsxs)(p.Fragment,{children:[(0,p.jsx)(as,{onClick:()=>{x(),i?.()},className:"react-flow__controls-zoomin",title:w["controls.zoomIn.ariaLabel"],"aria-label":w["controls.zoomIn.ariaLabel"],disabled:b,children:(0,p.jsx)(ts,{})}),(0,p.jsx)(as,{onClick:()=>{k(),a?.()},className:"react-flow__controls-zoomout",title:w["controls.zoomOut.ariaLabel"],"aria-label":w["controls.zoomOut.ariaLabel"],disabled:v,children:(0,p.jsx)(ns,{})})]}),n&&(0,p.jsx)(as,{className:"react-flow__controls-fitview",onClick:()=>{S(o),l?.()},title:w["controls.fitView.ariaLabel"],"aria-label":w["controls.fitView.ariaLabel"],children:(0,p.jsx)(rs,{})}),r&&(0,p.jsx)(as,{className:"react-flow__controls-interactive",onClick:()=>{g.setState({nodesDraggable:!y,nodesConnectable:!y,elementsSelectable:!y}),s?.(!y)},title:w["controls.interactive.ariaLabel"],"aria-label":w["controls.interactive.ariaLabel"],children:y?(0,p.jsx)(is,{}):(0,p.jsx)(os,{})}),c]})}ss.displayName="Controls",(0,f.memo)(ss);var us=(0,f.memo)(function({id:e,x:t,y:n,width:r,height:o,style:i,color:a,strokeColor:l,strokeWidth:s,className:u,borderRadius:c,shapeRendering:d,selected:f,onClick:m}){let{background:g,backgroundColor:y}=i||{},v=a||g||y;return(0,p.jsx)("rect",{className:h(["react-flow__minimap-node",{selected:f},u]),x:t,y:n,rx:c,ry:c,width:r,height:o,style:{fill:v,stroke:l,strokeWidth:s},shapeRendering:d,onClick:m?t=>m(t,e):void 0})}),cs=e=>e.nodes.map(e=>e.id),ds=e=>e instanceof Function?e:()=>e,fs=(0,f.memo)(function({id:e,nodeColorFunc:t,nodeStrokeColorFunc:n,nodeClassNameFunc:r,nodeBorderRadius:o,nodeStrokeWidth:i,shapeRendering:a,NodeComponent:l,onClick:s}){let{node:u,x:c,y:d,width:f,height:h}=yi(t=>{let n=t.nodeLookup.get(e);if(!n)return{node:void 0,x:0,y:0,width:0,height:0};let r=n.internals.userNode,{x:o,y:i}=n.internals.positionAbsolute,{width:a,height:l}=Br(r);return{node:r,x:o,y:i,width:a,height:l}},fi);return u&&!u.hidden&&Wr(u)?(0,p.jsx)(l,{x:c,y:d,width:f,height:h,style:u.style,selected:!!u.selected,className:r(u),color:t(u),borderRadius:o,strokeColor:n(u),strokeWidth:i,shapeRendering:a,onClick:s,id:u.id}):null}),ps=(0,f.memo)(function({nodeStrokeColor:e,nodeColor:t,nodeClassName:n="",nodeBorderRadius:r=5,nodeStrokeWidth:o,nodeComponent:i=us,onClick:a}){let l=yi(cs,fi),s=ds(t),u=ds(e),c=ds(n),d=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return(0,p.jsx)(p.Fragment,{children:l.map(e=>(0,p.jsx)(fs,{id:e,nodeColorFunc:s,nodeStrokeColorFunc:u,nodeClassNameFunc:c,nodeBorderRadius:r,nodeStrokeWidth:o,NodeComponent:i,onClick:a,shapeRendering:d},e))})}),hs=e=>!e.hidden,ms=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};return{viewBB:t,boundingRect:e.nodeLookup.size>0?Ir(br(e.nodeLookup,{filter:hs}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}};function gs({style:e,className:t,nodeStrokeColor:n,nodeColor:r,nodeClassName:o="",nodeBorderRadius:i=5,nodeStrokeWidth:a,nodeComponent:l,bgColor:s,maskColor:u,maskStrokeColor:c,maskStrokeWidth:d,position:m="bottom-right",onClick:g,onNodeClick:y,pannable:v=!1,zoomable:b=!1,ariaLabel:w,inversePan:x,zoomStep:k=1,offsetScale:S=5}){let E=vi(),C=(0,f.useRef)(null),{boundingRect:M,viewBB:P,rfId:O,panZoom:T,translateExtent:_,flowWidth:N,flowHeight:I,ariaLabelConfig:z}=yi(ms,fi),R=e?.width??200,L=e?.height??150,A=M.width/R,D=M.height/L,F=Math.max(A,D),j=F*R,H=F*L,V=S*F,$=M.x-(j-M.width)/2-V,B=M.y-(H-M.height)/2-V,W=j+2*V,q=H+2*V,U=`react-flow__minimap-desc-${O}`,K=(0,f.useRef)(0),Y=(0,f.useRef)();K.current=F,(0,f.useEffect)(()=>{if(C.current&&T)return Y.current=function({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){let o=_e(e);return{update:function({translateExtent:e,width:i,height:a,zoomStep:l=1,pannable:s=!0,zoomable:u=!0,inversePan:c=!1}){let d=[0,0],f=tr().on("start",e=>{("mousedown"===e.sourceEvent.type||"touchstart"===e.sourceEvent.type)&&(d=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on("zoom",s?o=>{let l=n();if("mousemove"!==o.sourceEvent.type&&"touchmove"!==o.sourceEvent.type||!t)return;let s=[o.sourceEvent.clientX??o.sourceEvent.touches[0].clientX,o.sourceEvent.clientY??o.sourceEvent.touches[0].clientY],u=[s[0]-d[0],s[1]-d[1]];d=s;let f=r()*Math.max(l[2],Math.log(l[2]))*(c?-1:1),p={x:l[0]-u[0]*f,y:l[1]-u[1]*f},h=[[0,0],[i,a]];t.setViewportConstrained({x:p.x,y:p.y,zoom:l[2]},h,e)}:null).on("zoom.wheel",u?e=>{if("wheel"!==e.sourceEvent.type||!t)return;let r=n(),o=e.sourceEvent.ctrlKey&&Vr()?10:1,i=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*l,a=r[2]*2**(i*o);t.scaleTo(a)}:null);o.call(f,{})},destroy:function(){o.on("zoom",null)},pointer:Ne}}({domNode:C.current,panZoom:T,getTransform:()=>E.getState().transform,getViewScale:()=>K.current}),()=>{Y.current?.destroy()}},[T]),(0,f.useEffect)(()=>{Y.current?.update({translateExtent:_,width:N,height:I,inversePan:x,pannable:v,zoomStep:k,zoomable:b})},[v,b,x,k,_,N,I]);let X=g?e=>{let[t,n]=Y.current?.pointer(e)||[0,0];g(e,{x:t,y:n})}:void 0,Z=y?(0,f.useCallback)((e,t)=>{let n=E.getState().nodeLookup.get(t).internals.userNode;y(e,n)},[]):void 0,G=w??z["minimap.ariaLabel"];return(0,p.jsx)(Pi,{position:m,style:{...e,"--xy-minimap-background-color-props":"string"==typeof s?s:void 0,"--xy-minimap-mask-background-color-props":"string"==typeof u?u:void 0,"--xy-minimap-mask-stroke-color-props":"string"==typeof c?c:void 0,"--xy-minimap-mask-stroke-width-props":"number"==typeof d?d*F:void 0,"--xy-minimap-node-background-color-props":"string"==typeof r?r:void 0,"--xy-minimap-node-stroke-color-props":"string"==typeof n?n:void 0,"--xy-minimap-node-stroke-width-props":"number"==typeof a?a:void 0},className:h(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:(0,p.jsxs)("svg",{width:R,height:L,viewBox:`${$} ${B} ${W} ${q}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":U,ref:C,onClick:X,children:[G&&(0,p.jsx)("title",{id:U,children:G}),(0,p.jsx)(ps,{onClick:Z,nodeColor:r,nodeStrokeColor:n,nodeBorderRadius:i,nodeClassName:o,nodeStrokeWidth:a,nodeComponent:l}),(0,p.jsx)("path",{className:"react-flow__minimap-mask",d:`M${$-V},${B-V}h${W+2*V}v${q+2*V}h${-W-2*V}z\n M${P.x},${P.y}h${P.width}v${P.height}h${-P.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}gs.displayName="MiniMap",(0,f.memo)(gs);var ys={[jo.Line]:"right",[jo.Handle]:"bottom-right"},vs=(0,f.memo)(function({nodeId:e,position:t,variant:n=jo.Handle,className:r,style:o,children:i,color:a,minWidth:l=10,minHeight:s=10,maxWidth:u=Number.MAX_VALUE,maxHeight:c=Number.MAX_VALUE,keepAspectRatio:d=!1,resizeDirection:m,autoScale:g=!0,shouldResize:y,onResizeStart:v,onResize:b,onResizeEnd:w}){let x=Ca(),k="string"==typeof e?e:x,S=vi(),E=(0,f.useRef)(null),C=n===jo.Handle,M=yi((0,f.useCallback)((e=>t=>e?`${Math.max(1/t.transform[2],1)}`:void 0)(C&&g),[C,g]),fi),P=(0,f.useRef)(null),O=t??ys[n];return(0,f.useEffect)(()=>{if(E.current&&k)return P.current||=function({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:o}){let i=_e(e),a={controlDirection:Yo("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};return{update:function({controlPosition:e,boundaries:l,keepAspectRatio:s,resizeDirection:u,onResizeStart:c,onResize:d,onResizeEnd:f,shouldResize:p}){let h={...Jo},m={...ei};a={boundaries:l,resizeDirection:u,keepAspectRatio:s,controlDirection:Yo(e)};let g,y,v,b,w=null,x=[],k=!1,S=We().on("start",e=>{let{nodeLookup:r,transform:o,snapGrid:i,snapToGrid:a,nodeOrigin:l,paneDomNode:s}=n();if(g=r.get(t),!g)return;w=s?.getBoundingClientRect()??null;let{xSnapped:u,ySnapped:d}=Yr(e.sourceEvent,{transform:o,snapGrid:i,snapToGrid:a,containerBounds:w});h={width:g.measured.width??0,height:g.measured.height??0,x:g.position.x??0,y:g.position.y??0},m={...h,pointerX:u,pointerY:d,aspectRatio:h.width/h.height},y=void 0,v=$r(g.extent)?g.extent:void 0,g.parentId&&("parent"===g.extent||g.expandParent)&&(y=r.get(g.parentId)),y&&"parent"===g.extent&&(v=[[0,0],[y.measured.width,y.measured.height]]),x=[],b=void 0;for(let[e,n]of r)if(n.parentId===t&&(x.push({id:e,position:{...n.position},extent:n.extent}),"parent"===n.extent||n.expandParent)){let e=ti(n,g,n.origin??l);b=b?[[Math.min(e[0][0],b[0][0]),Math.min(e[0][1],b[0][1])],[Math.max(e[1][0],b[1][0]),Math.max(e[1][1],b[1][1])]]:e}c?.(e,{...h})}).on("drag",e=>{let{transform:t,snapGrid:o,snapToGrid:i,nodeOrigin:l}=n(),s=Yr(e.sourceEvent,{transform:t,snapGrid:o,snapToGrid:i,containerBounds:w}),u=[];if(!g)return;let{x:c,y:f,width:S,height:E}=h,C={},M=g.origin??l,{width:P,height:O,x:T,y:_}=function(e,t,n,r,o,i,a,l){let{affectsX:s,affectsY:u}=t,{isHorizontal:c,isVertical:d}=t,f=c&&d,{xSnapped:p,ySnapped:h}=n,{minWidth:m,maxWidth:g,minHeight:y,maxHeight:v}=r,{x:b,y:w,width:x,height:k,aspectRatio:S}=e,E=Math.floor(c?p-e.pointerX:0),C=Math.floor(d?h-e.pointerY:0),M=x+(s?-E:E),P=k+(u?-C:C),O=-i[0]*x,T=-i[1]*k,_=Go(M,m,g),N=Go(P,y,v);if(a){let e=0,t=0;s&&E<0?e=Xo(b+E+O,a[0][0]):!s&&E>0&&(e=Zo(b+M+O,a[1][0])),u&&C<0?t=Xo(w+C+T,a[0][1]):!u&&C>0&&(t=Zo(w+P+T,a[1][1])),_=Math.max(_,e),N=Math.max(N,t)}if(l){let e=0,t=0;s&&E>0?e=Zo(b+E,l[0][0]):!s&&E<0&&(e=Xo(b+M,l[1][0])),u&&C>0?t=Zo(w+C,l[0][1]):!u&&C<0&&(t=Xo(w+P,l[1][1])),_=Math.max(_,e),N=Math.max(N,t)}if(o){if(c){let e=Go(M/S,y,v)*S;if(_=Math.max(_,e),a){let e=0;e=!s&&!u||s&&!u&&f?Zo(w+T+M/S,a[1][1])*S:Xo(w+T+(s?E:-E)/S,a[0][1])*S,_=Math.max(_,e)}if(l){let e=0;e=!s&&!u||s&&!u&&f?Xo(w+M/S,l[1][1])*S:Zo(w+(s?E:-E)/S,l[0][1])*S,_=Math.max(_,e)}}if(d){let e=Go(P*S,m,g)/S;if(N=Math.max(N,e),a){let e=0;e=!s&&!u||u&&!s&&f?Zo(b+P*S+O,a[1][0])/S:Xo(b+(u?C:-C)*S+O,a[0][0])/S,N=Math.max(N,e)}if(l){let e=0;e=!s&&!u||u&&!s&&f?Xo(b+P*S,l[1][0])/S:Zo(b+(u?C:-C)*S,l[0][0])/S,N=Math.max(N,e)}}}C+=C<0?N:-N,E+=E<0?_:-_,o&&(f?M>P*S?C=(Qo(s,u)?-E:E)/S:E=(Qo(s,u)?-C:C)*S:c?(C=E/S,u=s):(E=C*S,s=u));let I=s?b+E:b,z=u?w+C:w;return{width:x+(s?-E:E),height:k+(u?-C:C),x:i[0]*E*(s?-1:1)+I,y:i[1]*C*(u?-1:1)+z}}(m,a.controlDirection,s,a.boundaries,a.keepAspectRatio,M,v,b),N=P!==S,I=O!==E,z=T!==c&&N,R=_!==f&&I;if(!(z||R||N||I))return;if((z||R||1===M[0]||1===M[1])&&(C.x=z?T:h.x,C.y=R?_:h.y,h.x=C.x,h.y=C.y,x.length>0)){let e=T-c,t=_-f;for(let n of x)n.position={x:n.position.x-e+M[0]*(P-S),y:n.position.y-t+M[1]*(O-E)},u.push(n)}if((N||I)&&(C.width=!N||a.resizeDirection&&"horizontal"!==a.resizeDirection?h.width:P,C.height=!I||a.resizeDirection&&"vertical"!==a.resizeDirection?h.height:O,h.width=C.width,h.height=C.height),y&&g.expandParent){let e=M[0]*(C.width??0);C.x&&C.x0?1:a<0?-1:0,l>0?1:l<0?-1:0];return a&&o&&(s[0]*=-1),l&&i&&(s[1]*=-1),s}({width:h.width,prevWidth:S,height:h.height,prevHeight:E,affectsX:a.controlDirection.affectsX,affectsY:a.controlDirection.affectsY}),A={...h,direction:L};!1!==p?.(e,A)&&(k=!0,d?.(e,A),r(C,u))}).on("end",e=>{k&&=(f?.(e,{...h}),o?.({...h}),!1)});i.call(S)},destroy:function(){i.on(".drag",null)}}}({domNode:E.current,nodeId:k,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:o,domNode:i}=S.getState();return{nodeLookup:e,transform:t,snapGrid:n,snapToGrid:r,nodeOrigin:o,paneDomNode:i}},onChange:(e,t)=>{let{triggerNodeChanges:n,nodeLookup:r,parentLookup:o,nodeOrigin:i}=S.getState(),a=[],l={x:e.x,y:e.y},s=r.get(k);if(s&&s.expandParent&&s.parentId){let t=s.origin??i,n=e.width??s.measured.width??0,u=e.height??s.measured.height??0,c=To([{id:s.id,parentId:s.parentId,rect:{width:n,height:u,...qr({x:e.x??s.position.x,y:e.y??s.position.y},{width:n,height:u},s.parentId,r,t)}}],r,o,i);a.push(...c),l.x=e.x?Math.max(t[0]*n,e.x):void 0,l.y=e.y?Math.max(t[1]*u,e.y):void 0}if(void 0!==l.x&&void 0!==l.y){let e={id:k,type:"position",position:{...l}};a.push(e)}if(void 0!==e.width&&void 0!==e.height){let t={id:k,type:"dimensions",resizing:!0,setAttributes:!m||("horizontal"===m?"width":"height"),dimensions:{width:e.width,height:e.height}};a.push(t)}for(let e of t){let t={...e,type:"position"};a.push(t)}n(a)},onEnd:({width:e,height:t})=>{let n={id:k,type:"dimensions",resizing:!1,dimensions:{width:e,height:t}};S.getState().triggerNodeChanges([n])}}),P.current.update({controlPosition:O,boundaries:{minWidth:l,minHeight:s,maxWidth:u,maxHeight:c},keepAspectRatio:d,resizeDirection:m,onResizeStart:v,onResize:b,onResizeEnd:w,shouldResize:y}),()=>{P.current?.destroy()}},[O,l,s,u,c,d,v,b,w,y]),(0,p.jsx)("div",{className:h(["react-flow__resize-control","nodrag",...O.split("-"),n,r]),ref:E,style:{...o,scale:M,...a&&{[C?"backgroundColor":"borderColor"]:a}},children:i})}),bs=(...e)=>e.filter((e,t,n)=>!!e&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim(),ws=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),xs=e=>{let t=(e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()))(e);return t.charAt(0).toUpperCase()+t.slice(1)},ks={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},Ss=e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0;return!1},Es=(0,f.createContext)({}),Cs=(0,f.forwardRef)(({color:e,size:t,strokeWidth:n,absoluteStrokeWidth:r,className:o="",children:i,iconNode:a,...l},s)=>{let{size:u=24,strokeWidth:c=2,absoluteStrokeWidth:d=!1,color:p="currentColor",className:h=""}=(0,f.useContext)(Es)??{},m=r??d?24*Number(n??c)/Number(t??u):n??c;return(0,f.createElement)("svg",{ref:s,...ks,width:t??u??ks.width,height:t??u??ks.height,stroke:e??p,strokeWidth:m,className:bs("lucide",h,o),...!i&&!Ss(l)&&{"aria-hidden":"true"},...l},[...a.map(([e,t])=>(0,f.createElement)(e,t)),...Array.isArray(i)?i:[i]])}),Ms=(e,t)=>{let n=(0,f.forwardRef)(({className:n,...r},o)=>(0,f.createElement)(Cs,{ref:o,iconNode:t,className:bs(`lucide-${ws(xs(e))}`,`lucide-${e}`,n),...r}));return n.displayName=xs(e),n},Ps=Ms("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),Os=Ms("app-window",[["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}],["path",{d:"M10 4v4",key:"pp8u80"}],["path",{d:"M2 8h20",key:"d11cs7"}],["path",{d:"M6 4v4",key:"1svtjw"}]]),Ts=Ms("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),_s=Ms("arrow-left-right",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]),Ns=Ms("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),Is=Ms("arrow-up-right",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]),zs=Ms("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),Rs=Ms("blocks",[["path",{d:"M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2",key:"1ah6g2"}],["rect",{x:"14",y:"2",width:"8",height:"8",rx:"1",key:"88lufb"}]]),Ls=Ms("box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]),As=Ms("boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]),Ds=Ms("brush",[["path",{d:"m11 10 3 3",key:"fzmg1i"}],["path",{d:"M6.5 21A3.5 3.5 0 1 0 3 17.5a2.62 2.62 0 0 1-.708 1.792A1 1 0 0 0 3 21z",key:"p4q2r7"}],["path",{d:"M9.969 17.031 21.378 5.624a1 1 0 0 0-3.002-3.002L6.967 14.031",key:"wy6l02"}]]),Fs=Ms("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),js=Ms("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),Hs=Ms("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),Vs=Ms("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),$s=Ms("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),Bs=Ms("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),Ws=Ms("circle-check",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),qs=Ms("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),Us=Ms("circle-play",[["path",{d:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),Ks=Ms("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Ys=Ms("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),Xs=Ms("circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),Zs=Ms("clipboard-copy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]),Gs=Ms("clock-3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6h4",key:"135r8i"}]]),Qs=Ms("clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]]),Js=Ms("cloud-download",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]),eu=Ms("columns-2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]),tu=Ms("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),nu=Ms("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),ru=Ms("database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),ou=Ms("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),iu=Ms("ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),au=Ms("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),lu=Ms("eraser",[["path",{d:"M21 21H8a2 2 0 0 1-1.42-.587l-3.994-3.999a2 2 0 0 1 0-2.828l10-10a2 2 0 0 1 2.829 0l5.999 6a2 2 0 0 1 0 2.828L12.834 21",key:"g5wo59"}],["path",{d:"m5.082 11.09 8.828 8.828",key:"1wx5vj"}]]),su=Ms("expand",[["path",{d:"m15 15 6 6",key:"1s409w"}],["path",{d:"m15 9 6-6",key:"ko1vev"}],["path",{d:"M21 16v5h-5",key:"1ck2sf"}],["path",{d:"M21 8V3h-5",key:"1qoq8a"}],["path",{d:"M3 16v5h5",key:"1t08am"}],["path",{d:"m3 21 6-6",key:"wwnumi"}],["path",{d:"M3 8V3h5",key:"1ln10m"}],["path",{d:"M9 9 3 3",key:"v551iv"}]]),uu=Ms("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]),cu=Ms("file-braces-corner",[["path",{d:"M14 22h4a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v6",key:"14cnrg"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M5 14a1 1 0 0 0-1 1v2a1 1 0 0 1-1 1 1 1 0 0 1 1 1v2a1 1 0 0 0 1 1",key:"sr0ebq"}],["path",{d:"M9 22a1 1 0 0 0 1-1v-2a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-2a1 1 0 0 0-1-1",key:"w793db"}]]),du=Ms("file-clock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v2.85",key:"ryk6xj"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 14v2.2l1.6 1",key:"6m4bie"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}]]),fu=Ms("file-down",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]),pu=Ms("file-plus-corner",[["path",{d:"M11.35 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v5.35",key:"17jvcc"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M14 19h6",key:"bvotb8"}],["path",{d:"M17 16v6",key:"18yu1i"}]]),hu=Ms("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),mu=Ms("files",[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"14sh0y"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z",key:"1970lx"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1",key:"l4dndm"}]]),gu=Ms("film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]),yu=Ms("flask-conical",[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]]),vu=Ms("folder-open",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]),bu=Ms("folder-search",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),wu=Ms("folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]),xu=Ms("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]),ku=Ms("gallery-vertical-end",[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]]),Su=Ms("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),Eu=Ms("git-branch",[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]]),Cu=Ms("grid-2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]),Mu=Ms("hard-drive",[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]]),Pu=Ms("heart",[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]]),Ou=Ms("history",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]),Tu=Ms("house",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]]),_u=Ms("image-plus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]),Nu=Ms("image-up",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19.5 3-3 3 3",key:"9vmjn0"}],["path",{d:"M17 22v-5.5",key:"1aa6fl"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]),Iu=Ms("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),zu=Ms("images",[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",key:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]]),Ru=Ms("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),Lu=Ms("key-round",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]),Au=Ms("layers",[["path",{d:"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z",key:"zw3jo"}],["path",{d:"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12",key:"1wduqc"}],["path",{d:"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17",key:"kqbvx6"}]]),Du=Ms("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]),Fu=Ms("layout-template",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]),ju=Ms("library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]),Hu=Ms("list-checks",[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]]),Vu=Ms("list-plus",[["path",{d:"M16 5H3",key:"m91uny"}],["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 19H3",key:"zzsher"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]),$u=Ms("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),Bu=Ms("log-out",[["path",{d:"m16 17 5-5-5-5",key:"1bji2h"}],["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}]]),Wu=Ms("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),qu=Ms("maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]),Uu=Ms("memory-stick",[["path",{d:"M12 12v-2",key:"fwoke6"}],["path",{d:"M12 18v-2",key:"qj6yno"}],["path",{d:"M16 12v-2",key:"heuere"}],["path",{d:"M16 18v-2",key:"s1ct0w"}],["path",{d:"M2 11h1.5",key:"15p63e"}],["path",{d:"M20 18v-2",key:"12ehxp"}],["path",{d:"M20.5 11H22",key:"khsy7a"}],["path",{d:"M4 18v-2",key:"1c3oqr"}],["path",{d:"M8 12v-2",key:"1mwtfd"}],["path",{d:"M8 18v-2",key:"qcmpov"}],["rect",{x:"2",y:"6",width:"20",height:"10",rx:"2",key:"1qcswk"}]]),Ku=Ms("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]),Yu=Ms("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),Xu=Ms("music-2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]),Zu=Ms("music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]),Gu=Ms("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),Qu=Ms("octagon",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]),Ju=Ms("package-open",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]),ec=Ms("package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]),tc=Ms("paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]),nc=Ms("panel-right-close",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]),rc=Ms("panel-right-open",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]),oc=Ms("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),ic=Ms("pin-off",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]]),ac=Ms("pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]),lc=Ms("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]),sc=Ms("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),uc=Ms("power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]),cc=Ms("refresh-ccw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]),dc=Ms("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),fc=Ms("repeat-2",[["path",{d:"m2 9 3-3 3 3",key:"1ltn5i"}],["path",{d:"M13 18H7a2 2 0 0 1-2-2V6",key:"1r6tfw"}],["path",{d:"m22 15-3 3-3-3",key:"4rnwn2"}],["path",{d:"M11 6h6a2 2 0 0 1 2 2v10",key:"2f72bc"}]]),pc=Ms("repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]),hc=Ms("rocket",[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]]),mc=Ms("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),gc=Ms("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),yc=Ms("save-all",[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]),vc=Ms("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]),bc=Ms("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),wc=Ms("server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]),xc=Ms("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),kc=Ms("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),Sc=Ms("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),Ec=Ms("shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]),Cc=Ms("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]),Mc=Ms("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]),Pc=Ms("square-play",[["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}],["path",{d:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}]]),Oc=Ms("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),Tc=Ms("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]),_c=Ms("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Nc=Ms("truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]),Ic=Ms("type",[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]]),zc=Ms("ungroup",[["rect",{width:"8",height:"6",x:"5",y:"4",rx:"1",key:"nzclkv"}],["rect",{width:"8",height:"6",x:"11",y:"14",rx:"1",key:"4tytwb"}]]),Rc=Ms("upload",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]),Lc=Ms("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),Ac=Ms("wand-sparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]),Dc=Ms("webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]),Fc=Ms("wifi-off",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),jc=Ms("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),Hc=Ms("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),Vc=Ms("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),$c=Ms("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Bc=e=>e?.ownerDocument??document,Wc=e=>e&&"window"in e&&e.window===e?e:Bc(e).defaultView||window;function qc(e,t){return!(!t||!e)&&e.contains(t)}var Uc=(e=document)=>e.activeElement;function Kc(e){return e.target}var Yc=null,Xc=typeof document<"u"?f.useLayoutEffect:()=>{};function Zc(e){let t=e;return t.nativeEvent=e,t.isDefaultPrevented=()=>t.defaultPrevented,t.isPropagationStopped=()=>t.cancelBubble,t.persist=()=>{},t}function Gc(e){let t=(0,f.useRef)({isFocused:!1,observer:null});return Xc(()=>{let e=t.current;return()=>{e.observer&&=(e.observer.disconnect(),null)}},[]),(0,f.useCallback)(n=>{let r=Kc(n);if(r instanceof HTMLButtonElement||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement){t.current.isFocused=!0;let n=r;n.addEventListener("focusout",r=>{if(t.current.isFocused=!1,n.disabled){let t=Zc(r);e?.(t)}t.current.observer&&(t.current.observer.disconnect(),t.current.observer=null)},{once:!0}),t.current.observer=new MutationObserver(()=>{if(t.current.isFocused&&n.disabled){t.current.observer?.disconnect();let e=n===Uc()?null:Uc();n.dispatchEvent(new FocusEvent("blur",{relatedTarget:e})),n.dispatchEvent(new FocusEvent("focusout",{bubbles:!0,relatedTarget:e}))}}),t.current.observer.observe(n,{attributes:!0,attributeFilter:["disabled"]})}},[e])}function Qc(e){if(typeof window>"u"||null==window.navigator)return!1;let t=window.navigator.userAgentData?.brands;return Array.isArray(t)&&t.some(t=>e.test(t.brand))||e.test(window.navigator.userAgent)}function Jc(e){return typeof window<"u"&&null!=window.navigator&&e.test(window.navigator.userAgentData?.platform||window.navigator.platform)}function ed(e){let t=null;return()=>(t??=e(),t)}var td=ed(function(){return Jc(/^Mac/i)}),nd=ed(function(){return Jc(/^iPad/i)||td()&&navigator.maxTouchPoints>1}),rd=ed(function(){return Qc(/AppleWebKit/i)&&!od()}),od=ed(function(){return Qc(/Chrome/i)}),id=ed(function(){return Qc(/Android/i)}),ad=ed(function(){return Qc(/Firefox/i)});function ld(e,t,n=!0){let{metaKey:r,ctrlKey:o,altKey:i,shiftKey:a}=t;ad()&&window.event?.type?.startsWith("key")&&"_blank"===e.target&&(td()?r=!0:o=!0);let l=rd()&&td()&&!nd()?new KeyboardEvent("keydown",{keyIdentifier:"Enter",metaKey:r,ctrlKey:o,altKey:i,shiftKey:a}):new MouseEvent("click",{metaKey:r,ctrlKey:o,altKey:i,shiftKey:a,detail:1,bubbles:!0,cancelable:!0});ld.isOpening=n,function(e){if(function(){if(null==Yc){Yc=!1;try{document.createElement("div").focus({get preventScroll(){return Yc=!0,!0}})}catch{}}return Yc}())e.focus({preventScroll:!0});else{let t=function(e){let t=e.parentNode,n=[],r=document.scrollingElement||document.documentElement;for(;t instanceof HTMLElement&&t!==r;)(t.offsetHeight"u"||typeof document>"u")return;let t=Wc(e),n=Bc(e);if(cd.get(t))return;let r=t.HTMLElement.prototype.focus;t.HTMLElement.prototype.focus=function(){dd=!0,r.apply(this,arguments)},n.addEventListener("keydown",md,!0),n.addEventListener("keyup",md,!0),n.addEventListener("click",yd,!0),t.addEventListener("focus",vd,!0),t.addEventListener("blur",bd,!1),typeof PointerEvent<"u"&&(n.addEventListener("pointerdown",gd,!0),n.addEventListener("pointermove",gd,!0),n.addEventListener("pointerup",gd,!0)),t.addEventListener("beforeunload",()=>{xd(e)},{once:!0}),cd.set(t,{focus:r})}var xd=(e,t)=>{let n=Wc(e),r=Bc(e);t&&r.removeEventListener("DOMContentLoaded",t),cd.has(n)&&(n.HTMLElement.prototype.focus=cd.get(n).focus,r.removeEventListener("keydown",md,!0),r.removeEventListener("keyup",md,!0),r.removeEventListener("click",yd,!0),n.removeEventListener("focus",vd,!0),n.removeEventListener("blur",bd,!1),typeof PointerEvent<"u"&&(r.removeEventListener("pointerdown",gd,!0),r.removeEventListener("pointermove",gd,!0),r.removeEventListener("pointerup",gd,!0)),cd.delete(n))};function kd(){return"pointer"!==sd}typeof document<"u"&&function(e){let t,n=Bc(e);"loading"===n.readyState?(t=()=>{wd(e)},n.addEventListener("DOMContentLoaded",t)):wd(e)}();var Sd=new Set(["checkbox","radio","range","color","file","image","button","submit","reset"]);function Ed(){let e=(0,f.useRef)(new Map),t=(0,f.useCallback)((t,n,r,o)=>{let i=o?.once?(...t)=>{e.current.delete(r),r(...t)}:r;e.current.set(r,{type:n,eventTarget:t,fn:i,options:o}),t.addEventListener(n,i,o)},[]),n=(0,f.useCallback)((t,n,r,o)=>{let i=e.current.get(r)?.fn||r;t.removeEventListener(n,i,o),e.current.delete(r)},[]),r=(0,f.useCallback)(()=>{e.current.forEach((e,t)=>{n(e.eventTarget,e.type,t,e.options)})},[n]);return(0,f.useEffect)(()=>r,[r]),{addGlobalListener:t,removeGlobalListener:n,removeAllGlobalListeners:r}}function Cd(e={}){let{autoFocus:t=!1,isTextInput:n,within:r}=e,o=(0,f.useRef)({isFocused:!1,isFocusVisible:t||kd()}),[i,a]=(0,f.useState)(!1),[l,s]=(0,f.useState)(()=>o.current.isFocused&&o.current.isFocusVisible),u=(0,f.useCallback)(()=>s(o.current.isFocused&&o.current.isFocusVisible),[]),c=(0,f.useCallback)(e=>{o.current.isFocused=e,o.current.isFocusVisible=kd(),a(e),u()},[u]);!function(e,t,n){wd(),(0,f.useEffect)(()=>{if(!1===n?.enabled)return;let e=(e,t)=>{(function(e,t,n){let r=n?Kc(n):void 0,o=Bc(r),i=Wc(r),a=void 0===i?HTMLInputElement:i.HTMLInputElement,l=void 0===i?HTMLTextAreaElement:i.HTMLTextAreaElement,s=void 0===i?HTMLElement:i.HTMLElement,u=void 0===i?KeyboardEvent:i.KeyboardEvent,c=Uc(o);return!((e=e||c instanceof a&&!Sd.has(c.type)||c instanceof l||c instanceof s&&c.isContentEditable)&&"keyboard"===t&&n instanceof u&&!pd[n.key])})(!!n?.isTextInput,e,t)&&(e=>{o.current.isFocusVisible=e,u()})(kd())};return ud.add(e),()=>{ud.delete(e)}},t)}(0,[n,i],{enabled:i,isTextInput:n});let{focusProps:d}=function(e){let{isDisabled:t,onFocus:n,onBlur:r,onFocusChange:o}=e,i=(0,f.useCallback)(e=>{if(Kc(e)===e.currentTarget)return r&&r(e),o&&o(!1),!0},[r,o]),a=Gc(i),l=(0,f.useCallback)(e=>{let t=Kc(e),r=Bc(t),i=r?Uc(r):Uc();t===e.currentTarget&&t===i&&(n&&n(e),o&&o(!0),a(e))},[o,n,a]);return{focusProps:{onFocus:!t&&(n||o||r)?l:void 0,onBlur:t||!r&&!o?void 0:i}}}({isDisabled:r,onFocusChange:c}),{focusWithinProps:p}=function(e){let{isDisabled:t,onBlurWithin:n,onFocusWithin:r,onFocusWithinChange:o}=e,i=(0,f.useRef)({isFocusWithin:!1}),{addGlobalListener:a,removeAllGlobalListeners:l}=Ed(),s=(0,f.useCallback)(e=>{qc(e.currentTarget,Kc(e))&&i.current.isFocusWithin&&!qc(e.currentTarget,e.relatedTarget)&&(i.current.isFocusWithin=!1,l(),n&&n(e),o&&o(!1))},[n,o,i,l]),u=Gc(s),c=(0,f.useCallback)(e=>{if(!qc(e.currentTarget,Kc(e)))return;let t=Kc(e),n=Bc(t),l=Uc(n);if(!i.current.isFocusWithin&&l===t){r&&r(e),o&&o(!0),i.current.isFocusWithin=!0,u(e);let t=e.currentTarget;a(n,"focus",e=>{let r=Kc(e);if(i.current.isFocusWithin&&!qc(t,r)){let e=new n.defaultView.FocusEvent("blur",{relatedTarget:r});!function(e,t){Object.defineProperty(e,"target",{value:t}),Object.defineProperty(e,"currentTarget",{value:t})}(e,t);let o=Zc(e);s(o)}},{capture:!0})}},[r,o,u,a,s]);return t?{focusWithinProps:{onFocus:void 0,onBlur:void 0}}:{focusWithinProps:{onFocus:c,onBlur:s}}}({isDisabled:!r,onFocusWithinChange:c});return{isFocused:i,isFocusVisible:l,focusProps:r?p:d}}var Md=!1,Pd=0;function Od(e){"touch"===e.pointerType&&(Md=!0,setTimeout(()=>{Md=!1},500))}function Td(){let e=Bc(null);if(void 0!==e)return 0===Pd&&typeof PointerEvent<"u"&&e.addEventListener("pointerup",Od),Pd++,()=>{!(--Pd>0)&&typeof PointerEvent<"u"&&e.removeEventListener("pointerup",Od)}}function _d(e){let{onHoverStart:t,onHoverChange:n,onHoverEnd:r,isDisabled:o}=e,[i,a]=(0,f.useState)(!1),l=(0,f.useRef)({isHovered:!1,ignoreEmulatedMouseEvents:!1,pointerType:"",target:null}).current;(0,f.useEffect)(Td,[]);let{addGlobalListener:s,removeAllGlobalListeners:u}=Ed(),{hoverProps:c,triggerHoverEnd:d}=(0,f.useMemo)(()=>{let e=(e,r)=>{if(l.pointerType=r,o||"touch"===r||l.isHovered||!qc(e.currentTarget,Kc(e)))return;l.isHovered=!0;let u=e.currentTarget;l.target=u,s(Bc(Kc(e)),"pointerover",e=>{l.isHovered&&l.target&&!qc(l.target,Kc(e))&&i(e,e.pointerType)},{capture:!0}),t&&t({type:"hoverstart",target:u,pointerType:r}),n&&n(!0),a(!0)},i=(e,t)=>{let o=l.target;l.pointerType="",l.target=null,"touch"!==t&&l.isHovered&&o&&(l.isHovered=!1,u(),r&&r({type:"hoverend",target:o,pointerType:t}),n&&n(!1),a(!1))},c={};return typeof PointerEvent<"u"&&(c.onPointerEnter=t=>{Md&&"mouse"===t.pointerType||e(t,t.pointerType)},c.onPointerLeave=e=>{!o&&qc(e.currentTarget,Kc(e))&&i(e,e.pointerType)}),{hoverProps:c,triggerHoverEnd:i}},[t,n,r,o,l,s,u]);return(0,f.useEffect)(()=>{o&&d({currentTarget:l.target},l.pointerType)},[o]),{hoverProps:c,isHovered:i}}var Nd=Object.defineProperty,Id=(e,t,n)=>(((e,t,n)=>{t in e?Nd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"==typeof t?t:t+"",n),n),zd=new class{constructor(){Id(this,"current",this.detect()),Id(this,"handoffState","pending"),Id(this,"currentId",0)}set(e){this.current!==e&&(this.handoffState="pending",this.currentId=0,this.current=e)}reset(){this.set(this.detect())}nextId(){return++this.currentId}get isServer(){return"server"===this.current}get isClient(){return"client"===this.current}detect(){return typeof window>"u"||typeof document>"u"?"server":"client"}handoff(){"pending"===this.handoffState&&(this.handoffState="complete")}get isHandoffComplete(){return"complete"===this.handoffState}};function Rd(e){return zd.isServer?null:null==e?document:e?.ownerDocument??document}function Ld(e){return zd.isServer?null:null==e?document:(e?.getRootNode)?.call(e)??document}function Ad(e){return Ld(e)?.activeElement??null}function Dd(e){return Ad(e)===e}function Fd(e){"function"==typeof queueMicrotask?queueMicrotask(e):Promise.resolve().then(e).catch(e=>setTimeout(()=>{throw e}))}function jd(){let e=[],t={addEventListener:(e,n,r,o)=>(e.addEventListener(n,r,o),t.add(()=>e.removeEventListener(n,r,o))),requestAnimationFrame(...e){let n=requestAnimationFrame(...e);return t.add(()=>cancelAnimationFrame(n))},nextFrame:(...e)=>t.requestAnimationFrame(()=>t.requestAnimationFrame(...e)),setTimeout(...e){let n=setTimeout(...e);return t.add(()=>clearTimeout(n))},microTask(...e){let n={current:!0};return Fd(()=>{n.current&&e[0]()}),t.add(()=>{n.current=!1})},style(e,t,n){let r=e.style.getPropertyValue(t);return Object.assign(e.style,{[t]:n}),this.add(()=>{Object.assign(e.style,{[t]:r})})},group(e){let t=jd();return e(t),this.add(()=>t.dispose())},add:t=>(e.includes(t)||e.push(t),()=>{let n=e.indexOf(t);if(n>=0)for(let t of e.splice(n,1))t()}),dispose(){for(let t of e.splice(0))t()}};return t}function Hd(){let[e]=(0,f.useState)(jd);return(0,f.useEffect)(()=>()=>e.dispose(),[e]),e}var Vd=(e,t)=>{zd.isServer?(0,f.useEffect)(e,t):(0,f.useLayoutEffect)(e,t)};function $d(e){let t=(0,f.useRef)(e);return Vd(()=>{t.current=e},[e]),t}var Bd=function(e){let t=$d(e);return f.useCallback((...e)=>t.current(...e),[t])};function Wd({disabled:e=!1}={}){let t=(0,f.useRef)(null),[n,r]=(0,f.useState)(!1),o=Hd(),i=Bd(()=>{t.current=null,r(!1),o.dispose()}),a=Bd(e=>{if(o.dispose(),null===t.current){t.current=e.currentTarget,r(!0);{let n=Rd(e.currentTarget);o.addEventListener(n,"pointerup",i,!1),o.addEventListener(n,"pointermove",e=>{if(t.current){let n=function(e){let t=e.width/2,n=e.height/2;return{top:e.clientY-n,right:e.clientX+t,bottom:e.clientY+n,left:e.clientX-t}}(e);r(function(e,t){return!(!e||!t||e.rightt.right||e.bottomt.bottom)}(n,t.current.getBoundingClientRect()))}},!1),o.addEventListener(n,"pointercancel",i,!1)}}});return{pressed:n,pressProps:e?{}:{onPointerDown:a,onPointerUp:i,onClick:i}}}function qd(e){return(0,f.useMemo)(()=>e,Object.values(e))}var Ud=(0,f.createContext)(void 0);function Kd(){return(0,f.useContext)(Ud)}function Yd(...e){return Array.from(new Set(e.flatMap(e=>"string"==typeof e?e.split(" "):[]))).filter(Boolean).join(" ")}function Xd(e,t,...n){if(e in t){let r=t[e];return"function"==typeof r?r(...n):r}let r=Error(`Tried to handle "${e}" but there is no handler defined. Only defined handlers are: ${Object.keys(t).map(e=>`"${e}"`).join(", ")}.`);throw Error.captureStackTrace&&Error.captureStackTrace(r,Xd),r}var Zd=(e=>(e[e.None=0]="None",e[e.RenderStrategy=1]="RenderStrategy",e[e.Static=2]="Static",e))(Zd||{}),Gd=(e=>(e[e.Unmount=0]="Unmount",e[e.Hidden=1]="Hidden",e))(Gd||{});function Qd(){let e=function(){let e=(0,f.useRef)([]),t=(0,f.useCallback)(t=>{for(let n of e.current)null!=n&&("function"==typeof n?n(t):n.current=t)},[]);return(...n)=>{if(!n.every(e=>null==e))return e.current=n,t}}();return(0,f.useCallback)(t=>function({ourProps:e,theirProps:t,slot:n,defaultTag:r,features:o,visible:i=!0,name:a,mergeRefs:l}){l??=ef;let s=tf(t,e);if(i)return Jd(s,n,r,a,l);let u=o??0;if(2&u){let{static:e=!1,...t}=s;if(e)return Jd(t,n,r,a,l)}if(1&u){let{unmount:e=!0,...t}=s;return Xd(+!e,{0:()=>null,1:()=>Jd({...t,hidden:!0,style:{display:"none"}},n,r,a,l)})}return Jd(s,n,r,a,l)}({mergeRefs:e,...t}),[e])}function Jd(e,t={},n,r,o){let{as:i=n,children:a,refName:l="ref",...s}=af(e,["unmount","static"]),u=void 0===e.ref?{}:{[l]:e.ref},c="function"==typeof a?a(t):a;c=sf(c),"className"in s&&s.className&&"function"==typeof s.className&&(s.className=s.className(t)),s["aria-labelledby"]&&s["aria-labelledby"]===s.id&&(s["aria-labelledby"]=void 0);let d={};if(t){let e=!1,n=[];for(let[r,o]of Object.entries(t))"boolean"==typeof o&&(e=!0),!0===o&&n.push(r.replace(/([A-Z])/g,e=>`-${e.toLowerCase()}`));if(e){d["data-headlessui-state"]=n.join(" ");for(let e of n)d[`data-${e}`]=""}}if(uf(i)&&(Object.keys(of(s)).length>0||Object.keys(of(d)).length>0)){if(!(!(0,f.isValidElement)(c)||Array.isArray(c)&&c.length>1||function(e){return uf(e.type)}(c))){let e=c.props?.className,t="function"==typeof e?(...t)=>Yd(e(...t),s.className):Yd(e,s.className),n=t?{className:t}:{},r=tf(c.props,of(af(s,["ref"])));for(let e in d)e in r&&delete d[e];return(0,f.cloneElement)(c,Object.assign({},r,d,u,{ref:o(lf(c),u.ref)},n))}if(Object.keys(of(s)).length>0)throw Error(['Passing props on "Fragment"!',"",`The current component <${r} /> is rendering a "Fragment".`,"However we need to passthrough the following props:",Object.keys(of(s)).concat(Object.keys(of(d))).map(e=>` - ${e}`).join("\n"),"","You can apply a few solutions:",['Add an `as="..."` prop, to ensure that we render an actual element instead of a "Fragment".',"Render a single element as the child so that we can forward the props onto that element."].map(e=>` - ${e}`).join("\n")].join("\n"))}return(0,f.createElement)(i,Object.assign({},af(s,["ref"]),!uf(i)&&u,!uf(i)&&d),c)}function ef(...e){return e.every(e=>null==e)?void 0:t=>{for(let n of e)null!=n&&("function"==typeof n?n(t):n.current=t)}}function tf(...e){if(0===e.length)return{};if(1===e.length)return e[0];let t={},n={};for(let r of e)for(let e in r)e.startsWith("on")&&"function"==typeof r[e]?(n[e]??(n[e]=[]),n[e].push(r[e])):t[e]=r[e];if(t.disabled||t["aria-disabled"])for(let e in n)/^(on(?:Click|Pointer|Mouse|Key)(?:Down|Up|Press)?)$/.test(e)&&(n[e]=[e=>(e?.preventDefault)?.call(e)]);for(let e in n)Object.assign(t,{[e](t,...r){let o=n[e];for(let e of o){if((t instanceof Event||t?.nativeEvent instanceof Event)&&t.defaultPrevented)return;e(t,...r)}}});return t}function nf(...e){if(0===e.length)return{};if(1===e.length)return e[0];let t={},n={};for(let r of e)for(let e in r)e.startsWith("on")&&"function"==typeof r[e]?(n[e]??(n[e]=[]),n[e].push(r[e])):t[e]=r[e];for(let e in n)Object.assign(t,{[e](...t){let r=n[e];for(let e of r)e?.(...t)}});return t}function rf(e){return Object.assign((0,f.forwardRef)(e),{displayName:e.displayName??e.name})}function of(e){let t=Object.assign({},e);for(let e in t)void 0===t[e]&&delete t[e];return t}function af(e,t=[]){let n=Object.assign({},e);for(let e of t)e in n&&delete n[e];return n}function lf(e){return"19.2.7".split(".")[0]>="19"?e.props.ref:e.ref}function sf(e){if(null!=e&&e.$$typeof===Symbol.for("react.lazy")){let t=e._payload;if(null!=t&&"fulfilled"===t.status)return sf(t.value)}return e}function uf(e){return e===f.Fragment||e===Symbol.for("react.fragment")}function cf(e,t,n){let[r,o]=(0,f.useState)(n),i=void 0!==e,a=(0,f.useRef)(i),l=(0,f.useRef)(!1),s=(0,f.useRef)(!1);return!i||a.current||l.current?!i&&a.current&&!s.current&&(s.current=!0,a.current=i,console.error("A component is changing from controlled to uncontrolled. This may be caused by the value changing from a defined value to undefined, which should not happen.")):(l.current=!0,a.current=i,console.error("A component is changing from uncontrolled to controlled. This may be caused by the value changing from undefined to a defined value, which should not happen.")),[i?e:r,Bd(e=>(i||(0,pi.flushSync)(()=>o(e)),t?.(e)))]}function df(e){let[t]=(0,f.useState)(e);return t}function ff(e={},t=null,n=[]){for(let[r,o]of Object.entries(e))hf(n,pf(t,r),o);return n}function pf(e,t){return e?e+"["+t+"]":t}function hf(e,t,n){if(Array.isArray(n))for(let[r,o]of n.entries())hf(e,pf(t,r.toString()),o);else n instanceof Date?e.push([t,n.toISOString()]):"boolean"==typeof n?e.push([t,n?"1":"0"]):"string"==typeof n?e.push([t,n]):"number"==typeof n?e.push([t,`${n}`]):null==n?e.push([t,""]):function(e){if("[object Object]"!==Object.prototype.toString.call(e))return!1;let t=Object.getPrototypeOf(e);return null===t||null===Object.getPrototypeOf(t)}(n)&&!(0,f.isValidElement)(n)&&ff(n,t,e)}function mf(e){var t;let n=e?.form??e.closest("form");if(n){for(let t of n.elements)if(t!==e&&("INPUT"===t.tagName&&"submit"===t.type||"BUTTON"===t.tagName&&"submit"===t.type||"INPUT"===t.nodeName&&"image"===t.type))return void t.click();null==(t=n.requestSubmit)||t.call(n)}}var gf=(e=>(e[e.None=1]="None",e[e.Focusable=2]="Focusable",e[e.Hidden=4]="Hidden",e))(gf||{}),yf=rf(function(e,t){let{features:n=1,...r}=e,o={ref:t,"aria-hidden":!(2&~n)||(r["aria-hidden"]??void 0),hidden:!(4&~n)||void 0,style:{position:"fixed",top:1,left:1,width:1,height:0,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0",...!(4&~n)&&!!(2&~n)&&{display:"none"}}};return Qd()({ourProps:o,theirProps:r,slot:{},defaultTag:"span",name:"Hidden"})}),vf=(0,f.createContext)(null);function bf({children:e}){let t=(0,f.useContext)(vf);if(!t)return f.createElement(f.Fragment,null,e);let{target:n}=t;return n?(0,pi.createPortal)(f.createElement(f.Fragment,null,e),n):null}function wf({data:e,form:t,disabled:n,onReset:r,overrides:o}){let[i,a]=(0,f.useState)(null),l=Hd();return(0,f.useEffect)(()=>{if(r&&i)return l.addEventListener(i,"reset",r)},[i,t,r]),f.createElement(bf,null,f.createElement(xf,{setForm:a,formId:t}),ff(e).map(([e,r])=>f.createElement(yf,{features:gf.Hidden,...of({key:e,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:t,disabled:n,name:e,value:r,...o})})))}function xf({setForm:e,formId:t}){return(0,f.useEffect)(()=>{if(t){let n=document.getElementById(t);n&&e(n)}},[e,t]),t?null:f.createElement(yf,{features:gf.Hidden,as:"input",type:"hidden",hidden:!0,readOnly:!0,ref:t=>{if(!t)return;let n=t.closest("form");n&&e(n)}})}var kf=(0,f.createContext)(void 0);function Sf(){return(0,f.useContext)(kf)}function Ef(e){return!("object"!=typeof e||!e)&&"nodeType"in e}function Cf(e){return Ef(e)&&"tagName"in e}function Mf(e){return Cf(e)&&"accessKey"in e}function Pf(e){return Cf(e)&&"tabIndex"in e}function Of(e){return Mf(e)&&"INPUT"===e.nodeName}function Tf(e){return Mf(e)&&"LABEL"===e.nodeName}function _f(e){return Mf(e)&&"FIELDSET"===e.nodeName}function Nf(e){return Mf(e)&&"LEGEND"===e.nodeName}function If(e){let t=e.parentElement,n=null;for(;t&&!_f(t);)Nf(t)&&(n=t),t=t.parentElement;let r=""===t?.getAttribute("disabled");return(!r||!function(e){if(!e)return!1;let t=e.previousElementSibling;for(;null!==t;){if(Nf(t))return!1;t=t.previousElementSibling}return!0}(n))&&r}var zf=Symbol();function Rf(e,t=!0){return Object.assign(e,{[zf]:t})}function Lf(...e){let t=(0,f.useRef)(e);(0,f.useEffect)(()=>{t.current=e},[e]);let n=Bd(e=>{for(let n of t.current)null!=n&&("function"==typeof n?n(e):n.current=e)});return e.every(e=>null==e||e?.[zf])?void 0:n}var Af=(0,f.createContext)(null);function Df(){let e=(0,f.useContext)(Af);if(null===e){let e=Error("You used a component, but it is not inside a relevant parent.");throw Error.captureStackTrace&&Error.captureStackTrace(e,Df),e}return e}function Ff(){return(0,f.useContext)(Af)?.value??void 0}function jf(){let[e,t]=(0,f.useState)([]);return[e.length>0?e.join(" "):void 0,(0,f.useMemo)(()=>function(e){let n=Bd(e=>(t(t=>[...t,e]),()=>t(t=>{let n=t.slice(),r=n.indexOf(e);return-1!==r&&n.splice(r,1),n}))),r=(0,f.useMemo)(()=>({register:n,slot:e.slot,name:e.name,props:e.props,value:e.value}),[n,e.slot,e.name,e.props,e.value]);return f.createElement(Af.Provider,{value:r},e.children)},[t])]}Af.displayName="DescriptionContext";var Hf=rf(function(e,t){let n=(0,f.useId)(),r=Kd(),{id:o=`headlessui-description-${n}`,...i}=e,a=Df(),l=Lf(t);Vd(()=>a.register(o),[o,a.register]);let s=qd({...a.slot,disabled:r||!1}),u={ref:l,...a.props,id:o};return Qd()({ourProps:u,theirProps:i,slot:s,defaultTag:"p",name:a.name||"Description"})}),Vf=Object.assign(Hf,{}),$f=(e=>(e.Space=" ",e.Enter="Enter",e.Escape="Escape",e.Backspace="Backspace",e.Delete="Delete",e.ArrowLeft="ArrowLeft",e.ArrowUp="ArrowUp",e.ArrowRight="ArrowRight",e.ArrowDown="ArrowDown",e.Home="Home",e.End="End",e.PageUp="PageUp",e.PageDown="PageDown",e.Tab="Tab",e))($f||{}),Bf=(0,f.createContext)(null);function Wf(){let e=(0,f.useContext)(Bf);if(null===e){let e=Error("You used a