ima2-gen 3.25.0 → 3.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +10 -2
- package/bin/commands/update.js +161 -0
- package/bin/ima2.js +11 -8
- package/bin/lib/helpText.js +1 -0
- package/bin/lib/npmUpdate.js +149 -0
- package/bin/lib/updateNotice.js +30 -0
- package/config.js +10 -0
- package/docs/API.md +13 -0
- package/docs/migration/runtime-test-inventory.md +6 -1
- package/lib/updateCache.js +128 -0
- package/lib/updateCheck.js +118 -0
- package/lib/updateVersion.js +59 -0
- package/package.json +2 -2
- package/routes/events.js +8 -3
- package/routes/index.js +2 -0
- package/routes/update.js +67 -0
- package/server.js +7 -0
- package/skills/ima2/SKILL.md +4 -0
- package/ui/dist/.vite/manifest.json +71 -64
- package/ui/dist/assets/{AgentWorkspace-DXPJup3F.js → AgentWorkspace-DGEWNErN.js} +1 -1
- package/ui/dist/assets/App-CZZNsSpb.css +1 -0
- package/ui/dist/assets/App-b7KJO01r.js +9 -0
- package/ui/dist/assets/AssetGenWorkspace-woj0orEW.js +2 -0
- package/ui/dist/assets/{AssetMediaLightbox-CV9ME5oR.js → AssetMediaLightbox-39eeVLgg.js} +1 -1
- package/ui/dist/assets/{AssetsWorkspace-DWzOEvQE.js → AssetsWorkspace-feT-v8BY.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-B1qS17V6.js → CardNewsWorkspace-Bce7Qq0s.js} +1 -1
- package/ui/dist/assets/{GenerationRequestLogPanel-DyFi62oC.js → GenerationRequestLogPanel-D6jO_fXj.js} +1 -1
- package/ui/dist/assets/{HomeWorkspace-BHdt4qCg.js → HomeWorkspace-C7SABT2o.js} +1 -1
- package/ui/dist/assets/{KeyingPanel-CyycINzW.js → KeyingPanel-DWaV9fRG.js} +1 -1
- package/ui/dist/assets/{NodeCanvas-BdKhUDjc.js → NodeCanvas-ybOBBYto.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-CMXjpe3Y.js → PromptBuilderPanel-C1DLHD9Q.js} +1 -1
- package/ui/dist/assets/PromptImportDialog-OGyYU5K5.js +2 -0
- package/ui/dist/assets/{PromptImportDiscoverySection-C0WBOpMu.js → PromptImportDiscoverySection-Cwigr40k.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-DqAoW1I_.js → PromptImportFolderSection-B1XqjRbl.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-B6a4fySv.js → PromptLibraryPanel-v7hIoYy-.js} +2 -2
- package/ui/dist/assets/{SettingsWorkspace-BF_e8kUk.js → SettingsWorkspace-CGZXJLgN.js} +1 -1
- package/ui/dist/assets/{SpriteRecipeWorkspace-BbkGaNby.js → SpriteRecipeWorkspace-Cm5wizr5.js} +1 -1
- package/ui/dist/assets/{index-CDZTiRZg.js → index-CJ-sBrSx.js} +9 -8
- package/ui/dist/assets/{index-BrM_ZMPs.js → index-CUMOJ4Vx.js} +3 -3
- package/ui/dist/assets/{pptxgen.es-DWAWViwz.js → pptxgen.es-XHiluGIr.js} +1 -1
- package/ui/dist/assets/{promptBuilderStore-CCMVetZf.js → promptBuilderStore-BKNNtgtk.js} +1 -1
- package/ui/dist/assets/useAgentDialogFocus-CZabQdET.js +1 -0
- package/ui/dist/index.html +1 -1
- package/ui/dist/assets/App-BdynRa0c.js +0 -9
- package/ui/dist/assets/AssetGenWorkspace-CFjZEEJn.js +0 -2
- package/ui/dist/assets/PromptImportDialog-Dd1sw7H6.js +0 -2
- package/ui/dist/assets/useAgentDialogFocus-Cxfj1Zq7.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CUMOJ4Vx.js","assets/index-CJ-sBrSx.js","assets/index-Dznqt1dP.css","assets/PromptLibraryPanel-v7hIoYy-.js","assets/PromptBuilderPanel-C1DLHD9Q.js","assets/promptBuilderStore-BKNNtgtk.js","assets/GenerationRequestLogPanel-D6jO_fXj.js","assets/clipboard-DirTPLEi.js","assets/NodeCanvas-ybOBBYto.js","assets/AssetMediaLightbox-39eeVLgg.js","assets/useAgentDialogFocus-CZabQdET.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-CGZXJLgN.js","assets/CardNewsWorkspace-Bce7Qq0s.js","assets/AgentWorkspace-DGEWNErN.js","assets/AssetsWorkspace-feT-v8BY.js","assets/KeyingPanel-DWaV9fRG.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-woj0orEW.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-C7SABT2o.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as gn,i as ue,c as et,r as Bi,g as he,a as ou,b as su,L as Nt,z as au,d as iu,e as lu,k as cu,f as g,s as du,l as uu,j as s,h as mu,B as Kr,_ as Le}from"./index-CJ-sBrSx.js";const ya=e=>{let t;const n=new Set,r=(d,m)=>{const u=typeof d=="function"?d(t):d;if(!Object.is(u,t)){const p=t;t=m??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(h=>h(t,p))}},o=()=>t,l={setState:r,getState:o,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,o,l);return l},pu=(e=>e?ya(e):ya),fu=e=>e;function hu(e,t=fu){const n=gn.useSyncExternalStore(e.subscribe,gn.useCallback(()=>t(e.getState()),[e,t]),gn.useCallback(()=>t(e.getInitialState()),[e,t]));return gn.useDebugValue(n),n}const va=e=>{const t=pu(e),n=r=>hu(t,r);return Object.assign(n,t),n},Wi=(e=>e?va(e):va);async function Se(e,t){const n=he();let r=!1;try{if(typeof window<"u"){const a=new URL(e,window.location.href);r=a.origin===window.location.origin&&/^\/(api|generated)(?:\/|$)/i.test(a.pathname)}}catch{}if(r&&t?.signal?.throwIfAborted(),r&&ue())throw et(n-1);const o=await fetch(e,t);if(r&&o.status===401){const i=await o.clone().json().catch(()=>null);if(i?.error?.code==="LAN_TOKEN_REQUIRED"||i?.code==="LAN_TOKEN_REQUIRED"){Bi(n);try{await o.body?.cancel()}catch{}throw et(n)}}return o}async function $(e,t){const n=await Se(e,t),r=await n.json().catch(()=>({}));if(!n.ok){const o=r.error,a=r.code,i=typeof o=="string"?o:o?.message??`Request failed: ${n.status}`,l=r,c=typeof l.error=="object"&&l.error?l.error:void 0,d=new Error(i);d.status=n.status,c?.code?d.code=c.code:a&&(d.code=a);const m=c?.rawCode??l.rawCode,u=c?.errorClass??l.errorClass;throw typeof m=="string"&&(d.rawCode=m),typeof u=="string"&&(d.errorClass=u),typeof r.currentVersion=="number"&&(d.currentVersion=r.currentVersion),d}return r}async function Ji(e,t){t?.throwIfAborted();const n=await Se(e,{method:"GET",signal:t});if(!n.ok){try{await n.body?.cancel()}catch{}const o=new Error(`Request failed: ${n.status}`);throw o.status=n.status,o}t?.throwIfAborted();const r=await n.json();return t?.throwIfAborted(),r}let dn=null;function Yi(){if(!dn){const e=localStorage.getItem("ima2.browserId");e?dn=e:(dn=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",dn))}return dn}function Zt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Yi()};return $(e,{...t,headers:n})}function Xi(){return $("/api/capabilities")}function Zi(e){const t=new URLSearchParams;e?.kind&&t.set("kind",e.kind),e?.sessionId&&t.set("sessionId",e.sessionId),e?.includeTerminal&&t.set("includeTerminal","1");const n=t.size>0?`?${t.toString()}`:"";return $(`/api/inflight${n}`)}function Ae(e){return $(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function gu(){return $("/api/oauth/status")}function yu(){return $("/api/billing")}const vu=5400*1e3,bu=2e3,ba=3e4;let fe=null,Er="";const Ko=new Set,Bo=new Set;let Wo=null,Ze=null,xa=!1,vr=0,Nr=0,Sa=!1;const xu=3;let fs=null;const Su=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function Iu(){return Er?`/api/events?lastEventId=${encodeURIComponent(Er)}`:"/api/events"}function wu(){Nr+=1;const e=fe;fe=null,e?.close(),Ze&&(clearTimeout(Ze),Ze=null)}function _u(){Sa||typeof window>"u"||(window.addEventListener(Nt,wu),Sa=!0)}function Ia(e,t){if(e!==Nr||t!==he()||ue()||fe)return;const n=Math.min(bu*Math.pow(1.5,vr),ba),r=Math.min(n*(.8+Math.random()*.4),ba);vr+=1,Ze=setTimeout(hs,r),fs?.(vr>=xu?"failed":"reconnecting")}function hs(){if(_u(),ue()||fe&&fe.readyState!==EventSource.CLOSED)return;Nr+=1;const e=new EventSource(Iu());fe=e,Ze&&(clearTimeout(Ze),Ze=null),e.onopen=()=>{if(fe!==e)return;Ze&&(clearTimeout(Ze),Ze=null),vr=0;const t=xa;xa=!0,t&&Wo?.(),fe===e&&fs?.("connected")};for(const t of Su)e.addEventListener(t,n=>{fe!==e||typeof n.data!="string"||Eu(t,n)});e.addEventListener("update",t=>{if(fe!==e||typeof t.data!="string")return;let n;try{n=JSON.parse(t.data)}catch{return}if(!(n===null||typeof n!="object"||Array.isArray(n)))for(const r of Bo)r(n)}),e.addEventListener("replay-gap",()=>{fe===e&&(Er="",Wo?.())}),e.onerror=t=>{if(fe!==e||typeof t.data=="string")return;fe=null,e.close();const n=++Nr,r=he();if(ou()?.mode==="lan"){const o=()=>Ia(n,r);su().then(o,o)}else Ia(n,r)}}function Eu(e,t){t.lastEventId&&(Er=t.lastEventId);let n;try{n=JSON.parse(t.data)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;const r=n,o=r.jobId??r.requestId;if(!(typeof o!="string"||!o))for(const a of Ko)a.jobId===o&&(a.event!==null&&a.event!==e||a.handler(e,r))}function Tt(e,t,n){const r={jobId:e,event:t,handler:n};return Ko.add(r),(!fe||fe.readyState===EventSource.CLOSED)&&hs(),()=>{Ko.delete(r)}}function Nu(e){return Bo.add(e),()=>{Bo.delete(e)}}function Qt(e,t=vu){const n=setTimeout(e,t);return()=>clearTimeout(n)}function wa(e){Wo=e}function _a(e){fs=e}function Pt(){(!fe||fe.readyState===EventSource.CLOSED)&&hs()}function Br(e=1e4){const t=he();return ue()?Promise.reject(et(t-1)):(Pt(),fe&&fe.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const o=Date.now(),a=()=>{if(t!==he()||ue()){r(et(t));return}if(fe&&fe.readyState===EventSource.OPEN){n();return}if(Date.now()-o>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const ku=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],ju={AUTH_INVALID:{surface:"card",cardKey:"errorCard.authClass",cta:"reauth"},AUTH_EXPIRED:{surface:"card",cardKey:"errorCard.authClass",cta:"reauth"},BILLING_REQUIRED:{surface:"card",cardKey:"errorCard.billingRequired"},RATE_LIMITED:{surface:"toast",toastKey:"toast.errorClass.rateLimited",cta:"retry"},PROVIDER_TIMEOUT:{surface:"toast",toastKey:"toast.errorClass.providerTimeout",cta:"retry"},NETWORK_FAILURE:{surface:"toast",toastKey:"toast.errorClass.networkFailure",cta:"retry"},CONTENT_REJECTED:{surface:"toast",toastKey:"toast.errorClass.contentRejected"},CAPABILITY_UNSUPPORTED:{surface:"toast",toastKey:"toast.errorClass.capabilityUnsupported"},MODEL_UNAVAILABLE:{surface:"toast",toastKey:"toast.errorClass.modelUnavailable"},INTERNAL_STATE_ERROR:{surface:"toast",toastKey:"toast.errorClass.internalState",cta:"reload"}};function Cu(e){return typeof e=="string"&&ku.includes(e)}function Ea(e){if(typeof e=="string")return ju[e]}const Qi="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Xe={LAN_TOKEN_REQUIRED:{surface:"toast"},REF_TOO_LARGE:{surface:"toast",toastKey:"toast.refTooLarge"},REF_NOT_BASE64:{surface:"toast",toastKey:"toast.refNotBase64"},REF_EMPTY:{surface:"toast",toastKey:"toast.refEmpty"},REF_TOO_MANY:{surface:"toast",toastKey:"toast.refLimitExceeded"},MINIMAX_MODEL_REQUIRES_REFERENCE:{surface:"toast",toastKey:"toast.minimaxModelRequiresReference"},NAI_REF_UNSUPPORTED:{surface:"toast",toastKey:"toast.naiRefUnsupported"},NAI_EDIT_UNSUPPORTED:{surface:"toast",toastKey:"toast.naiEditUnsupported"},NAI_API_KEY_MISSING:{surface:"card",cardKey:"errorCard.naiApiKeyMissing",cta:"reauth"},GROK_API_KEY_MISSING:{surface:"card",cardKey:"errorCard.grokApiKeyMissing",cta:"reauth"},NAI_AUTH_FAILED:{surface:"card",cardKey:"errorCard.naiAuthFailed",cta:"reauth"},NAI_SUBSCRIPTION_REQUIRED:{surface:"card",cardKey:"errorCard.naiSubscriptionRequired",cta:"dismiss"},NAI_USAGE_EXHAUSTED:{surface:"card",cardKey:"errorCard.naiUsageExhausted",cta:"dismiss"},NAI_RATE_LIMITED:{surface:"toast",toastKey:"toast.naiRateLimited",cta:"retry"},NAI_BAD_REQUEST:{surface:"toast",toastKey:"toast.naiBadRequest"},NAI_ZIP_INVALID:{surface:"card",cardKey:"errorCard.naiZipInvalid",cta:"retry"},NAI_ZIP_UNSUPPORTED:{surface:"card",cardKey:"errorCard.naiZipInvalid",cta:"retry"},NAI_ZIP_TOO_LARGE:{surface:"card",cardKey:"errorCard.naiZipInvalid",cta:"retry"},NAI_RESPONSE_NOT_ZIP:{surface:"card",cardKey:"errorCard.naiResponseNotZip",cta:"retry"},NAI_IMAGE_INVALID:{surface:"card",cardKey:"errorCard.naiImageInvalid",cta:"retry"},NAI_EMPTY_IMAGE:{surface:"card",cardKey:"errorCard.naiImageInvalid",cta:"retry"},NAI_MASK_UNSUPPORTED:{surface:"toast",toastKey:"toast.naiMaskUnsupported"},NAI_UPSTREAM_ERROR:{surface:"card",cardKey:"errorCard.naiUpstreamError",cta:"retry"},MODERATION_REFUSED:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},SAFETY_REFUSAL:{surface:"card",cardKey:"errorCard.moderationRefused",cta:"dismiss"},EMPTY_RESPONSE:{surface:"card",cardKey:"errorCard.emptyResponse",cta:"dismiss"},STREAM_PARSE_FAILED:{surface:"card",cardKey:"errorCard.streamParseFailed",cta:"retry"},IMAGE_TOOL_NOT_CALLED:{surface:"card",cardKey:"errorCard.imageToolNotCalled",cta:"retry"},WEB_SEARCH_ONLY_RESPONSE:{surface:"card",cardKey:"errorCard.webSearchOnlyResponse",cta:"retry"},IMAGE_TOOL_FAILED:{surface:"card",cardKey:"errorCard.imageToolFailed",cta:"retry"},IMAGE_TOOL_COMPLETED_WITHOUT_RESULT:{surface:"card",cardKey:"errorCard.imageToolNoResult",cta:"retry"},PROVIDER_EMPTY_IMAGE:{surface:"card",cardKey:"errorCard.providerEmptyImage",cta:"retry"},OAUTH_IMAGE_CAPABILITY_UNAVAILABLE:{surface:"card",cardKey:"errorCard.oauthImageCapabilityUnavailable",cta:"dismiss"},RESPONSES_STREAM_ERROR:{surface:"card",cardKey:"errorCard.responsesStreamError",cta:"retry"},UPSTREAM_5XX:{surface:"card",cardKey:"errorCard.upstream5xx",cta:"retry"},AUTH_CHATGPT_EXPIRED:{surface:"card",cardKey:"errorCard.authChatgptExpired",cta:"reauth"},AUTH_API_KEY_INVALID:{surface:"card",cardKey:"errorCard.authApiKeyInvalid",cta:"dismiss"},NETWORK_FAILED:{surface:"card",cardKey:"errorCard.networkFailed",cta:"reload"},OAUTH_UNAVAILABLE:{surface:"card",cardKey:"errorCard.oauthUnavailable",cta:"reload"},INVALID_REQUEST:{surface:"card",cardKey:"errorCard.invalidRequest",cta:"dismiss"},INVALID_MODERATION:{surface:"toast",toastKey:"toast.generateFailed"},APIKEY_DISABLED:{surface:"card",cardKey:"errorCard.apikeyDisabled",cta:"dismiss"},AGY_GENERATION_FAILED:{surface:"card",cardKey:"errorCard.agyGenerationFailed",cta:"retry"},AGY_TIMEOUT:{surface:"card",cardKey:"errorCard.agyTimeout",cta:"retry"},JOB_TRACKING_TIMEOUT:{surface:"toast",toastKey:"toast.jobTrackingTimeout"},AGY_PROCESS_ERROR:{surface:"card",cardKey:"errorCard.agyProcessError",cta:"retry"},AGY_QUOTA_EXHAUSTED:{surface:"card",cardKey:"errorCard.agyQuotaExhausted",cta:"dismiss"},AGY_PARSE_FAILED:{surface:"card",cardKey:"errorCard.agyProcessError",cta:"retry"},AGY_ARTIFACT_NOT_FOUND:{surface:"card",cardKey:"errorCard.agyProcessError",cta:"retry"},DB_ERROR:{surface:"toast",toastKey:"toast.generateFailed"},UNKNOWN:{surface:"toast",toastKey:"toast.generateFailed"}};function Na(e){const t=(e||"").toLowerCase();return t?t.includes("moderation_blocked")||t.includes("moderation refused")?"MODERATION_REFUSED":t.includes("no image data returned")?"EMPTY_RESPONSE":t.includes("stream could not be parsed")?"STREAM_PARSE_FAILED":t.includes("web search but not the image tool")?"WEB_SEARCH_ONLY_RESPONSE":t.includes("without calling the image tool")?"IMAGE_TOOL_NOT_CALLED":t.includes("image tool call failed")?"IMAGE_TOOL_FAILED":t.includes("image tool completed without image data")?"IMAGE_TOOL_COMPLETED_WITHOUT_RESULT":t.includes("token is expired")||t.includes("sign in again")||t.includes("access token")&&t.includes("expired")||t.includes("token")&&t.includes("expired")&&!t.includes("api key")?"AUTH_CHATGPT_EXPIRED":t.includes("incorrect api key")||t.includes("invalid authentication")||t.includes("exceeded your current quota")||t.includes("incorrect organization")?"AUTH_API_KEY_INVALID":t.includes("failed to fetch")||t.includes("econnrefused")||t.includes("econnreset")||t.includes("enotfound")||t.includes("etimedout")||t.includes("network error")?"NETWORK_FAILED":t.includes("oauth")&&(t.includes("not running")||t.includes("unavailable")||t.includes("not ready"))?"OAUTH_UNAVAILABLE":t.includes("invalid_request_error")||t.includes("invalid_value")||t.includes("invalid size")||t.includes("invalid request")||t.includes("requested resolution")||t.includes("minimum pixel budget")||t.includes("unsupported value")?"INVALID_REQUEST":t.includes("resource exhausted")||t.includes("exhausted your capacity")||t.includes("quota will reset")?"AGY_QUOTA_EXHAUSTED":t.includes("agy generation timed out")?"AGY_TIMEOUT":t.includes("agy generation failed")?"AGY_GENERATION_FAILED":t.includes("agy process error")||t.includes("agy exited")?"AGY_PROCESS_ERROR":t.includes("agy artifact not found")?"AGY_ARTIFACT_NOT_FOUND":t.includes("could not parse artifact path from agy")?"AGY_PARSE_FAILED":t.includes("an error occurred while processing")||/\b5\d\d\b/.test(t)?"UPSTREAM_5XX":"UNKNOWN":"UNKNOWN"}const Au=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function Tu(e){const t=(e||"").toLowerCase();return t.includes("request was rejected")||t.includes("prompt was rejected")?"input":t.includes("image was filtered")||t.includes("generated image")?"output":"unknown"}function at(e){const t=e,n=t&&typeof t=="object"?t:{},r=typeof n.message=="string"?n.message:String(e??""),o=typeof n.code=="string"?n.code:"";if(o==="LAN_TOKEN_REQUIRED")return{code:"LAN_TOKEN_REQUIRED",spec:Xe.LAN_TOKEN_REQUIRED,message:et().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=o&&o in Xe?o:a&&a in Xe?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Xe.JOB_TRACKING_TIMEOUT,message:Qi};const c=Cu(i)?Ea(i):void 0,d=l?Au.includes(l):!1,m=Ea(i);let u,p;c&&!d?(u=l??"UNKNOWN",p=c):d&&l||l?(u=l,p=Xe[l]):m?(u=Na(r),p=m):(u=Na(r),p=Xe[u]??Xe.UNKNOWN);const h=u==="MODERATION_REFUSED"||u==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||Tu(r):void 0;return{code:u,spec:p,message:r,...a?{rawCode:a}:o&&!l?{rawCode:o}:{},...i&&(c||m)?{errorClass:i}:{},...h?{moderationStage:h}:{}}}function Pu(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function nt(e,t="Generation failed"){const n=e.error;let r=t,o,a,i,l;const c=Pu(e);if(c&&c.terminal===!0&&(typeof c.phase=="string"&&(l=c.phase),c.error&&typeof c.error=="object"&&(typeof c.error.code=="string"&&(o=c.error.code),typeof c.error.message=="string"&&c.error.message&&(r=c.error.message))),typeof n=="string")r===t&&(r=n);else if(n&&typeof n=="object"){const p=n;typeof p.message=="string"&&p.message&&r===t&&(r=p.message),typeof p.code=="string"&&(o=o??p.code),typeof p.rawCode=="string"&&(a=p.rawCode),typeof p.errorClass=="string"&&(i=p.errorClass)}typeof e.code=="string"&&(o=o??e.code),typeof e.rawCode=="string"&&(a=a??e.rawCode),typeof e.errorClass=="string"&&(i=i??e.errorClass);let d=typeof e.status=="number"?e.status:void 0;const m=at({code:o,rawCode:a,message:r,errorClass:i});m.code==="JOB_TRACKING_TIMEOUT"&&(o=m.code,r=m.message,d=504,l="timed_out",a=void 0,i=void 0);const u=new Error(r);return u.code=o,u.status=d,a&&(u.rawCode=a),i&&(u.errorClass=i),l&&(u.phase=l),u}const ka=5e3,ja=3e4;function Ru(e){if(!e)return ka;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(ja,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(ja,Math.max(1e3,n-Date.now())):ka}function Mu(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function ho(){return new DOMException("Aborted","AbortError")}function Wr(...e){const t=e.filter(o=>!!o);if(t.length===0)return;if(t.length===1)return t[0];if(typeof AbortSignal.any=="function")return AbortSignal.any(t);const n=new AbortController,r=()=>{for(const o of t)o.removeEventListener("abort",r);n.abort()};return t.some(o=>o.aborted)?r():t.forEach(o=>o.addEventListener("abort",r,{once:!0})),n.signal}async function Jr({url:e,payload:t,requestId:n,signal:r,parseError:o}){const a=he();let i=null;const l=c=>new Promise((d,m)=>{if(r?.aborted){m(ho());return}const u=()=>{i&&(clearTimeout(i),i=null),m(ho())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",u),d()},c),r?.addEventListener("abort",u,{once:!0})});for(;;){if(r?.aborted)throw ho();if(a!==he())throw et(a);if(ue())throw et(a-1);const c=await Se(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,async:!0,requestId:n}),signal:r});if(c.ok)return;const d=await c.json().catch(()=>({}));if(Mu(c,d)){await l(Ru(c.headers.get("Retry-After")));continue}throw o(c,d)}}async function el(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return Pt(),new Promise((r,o)=>{let a=!1;const i=new AbortController,l=Wr(t.signal,i.signal),c=u=>{a||(a=!0,m(),d(),u())},d=Tt(n,null,(u,p)=>{a||(u==="done"?c(()=>r(p)):u==="error"&&c(()=>o(nt(p,"Generation failed"))))}),m=Qt(()=>{c(()=>{i.abort(),Ae(n),o(new Error("Generation stream timed out"))})});if(t.signal){if(t.signal.aborted){c(()=>{i.abort(),Ae(n),o(new DOMException("Aborted","AbortError"))});return}t.signal.addEventListener("abort",()=>{c(()=>{i.abort(),Ae(n),o(new DOMException("Aborted","AbortError"))})},{once:!0})}Jr({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(u,p)=>{const h=nt(p,`Request failed: ${u.status}`);return h.status=h.status??u.status,h}}).then(()=>{}).catch(u=>{c(()=>o(u instanceof Error?u:new Error(String(u))))})})}async function Lu(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return Pt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Wr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Tt(r,null,(p,h)=>{i||(p==="partial"?t.onPartial?.(h):p==="image"?t.onImage?.(h):p==="phase"?t.onPhase?.(h):p==="done"?d(()=>o(h)):p==="error"&&d(()=>a(nt(h,"Multimode generation failed"))))}),u=Qt(()=>{d(()=>{l.abort(),Ae(r),a(new Error("Multimode generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}Jr({url:"/api/generate/multimode",payload:e,requestId:r,signal:c,parseError:(p,h)=>{const x=new Error(h.error??`Request failed: ${p.status}`);return x.code=h.code,x.status=h.status??p.status,x}}).then(()=>{}).catch(p=>{d(()=>a(p instanceof Error?p:new Error(String(p))))})})}function M_(e){return $("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Ou(e){const t=await e.arrayBuffer(),n=await Se("/api/history/import-local",{method:"POST",headers:{"Content-Type":e.type||"image/png","X-Ima2-Original-Filename":encodeURIComponent(e.name)},body:t});if(!n.ok){let o={};try{o=await n.json()}catch{}const a=new Error(o.error||`Import failed (${n.status})`);throw a.code=o.code||"IMPORT_FAILED",a}return(await n.json()).item}function L_(e){return $("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function O_(){return $("/api/prompt-builder/config")}function F_(e){return $("/api/prompt-builder/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function gs(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return Pt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Wr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Tt(r,null,(p,h)=>{i||(p==="planning"?t.onPlanning?.():p==="submitted"?t.onSubmitted?.(h):p==="progress"?t.onProgress?.(h):p==="done"?d(()=>o(h)):p==="error"&&d(()=>a(nt(h,"Video generation failed"))))}),u=Qt(()=>{d(()=>{l.abort(),Ae(r),a(new Error("Video generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}Jr({url:"/api/video/generate",payload:{provider:"grok",...e},requestId:r,signal:c,parseError:(p,h)=>{const x=new Error(h.error??`Request failed: ${p.status}`);return x.code=h.code,x.status=h.status??p.status,x}}).then(()=>{}).catch(p=>{d(()=>a(p instanceof Error?p:new Error(String(p))))})})}function en(e={}){const t=new URLSearchParams;return t.set("limit",String(e.limit??50)),e.since!=null&&t.set("since",String(e.since)),e.cursor&&(t.set("before",String(e.cursor.before)),t.set("beforeFilename",e.cursor.beforeFilename)),e.sessionId&&t.set("sessionId",e.sessionId),e.favoritesOnly&&t.set("favoritesOnly","1"),Zt(`/api/history?${t.toString()}`)}function Fu(e={}){const t=new URLSearchParams;return t.set("groupBy","session"),t.set("limit",String(e.limit??200)),e.cursor&&(t.set("before",String(e.cursor.before)),t.set("beforeFilename",e.cursor.beforeFilename)),e.sessionId&&t.set("sessionId",e.sessionId),Zt(`/api/history?${t.toString()}`)}function Du(e){return Zt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function Gu(){return(await $("/api/storage/status")).data}function zu(){return $("/api/storage/open-generated-dir",{method:"POST"})}function tl(e){return $(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function Uu(e){return $(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function $u(e,t){return $(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function qu(e){return $("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function Hu(){return $("/api/sessions")}function Vu(e){return $("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function nl(e){return $(`/api/sessions/${encodeURIComponent(e)}`)}function Ku(e,t){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function Bu(e){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function Wu(e,t,n,r,o={}){const a={"Content-Type":"application/json","If-Match":String(t)};return o.saveId&&(a["X-Ima2-Graph-Save-Id"]=o.saveId),o.saveReason&&(a["X-Ima2-Graph-Save-Reason"]=o.saveReason),o.tabId&&(a["X-Ima2-Tab-Id"]=o.tabId),$(`/api/sessions/${encodeURIComponent(e)}/graph`,{method:"PUT",headers:a,body:JSON.stringify({nodes:n,edges:r})})}function Ju(e){return $("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function D_(e){return Zt(`/api/annotations/${encodeURIComponent(e)}`)}async function G_(e,t){await Zt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function z_(e){await Zt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function U_(e){const t=new URLSearchParams({sourceFilename:e.sourceFilename});return $(`/api/canvas-versions?${t.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e.image})}function $_(e,t){const n=new URLSearchParams;t.sourceFilename&&n.set("sourceFilename",t.sourceFilename);const r=n.size>0?`?${n.toString()}`:"";return $(`/api/canvas-versions/${encodeURIComponent(e)}${r}`,{method:"PUT",headers:{"Content-Type":"image/png",...t.pixelEdited?{"X-Ima2-Canvas-Pixel-Edited":"true"}:{}},body:t.image})}function q_(e,t,n){return $(`/api/canvas-versions/${encodeURIComponent(e)}/annotation-bake`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshot:t,annotationOnly:n})})}function H_(e){return $(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function Yu(e){const t=new URLSearchParams;return $(`/api/prompts?${t.toString()}`)}function Xu(e){return $("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Zu(e){return $(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function Qu(e){return $(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function em(e){return $("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function V_(e){return $("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function K_(e){return $("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function B_(){return $("/api/prompts/import/curated-sources")}function W_(e){return $("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function J_(e){return $("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Y_(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return $(`/api/prompts/import/discovery${n}`)}function X_(e){return $("/api/prompts/import/discovery-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({q:e.q,seeds:e.seeds,limit:e.limit})})}function Z_(e){return $("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Q_(e){return $("/api/prompts/import/folder-files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input}})})}function e0(e){return $("/api/prompts/import/folder-preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input},paths:e.paths})})}function ys(e){const t=new URLSearchParams;e.kind&&t.set("kind",e.kind),e.folderId&&t.set("folderId",e.folderId),e.tag&&t.set("tag",e.tag),e.q&&t.set("q",e.q),e.filePath&&t.set("filePath",e.filePath),e.cursor&&t.set("cursor",e.cursor),e.limit&&t.set("limit",String(e.limit));const n=t.toString();return $(`/api/assets${n?`?${n}`:""}`)}function tm(e){return $(`/api/assets/${encodeURIComponent(e)}`)}function Yr(e){return $("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function t0(e){return $("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function rl(e,t){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function n0(e,t){const n=new URLSearchParams;n.set("source",t.source),n.set("kind","keyed-png"),t.projectId&&n.set("projectId",t.projectId),t.name&&n.set("name",t.name),t.meta&&n.set("meta",JSON.stringify(t.meta));const r=await Se(`/api/assets/derived?${n.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e});if(!r.ok){const o=await r.json().catch(()=>({}));throw new Error(o.error||`derived upload failed (${r.status})`)}return r.json()}async function nm(e){const t=new URLSearchParams;t.set("source",e.source),t.set("kind","vector-svg"),e.preset&&t.set("preset",e.preset),e.colorPrecision!==void 0&&t.set("colorPrecision",String(e.colorPrecision)),e.filterSpeckle!==void 0&&t.set("filterSpeckle",String(e.filterSpeckle)),e.cornerThreshold!==void 0&&t.set("cornerThreshold",String(e.cornerThreshold)),e.projectId&&t.set("projectId",e.projectId),e.name&&t.set("name",e.name);const n=await Se(`/api/assets/derived?${t.toString()}`,{method:"POST",signal:e.signal});if(!n.ok){const r=await n.json().catch(()=>({}));throw new Error(r.error||`vectorize failed (${n.status})`)}return n.json()}function r0(e){return $("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function rm(e){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function vs(){return $("/api/assets/folders")}function om(e){return $("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ol(e,t){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function sm(e){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function bs(){return $("/api/assets/tags")}function o0(){return $("/api/assets/all",{method:"DELETE"})}async function am(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return Pt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Wr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Tt(r,null,(p,h)=>{i||(p==="partial"?t.onPartial?.(h):p==="phase"?t.onPhase?.(h):p==="done"?d(()=>o(h)):p==="error"&&d(()=>a(nt(h,"Node generation failed"))))}),u=Qt(()=>{d(()=>{l.abort(),Ae(r),a(new Error("Node generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ae(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}Jr({url:"/api/node/generate",payload:e,requestId:r,signal:c,parseError:(p,h)=>{const x=h?.error?.message??`Request failed: ${p.status}`,S=new Error(x);return S.code=h?.error?.code,S.status=h?.status??p.status,S}}).then(()=>{}).catch(p=>{d(()=>a(p instanceof Error?p:new Error(String(p))))})})}const xs=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],im=new Set(xs);function Rt(e){return typeof e=="string"&&im.has(e)}const Mt={oauth:{image:["gpt-6-luna","gpt-6-sol","gpt-6-astra"],video:[]},api:{image:["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-6-astra"],video:[]},grok:{image:["grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality"],video:["grok-imagine-video","grok-imagine-video-1.5","grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]},"grok-api":{image:["grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality"],video:["grok-imagine-video","grok-imagine-video-1.5","grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]},agy:{image:["nano-banana-2","nano-banana-pro"],video:[]},"gemini-api":{image:["nano-banana-2","nano-banana-pro"],video:[]},atlascloud:{image:["openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit"],video:[]},minimax:{image:["image-01","image-01-live"],video:[]},nai:{image:["nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],video:[]},comfy:{image:[],video:[]}},lm=["gpt-6-luna","gpt-6-sol","gpt-6-astra","gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality","nano-banana-2","nano-banana-pro","openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit","image-01","image-01-live","nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],sl={oauth:{},api:{},grok:{image:5,edit:5,video:14},"grok-api":{image:5,edit:5,video:14},agy:{image:3,edit:3},"gemini-api":{image:3,edit:3},atlascloud:{image:10,edit:10},minimax:{image:1,edit:1},nai:{},comfy:{image:4,edit:4}},Ss={oauth:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!0,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},api:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!0,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!0,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!0,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},grok:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"}},"grok-api":{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"}},agy:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},"gemini-api":{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},atlascloud:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},minimax:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},nai:{generate:{supported:!0,references:!1,mask:!1,streaming:!1,catalogAccess:"static"},edit:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"},multimode:{supported:!0,references:!1,mask:!1,streaming:!1,catalogAccess:"static"},node:{supported:!0,references:!1,mask:!1,streaming:!1,catalogAccess:"static"},video:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"static"}},comfy:{generate:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"runtime"},edit:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"runtime"},multimode:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"runtime"},node:{supported:!1,references:!1,mask:!1,streaming:!1,catalogAccess:"runtime"},video:{supported:!0,references:!0,mask:!1,streaming:!1,catalogAccess:"runtime"}}},al=[{value:"gpt-image-2.5-sunburst",label:"GPT Image2.5 Sunburst"},{value:"gpt-image-2.5-flare",label:"GPT Image2.5 Flare"}];function Is(e){return al.some(t=>t.value===e)}function Lt(e,t,n){return(n==="xhigh"||n==="max")&&(e!=="api"||!Is(t))?"medium":n}const kr="gpt-6-luna",Ke=[{value:"gpt-6-luna",shortLabel:"6l",fullLabelKey:"settings.imageModel.gpt6Luna"},{value:"gpt-6-sol",shortLabel:"6s",fullLabelKey:"settings.imageModel.gpt6Sol"},{value:"gpt-6-astra",shortLabel:"6a",fullLabelKey:"settings.imageModel.gpt6Astra"},{value:"gpt-5.6-luna",shortLabel:"5.6l",fullLabelKey:"settings.imageModel.gpt56Luna",providerHint:"api"},{value:"gpt-5.6-terra",shortLabel:"5.6t",fullLabelKey:"settings.imageModel.gpt56Terra",providerHint:"api"},{value:"gpt-5.6-sol",shortLabel:"5.6s",fullLabelKey:"settings.imageModel.gpt56Sol",providerHint:"api"},{value:"gpt-5.5",shortLabel:"5.5",fullLabelKey:"settings.imageModel.gpt55",providerHint:"api"},{value:"gpt-5.4",shortLabel:"5.4",fullLabelKey:"settings.imageModel.gpt54",providerHint:"api"},{value:"gpt-5.4-mini",shortLabel:"5.4m",fullLabelKey:"settings.imageModel.gpt54Mini",providerHint:"api"},{value:"grok-imagine-image-2.0",shortLabel:"grok2",fullLabelKey:"settings.imageModel.grokImagine20"},{value:"grok-imagine-image-quality",shortLabel:"grok+",fullLabelKey:"settings.imageModel.grokImagineQuality"},{value:"grok-imagine-image",shortLabel:"grok",fullLabelKey:"settings.imageModel.grokImagine"},{value:"nano-banana-2",shortLabel:"nb2 agy",fullLabelKey:"settings.imageModel.nanoBanana2",providerHint:"agy"},{value:"nano-banana-2",shortLabel:"nb2 api",fullLabelKey:"settings.imageModel.nanoBanana2Api",providerHint:"gemini-api"},{value:"nano-banana-pro",shortLabel:"nbp agy",fullLabelKey:"settings.imageModel.nanoBananaPro",providerHint:"agy"},{value:"nano-banana-pro",shortLabel:"nbp api",fullLabelKey:"settings.imageModel.nanoBananaPro",providerHint:"gemini-api"},{value:"openai/gpt-image-2/text-to-image",shortLabel:"atlas",fullLabelKey:"settings.imageModel.atlasCloudGptImage2",providerHint:"atlascloud"},{value:"openai/gpt-image-2/edit",shortLabel:"atlas edit",fullLabelKey:"settings.imageModel.atlasCloudGptImage2Edit",providerHint:"atlascloud"},{value:"image-01",shortLabel:"minimax",fullLabelKey:"settings.imageModel.minimaxImage01",providerHint:"minimax"},{value:"image-01-live",shortLabel:"minimax live",fullLabelKey:"settings.imageModel.minimaxImage01Live",providerHint:"minimax"},{value:"nai-diffusion-5-full",shortLabel:"nai v5",fullLabelKey:"settings.imageModel.naiDiffusion5Full",providerHint:"nai"},{value:"nai-diffusion-5-curated",shortLabel:"nai v5 cur",fullLabelKey:"settings.imageModel.naiDiffusion5Curated",providerHint:"nai"},{value:"nai-diffusion-4-5-full",shortLabel:"nai v4.5",fullLabelKey:"settings.imageModel.naiDiffusion45Full",providerHint:"nai"},{value:"nai-diffusion-4-5-curated",shortLabel:"nai v4.5 cur",fullLabelKey:"settings.imageModel.naiDiffusion45Curated",providerHint:"nai"}],ws=new Set(Mt["gemini-api"].image),il=new Set(Mt.atlascloud.image),ll=new Set(Mt.minimax.image),cl=new Set(Mt.nai.image),cm=new Set(Mt.oauth.image),dm=new Set(Mt.api.image),dl=Ke.filter(e=>cm.has(e.value)),um=["gpt-5.6-luna","gpt-6-astra","gpt-5.6-terra","gpt-5.6-sol","gpt-5.5","gpt-5.4","gpt-5.4-mini"],mm=um.map(e=>Ke.find(t=>t.value===e)).filter(e=>e!==void 0&&dm.has(e.value)),s0=dl,ul=Ke.filter(e=>e.value.startsWith("grok-")),pm=Ke.filter(e=>ws.has(e.value)),fm=Ke.filter(e=>il.has(e.value)),hm=Ke.filter(e=>ll.has(e.value)),ml=Ke.filter(e=>cl.has(e.value)),a0=[];function gm(e){return Ke.some(t=>t.value===e)}function ym(e){return typeof e=="string"&&e.startsWith("grok-")}function vm(e){return typeof e=="string"&&ws.has(e)}function bm(e){return e==="grok"||e==="grok-api"?ul:e==="agy"||e==="gemini-api"?pm.filter(t=>!t.providerHint||t.providerHint===e):e==="atlascloud"?fm:e==="minimax"?hm:e==="nai"?ml:e==="comfy"?[]:e==="api"?mm:dl}function pl(e,t){return e?ws.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:il.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:ll.has(e)?t==="minimax"?`${e} minimax`:e:cl.has(e)?Ke.find(n=>n.value===e)?.shortLabel??e:Ke.find(n=>n.value===e)?.shortLabel??e:null}const _s="grok-imagine-video",rt="grok-imagine-video-1.5",fl="grok-imagine-video-1.5-preview",hl="grok-imagine-video-1.5-2026-05-30",xm=15,Sm=10,Ca=15,Im=[{value:_s,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:rt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function wm(e){return e===_s||e===rt||e===fl||e===hl}function Ot(e){return wm(e)?e===fl||e===hl?rt:e:!1}function Aa(e,t){if(t!=="reference-to-video")return Ca;const n=Ot(e);return n?n===rt?xm:Sm:Ca}function _m(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function go(e,t,n){return t!=="1080p"?!0:e===rt&&(n==="text-to-video"||n==="image-to-video")}const Wt="comfy-video:",gl="video:";function Em(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Wt}${a}`:o??"":(t==="grok"||t==="grok-api")&&r?`${gl}${r}`:n}const Jo=new Set(lm),Nm={oauth:kr,api:"gpt-5.6-luna",grok:"grok-imagine-image-2.0","grok-api":"grok-imagine-image-2.0",agy:"nano-banana-2","gemini-api":"nano-banana-pro",atlascloud:"openai/gpt-image-2/text-to-image",minimax:"image-01",nai:"nai-diffusion-5-full",comfy:kr},km={"gpt-5.6-sol":"gpt-6-sol","gpt-5.6-luna":"gpt-6-luna","gpt-5.6-terra":"gpt-6-luna","gpt-5.5":"gpt-6-luna","gpt-5.4":"gpt-6-luna","gpt-5.4-mini":"gpt-6-luna"};function Xr(e,t){return typeof t=="string"&&Jo.has(t)&&Mt[e].image.includes(t)}function Sn(e){return typeof e=="string"&&e.trim().length>0?e:null}function yl(e,t){if(Ot(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Xr(n,e))return n;return"oauth"}function dt(e){const t=Rt(e.provider)?e.provider:yl(e.imageModel,e.videoModelSelected);if(t==="comfy"){const r=Sn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Jo.has(e.imageModel)?e.imageModel:kr,videoModelSelected:!1,comfyWorkflow:Sn(e.comfyWorkflow)??(r&&!Jo.has(r)?r:null),comfyVideoWorkflow:Sn(e.comfyVideoWorkflow)}}const n=t==="oauth"&&typeof e.imageModel=="string"?km[e.imageModel]??e.imageModel:e.imageModel;return{provider:t,imageModel:Xr(t,n)?n:Nm[t],videoModelSelected:t==="grok"||t==="grok-api"?Ot(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function jm(e,t){return Rt(e)&&Xr(e,t)?e:yl(t,!1)}function Cm(e,t,n){return e.provider===t?e:dt(n?t==="comfy"?{provider:t,imageModel:e.imageModel,comfyWorkflow:n.image,comfyVideoWorkflow:n.kind==="video"?n.video:null}:{provider:t,imageModel:n.image,videoModelSelected:n.kind==="video"?n.video:!1}:{provider:t,imageModel:e.imageModel})}function Ta(e){return e.provider==="comfy"?{kind:e.comfyVideoWorkflow?"video":"image",...e.comfyWorkflow?{image:e.comfyWorkflow}:{},...e.comfyVideoWorkflow?{video:e.comfyVideoWorkflow}:{}}:{kind:e.videoModelSelected?"video":"image",image:e.imageModel,...e.videoModelSelected?{video:e.videoModelSelected}:{}}}function vl(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Yo(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of xs){if(!Object.hasOwn(e,n))continue;const r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;const o=r;if(o.kind!=="image"&&o.kind!=="video")continue;const a=n==="comfy"?Sn(o.image):Xr(n,o.image)?o.image:null,i=n==="comfy"?Sn(o.video):n==="grok"||n==="grok-api"?Ot(o.video):!1;t[n]={kind:o.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Am="none",Xo=[{value:"none",shortLabel:"off",fullLabelKey:"settings.reasoning.none"},{value:"low",shortLabel:"low",fullLabelKey:"settings.reasoning.low"},{value:"medium",shortLabel:"med",fullLabelKey:"settings.reasoning.medium"},{value:"high",shortLabel:"high",fullLabelKey:"settings.reasoning.high"},{value:"xhigh",shortLabel:"xhigh",fullLabelKey:"settings.reasoning.xhigh"},{value:"max",shortLabel:"max",fullLabelKey:"settings.reasoning.max"}];function bl(e){return Xo.some(t=>t.value===e)}const Tm={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Pm(e){return!bl(e)||e==="none"?null:`R:${Tm[e]}`}const Ne=["ima2.rightPanelOpen","ima2.uiMode","ima2.historyStripLayout","ima2.canvas.exportBackground.v1","ima2.imageModel","ima2.reasoningEffort","ima2.webSearchEnabled","ima2.generationDefaults","ima2.inFlight","ima2.selectedFilename","ima2.activeSessionId","ima2.graphTabId","ima2.galleryScope","ima2.galleryDefaultScope","ima2.locale","ima2.workspaceProfile","ima2.workspaceOverrides","ima2.videoDefaults","ima2.agentPanePreference","ima2.naiOptions","ima2.coreSelectionMemory.v1","ima2.onboardingDismissed"],xl=Ne[0],Sl=Ne[1],Il=Ne[2],wl=Ne[3],Es=Ne[4],_l=Ne[5],El=Ne[6],Ns=Ne[7],Nl=Ne[8],Zo=Ne[9],Qo=Ne[10],Pa=Ne[11],ks=Ne[12],kl=Ne[13],js=Ne[17],jl=Ne[19],Cl=Ne[20],Al=Ne[21],Rm=!0,Mm=!1,tn=!0,Tl=Mm,nn=!0,Lm=24;function es(e){return Math.min(Lm,Math.max(1,Math.trunc(e||1)))}const Ra={ko:cu,en:lu,"zh-Hant":iu,"zh-Hans":au};function Ma(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function Om(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function O(e,t){const n=f.getState().locale;return Pl(n,e,t)}function Pl(e,t,n){const r=Ma(Ra[e],t),o=typeof r=="string"?r:Ma(Ra.en,t),a=typeof o=="string"?o:t;return n?Om(a,n):a}function V(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>Pl(e,t,n)}}function Fm(e){return Math.round(e/16)*16}const _t=16,Cs=3840,yo=655360,br=8294400,Dm=3,qt=3,La=Math.floor(Math.sqrt(br)/_t)*_t,Rl=_t,Gm=Cs,Jn=Dm;function Oa(e){return Math.floor(e/16)*16}function jr(e){return Math.ceil(e/16)*16}function Ue(e){return Math.min(Gm,Math.max(Rl,e))}function ot(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function kt(e,t){e.includes(t)||e.push(t)}function Fa(e,t){const n=Fm(e);return n!==e&&kt(t,"snap"),n}function Da(e,t){return e<Rl&&kt(t,"min"),e>Cs&&kt(t,"maxEdge"),Ue(e)}function Ga(e,t,n){return e>t*Jn?(kt(n,"ratio"),{w:e,h:Ue(jr(e/Jn))}):t>e*Jn?(kt(n,"ratio"),{w:Ue(jr(t/Jn)),h:t}):{w:e,h:t}}function zm(e,t,n){if(e*t<yo){kt(n,"minPixels");const i=Math.sqrt(yo/(e*t));let l=Ue(jr(e*i)),c=Ue(jr(t*i));for(;l*c<yo;)l<=c?l=Ue(l+_t):c=Ue(c+_t);return{w:l,h:c}}if(e*t<=br)return{w:e,h:t};kt(n,"maxPixels");const r=Math.sqrt(br/(e*t));let o=Ue(Oa(e*r)),a=Ue(Oa(t*r));for(;o*a>br;)o>=a?o=Ue(o-_t):a=Ue(a-_t);return{w:o,h:a}}function As(e,t,n,r){const o=[],a=ot(e,n),i=ot(t,r);let l=Da(Fa(a,o),o),c=Da(Fa(i,o),o);return{w:l,h:c}=Ga(l,c,o),{w:l,h:c}=zm(l,c,o),{w:l,h:c}=Ga(l,c,o),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:o}}function Ml(e,t,n,r){const o=As(e,t,n,r);return{w:o.w,h:o.h}}const Um=[{id:"free",label:"Free",w:0,h:0},{id:"1:1",label:"1:1",w:1,h:1},{id:"3:2",label:"3:2",w:3,h:2},{id:"2:3",label:"2:3",w:2,h:3},{id:"16:9",label:"16:9",w:16,h:9},{id:"9:16",label:"9:16",w:9,h:16},{id:"21:9",label:"21:9",w:21,h:9},{id:"9:21",label:"9:21",w:9,h:21}];function $m(e,t){return`${e}x${t}`}function qm(e,t=1024){if(e.id==="free")return null;const n=t,r=e.w>=e.h,o=r?Math.round(n*e.w/e.h):n,a=r?n:Math.round(n*e.h/e.w);return Ml(o,a,o,a)}function Zr(e){const t=Ml(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function Ht(e){return e.slice(0,qt).map(Zr)}function Hm(e,t){const n=Zr(t),r=e.findIndex(o=>o.id===n.id);return r>=0?Ht(e.map((o,a)=>a===r?n:o)):e.length>=qt?Ht(e):Ht([...e,n])}function Vm(e,t,n){const r=Zr({...n,id:t});return Ht(e.map(o=>o.id===t?r:o))}const Km=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],Bm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],Wm=[{value:"1024x1824",label:"1024×1824",sub:"9:16"},{value:"2048x2048",label:"2048×2048",sub:"2K 1:1"},{value:"2048x1152",label:"2048×1152",sub:"2K 16:9"}],Jm=[{value:"1152x2048",label:"1152×2048",sub:"2K 9:16"},{value:"3840x2160",label:"3840×2160",sub:"4K 16:9"},{value:"2160x3840",label:"2160×3840",sub:"4K 9:16"}];function Ym(){return[{value:"auto",label:O("size.autoLabel"),sub:O("size.autoSub")},{value:"custom",label:O("size.customLabel"),sub:O("size.customSub")}]}const Ll=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],Ol=["native","karras","exponential","polyexponential"],Fl=["heavy","light","furryFocus","humanFocus","none"],Dl=["standard","light","none"],Xm={sampler:"k_euler_ancestral",noiseSchedule:"karras",steps:23,scale:5,cfgRescale:0,ucPresetId:"heavy",qualityPresetId:"standard",varietyPlus:!1,straightAlpha:!1,autoSmea:!1,decrisper:!1,seed:null},Cr={min:1,max:50},Ar={min:1,max:10},Tr={min:0,max:1},Gl=2**32-1;function Zm(e,t){return{...Xm,...e??{},...t}}function ts(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Yn(e,t){return typeof e=="string"&&t.includes(e)?e:void 0}function vo(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function zl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Yn(t.sampler,Ll);r!==void 0&&(n.sampler=r);const o=Yn(t.noiseSchedule,Ol);o!==void 0&&(n.noiseSchedule=o);const a=Yn(t.ucPresetId,Fl);a!==void 0&&(n.ucPresetId=a);const i=Yn(t.qualityPresetId,Dl);i!==void 0&&(n.qualityPresetId=i);const l=vo(t.steps,Cr.min,Cr.max);l!==void 0&&(n.steps=l);const c=vo(t.scale,Ar.min,Ar.max);c!==void 0&&(n.scale=c);const d=vo(t.cfgRescale,Tr.min,Tr.max);return d!==void 0&&(n.cfgRescale=d),typeof t.varietyPlus=="boolean"&&(n.varietyPlus=t.varietyPlus),typeof t.straightAlpha=="boolean"&&(n.straightAlpha=t.straightAlpha),typeof t.autoSmea=="boolean"&&(n.autoSmea=t.autoSmea),typeof t.decrisper=="boolean"&&(n.decrisper=t.decrisper),t.seed===null?n.seed=null:typeof t.seed=="number"&&Number.isInteger(t.seed)&&t.seed>=0&&t.seed<=Gl&&(n.seed=t.seed),n}function Be(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const ns="vid:",rs="img:",Qm=/^[\p{L}\p{N}_-]{1,32}$/u;function Ts(e){return Qm.test(e)}function ep(e){return e.references.some(t=>t.tag!==void 0&&!Ts(t.tag))}function Ul(e){return e==="video"?"video":"image"}function Qr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function tp(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function eo(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=Object.entries(e).slice(0,24);return Object.fromEntries(t.filter(([n,r])=>/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(n)&&tp(r)))}function za(e,t){return!(e.type==="number"&&typeof t!="number"||e.type==="boolean"&&typeof t!="boolean"||e.type==="string"&&typeof t!="string"||e.type==="string_array"||e.options&&!e.options.includes(t)||typeof t=="number"&&e.min!==void 0&&t<e.min||typeof t=="number"&&e.max!==void 0&&t>e.max)}function $l(e,t,n){const r=Qr(t),o=eo(n),a={};for(const i of e.parameters){const l=o[i.name];l!==void 0&&za(i,l)?a[i.name]=l:i.default!==void 0&&za(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function np(e){return e?$l(e,null,{}):{ratio:null,parameters:{}}}function rp(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function ql(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.filename!="string"||t.filename.length===0)return null;const n=typeof t.tag=="string"?t.tag.slice(0,128):"",r=typeof t.dataUrl=="string"&&/^data:image\/(?:png|jpeg|webp);base64,/i.test(t.dataUrl)?t.dataUrl:null,o=typeof t.displayName=="string"&&t.displayName?t.displayName.slice(0,180):null;return{filename:t.filename,...n?{tag:n}:{},...r?{dataUrl:r}:{},...o?{displayName:o}:{}}}function Ps(e){if(!e||typeof e!="object")return Be();const t=e,n=Array.isArray(t.references)?t.references.map(ql).filter(r=>!!r):[];return{startFrameFilename:typeof t.startFrameFilename=="string"&&t.startFrameFilename?t.startFrameFilename:null,endFrameFilename:typeof t.endFrameFilename=="string"&&t.endFrameFilename?t.endFrameFilename:null,references:n.filter((r,o)=>n.findIndex(a=>a.filename===r.filename)===o).slice(0,3),referenceVideoFilename:typeof t.referenceVideoFilename=="string"&&t.referenceVideoFilename?t.referenceVideoFilename:null}}function Rs(e,t){const n=Ps(t),r=e.includes("start_image")?n.startFrameFilename:null;return{startFrameFilename:r,endFrameFilename:e.includes("end_image")&&r?n.endFrameFilename:null,references:e.includes("image_references")?n.references:[],referenceVideoFilename:e.includes("video_references")?n.referenceVideoFilename:null}}function Hl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function op(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:Ul(e.mcpMediaKind),ratio:Qr(e.mcpRatio),parameters:eo(e.mcpParameters)}}function Xn(e,t){return`${e==="video"?ns:rs}${t}`}function sp(e){if(e.startsWith(ns)){const t=e.slice(ns.length);return t?{kind:"video",model:t}:null}if(e.startsWith(rs)){const t=e.slice(rs.length);return t?{kind:"image",model:t}:null}return null}function Vl(e){const t=e.normalize("NFKC").replace(/\s+/g,"_").replace(/[^\p{L}\p{N}_-]/gu,"").slice(0,32);return t.length>0?t:null}function ap(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const o=Ul(e.mcpMediaKind),a=Qr(e.mcpRatio),i=eo(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=v=>c===void 0||c.includes(v),m=Ps(e.mcpReferenceSelection),u=l?d("start_image")?m.startFrameFilename:null:o==="video"?e.currentImageFilename??null:null,p=l&&d("image_references")?m.references:[],h=d("image_references")?e.elementReferences??[]:[],x=[...p,...h].map(ql).filter(v=>!!v).filter((v,y,w)=>w.findIndex(I=>I.filename===v.filename)===y).slice(0,3);if(x.some(v=>v.dataUrl||v.tag!==void 0&&!Ts(v.tag)))return null;const S=l&&d("end_image")&&u?m.endFrameFilename:null,b=l&&d("video_references")?m.referenceVideoFilename:null;return{provider:r,kind:o,prompt:t,model:e.mcpModel??void 0,...a?{ratio:a}:{},...Object.keys(i).length>0?{parameters:i}:{},startFrameFilename:u??void 0,...S?{endFrameFilename:S}:{},...x.length>0?{references:x.map(({filename:v,tag:y})=>({filename:v,...y?{tag:y}:{}}))}:{},...b?{referenceVideoFilename:b}:{},...e.mcpCharacterElementId?{characterElementId:e.mcpCharacterElementId}:{},...n?{requestId:n}:{}}}function On(e,t){const n=t.filter(o=>o.placement!=="after"),r=t.filter(o=>o.placement==="after");return[...n.map(o=>o.text.trim()).filter(Boolean),e.trim(),...r.map(o=>o.text.trim()).filter(Boolean)].filter(Boolean).join(`
|
|
3
|
+
|
|
4
|
+
`)}function ip(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.id!="string"||typeof t.name!="string"||typeof t.text!="string"?null:{id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}}function Fn(e){if(!Array.isArray(e))return null;const t=e.map(ip);return t.every(n=>n!==null)?t:null}function Ms(e){return e.map(t=>({id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}))}function lp(e){const t=Fn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function cp(){try{const e=localStorage.getItem(xl);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function dp(){try{const e=localStorage.getItem(Sl);if(e==="agent")return nn?e:"classic";if(e==="card-news")return Tl?e:"classic";if(e==="node")return tn?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function up(){try{const e=localStorage.getItem(Il);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function Ua(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function $a(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(wl);if(!e)return{mode:"alpha",matteColor:"#ffffff"};const t=JSON.parse(e),n=t.mode==="matte"?"matte":"alpha",r=typeof t.matteColor=="string"&&/^#[0-9a-fA-F]{6}$/.test(t.matteColor)?t.matteColor:"#ffffff";return{mode:n,matteColor:r}}catch{return{mode:"alpha",matteColor:"#ffffff"}}}function Kl(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(wl,JSON.stringify({mode:e,matteColor:t}))}catch{}}function Bl(e){try{localStorage.setItem(Es,e)}catch{}}function mp(){try{const e=localStorage.getItem(_l);if(bl(e))return e}catch{}return Am}function pp(e){try{localStorage.setItem(_l,e)}catch{}}function fp(){try{const e=localStorage.getItem(jl);return e?zl(JSON.parse(e)):{}}catch{return{}}}function Wl(e){try{localStorage.setItem(jl,JSON.stringify(e))}catch{}}function hp(){try{const e=localStorage.getItem(El);if(e==="false")return!1;if(e==="true")return!0}catch{}return Rm}function gp(e){try{localStorage.setItem(El,String(e))}catch{}}const qa={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function to(){try{const e=localStorage.getItem(js);if(!e)return qa;const t=JSON.parse(e);return{model:Ot(t.model),duration:typeof t.duration=="number"?t.duration:5,resolution:t.resolution==="480p"||t.resolution==="720p"||t.resolution==="1080p"?t.resolution:"480p",aspectRatio:typeof t.aspectRatio=="string"?t.aspectRatio:"auto",singleRefMode:t.singleRefMode==="reference-to-video"?"reference-to-video":"image-to-video"}}catch{return qa}}function yn(e){try{const t=to();localStorage.setItem(js,JSON.stringify({...t,...e}))}catch{}}function Jl(){try{const e=localStorage.getItem(Zo);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function it(e){try{e?localStorage.setItem(Zo,e):localStorage.removeItem(Zo)}catch{}}function yp(){try{const e=localStorage.getItem(Qo);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function Ls(e){try{e?localStorage.setItem(Qo,e):localStorage.removeItem(Qo)}catch{}}function vp(e,t){return`${e}x${t}`}function En(e){return es(e)}const Yl=new Set(["1024x1024","1536x1024","1024x1536","1360x1024","1024x1360","1824x1024","1024x1824","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840","auto","custom"]);function bp(e){if(typeof e!="string")return{};if(Yl.has(e))return{preset:e};const t=/^(\d+)x(\d+)$/.exec(e);if(!t)return{};const n=Number(t[1]),r=Number(t[2]);return!Number.isFinite(n)||!Number.isFinite(r)?{}:{preset:"custom",w:n,h:r}}function Xl(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"}function Zl(e){return e==="png"||e==="jpeg"||e==="webp"}function Ql(e){return e==="low"||e==="auto"}function xp(e){return Rt(e)}function Sp(e){return e==="auto"||e==="direct"}function Ip(e){return typeof e=="string"&&Yl.has(e)}function rn(){try{const e=localStorage.getItem(Ns);if(!e)return{};const t=JSON.parse(e),n={};xp(t.provider)&&(n.provider=t.provider);const r=t.mcpProvider,o=t.mcpModel;(typeof r=="string"||r===null)&&(n.mcpProvider=r),(typeof o=="string"||o===null)&&(n.mcpModel=o),(t.mcpMediaKind==="image"||t.mcpMediaKind==="video")&&(n.mcpMediaKind=t.mcpMediaKind),(typeof t.comfyWorkflow=="string"||t.comfyWorkflow===null)&&(n.comfyWorkflow=t.comfyWorkflow),(typeof t.comfyVideoWorkflow=="string"||t.comfyVideoWorkflow===null)&&(n.comfyVideoWorkflow=t.comfyVideoWorkflow),"mcpRatio"in t&&(n.mcpRatio=Qr(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=eo(t.mcpParameters)),"imageToolModel"in t&&(n.imageToolModel=t.provider==="api"&&Is(t.imageToolModel)?t.imageToolModel:null),Xl(t.quality)&&(n.quality=Lt(t.provider,n.imageToolModel,t.quality)),Ip(t.sizePreset)&&(n.sizePreset=t.sizePreset),typeof t.customW=="number"&&Number.isFinite(t.customW)&&(n.customW=ot(t.customW,1920)),typeof t.customH=="number"&&Number.isFinite(t.customH)&&(n.customH=ot(t.customH,1088)),Zl(t.format)&&(n.format=t.format),Ql(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=En(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=En(t.multimodeMaxImages)),Sp(t.promptMode)&&(n.promptMode=t.promptMode),typeof t.prompt=="string"&&(n.prompt=t.prompt),typeof t.negativePrompt=="string"&&(n.negativePrompt=t.negativePrompt);const a=Fn(t.insertedPrompts);return a&&(n.insertedPrompts=a),n}catch{return{}}}function wp(){return op(rn())}function Dn(e,t,n="image"){te({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function te(e){try{const t=rn();localStorage.setItem(Ns,JSON.stringify({...t,...e}))}catch{}}function ec(){const e=localStorage.getItem(Cl);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function tc(){try{const e=ec();return e?.version===1?Yo(e.lanes):{}}catch{return{}}}function _p(e){try{let t=null;try{t=ec()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Yo(t.lanes):{},...Yo(e)};localStorage.setItem(Cl,JSON.stringify({version:1,lanes:r}))}catch{}}function nc(){const e=rn(),t=to();let n=null;try{n=localStorage.getItem(Es)}catch{}return dt({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Ep(e){Bl(e.imageModel),yn({model:e.videoModelSelected}),te({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Np(e,t,n){const r=new Set(e.map(l=>l.id));if(!r.has(n))return[];const o=new Map;for(const l of r)o.set(l,new Set);for(const l of t)!r.has(l.source)||!r.has(l.target)||(o.get(l.source)?.add(l.target),o.get(l.target)?.add(l.source));const a=new Set,i=[n];for(let l=0;l<i.length;l++){const c=i[l];if(!a.has(c)){a.add(c);for(const d of o.get(c)??[])a.has(d)||i.push(d)}}return e.filter(l=>a.has(l.id)).map(l=>l.id)}function rc(e){return e.filter(t=>t.selected).map(t=>t.id)}function Nn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function kp(e,t,n,r){const o=new Set(Np(e,t,n));if(!o.size)return e;if(!r)return Nn(e,o);const a=e.find(c=>c.id===n),i=e.some(c=>o.has(c.id)&&c.selected),l=new Set(rc(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of o)l.add(c);return Nn(e,l)}const jp={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Ha=16777216;function Va(e,t,n){let r=e,o=t;if(r<=0||o<=0)return{w:1,h:1};const a=Math.max(r,o);if(a>n){const i=n/a;r=Math.round(r*i),o=Math.round(o*i)}if(r*o>Ha){const i=Math.sqrt(Ha/(r*o));r=Math.max(1,Math.floor(r*i)),o=Math.max(1,Math.floor(o*i))}return{w:r,h:o}}function Zn(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?t(r.result):n(new Error("FileReader returned non-string"))},r.onerror=()=>n(r.error??new Error("FileReader failed")),r.readAsDataURL(e)})}function bo(e,t,n){return new Promise((r,o)=>{e.toBlob(a=>a?r(a):o(new Error("canvas.toBlob returned null")),t,n)})}function Qn(e){const t=e.indexOf(",");return t<0?e.length:e.length-t-1}async function Os(e,t={}){const n={...jp,...t},r=await Zn(e);if(Qn(r)<=n.maxB64Bytes)return r;let o;try{o=await createImageBitmap(e)}catch(a){throw new Error("이미지 디코드 실패. JPEG/PNG로 변환 후 다시 시도해 주세요.",{cause:a})}try{const{w:a,h:i}=Va(o.width,o.height,n.maxEdge),l=document.createElement("canvas");l.width=a,l.height=i;const c=l.getContext("2d");if(!c)throw new Error("canvas 2d context unavailable");if(c.drawImage(o,0,0,a,i),n.preserveTransparency){const m=await bo(l,"image/png"),u=await Zn(m);if(Qn(u)>n.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return u}for(const m of n.qualityLadder){const u=await bo(l,"image/jpeg",m),p=await Zn(u);if(Qn(p)<=n.maxB64Bytes)return p}const d=Va(a,i,2048);l.width=d.w,l.height=d.h,c.drawImage(o,0,0,d.w,d.h);for(const m of[.7,.5,.35]){const u=await bo(l,"image/jpeg",m),p=await Zn(u);if(Qn(p)<=n.maxB64Bytes)return p}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{o.close?.()}}function Pr(e){const t=(e.type||"").toLowerCase();if(t.includes("heic")||t.includes("heif"))return!0;const n=(e.name||"").toLowerCase();return n.endsWith(".heic")||n.endsWith(".heif")}function oc(e){return(e.type||"").toLowerCase()==="image/png"}const sc=18e4;function Cp(e){const t=e.uiMode==="node"?[{kind:"node",sessionId:e.activeSessionId??void 0}]:[{kind:"classic"}];e.inFlight.some(n=>n.kind==="multimode")&&t.push({kind:"multimode"}),t.push({kind:"video"}),t.push({kind:"mcp-image"},{kind:"mcp-video"});for(const n of e.inFlight)kn(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function kn(e,t){const n=e.kind??"classic";return t.some(r=>n===r.kind&&(r.kind!=="node"||(e.sessionId??null)===(r.sessionId??null)))}async function ac(e){const t=await Promise.all(e.map(n=>Zi({kind:n.kind,sessionId:n.sessionId,includeTerminal:!0})));return{jobs:t.flatMap(n=>n.jobs),terminalJobs:t.flatMap(n=>n.terminalJobs??[])}}function Rr(e){const t=e.meta??{},n=e.kind==="classic"||e.kind==="node"||e.kind==="multimode"||e.kind==="video"?e.kind:t.kind==="classic"||t.kind==="node"||t.kind==="multimode"||t.kind==="video"?t.kind:os(e.kind)??os(t.kind);return{id:e.requestId,prompt:typeof e.prompt=="string"?e.prompt:"",startedAt:e.startedAt,composerPrompt:typeof t.composerPrompt=="string"?t.composerPrompt:void 0,composerInsertedPrompts:Fn(t.composerInsertedPrompts)??void 0,phase:typeof e.phase=="string"?e.phase:void 0,sessionId:typeof t.sessionId=="string"?t.sessionId:null,parentNodeId:typeof t.parentNodeId=="string"?t.parentNodeId:null,clientNodeId:typeof t.clientNodeId=="string"?t.clientNodeId:null,kind:n}}function Ap(e){const t=typeof e.errorCode=="string"&&e.errorCode?e.errorCode:"UNKNOWN",n=new Error(t==="JOB_TRACKING_TIMEOUT"?Qi:t==="EMPTY_RESPONSE"?"No image data returned from the image backend.":"Generation failed on the server.");return n.code=t,n.status=typeof e.httpStatus=="number"?e.httpStatus:void 0,n}function on(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Ka(e){return e.filename||e.image}function Ba(e,t){const n=new Map(e.map(r=>[Ka(r),r]));for(const r of t)n.set(Ka(r),r);return[...n.values()].sort((r,o)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(o.sequenceIndex??Number.MAX_SAFE_INTEGER))}function Tp(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"prompt"in e&&typeof e.prompt=="string"&&"startedAt"in e&&typeof e.startedAt=="number"}function ic({includeExpired:e=!1}={}){try{const t=localStorage.getItem(Nl);if(!t)return[];const n=JSON.parse(t);if(!Array.isArray(n))return[];const r=Date.now();return n.filter(o=>Tp(o)&&(e||r-o.startedAt<sc)).map(o=>({id:o.id,prompt:o.prompt,startedAt:o.startedAt,composerPrompt:typeof o.composerPrompt=="string"?o.composerPrompt:void 0,composerInsertedPrompts:Fn(o.composerInsertedPrompts)??void 0,phase:typeof o.phase=="string"?o.phase:void 0,sessionId:typeof o.sessionId=="string"?o.sessionId:null,parentNodeId:typeof o.parentNodeId=="string"?o.parentNodeId:null,clientNodeId:typeof o.clientNodeId=="string"?o.clientNodeId:null,kind:o.kind==="classic"||o.kind==="node"||o.kind==="multimode"||o.kind==="video"?o.kind:os(o.kind)}))}catch{return[]}}function os(e){return e==="classic"||e==="node"||e==="multimode"||e==="video"||e==="mcp-image"||e==="mcp-video"||typeof e=="string"&&e.startsWith("mcp-action-")?e:void 0}const Ve=500,Fs=5;function Pp(e){return e==="classic"||e==="edit"||e==="generate"||e==="card-news-card"||e==="card-news-set"?e:null}function Gn(e){const t=Fn(e.composerInsertedPrompts),n=e.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(e.filename??"");return{image:e.url,url:e.url,providerUrl:e.providerUrl??null,mediaType:e.mediaType,video:e.video??null,videoSeries:e.videoSeries??null,videoContinuity:e.videoContinuity??null,videoLineage:e.videoLineage??null,filename:e.filename,thumb:e.thumb??(n?void 0:e.url),prompt:e.prompt??void 0,userPrompt:e.userPrompt??null,revisedPrompt:e.revisedPrompt??null,promptMode:e.promptMode??null,composerPrompt:e.composerPrompt??null,composerInsertedPrompts:t?Ms(t):null,size:e.size??void 0,quality:e.quality??void 0,format:e.format,model:e.model??void 0,imageToolModel:e.imageToolModel??null,reasoningEffort:e.reasoningEffort??void 0,elapsed:e.elapsed??void 0,provider:e.provider,usage:e.usage??void 0,createdAt:e.createdAt,sessionId:e.sessionId??null,nodeId:e.nodeId??null,parentNodeId:e.parentNodeId??null,clientNodeId:e.clientNodeId??null,requestId:e.requestId??null,kind:Pp(e.kind),canvasVersion:!!e.canvasVersion,canvasSourceFilename:e.canvasSourceFilename??null,canvasEditableFilename:e.canvasEditableFilename??null,canvasMergedAt:e.canvasMergedAt??void 0,annotationsBaked:!!e.annotationsBaked,annotationSnapshot:e.annotationSnapshot??null,annotationOnly:!!e.annotationOnly,setId:e.setId??null,cardId:e.cardId??null,cardOrder:e.cardOrder??null,headline:e.headline??null,body:e.body??null,cards:e.cards,refsCount:e.refsCount??0,webSearchCalls:e.webSearchCalls??0,isFavorite:e.isFavorite??!1,sequenceId:e.sequenceId??null,sequenceIndex:e.sequenceIndex??null,sequenceTotalRequested:e.sequenceTotalRequested??null,sequenceTotalReturned:e.sequenceTotalReturned??null,sequenceStatus:e.sequenceStatus??null}}function $e(e){return e.filename??e.image}function lc(e,t){const n=$e(t);return e.filter(r=>$e(r)!==n)}function cc(e,t){const n=$e(t);return e.find(r=>$e(r)===n)}function dc(e,t){return t?{...t,...e,createdAt:e.createdAt??t.createdAt,requestId:e.requestId??t.requestId,sessionId:e.sessionId??t.sessionId,kind:e.kind??t.kind,refsCount:e.refsCount??t.refsCount,isFavorite:e.isFavorite??t.isFavorite}:e}function uc(e,t){const n=new Map(e.map(r=>[$e(r),r]));for(const r of t)n.set($e(r),r);return[...e.map(r=>n.get($e(r))??r),...t.filter(r=>!e.some(o=>$e(o)===$e(r)))]}function no(e,t){return e.slice(0,Math.max(Ve,t))}function Ds(e){return e.replace(/^data:[^;]+;base64,/,"")}async function zn(e,t="reference.png"){const n=await Se(e);if(!n.ok)throw new Error(`reference fetch failed: ${n.status}`);const r=await n.blob(),o=new File([r],t,{type:r.type||"image/png"});return Os(o,{preserveTransparency:!1})}function Rp(e,t){let n=!1;const r={};for(const[o,a]of Object.entries(e)){const i=a.images.filter(l=>l.filename!==t);if(i.length===a.images.length){r[o]=a;continue}n=!0,i.length!==0&&(r[o]={...a,images:i,returned:i.length,status:a.status==="complete"&&i.length<a.requested?"partial":a.status})}return n?r:e}function Pe(e){try{localStorage.setItem(Nl,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function Mp(e){return Zm(e.naiServerDefaults,e.naiOptionOverrides)}function ro(e,t){if(e.provider==="grok"||e.provider==="grok-api"||e.provider==="agy"||e.provider==="gemini-api"||e.provider==="atlascloud"||e.provider==="minimax"||e.provider==="nai"||e.sizePreset!=="custom")return null;const n=As(e.customW,e.customH,e.customW,e.customH);return n.adjusted?{requestedW:n.requestedW,requestedH:n.requestedH,adjustedW:n.w,adjustedH:n.h,reasons:n.reasons,continuation:t}:null}function Lp(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):Fs}async function Op(e){try{const t=await Xi();e({referenceLimit:Lp(t.limits?.maxRefCount),naiServerDefaults:zl(t.defaults?.nai??null)})}catch{e({referenceLimit:Fs})}}function Gs(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}async function Fp(e){const t=await Se(e);if(!t.ok)throw new Error(`reference fetch failed: ${t.status}`);const n=await t.blob();return Gs(new File([n],"reference.png",{type:n.type||"image/png"}))}function Dp(e,t=256){return new Promise(n=>{const r=new Image;r.onload=()=>{const o=Math.min(1,t/Math.max(r.width,r.height)),a=document.createElement("canvas");a.width=r.width*o,a.height=r.height*o;const i=a.getContext("2d");if(!i)return n(e);i.drawImage(r,0,0,a.width,a.height),n(a.toDataURL("image/jpeg",.6))},r.onerror=()=>n(e),r.src=e})}function Gp(e){return e?.type==="elementReferenceNode"||e?.data?.nodeType==="element-reference"}function mc(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.filter(r=>!Gp(n.get(r.source)))}function pc(e,t,n){return mc(e,t).filter(r=>r.target===n)}function zp(e,t,n){if(t===n)return!0;const r=new Map;for(const i of e){const l=r.get(i.source)??[];l.push(i.target),r.set(i.source,l)}const o=new Set([n]),a=[n];for(let i=0;i<a.length;i++)for(const l of r.get(a[i])??[]){if(l===t)return!0;o.has(l)||(o.add(l),a.push(l))}return!1}function i0(e,t){const n=new Map,r=new Map;for(const i of e)n.set(i.id,0);for(const i of t){n.set(i.target,(n.get(i.target)??0)+1);const l=r.get(i.source)??[];l.push(i.target),r.set(i.source,l)}const o=e.filter(i=>(n.get(i.id)??0)===0).map(i=>i.id);let a=0;for(let i=0;i<o.length;i++){a+=1;for(const l of r.get(o[i])??[]){const c=(n.get(l)??0)-1;n.set(l,c),c===0&&o.push(l)}}return a<e.length}function De(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const o=pc(e,t,r.id),i=(o[0]?n.get(o[0].source):null)?.data.serverNodeId??null,l=new Set(i?[i]:[]),c=[];for(const u of o.slice(1)){const p=n.get(u.source)?.data.serverNodeId;!p||l.has(p)||(l.add(p),c.push(p))}const d=r.data.extraParentServerNodeIds??[];return r.data.parentServerNodeId===i&&d.length===c.length&&d.every((u,p)=>u===c[p])?r:{...r,data:{...r.data,parentServerNodeId:i,extraParentServerNodeIds:c}}})}const fc="ima2.nodeRefs.v1";function zs(){try{const e=localStorage.getItem(fc);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function hc(e){try{localStorage.setItem(fc,JSON.stringify(e))}catch{}}function Up(e,t){if(!e)return[];const n=zs()[e]?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function oo(e,t,n){if(!e)return;const r=zs(),o={...r[e]??{}};n.length===0?delete o[t]:o[t]=n,r[e]=o,hc(r)}function Us(e,t){oo(e,t,[])}function $p(e,t){if(!e)return;const n=zs(),r=n[e];if(!r)return;const o=new Set(t);for(const a of Object.keys(r))o.has(a)||delete r[a];n[e]=r,hc(n)}const qp=/\.(mp4|webm|mov)$/i;function tt(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return qp.test(t)||e.startsWith("data:video/")}function xe(e){return e?e.mediaType==="video"?!0:tt(e.filename)||tt(e.url)||tt(e.image):!1}const Hp=15e3;function $s(e,t,n={}){return new Promise((r,o)=>{const a=document.createElement("video");a.crossOrigin="anonymous",a.preload="auto",a.muted=!0;let i=!1,l=null;const c=()=>{l!==null&&clearTimeout(l),n.signal?.removeEventListener("abort",m),a.onloadedmetadata=null,a.onseeked=null,a.onerror=null,a.src="",a.load()},d=u=>{i||(i=!0,c(),u())};function m(){d(()=>o(Object.assign(new Error("frame extraction aborted"),{code:"VIDEO_FRAME_EXTRACT_ABORTED"})))}if(n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m),l=setTimeout(()=>{d(()=>o(new Error("frame extraction timed out")))},Hp),a.onloadedmetadata=()=>{const u=a.duration;if(!Number.isFinite(u)||u<=0){d(()=>o(new Error("video duration is unavailable")));return}a.currentTime=Math.max(0,t(u))},a.onseeked=()=>{try{const u=document.createElement("canvas");u.width=a.videoWidth,u.height=a.videoHeight;const p=u.getContext("2d");if(!p){d(()=>o(new Error("canvas 2d context unavailable")));return}p.drawImage(a,0,0);const h=u.toDataURL("image/jpeg",.85);d(()=>r(h))}catch(u){d(()=>o(u))}},a.onerror=()=>{d(()=>o(new Error("Failed to load video for frame extraction")))},a.src=e})}function sn(e,t){return $s(e,n=>n-.1,t)}function gc(e,t){return $s(e,n=>Math.min(n*.3,.4),t)}function yc(e,t){return $s(e,n=>n/2,t)}function vc(e){const t=e.nodes.map(r=>{const o=r.data??{},a=typeof o.imageUrl=="string"&&o.imageUrl.length>0?o.imageUrl:null,i=typeof o.serverNodeId=="string"&&o.serverNodeId.length>0?`/generated/${o.serverNodeId}.png`:null,l=a??i,c={...o,clientId:r.id,serverNodeId:o.serverNodeId??null,parentServerNodeId:o.parentServerNodeId??null,prompt:typeof o.prompt=="string"?o.prompt:"",imageUrl:l,status:o.status??(l?"ready":"empty"),pendingRequestId:o.pendingRequestId??null,recoveryRequestId:o.recoveryRequestId??null,pendingPhase:o.pendingPhase??null,pendingStartedAt:typeof o.pendingStartedAt=="number"?o.pendingStartedAt:null,partialImageUrl:null,error:o.error,elapsed:o.elapsed,reasoningEffort:o.reasoningEffort,webSearchCalls:o.webSearchCalls,model:o.model??null,size:o.size??null,referenceImages:Up(e.id,r.id),video:o.video??null};return{id:r.id,type:o.nodeType==="element-reference"?"elementReferenceNode":"imageNode",position:{x:r.x,y:r.y},data:c}}),n=e.edges.map(r=>{const o=r.data??{};return{id:r.id,source:r.source,target:r.target,sourceHandle:typeof o.sourceHandle=="string"?o.sourceHandle:null,targetHandle:typeof o.targetHandle=="string"?o.targetHandle:null}});return{graphNodes:De(t,n),graphEdges:n,graphVersion:e.graphVersion}}const Vp=800;let Qe=null,xr=!1,Sr=!1,wt=null,bc=0;function xc(){try{const e=sessionStorage.getItem(Pa);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(Pa,t),t}catch{return"tab_unavailable"}}function Sc(e){const t={...e};return delete t.referenceImages,delete t.partialImageUrl,e.status==="pending"||e.status==="reconciling"?{...t,status:"empty",pendingRequestId:null,recoveryRequestId:e.pendingRequestId??e.recoveryRequestId??null,pendingPhase:null,pendingStartedAt:null,error:void 0}:t}function Ic(e){return e.map(t=>({id:t.id,source:t.source,target:t.target,data:{sourceHandle:t.sourceHandle??null,targetHandle:t.targetHandle??null}}))}async function wc(e,t){const n=e().activeSessionId;if(!n||e().graphNodes.filter(l=>!l.data.imageUrl&&!l.data.serverNodeId).length===0)return;let o=[];try{o=(await en({sessionId:n,limit:Ve})).items}catch{return}let a=!1;const i=e().graphNodes.map(l=>{if(l.data.imageUrl||l.data.serverNodeId)return l;const c=l.data.pendingStartedAt??0,d=l.data.pendingRequestId??l.data.recoveryRequestId??null,u=(d?o.find(p=>(p.sessionId??null)===n&&(p.requestId??null)===d):null)??o.find(p=>(p.sessionId??null)===n&&(p.clientNodeId??null)===l.id&&(!c||(p.createdAt??0)>=c));return u?(a=!0,{...l,data:{...l.data,status:"ready",imageUrl:u.url,serverNodeId:u.nodeId??l.data.serverNodeId,size:u.size??l.data.size??null,elapsed:u.elapsed??l.data.elapsed,reasoningEffort:u.reasoningEffort??l.data.reasoningEffort,video:u.video??l.data.video??null,pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0}}):l});a&&(t({graphNodes:i}),Ec(e,t,"recovery"))}async function Kp(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await nl(n),{graphNodes:o,graphEdges:a,graphVersion:i}=vc(r);t({graphNodes:o,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(O("toast.sessionReloadedElsewhere"),!0),await wc(e,t).catch(()=>{})}async function Bp(e,t,n){const r=e().activeSessionId,o=e().activeSessionGraphVersion;if(!r||o==null)return"skipped";const{graphNodes:a,graphEdges:i,sessionLoading:l}=e();if(l||a.length===0&&o>0)return"skipped";const c=a.map(u=>({id:u.id,x:u.position.x,y:u.position.y,data:Sc(u.data)})),d=Ic(i),m=`gs_${Date.now().toString(36)}_${++bc}`;try{const u=await Wu(r,o,c,d,{saveId:m,saveReason:n,tabId:xc()});return e().activeSessionId!==r?"skipped":($p(r,e().graphNodes.map(p=>p.id)),t({activeSessionGraphVersion:u.graphVersion}),"saved")}catch(u){return u.status===409?(await Kp(e,t),"conflict"):(console.warn("[sessions] save failed:",u),"failed")}}async function _c(e,t,n){return xr?(Sr=!0,wt||"skipped"):(xr=!0,wt=(async()=>{let r=n,o="skipped";do{if(Sr=!1,o=await Bp(e,t,r),o==="conflict"||o==="failed")break;r="queued"}while(Sr);return o})().finally(()=>{xr=!1,wt=null}),wt)}function Ec(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(Qe&&clearTimeout(Qe),Qe=setTimeout(()=>{Qe=null,_c(e,t,n)},Vp)))}async function Wp(e,t,n="manual"){let r=!1;if(Qe&&(clearTimeout(Qe),Qe=null,r=!0),xr){if(Sr=!0,(wt?await wt:"skipped")==="failed")throw new Error(O("modal.graphSaveFailed"));return}if(r&&await _c(e,t,n)==="failed")throw new Error(O("modal.graphSaveFailed"))}function Jp(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;Qe&&(clearTimeout(Qe),Qe=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:Sc(i.data)})),r=Ic(t.graphEdges),o=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{Se(o,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++bc}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":xc()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function bt(e,t,n,r={}){const o=xe(e)?void 0:await Dp(e.image).catch(()=>e.image),a=e.filename?`/generated/${e.filename}`:e.image,i={...e,thumb:o,url:a,createdAt:e.createdAt||Date.now()},l=n(),c=cc(l.history,i),d=dc(i,c),m=lc(l.history,d),u=no([d,...m],l.loadedHistoryRetainLimit+1),h=!(r.autoSelectStartedAt!=null&&l.lastHistorySelectedAt>r.autoSelectStartedAt)&&(!l.currentImage||r.autoSelectStartedAt==null||l.lastHistorySelectedAt<=r.autoSelectStartedAt);h&&it(d.filename??null),t({history:u,...h?{currentImage:d}:{},loadedHistoryRetainLimit:Math.max(l.loadedHistoryRetainLimit,Math.min(l.history.length+1,l.loadedHistoryRetainLimit+1)),unseenGeneratedCount:l.unseenGeneratedCount+1})}function Yp(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const Xp=30;function xo(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function Zp(e,t,n=Xp){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function Qp(e,t,n){if(e.length===0)return null;const r=e[e.length-1];return{past:e.slice(0,-1),restored:r,future:[...n,t]}}function ef(e,t,n){if(n.length===0)return null;const r=n[n.length-1];return{past:[...e,t],restored:r,future:n.slice(0,-1)}}const tf=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function Wa(e,t){const n=new Map(t.map(o=>[o.id,o]));return{nodes:e.nodes.map(o=>{const a=n.get(o.id);if(!a||!(a.data.status==="pending"||a.data.status==="reconciling"))return o;const l={...o.data};for(const c of tf)l[c]=a.data[c];return{...o,data:l}}),edges:e.edges}}function nf(e){return e.data.status==="ready"&&!!e.data.imageUrl}function rf(e,t,n){const r=new Set(n),o=new Set(e.map(u=>u.id)),a=new Map,i=new Map;for(const u of r)o.has(u)&&(a.set(u,0),i.set(u,[]));for(const u of t)!r.has(u.source)||!r.has(u.target)||(i.get(u.source)?.push(u.target),a.set(u.target,(a.get(u.target)??0)+1));const l=e.map(u=>u.id),c=l.filter(u=>r.has(u)&&(a.get(u)??0)===0),d=[];for(let u=0;u<c.length;u++){const p=c[u];d.push(p);for(const h of i.get(p)??[])a.set(h,(a.get(h)??0)-1),(a.get(h)??0)===0&&c.push(h)}const m=new Set(d);return d.concat(l.filter(u=>r.has(u)&&!m.has(u)))}function of(e,t){const n=new Set(t),r=new Set,o=new Map;for(const i of e){const l=o.get(i.source)??[];l.push(i.target),o.set(i.source,l)}const a=[...n];for(let i=0;i<a.length;i++)for(const l of o.get(a[i])??[])n.has(l)||r.has(l)||(r.add(l),a.push(l));return[...r]}function sf(e,t){const n=new Map;for(const a of e){const i=n.get(a.source)??[];i.push(a.target),n.set(a.source,i)}const r=new Set,o=[t];for(let a=0;a<o.length;a++)for(const i of n.get(o[a])??[])r.has(i)||(r.add(i),o.push(i));return[...r]}function af(e,t,n){const r=new Set(n),o=new Map(e.map(i=>[i.id,i])),a=[];for(const i of t){if(!r.has(i.target)||r.has(i.source))continue;o.get(i.source)?.data.serverNodeId||a.push(i.target)}return a}function lf(e,t,n){const r=new Set(n),o=new Set(e.map(d=>d.id)),a=new Map,i=new Map;for(const d of r)o.has(d)&&(a.set(d,0),i.set(d,[]));for(const d of t)!a.has(d.source)||!a.has(d.target)||(i.get(d.source)?.push(d.target),a.set(d.target,(a.get(d.target)??0)+1));const l=[...a.keys()].filter(d=>(a.get(d)??0)===0),c=new Set;for(let d=0;d<l.length;d++){c.add(l[d]);for(const m of i.get(l[d])??[]){const u=(a.get(m)??0)-1;a.set(m,u),u===0&&l.push(m)}}return[...a.keys()].filter(d=>!c.has(d))}function We(e,t){const{code:n,spec:r,message:o}=at(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return Bi(typeof a=="number"?a:void 0),{code:n,message:o}}if(r.surface==="card")t.showErrorCard(n,{fallbackMessage:o,cardKey:r.cardKey,cta:r.cta});else{const a=r.toastKey?O(r.toastKey):o||O("toast.generateFailed");if(t.showToast(a,!0),n==="JOB_TRACKING_TIMEOUT")return{code:n,message:a}}return{code:n,message:o}}const cf=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],df=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function uf(e){if(cf.includes(e))return"auth";const t=Xe[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||df.includes(e)?"retry":"fix-input"}function Nc(e){const{code:t,message:n}=at(e),r=uf(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const mf=sl.grok.video,pf=3;function ff(e,t){return sl[e]?.[t]}function kc(e){if(e.mcpProvider)return pf;if(e.videoModelSelected)return Math.min(e.serverLimit,mf);if(Rt(e.provider)&&!Ss[e.provider].generate.references)return 0;const t=ff(e.provider,"image");return t===void 0?e.serverLimit:Math.min(e.serverLimit,t)}function qs(e,t={}){const n=t.provider??e.provider,r=t.imageModel??e.imageModel;if(n!=="nai")return{};const o={...e.naiOptionOverrides};ts(r)||(delete o.straightAlpha,delete o.qualityPresetId),o.seed===null&&delete o.seed;const a=e.negativePrompt.trim();return{...o,...a?{negativePrompt:a}:{}}}const Mr=new Map;function an(e,t){Mr.set(e,t)}function ln(e){Mr.delete(e)}function jc(e){Mr.get(e)?.abort(),Mr.delete(e)}const hf="element-source:",gf=500;function yf(e){return`${hf}${e}`}function l0(e,t){const n=yf(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function Cc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function vf(e=ys){const t=[],n=new Set,r=new Set;let o=null;try{do{const a=await e({kind:"element",folderId:null,tag:null,q:"",cursor:o,limit:gf});for(const i of a.assets)n.has(i.id)||(n.add(i.id),t.push(i));if(o=a.nextCursor,o&&r.has(o))throw new Error("element pagination returned a repeated cursor");o&&r.add(o)}while(o);return t}catch(a){throw a instanceof Error?a:new Error(String(a))}}function Ac(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function c0(e){const t=e.filePath??(e.kind==="element"?Cc(e)??"":""),n=Ac(t),r=e.metadata?.derivedKind,o=e.metadata?.backgroundPreset;return{image:n,url:n,filename:t,prompt:e.name,mediaType:e.kind==="video"?"video":"image",createdAt:e.createdAt,requestId:`asset:${e.id}`,...o==="transparent"?{backgroundPreset:"transparent"}:{},kind:typeof r=="string"&&(r.startsWith("keyed-")||r==="vector-svg")?"edit":"imported"}}const Ja=32,Ya="Image_",bf=/@([\p{L}\p{N}_-]+)/gu,xf=new Set([" "," ",`
|
|
5
|
+
`,"(","["]);function Tc(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${Ya}${r}`);)r+=1;return{tag:`${Ya}${r}`,nextAttachmentOrdinal:r+1}}function Sf(e,t){const n=new Set(t),r=e.slice(0,Ja)||"Element";if(!n.has(r))return r;let o=2;for(;;){const a=`_${o}`,i=`${r.slice(0,Ja-a.length)}${a}`;if(!n.has(i))return i;o+=1}}function Un(e){return e.trayItems.filter(t=>t.kind==="attachment")}function Pc(e){return e.trayItems.filter(t=>t.kind==="element")}function If(e){return Un(e).map(t=>t.source.dataUrl)}function wf(e){return Pc(e).map(t=>t.source.elementId)}function _f(e){const t={trayItems:e};return{referenceImages:If(t),selectedElementIds:wf(t)}}function Hs(e,t){return e.length<t}function so(e,t,n=Date.now()){const r={...e};for(const o of t)Object.defineProperty(r,o.tag,{value:n,enumerable:!0,configurable:!0,writable:!0});return r}function Ef(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Vs(e,t){if(!Ef(e,t))return e;const n={...e};return delete n[t],n}function Nf(e){const t=[];for(const n of e.matchAll(bf)){const r=n.index,o=r>0?e[r-1]:void 0;o!==void 0&&!xf.has(o)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function kf(e){return e.reduce((t,n)=>t+(n.kind==="attachment"?1:n.source.referenceFilenames.length),0)}function Ks(e,t){let n;return e(r=>{const o=t(r,r.activeReferenceLimit());if(n=o.result,!o.patch)return{};const a=o.patch.trayItems??r.trayItems,i=r.elementCatalog,l=o.patch.elementCatalog??i??null;return{...o.patch,trayItems:a,elementCatalog:l,missingElementIds:Lc(a,l),..._f(a)}}),n}function jf(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function Rc(e,t){const n=e??[],r=n.findIndex(o=>o.id===t.id);return r<0?[...n,t]:n.map((o,a)=>a===r?t:o)}function Cf(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function Mc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function Ir(e,t,n,r){return r&&(r.id!==e||r.kind!=="element")?null:Ks(t,(o,a)=>{if(!Hs(o.trayItems,a))return{result:null};if(o.trayItems.some(u=>u.kind==="element"&&u.source.elementId===e))return{result:null};const i=o,l=Cf(i,e,r),c=l?Vl(l.name):null;if(!l||!c)return{result:null};const d=Sf(c,o.trayItems.map(u=>u.tag)),m={kind:"element",tokenId:crypto.randomUUID(),tag:d,insertedAt:Date.now(),source:{elementId:e,nameAtInsertion:l.name,referenceFilenames:Mc(l)}};return{result:m,patch:{trayItems:[...o.trayItems,m],retiredTags:Vs(o.retiredTags,d),elementCatalog:Rc(i.elementCatalog,l)}}})}function Lc(e,t){if(t==null)return[];const n=new Set(t.map(o=>o.id)),r=new Set;return e.reduce((o,a)=>{if(a.kind!=="element")return o;const i=a.source.elementId;return!n.has(i)&&!r.has(i)&&o.push(i),r.add(i),o},[])}function ss(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function Af(e,t,n){Ks(t,r=>{const o=ss(r.trayItems,e);return o?{result:void 0,patch:{trayItems:r.trayItems.filter(a=>a.tokenId!==o.tokenId),retiredTags:so(r.retiredTags,[o])}}:{result:void 0}})}function Oc(e,t,n){const r=jf(e);t(o=>({elementCatalog:r,missingElementIds:Lc(o.trayItems,r)}))}function Fc(e,t,n){const r=new Map(e.map(l=>[l.id,l])),o=new Set,a=new Map,i=[...n];for(;i.length>0;){const l=i.shift();if(!o.has(l)){o.add(l);for(const c of t){if(c.target!==l)continue;const d=r.get(c.source);if(d)if(d.type==="elementReferenceNode"){if(!a.has(d.id)){const m=d.data;a.set(d.id,{nodeId:d.id,elementId:typeof m.elementId=="string"&&m.elementId?m.elementId:null,name:typeof m.elementName=="string"&&m.elementName||typeof m.elementId=="string"&&m.elementId||"element",missing:m.missing===!0})}}else i.push(d.id)}}}return[...a.values()]}const St=new Set;async function Tf(e,t,n){const r=[],o=[],a=[],i={};for(const l of e){if(l.missing||!l.elementId){if(l.missing)return{ok:!1,name:l.name};continue}let c;try{c=(await tm(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=Rc(n().elementCatalog,c),m=c.updatedAt??c.createdAt;a.push(c.id),i[c.id]=m,typeof c.notes=="string"&&c.notes.trim()&&o.push(`${c.name}: ${c.notes.trim()}`),t({elementCatalog:d,graphNodes:n().graphNodes.map(u=>u.id===l.nodeId?{...u,data:{...u.data,resolvedRevision:m,missing:!1}}:u)});for(const u of Mc(c))try{const p=await Fp(Ac(u));r.includes(p)||r.push(p)}catch{}}return{ok:!0,referenceDataUrls:r,notes:o,elementIds:a,revisions:i}}function Pf(e,t,n){const r=[];for(const o of[...e,...t])if(r.includes(o)||r.push(o),r.length>=n)break;return r}async function Rf(e,t,n,r,o){if(St.has(e))return null;St.add(e);const a=r().graphNodes,i=De(a,r().graphEdges);i.some((C,T)=>C!==a[T])&&n({graphNodes:i});const l=i.find(C=>C.id===e);if(!l)return St.delete(e),null;const c=Fc(r().graphNodes,r().graphEdges,[e]),d=await Tf(c,n,r);if(d.ok===!1)return r().showToast(O("node.elementMissing",{name:d.name}),!0),St.delete(e),null;const{prompt:m,parentServerNodeId:u}=l.data;if(!m.trim())return r().showToast(O("toast.promptRequired"),!0),St.delete(e),null;const p=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:p.provider,x=kc({provider:h,serverLimit:p.referenceLimit,videoModelSelected:!!p.videoModelSelected,mcpProvider:p.mcpProvider??null}),S=Pf(l.data.referenceImages??[],d.referenceDataUrls,x),b=typeof l.data.model=="string"&&l.data.model?l.data.model:p.imageModel,v=t.sizeOverride??(typeof l.data.size=="string"&&l.data.size?l.data.size:p.getResolvedSize()),y=t.parentServerNodeIdOverride!==void 0?t.parentServerNodeIdOverride:u,w=(l.data.extraParentServerNodeIds??[]).filter(C=>C&&C!==y);if(pc(i,r().graphEdges,e).length>0&&!y)return r().showToast(O("node.parentImageRequired"),!0),St.delete(e),null;const _=p.activeSessionId,N=Date.now(),j=Math.random().toString(36).slice(2,6),L=`fn_${e}_${N}_${j}`,q=new AbortController;an(L,q);const A=[...p.inFlight,{id:L,prompt:m,startedAt:N,kind:"node",sessionId:_,clientNodeId:e}];o(A),n({graphNodes:r().graphNodes.map(C=>C.id===e?{...C,data:{...C.data,status:"pending",pendingRequestId:L,recoveryRequestId:L,pendingPhase:"queued",pendingStartedAt:N,partialImageUrl:null,error:void 0,errorInfo:null,size:v}}:C),activeGenerations:p.activeGenerations+1,inFlight:A}),r().startInFlightPolling();let G=!0;try{const C=await am({parentNodeId:y,...w.length?{extraParentNodeIds:w}:{},prompt:m,quality:Lt(h,p.imageToolModel,p.quality),size:v,format:p.format,moderation:p.moderation,provider:h,model:b,...h==="api"&&p.imageToolModel?{imageToolModel:p.imageToolModel}:{},reasoningEffort:p.reasoningEffort,storyboard:p.storyboardActive||void 0,requestId:L,sessionId:_,clientNodeId:e,contextMode:"parent-plus-refs",searchMode:p.webSearchEnabled?"on":"off",webSearchEnabled:p.webSearchEnabled,...qs(p,{provider:h,imageModel:b}),...S.length?{references:S.map(Ds)}:{},...d.elementIds.length?{elementIds:d.elementIds,elementRevisions:d.revisions,elementNotes:d.notes}:{}},{onPartial:T=>{r().activeSessionId===_&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"pending",partialImageUrl:T.image,pendingPhase:"partial"}}:k)})},onPhase:T=>{r().activeSessionId===_&&T.phase&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,pendingPhase:T.phase??k.data.pendingPhase}}:k)})}},{signal:q.signal});return r().activeSessionId===_&&(n({graphNodes:r().graphNodes.map(T=>{if(T.id!==e)return T;const k={...T.data};return delete k.partialImageUrl,{...T,data:{...k,serverNodeId:C.nodeId,imageUrl:C.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:C.elapsed,reasoningEffort:C.reasoningEffort,webSearchCalls:C.webSearchCalls,model:C.model??null,imageToolModel:C.imageToolModel??null,size:C.size??null,errorInfo:null}}})}),G=!0,t.suppressToast||r().showToast(O("toast.nodeCreated",{id:C.nodeId.slice(0,8),elapsed:C.elapsed}))),C.nodeId}catch(C){if(on(C))return r().activeSessionId===_&&(n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:k.data.imageUrl?"ready":"empty",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0,errorInfo:null}}:k)}),G=!0),null;const T=C instanceof Error?C.message:O("toast.nodeCreateFailed");return r().activeSessionId===_&&(n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:T,errorInfo:Nc(C)}}:k)}),G=!0,We(C,r())),null}finally{St.delete(e);const C=r().inFlight.filter(T=>T.id!==L);o(C),ln(L),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:C}),r().activeSessionId===_&&G&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function Mf(e,t,n){if(n().nodeBatchRunning)return;const r=rc(n().graphNodes).filter(b=>n().graphNodes.find(v=>v.id===b)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(O("nodeBatch.noneSelected"),!0);return}const o=mc(n().graphNodes,n().graphEdges),a=af(n().graphNodes,o,r);if(a.length>0){n().showToast(O("nodeBatch.parentRequired",{count:a.length}),!0);return}const i=lf(n().graphNodes,n().graphEdges,r);if(i.length>0){n().showToast(O("nodeBatch.cycleBlocked",{count:i.length}),!0);return}const l=rf(n().graphNodes,o,r),c=new Set(r),d=l.filter(b=>{if(e==="regenerate-all")return!0;const v=n().graphNodes.find(y=>y.id===b);return v?!nf(v):!1});if(d.length===0){n().showToast(O("nodeBatch.nothingToRun"));return}const u=Fc(n().graphNodes,n().graphEdges,d).find(b=>b.missing);if(u){n().showToast(O("node.elementMissing",{name:u.name}),!0);return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});let p=0,h=0,x=0;const S=new Set;try{for(const b of d){if(n().nodeBatchStopping)break;if(S.has(b)){x+=1;continue}const v=De(n().graphNodes,n().graphEdges);v.some((N,j)=>N!==n().graphNodes[j])&&t({graphNodes:v});const y=v.find(N=>N.id===b)?.data.parentServerNodeId??null;if(!(n().videoModelSelected?await n().runVideoGenerate(b).then(()=>n().graphNodes.find(j=>j.id===b)?.data.serverNodeId??null):await n().runGenerateNodeInPlace(b,{parentServerNodeIdOverride:y,suppressToast:!0}))){h+=1;for(const N of sf(o,b))S.add(N);continue}p+=1;const I=new Set(of(o,c)),_=n().graphNodes.map(N=>I.has(N.id)?{...N,data:{...N.data,status:"stale",error:O("nodeBatch.staleBecauseParentChanged")}}:N);t({graphNodes:De(_,n().graphEdges)})}h>0?n().showToast(O("nodeBatch.partialFinished",{done:p,failed:h,skipped:x,total:d.length}),!0):n().showToast(O("nodeBatch.finished",{done:p,total:d.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function as(e){return Array.isArray(e.images)}function Lf(e,t){return e.modes.includes("both")||e.modes.includes(t)}function ao(e){const t=new Map(e.catalog.map(i=>[i.id,i])),n=[],r={},o=[],a=[];for(const i of e.presetIds){const l=t.get(i);if(!l||!Lf(l,e.mode)){a.push(i);continue}const c=l.perProvider?.[e.provider];n.push(c?.fragment??l.promptFragment),Object.assign(r,c?.params),o.push(i)}return{promptFragment:n.join(" "),params:r,appliedPresetIds:o,skipped:a}}const Of=[{id:"dolly-in",name:"Dolly In",category:"camera-motion",promptFragment:"a smooth cinematic dolly-in toward the subject with natural parallax",perProvider:{grok:{fragment:"camera: smooth dolly-in toward the subject, natural parallax"},gemini:{fragment:"The camera slowly dollies forward toward the subject with stable cinematic parallax."}},modes:["video"]},{id:"dolly-out",name:"Dolly Out",category:"camera-motion",promptFragment:"a controlled dolly-out revealing the wider environment around the subject",perProvider:{grok:{fragment:"camera: controlled dolly-out revealing the wider scene"},gemini:{fragment:"The camera smoothly pulls backward to reveal the surrounding environment."}},modes:["video"]},{id:"dolly-zoom",name:"Dolly Zoom",category:"camera-motion",promptFragment:"a dramatic dolly zoom with the subject scale held steady as perspective compresses",perProvider:{grok:{fragment:"camera: dramatic dolly zoom, subject scale locked, perspective warping"},gemini:{fragment:"Use a precise dolly zoom, maintaining subject size while the background perspective shifts dramatically."}},modes:["video"]},{id:"orbit-left",name:"Orbit Left",category:"camera-motion",promptFragment:"a smooth leftward orbit around the subject with strong dimensional parallax",perProvider:{grok:{fragment:"camera: smooth orbit left around subject"},gemini:{fragment:"The camera arcs counterclockwise around the subject in a smooth stabilized orbit."}},modes:["video"]},{id:"orbit-right",name:"Orbit Right",category:"camera-motion",promptFragment:"a smooth rightward orbit around the subject with strong dimensional parallax",perProvider:{grok:{fragment:"camera: smooth orbit right around subject"},gemini:{fragment:"The camera arcs clockwise around the subject in a smooth stabilized orbit."}},modes:["video"]},{id:"crane-up",name:"Crane Up",category:"camera-motion",promptFragment:"a graceful crane-up rising from subject level into a broad establishing view",perProvider:{grok:{fragment:"camera: graceful crane-up into a wide establishing view"},gemini:{fragment:"The camera rises vertically on a crane, transitioning into an elevated establishing view."}},modes:["video"]},{id:"crane-down",name:"Crane Down",category:"camera-motion",promptFragment:"a descending crane shot settling from an overhead view toward the subject",perProvider:{grok:{fragment:"camera: descending crane-down from overhead to subject level"},gemini:{fragment:"The camera descends smoothly from an elevated overview toward the subject."}},modes:["video"]},{id:"pan-left",name:"Pan Left",category:"camera-motion",promptFragment:"a measured pan left on a stable tripod head following the action",perProvider:{grok:{fragment:"camera: stable pan left following action"},gemini:{fragment:"Pan the camera steadily left while maintaining level framing."}},modes:["video"]},{id:"pan-right",name:"Pan Right",category:"camera-motion",promptFragment:"a measured pan right on a stable tripod head following the action",perProvider:{grok:{fragment:"camera: stable pan right following action"},gemini:{fragment:"Pan the camera steadily right while maintaining level framing."}},modes:["video"]},{id:"tilt-up",name:"Tilt Up",category:"camera-motion",promptFragment:"a deliberate tilt upward revealing the subject from base to top",perProvider:{grok:{fragment:"camera: deliberate tilt up, base-to-top reveal"},gemini:{fragment:"Tilt the camera upward in a controlled reveal from the lower frame to the upper subject."}},modes:["video"]},{id:"tilt-down",name:"Tilt Down",category:"camera-motion",promptFragment:"a deliberate tilt downward revealing the scene from top to ground level",perProvider:{grok:{fragment:"camera: deliberate tilt down, top-to-ground reveal"},gemini:{fragment:"Tilt the camera downward in a controlled reveal from above to ground level."}},modes:["video"]},{id:"tracking-left",name:"Tracking Left",category:"camera-motion",promptFragment:"a lateral tracking shot moving left alongside the subject at matched speed",perProvider:{grok:{fragment:"camera: lateral tracking left, speed matched to subject"},gemini:{fragment:"Track laterally left beside the moving subject, matching its speed and distance."}},modes:["video"]},{id:"tracking-right",name:"Tracking Right",category:"camera-motion",promptFragment:"a lateral tracking shot moving right alongside the subject at matched speed",perProvider:{grok:{fragment:"camera: lateral tracking right, speed matched to subject"},gemini:{fragment:"Track laterally right beside the moving subject, matching its speed and distance."}},modes:["video"]},{id:"fpv-drone",name:"FPV Drone",category:"camera-motion",promptFragment:"an agile FPV drone flight weaving close through the environment with dynamic banking",perProvider:{grok:{fragment:"camera: agile FPV drone flight, close fly-through, dynamic banking"},gemini:{fragment:"Use an agile first-person drone camera that banks and threads closely through the environment."}},modes:["video"]},{id:"handheld",name:"Handheld",category:"camera-motion",promptFragment:"natural documentary handheld movement with subtle operator sway and responsive reframing",perProvider:{grok:{fragment:"camera: natural handheld documentary movement, subtle sway"},gemini:{fragment:"Use restrained handheld camera motion with organic operator sway and responsive framing."}},modes:["video"]},{id:"whip-pan",name:"Whip Pan",category:"camera-motion",promptFragment:"a rapid whip pan with directional motion blur landing sharply on the next subject",perProvider:{grok:{fragment:"camera: fast whip pan with motion blur, sharp landing"},gemini:{fragment:"Execute a rapid whip pan with directional blur, resolving cleanly on the destination subject."}},modes:["video"]},{id:"crash-zoom",name:"Crash Zoom",category:"camera-motion",promptFragment:"an abrupt crash zoom into a critical detail with energetic lens compression",perProvider:{grok:{fragment:"camera: abrupt crash zoom into critical detail"},gemini:{fragment:"Snap into a fast crash zoom that emphasizes a critical detail with dramatic compression."}},modes:["video"]},{id:"bullet-time",name:"Bullet Time",category:"camera-motion",promptFragment:"a high-speed orbit around nearly frozen action with suspended particles and extreme temporal detail",perProvider:{grok:{fragment:"camera: bullet-time orbit around near-frozen action, suspended particles"},gemini:{fragment:"Create a bullet-time orbit around nearly frozen action, preserving crisp suspended particles and spatial detail."}},modes:["video"]},{id:"hyperlapse",name:"Hyperlapse",category:"camera-motion",promptFragment:"a stabilized forward-moving hyperlapse with accelerated environmental change and fixed visual anchor",perProvider:{grok:{fragment:"camera: stabilized moving hyperlapse, fixed anchor, accelerated surroundings"},gemini:{fragment:"Use a stabilized traveling hyperlapse with a locked visual anchor and rapidly changing surroundings."}},modes:["video"]},{id:"static",name:"Static",category:"camera-motion",promptFragment:"a locked-off static camera with no movement and a carefully composed stable frame",perProvider:{grok:{fragment:"camera: locked-off static shot, no movement"},gemini:{fragment:"Keep the camera completely locked off with stable composition and no camera movement."}},modes:["video"]}],Ff=[{id:"cinematic",name:"Cinematic",category:"style",promptFragment:"cinematic production design, anamorphic composition, restrained film grain, rich tonal separation",modes:["both"]},{id:"anime",name:"Anime",category:"style",promptFragment:"high-detail anime key visual, expressive linework, cel shading, deliberate color scripting",modes:["both"]},{id:"watercolor",name:"Watercolor",category:"style",promptFragment:"transparent watercolor washes on textured cold-press paper, soft pigment blooms and granulation",modes:["both"]},{id:"oil-painting",name:"Oil Painting",category:"style",promptFragment:"traditional oil painting with layered glazes, visible impasto brushwork and deep painterly color",modes:["both"]},{id:"pencil-sketch",name:"Pencil Sketch",category:"style",promptFragment:"graphite pencil drawing with confident contour lines, cross-hatching and subtle paper tooth",modes:["both"]},{id:"pixel-art",name:"Pixel Art",category:"style",promptFragment:"hand-crafted pixel art with a limited palette, crisp clusters and controlled dithering",modes:["both"]},{id:"vaporwave",name:"Vaporwave",category:"style",promptFragment:"vaporwave aesthetic, pastel neon gradients, retro digital artifacts, chrome accents and nostalgic geometry",modes:["both"]},{id:"noir",name:"Noir",category:"style",promptFragment:"classic film noir, high-contrast monochrome photography, oblique shadows and tense urban atmosphere",modes:["both"]},{id:"pop-art",name:"Pop Art",category:"style",promptFragment:"bold pop-art treatment with saturated primaries, halftone dots, graphic outlines and punchy repetition",modes:["both"]},{id:"surreal",name:"Surreal",category:"style",promptFragment:"dreamlike surrealism with impossible spatial relationships, symbolic objects and uncanny photoreal detail",modes:["both"]},{id:"photorealistic",name:"Photorealistic",category:"style",promptFragment:"photorealistic material detail, physically plausible optics, natural texture and true-to-life color response",modes:["both"]},{id:"minimalist",name:"Minimalist",category:"style",promptFragment:"minimalist visual language, essential forms, generous negative space and a disciplined reduced palette",modes:["both"]},{id:"baroque",name:"Baroque",category:"style",promptFragment:"opulent Baroque composition, dramatic diagonals, ornate detail, theatrical movement and rich fabrics",modes:["both"]},{id:"cyberpunk",name:"Cyberpunk",category:"style",promptFragment:"dense cyberpunk worldbuilding, rain-slick surfaces, layered neon signage, advanced machinery and urban decay",modes:["both"]},{id:"ukiyo-e",name:"Ukiyo-e",category:"style",promptFragment:"Japanese ukiyo-e woodblock print, flowing contour lines, flat mineral colors and decorative patterning",modes:["both"]}],Df=[{id:"golden-hour",name:"Golden Hour",category:"lighting",promptFragment:"warm low-angle golden-hour sunlight, long soft-edged shadows and luminous atmospheric haze",modes:["both"]},{id:"blue-hour",name:"Blue Hour",category:"lighting",promptFragment:"cool blue-hour ambient light with balanced practical lights and a deep cobalt sky",modes:["both"]},{id:"studio-softbox",name:"Studio Softbox",category:"lighting",promptFragment:"large studio softbox key light with smooth wrap, controlled fill and clean catchlights",modes:["both"]},{id:"hard-rim",name:"Hard Rim",category:"lighting",promptFragment:"hard back rim light carving a bright edge around the subject against a darker background",modes:["both"]},{id:"volumetric-fog",name:"Volumetric Fog",category:"lighting",promptFragment:"directional volumetric light shafts visible through fine atmospheric fog with layered depth",modes:["both"]},{id:"neon-glow",name:"Neon Glow",category:"lighting",promptFragment:"saturated neon illumination with colored spill, glossy reflections and luminous edge bloom",modes:["both"]},{id:"chiaroscuro",name:"Chiaroscuro",category:"lighting",promptFragment:"dramatic chiaroscuro lighting with a sculpted key, deep controlled shadow and painterly contrast",modes:["both"]},{id:"overcast-diffuse",name:"Overcast Diffuse",category:"lighting",promptFragment:"broad overcast daylight, exceptionally soft diffuse shadows and even natural skin tones",modes:["both"]},{id:"candlelight",name:"Candlelight",category:"lighting",promptFragment:"intimate flickering candlelight with warm falloff, soft amber highlights and deep surrounding shadow",modes:["both"]},{id:"moonlight",name:"Moonlight",category:"lighting",promptFragment:"cool directional moonlight with silver-blue highlights, subdued fill and nocturnal contrast",modes:["both"]}],Dc=[...Of,...Ff,...Df];function Gc(e){return Dc.find(t=>t.id===e)}function io(){return[...Dc]}function zc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Uc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function Gf(e,t,n){const r=n();if(r.uiMode!=="classic")return;const o=On(r.prompt,r.insertedPrompts);if(!o)return;const a=ao({catalog:io(),presetIds:r.selectedPresetIds,provider:Uc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Ms(r.insertedPrompts),d=e??r.getResolvedSize(),m=`mm_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=new AbortController;an(m,u);const p=Date.now(),h=p,x=En(r.multimodeMaxImages),S=[...r.inFlight,{id:m,prompt:i,startedAt:p,kind:"multimode",composerPrompt:l,composerInsertedPrompts:c}],b={sequenceId:m,requestId:m,requested:x,returned:0,images:[],partials:[],status:"pending"};Pe(S),t({activeGenerations:r.activeGenerations+1,inFlight:S,activeFlightIds:new Set([...r.activeFlightIds,m]),multimodeSequences:{...r.multimodeSequences,[m]:b},multimodePreviewFlightId:m}),n().startInFlightPolling();try{const v={prompt:i,quality:r.quality,size:d,format:r.format,moderation:r.moderation,provider:r.provider,maxImages:x,model:vl(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,webSearchEnabled:r.webSearchEnabled,requestId:m,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:zc(r),...qs(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(Ds)}:{}},y=await Lu(v,{onPartial:_=>{t(N=>{const j=N.multimodeSequences[m];return j?{multimodeSequences:{...N.multimodeSequences,[m]:{...j,partials:[...j.partials,{image:_.image,index:_.index??null}].slice(-x)}}}:{}})},onImage:_=>{t(N=>{const j=N.multimodeSequences[m];if(!j)return{};const L=Ba(j.images,[_]);return L.length===j.images.length?{}:{multimodeSequences:{...N.multimodeSequences,[m]:{...j,sequenceId:_.sequenceId??j.sequenceId,returned:L.length,images:L,status:"partial"}}}})}},{signal:u.signal}),w=y.images.map(_=>({..._,prompt:i,elapsed:Number.parseFloat(y.elapsed),provider:y.provider,usage:y.usage,requestId:_.requestId??y.requestId??m,composerPrompt:l,composerInsertedPrompts:c,quality:y.quality,size:y.size,model:y.model??null,imageToolModel:y.imageToolModel??null}));for(const _ of w)await bt(_,t,n,{autoSelectStartedAt:h});t(_=>({multimodeSequences:{..._.multimodeSequences,[m]:(()=>{const N=_.multimodeSequences[m],j=Ba(N?.images??[],w);return{sequenceId:y.sequenceId,requestId:m,requested:y.requested,returned:j.length,images:j,partials:[],status:y.status,elapsed:y.elapsed}})()}}));const I=y.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(O(I,{returned:y.returned,requested:y.requested,elapsed:y.elapsed}))}catch(v){v.name==="AbortError"||on(v)?t(y=>{const w=y.multimodeSequences[m];return w?{multimodeSequences:{...y.multimodeSequences,[m]:{...w,status:"canceled"}}}:{}}):(t(y=>{const w=y.multimodeSequences[m];return w?{multimodeSequences:{...y.multimodeSequences,[m]:{...w,status:"error",error:v.message}}}:{}}),We(v,n()))}finally{const v=n().inFlight.filter(y=>y.id!==m);Pe(v),ln(m),t(y=>{const w=new Set(y.activeFlightIds);w.delete(m);let I=y.multimodePreviewFlightId;const _=y.multimodeSequences[m]?.status,N=_==="complete"||_==="partial";if(I===m&&!N){const L=[...w];I=L.length>0?L[L.length-1]:null}const j={...y.multimodeSequences};return N&&I!==m&&delete j[m],{activeGenerations:Math.max(0,y.activeGenerations-1),inFlight:v,activeFlightIds:w,multimodePreviewFlightId:I,multimodeSequences:j}})}}async function zf(e,t,n){const r=n(),o=On(r.prompt,r.insertedPrompts);if(!o)return;const a=ao({catalog:io(),presetIds:r.selectedPresetIds,provider:Uc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Ms(r.insertedPrompts),d=e??r.getResolvedSize(),m=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=new AbortController;an(m,u);const p=Date.now(),h=p,x=[...r.inFlight,{id:m,prompt:i,startedAt:p,composerPrompt:l,composerInsertedPrompts:c}];Pe(x),t({activeGenerations:r.activeGenerations+1,inFlight:x}),n().startInFlightPolling();try{const S={prompt:i,quality:r.quality,size:d,format:r.format,moderation:r.moderation,provider:r.provider,n:r.provider==="nai"?1:r.count,model:vl(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,storyboard:r.storyboardActive||void 0,webSearchEnabled:r.webSearchEnabled,requestId:m,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:zc(r),...qs(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(Ds)}:{}},b=await el(S,{signal:u.signal});if(as(b)&&b.images.length>1){for(const v of b.images){const y={image:v.image,filename:v.filename,reasoningEffort:b.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:b.elapsed,provider:b.provider,providerUrl:v.providerUrl??null,usage:b.usage,requestId:b.requestId??m,quality:b.quality,size:b.size,model:b.model??null,imageToolModel:b.imageToolModel??null,createdAt:v.createdAt??Date.now()};await bt(y,t,n,{autoSelectStartedAt:h})}n().showToast(O("toast.generatedBatch",{count:b.images.length,elapsed:b.elapsed}))}else{let v;if(as(b)){const y=b.images[0];v={image:y.image,filename:y.filename,reasoningEffort:b.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:b.elapsed,provider:b.provider,providerUrl:y.providerUrl??null,usage:b.usage,requestId:b.requestId??m,quality:b.quality,size:b.size,model:b.model??null,imageToolModel:b.imageToolModel??null,createdAt:y.createdAt??Date.now()}}else v={image:b.image,filename:b.filename,reasoningEffort:b.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:b.elapsed,provider:b.provider,providerUrl:b.providerUrl??null,usage:b.usage,requestId:b.requestId??m,quality:b.quality,size:b.size,model:b.model??null,imageToolModel:b.imageToolModel??null,createdAt:b.createdAt??Date.now()};await bt(v,t,n,{autoSelectStartedAt:h}),n().showToast(O("toast.generatedSingle",{elapsed:b.elapsed}))}}catch(S){!(S instanceof Error&&S.name==="AbortError")&&!on(S)&&We(S,n())}finally{const S=n().inFlight.filter(b=>b.id!==m);Pe(S),ln(m),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:S})}}function Uf(e){const t=e?.status;return e?.code==="VIDEO_FRAME_EXTRACT_ABORTED"?!1:typeof t!="number"?!0:t>=500||t===503||t===504}async function $f(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,o=await Se(r,{signal:n.signal});if(!o.ok)throw Object.assign(new Error(`frame extraction failed (${o.status})`),{status:o.status});const a=await o.blob();return await new Promise((i,l)=>{const c=new FileReader;c.onload=()=>i(String(c.result)),c.onerror=()=>l(c.error??new Error("frame decode failed")),c.readAsDataURL(a)})}function qf(e){return{async extractFrame(t,n,r={}){if(t.kind==="generated"&&n==="last")try{return{dataUrl:await e.fetchGeneratedFrame(t.filename,"last",r),via:"server-ffmpeg"}}catch(a){if(!Uf(a))throw a}const o=t.kind==="url"?t.url:`/generated/${encodeURIComponent(t.filename)}`;return{dataUrl:await e.extractFromElement(o,n,r),via:"browser-canvas"}}}}const Hf=qf({fetchGeneratedFrame:$f,extractFromElement:(e,t,n)=>t==="last"?sn(e,n):t==="first"?gc(e,n):yc(e,n)}),Lr="Your video prompt should describe: visual flow, motion flow, sound/no-music intent, dialogue/no-dialogue, and the desired ending frame. Pace the scene to fill the selected duration naturally — opening composition, connected action/emotion change, and a stable ending frame.";function Vf(e){const t=e.length<=4?e:[e[0],...e.slice(-3)];return t.map((n,r)=>({...n,ordinal:r+1,role:r===0?"start":r===t.length-1?"parent":"ancestor"}))}function er(e){return typeof e=="string"&&e.trim()?e.trim():null}function $c(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:Vf(e.videoContinuity.entries)};const t=er(e.revisedPrompt)??er(e.prompt);if(!t)return null;const n=e.filename??null;return{lineageId:`lineage:${n??Date.now()}`,parentFilename:n,sourceFrame:"last",maxEntries:4,retention:"keep-start-plus-latest-3",entries:[{id:`clip:${n??"unknown"}`,ordinal:1,role:"start",filename:n,userPrompt:er(e.userPrompt)??er(e.prompt),revisedPrompt:t,createdAt:e.createdAt??Date.now()}]}}function jn(e){return{image:e.url||e.image,url:e.url,filename:e.filename,prompt:e.prompt??null,userPrompt:e.userPrompt??null,revisedPrompt:e.revisedPrompt??null,createdAt:e.createdAt,mediaType:e.mediaType,videoContinuity:e.videoContinuity??null}}function Kf(e){const t=e.entries[e.entries.length-1];return{id:`video-continuity:${e.lineageId}`,name:"Video Continuity",text:["Video continuity context:","The attached image is the last frame of the previous video.",t?`Continue from previous revisedPrompt #${t.ordinal}: ${t.revisedPrompt}`:null,"The new prompt must define next motion, camera, sound/music/no-music, dialogue/no-dialogue, and ending frame.","Pace the new clip to naturally fill the selected duration with a production-level sequence from the last-frame anchor."].filter(Boolean).join(`
|
|
6
|
+
`)}}function qc(e){if(!e?.entries?.length)return null;const t=e.entries[e.entries.length-1];return`${e.entries.length}/4 clips · last frame · ${t?.filename??"unsaved source"}`}function Hc(e){return e.provider==="comfy"&&e.comfyVideoWorkflow||(e.provider==="grok"||e.provider==="grok-api")&&e.videoModelSelected?"video":e.uiMode==="classic"&&e.multimode&&e.provider!=="nai"&&Rt(e.provider)&&Ss[e.provider].multimode.supported?"multimode":"image"}function Bf(e){return e.mcpProvider?e.multimode:Hc(e)==="multimode"}async function Wf(e,t){const n=t();if(!On(n.prompt,n.insertedPrompts)||Bs(t))return;const o=Hc(n);if(o==="video")return t().runVideoGenerate();const a=o==="multimode",i=ro(n,{kind:a?"multimode":"classic"});if(i){e({customSizeConfirm:i});return}if(a){await t().generateMultimode();return}await t().runGenerate()}function Jf(e,t){const n=t().multimodePreviewFlightId;n&&(jc(n),t().cancelInFlightJob(n),e(r=>{const o=r.multimodeSequences[n];return o?{multimodeSequences:{...r.multimodeSequences,[n]:{...o,status:"canceled"}}}:{}}))}function Bs(e){return(e().missingElementIds??[]).length>0?(e().showToast(O("toast.missingElements"),!0),!0):!1}async function Yf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Bs(t))return;const r=vp(n.adjustedW,n.adjustedH);if(e({customW:n.adjustedW,customH:n.adjustedH,customSizeConfirm:null}),n.continuation.kind==="classic"){await t().runGenerate(r);return}if(n.continuation.kind==="multimode"){await t().generateMultimode(r);return}if(n.continuation.kind==="node-in-place"){await t().runGenerateNodeInPlace(n.continuation.clientId,{sizeOverride:r});return}if(n.continuation.kind==="node-variation"){await t().generateNodeVariation(n.continuation.clientId,r);return}await t().runGenerateNode(n.continuation.clientId,r)}async function Xf(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return;const{prompt:o}=r.data;if(!o.trim()){n().showToast(O("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const a=ro(n(),{kind:"node",clientId:e});if(a){t({customSizeConfirm:a});return}await n().runGenerateNode(e)}async function Zf(e,t,n){const r=n().graphNodes.find(a=>a.id===e);if(!r)return;if(!r.data.prompt.trim()){n().showToast(O("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const o=ro(n(),{kind:"node-in-place",clientId:e});if(o){t({customSizeConfirm:o});return}await n().runGenerateNodeInPlace(e)}async function Qf(e,t,n,r){const o=r().graphNodes.find(i=>i.id===e);if(!o)return;if(!o.data.prompt.trim()){r().showToast(O("toast.promptRequired"),!0);return}if(r().videoModelSelected){const i=r().addSiblingNode(e);return r().runVideoGenerate(i)}if(!t){const i=ro(r(),{kind:"node-variation",clientId:e});if(i){n({customSizeConfirm:i});return}}const a=r().addSiblingNode(e);await r().runGenerateNodeInPlace(a,{sizeOverride:t})}async function eh(e,t,n,r){const a=r().graphNodes.find(i=>i.id===e)?.data.status==="ready"?r().addSiblingNode(e):e;await r().runGenerateNodeInPlace(a,{sizeOverride:t})}function Vc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Kc(e){if(e.provider==="comfy"&&e.comfyVideoWorkflow)return{provider:"comfy",model:e.comfyVideoWorkflow};const t=e.provider==="grok-api"?"grok-api":"grok",n=typeof e.videoModelSelected=="string"?e.videoModelSelected:void 0;return n?{provider:t,model:n}:{provider:t}}function Bc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function th(e,t,n){const r=e?n().graphNodes.find(I=>I.id===e):null,o=r?r.data.referenceImages??[]:n().referenceImages,a=o.length===1&&n().videoSingleRefMode==="image-to-video",i=r?r.data.prompt.trim():On(n().prompt,n().insertedPrompts);if(!i.trim()){n().showToast(Lr,!0);return}const l=n(),c=ao({catalog:io(),presetIds:l.selectedPresetIds,provider:Bc(l.provider),mode:"video"}),d=c.promptFragment?`${c.promptFragment} ${i}`:i;let m,u,p=r?r.data.videoContinuity??null:n().videoContinuityLineage,h;if(r&&o.length===0&&r.data.parentServerNodeId){const I=n().graphNodes.find(_=>_.data.serverNodeId===r.data.parentServerNodeId);if(I?.data.imageUrl)if(tt(I.data.imageUrl))try{const _=I.data.imageUrl.replace(/^\/generated\//,"");u=(await Hf.extractFrame({kind:"generated",filename:_},"last")).dataUrl,p=I.data.videoContinuity??$c({filename:_,prompt:I.data.prompt,userPrompt:I.data.prompt,revisedPrompt:I.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=_}catch{n().showToast(O("video.continuationFallbackT2V"),!0)}else m=I.data.imageUrl.replace(/^\/generated\//,"")}const x=Date.now(),S=x,b=`vid_${x}_${Math.random().toString(36).slice(2,6)}`,v=new AbortController;an(b,v);const y=n().activeSessionId,w=[...n().inFlight,{id:b,prompt:d,startedAt:x,kind:"video",sessionId:y,clientNodeId:e??null}];Pe(w),r&&t({graphNodes:n().graphNodes.map(I=>I.id===e?{...I,data:{...I.data,status:"pending",pendingRequestId:b,pendingPhase:"queued",pendingStartedAt:x,partialImageUrl:null,error:void 0,errorInfo:null}}:I)}),t({inFlight:w,activeGenerations:w.length,videoProgress:0}),n().startInFlightPolling();try{const I=n().providerUrlReference,_={prompt:d,requestId:b,...Kc(n()),referenceImages:o.length>0&&!a?o:void 0,sourceImage:a?o[0]:o.length>0?void 0:u,sourceFilename:o.length===0&&!u?m:void 0,continueFromVideo:h,continuityLineage:p,duration:n().videoDuration,resolution:n().videoResolution,aspectRatio:n().videoAspectRatio,...n().videoReferenceVoices.length>0?{referenceAudios:n().videoReferenceVoices}:{},topic:n().videoTopic||void 0,storyboard:n().storyboardActive||void 0,presetIds:c.appliedPresetIds,elementIds:Vc(n()),sessionId:y,clientNodeId:e??null,...I?{providerUrl:I}:{}},N=await gs(_,{onPlanning:()=>t({inFlight:n().inFlight.map(j=>j.id===b?{...j,phase:"planning"}:j)}),onSubmitted:()=>t({inFlight:n().inFlight.map(j=>j.id===b?{...j,phase:"streaming"}:j)}),onProgress:({progress:j})=>t({videoProgress:j??null})},{signal:v.signal});if(r&&N&&n().activeSessionId===y&&(t({graphNodes:n().graphNodes.map(j=>j.id===e?{...j,data:{...j.data,serverNodeId:N.filename.replace(/\.[^.]+$/,""),imageUrl:N.url,status:"ready",error:void 0,errorInfo:null,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:N.elapsed??void 0,model:N.effectiveModel??N.requestedModel??r.data.model??null,videoContinuity:N.videoContinuity??p,video:{...N.video??{},...N.videoSeries?.topic?{topic:N.videoSeries.topic}:{}}}}:j)}),n().scheduleGraphSave(),n().flushGraphSave("video-node-complete")),N){const j={image:N.url,filename:N.filename,url:N.url,mediaType:"video",prompt:d,elapsed:N.elapsed,video:N.video??{},videoSeries:N.videoSeries??null,videoContinuity:N.videoContinuity??null,revisedPrompt:N.revisedPrompt??null,requestId:N.requestId??b,createdAt:Date.now(),sessionId:y};await bt(j,t,n,{autoSelectStartedAt:S})}}catch(I){if(on(I))r&&n().activeSessionId===y&&t({graphNodes:n().graphNodes.map(_=>_.id===e?{..._,data:{..._.data,status:_.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0,errorInfo:null}}:_)});else{const _=at(I).code==="JOB_TRACKING_TIMEOUT",N=_?We(I,n()).message:I instanceof Error?I.message:"Video generation failed",j=_?{...Nc(I),message:N}:null;r&&n().activeSessionId===y&&t({graphNodes:n().graphNodes.map(L=>L.id===e?{...L,data:{...L.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:N,errorInfo:j}}:L)}),_||n().showToast(N,!0)}}finally{const I=n().inFlight.filter(_=>_.id!==b);Pe(I),ln(b),t({inFlight:I,activeGenerations:I.length,videoProgress:null}),n().startInFlightPolling()}}async function nh(e,t,n,r){const o=t?.trim();if(!o)throw r().showToast(Lr,!0),new Error(Lr);if(Bs(r))return!1;const a=r(),i=ao({catalog:io(),presetIds:a.selectedPresetIds,provider:Bc(a.provider),mode:"video"}),l=i.promptFragment?`${i.promptFragment} ${o}`:o,c=Date.now(),d=c,m=`vid_${c}_${Math.random().toString(36).slice(2,6)}`,u=new AbortController;an(m,u);const p=[...r().inFlight,{id:m,prompt:l,startedAt:c,kind:"video",sessionId:r().activeSessionId,clientNodeId:null}];Pe(p),n({inFlight:p,activeGenerations:p.length,videoProgress:0}),r().startInFlightPolling();try{const h={prompt:l,presetIds:i.appliedPresetIds,elementIds:Vc(r()),requestId:m,...Kc(r()),mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},x=await gs(h,{onPlanning:()=>n({inFlight:r().inFlight.map(b=>b.id===m?{...b,phase:"planning"}:b)}),onSubmitted:()=>n({inFlight:r().inFlight.map(b=>b.id===m?{...b,phase:"streaming"}:b)}),onProgress:({progress:b})=>n({videoProgress:b??null})},{signal:u.signal}),S={image:x.url,filename:x.filename,url:x.url,mediaType:"video",prompt:l,elapsed:x.elapsed,video:x.video??{},videoSeries:x.videoSeries??null,videoContinuity:x.videoContinuity??null,revisedPrompt:x.revisedPrompt??null,requestId:x.requestId??m,createdAt:Date.now(),sessionId:r().activeSessionId};await bt(S,n,r,{autoSelectStartedAt:d})}catch(h){return on(h)||(at(h).code==="JOB_TRACKING_TIMEOUT"?We(h,r()):r().showToast(h instanceof Error?h.message:"Video generation failed",!0)),!1}finally{const h=r().inFlight.filter(x=>x.id!==m);Pe(h),ln(m),n({inFlight:h,activeGenerations:h.length,videoProgress:null}),r().startInFlightPolling()}return!0}function is(e){return JSON.stringify([e.startedAt,e.kind??"classic",e.sessionId??null,e.parentNodeId??null,e.clientNodeId??null,e.phase??null,e.prompt,e.composerPrompt??null,e.composerInsertedPrompts??null])}function Cn(e){const t=new Map([...ic({includeExpired:!0}),...e.inFlight].map(n=>[n.id,n]));return{uiMode:e.uiMode,activeSessionId:e.activeSessionId??null,local:t,revisions:new Map([...t].map(([n,r])=>[n,is(r)])),memory:new Map(e.inFlight.map(n=>[n.id,n])),scopes:Cp({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function Ws(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function Wc(e,t){return new Set([...t.local].filter(([n,r])=>{const o=e.memory.has(n)&&t.memory.has(n)&&e.memory.get(n)!==t.memory.get(n);return e.local.has(n)&&e.revisions.get(n)===t.revisions.get(n)&&!o&&kn(r,e.scopes)}).map(([n])=>n))}function rh(e,t,n){const r=Rr(t),o=n==="reconcile"?{...e,...r,prompt:e.prompt||r.prompt,phase:e.phase||r.phase}:{...e,phase:r.phase,kind:r.kind,sessionId:r.sessionId,parentNodeId:r.parentNodeId,clientNodeId:r.clientNodeId};return is(o)===is(e)?e:o}function oh(e,t,n,r,o){if(t&&(o.mode==="reconcile"||!n))return[kn(Rr(t),r.scopes)?rh(e,t,o.mode):e];if(n)return kn(Rr(n),r.scopes)?(n.status==="error"&&o.terminalErrors.push(Ap(n)),[]):[e];const a=o.now-e.startedAt;return(o.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function Jc(e,t,n,r){if(!Ws(e,t))return null;const o=Cn(t),a=Wc(e,o),i=new Map(n.jobs.map(u=>[u.requestId,u])),l=new Map(n.terminalJobs.map(u=>[u.requestId,u])),c=[],d=[...o.local.values()].flatMap(u=>a.has(u.id)?oh(u,i.get(u.id),l.get(u.id),e,{...r,terminalErrors:c}):[u]),m=new Set;for(const[u,p]of i){const h=Rr(p);kn(h,e.scopes)&&(m.add(u),!((h.kind??"classic")==="classic"&&e.uiMode==="node")&&(h.kind==="node"&&(e.uiMode!=="node"||(h.sessionId??null)!==e.activeSessionId)||!e.local.has(u)&&!o.local.has(u)&&d.push(h)))}return{inFlight:d,terminalErrors:c,eligibleIds:a,serverActiveIds:m}}let An=0;function Tn(){if(An+=1,typeof window>"u")return;const e=window;e.__ima2InflightTimer!==void 0&&clearInterval(e.__ima2InflightTimer),e.__ima2InflightTimer=void 0,e.__ima2StopTicks=0,window.removeEventListener(Nt,Tn)}function sh(e,t,n){const r=n();Pe(e.inFlight),(e.inFlight.length!==r.inFlight.length||r.activeGenerations!==e.inFlight.length||e.inFlight.some((o,a)=>o!==r.inFlight[a]))&&t({inFlight:e.inFlight,activeGenerations:e.inFlight.length});for(const o of e.terminalErrors)We(o,n())}function ah(e,t){e.length&&t(n=>{const r=new Set(n.history.map($e)),o=e.filter(a=>{const i=$e(a);return r.has(i)?!1:(r.add(i),!0)});return o.length?(!n.currentImage&&o[0]?.filename&&it(o[0].filename),{history:no([...o,...n.history],Math.max(Ve,n.history.length+o.length)),currentImage:n.currentImage??o[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+o.length)}):{}})}function ih(e,t,n){const r=Cn(n()),o=Wc(e.snapshot,r),a=Date.now(),i=[...r.local.values()].filter(l=>!e.eligibleIds.has(l.id)||!o.has(l.id)||e.serverActiveIds.has(l.id)||a-l.startedAt<sc);i.length!==r.local.size&&(Pe(i),t({inFlight:i,activeGenerations:i.length}))}async function lh(e,t,n,r,o){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await en({limit:Ve,since:a});if(!o()||!Ws(e,r()))return;ah(i.map(Gn),n),t&&ih(t,n,r)}catch{}}function ch(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function dh(e,t,n){if(ue()){Tn();return}const r=he(),o=An,a=()=>!ue()&&r===he()&&o===An,i=Cn(t());let l=null;if(!ch(t(),n))try{const c=await ac(i.scopes);if(!a())return;const d=Jc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;sh(d,e,t),l={snapshot:Cn(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&Ws(i,t())&&await lh(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&Tn()}function uh(e,t){if(typeof window>"u"||ue())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(Nt,Tn),n.__ima2InflightTimer=window.setInterval(()=>dh(e,t,n),1500))}async function mh(e,t){if(ue())return;const n=he(),r=An;try{const o=Cn(t()),a=await ac(o.scopes);if(ue()||n!==he()||r!==An)return;const i=Jc(o,t(),a,{mode:"reconcile",now:Date.now()});if(!i)return;Pe(i.inFlight),e({inFlight:i.inFlight,activeGenerations:i.inFlight.length});for(const l of i.terminalErrors)We(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const jt=()=>"nc_"+Math.random().toString(36).slice(2,10);function Xa(e,t){return{x:e*360,y:t*320}}const ph=360,Yc=320;function fh(e,t,n){const r=new Set(n.filter(o=>o.source===e).map(o=>o.target));return t.filter(o=>r.has(o.id))}function Js(e){const t=e.filter(r=>!r.data.parentServerNodeId);if(t.length===0)return Xa(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:Xa(0,0).x,y:n+Yc}}function Xc(e,t,n){const r=fh(e.id,t,n),o=e.position.x+ph;if(r.length===0)return{x:o,y:e.position.y};const a=Math.max(...r.map(i=>i.position.y));return{x:o,y:a+Yc}}const Pn="source-right",Rn="target-left";function lo(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function hh(e,t){return e&&e.startsWith(`${t}-`)?e:null}function gh(e){switch(e){case"source-top":return"target-bottom";case"source-right":return"target-left";case"source-bottom":return"target-top";case"source-left":return"target-right";default:return null}}function yh(e,t){const n=jt();t().recordGraphHistory("add-root");const r={id:n,type:"imageNode",position:Js(t().graphNodes),data:{clientId:n,serverNodeId:null,parentServerNodeId:null,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return e({graphNodes:[...t().graphNodes,r]}),t().scheduleGraphSave(),n}function vh(e,t,n){const r=jt();n().recordGraphHistory("add-root-from-history");const o={id:r,type:"imageNode",position:Js(n().graphNodes),data:{clientId:r,serverNodeId:e.nodeId??null,parentServerNodeId:null,prompt:e.prompt??"",imageUrl:e.image,status:"ready",pendingRequestId:null,pendingPhase:null,model:e.model??null,size:e.size??null,elapsed:e.elapsed??void 0,video:e.video??null}};return t({uiMode:"node",graphNodes:[...n().graphNodes,o]}),n().scheduleGraphSave(),r}function bh(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return e;n().recordGraphHistory("add-child");const o=jt(),a={id:o,type:"imageNode",position:Xc(r,n().graphNodes,n().graphEdges),data:{clientId:o,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:tt(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:lo(e,o,Pn,Rn),source:e,target:o,sourceHandle:Pn,targetHandle:Rn};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&tt(r.data.imageUrl)){const l=r.data.imageUrl;r.data.video&&r.data.video.topic&&n().setVideoTopic(r.data.video.topic),(async()=>{try{const c=await sn(l);t({graphNodes:n().graphNodes.map(d=>d.id===o?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return o}function xh(e,t,n){const r=n().graphNodes.find(m=>m.id===e);if(!r)return e;n().recordGraphHistory("add-sibling");const o=n().graphEdges.find(m=>m.target===e);if(!o){const m=jt(),u={id:m,type:"imageNode",position:Js(n().graphNodes),data:{clientId:m,serverNodeId:null,parentServerNodeId:null,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...n().graphNodes,u]}),n().scheduleGraphSave(),m}const a=o.source,i=n().graphNodes.find(m=>m.id===a);if(!i)return e;const l=jt(),c={id:l,type:"imageNode",position:Xc(i,n().graphNodes,n().graphEdges),data:{clientId:l,serverNodeId:null,parentServerNodeId:r.data.parentServerNodeId,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},d={id:lo(a,l,Pn,Rn),source:a,target:l,sourceHandle:Pn,targetHandle:Rn};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function Sh(e,t,n,r,o){const a=o().graphNodes.find(u=>u.id===e);if(!a)return e;o().recordGraphHistory("add-child-at");const i=jt(),l=hh(n,"source")??Pn,c=gh(l)??Rn,d={id:i,type:"imageNode",position:t,data:{clientId:i,serverNodeId:null,parentServerNodeId:a.data.serverNodeId,prompt:"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},m={id:lo(e,i,l,c),source:e,target:i,sourceHandle:l,targetHandle:c};return r({graphNodes:[...o().graphNodes,d],graphEdges:[...o().graphEdges,m]}),o().scheduleGraphSave(),i}function Ih(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return e;n().recordGraphHistory("duplicate-branch");const o=jt(),a={id:o,type:"imageNode",position:{x:r.position.x+420,y:r.position.y+40},data:{clientId:o,serverNodeId:null,parentServerNodeId:null,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};if(t({graphNodes:[...n().graphNodes,a]}),n().scheduleGraphSave(),r.data.imageUrl){const i=r.data.imageUrl;(async()=>{try{const l=await zn(i,"node-reference.png");t({graphNodes:n().graphNodes.map(c=>c.id===o?{...c,data:{...c.data,referenceImages:[l]}}:c)})}catch{}})()}return o}function wh(e,t,n,r){n({graphNodes:r().graphNodes.map(o=>o.id===e?{...o,data:{...o.data,prompt:t}}:o)}),r().scheduleGraphSave()}function _h(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return;n().recordGraphHistory("delete-node");const o=r?.data?.pendingRequestId;o&&Ae(o),Us(n().activeSessionId,e);const a=n().graphNodes.filter(l=>l.id!==e),i=n().graphEdges.filter(l=>l.source!==e&&l.target!==e);t({graphNodes:De(a,i),graphEdges:i}),n().scheduleGraphSave()}function Eh(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)Us(n().activeSessionId,i);for(const i of n().graphNodes)r.has(i.id)&&i.data?.pendingRequestId&&Ae(i.data.pendingRequestId);const o=n().graphNodes.filter(i=>!r.has(i.id)),a=n().graphEdges.filter(i=>!r.has(i.source)&&!r.has(i.target));t({graphNodes:De(o,a),graphEdges:a}),n().scheduleGraphSave()}function Nh(e,t,n){const r=new Set(e);if(r.size===0)return;const o=n().graphEdges.filter(c=>r.has(c.id));if(o.length===0)return;n().recordGraphHistory("disconnect-edges");const a=n().graphEdges.filter(c=>!r.has(c.id)),i=new Set(o.map(c=>c.target)),l=n().graphNodes.map(c=>{if(!i.has(c.id))return c;const d=a.find(u=>u.target===c.id),m=d?n().graphNodes.find(u=>u.id===d.source):null;return{...c,data:{...c.data,parentServerNodeId:m?.data.serverNodeId??null}}});t({graphNodes:De(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(O("edge.disconnected"))}function kh(e,t,n,r,o,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(zp(a().graphEdges,e,t)){a().showToast(O("edge.cycleBlocked"),!0);return}if(!a().graphNodes.find(d=>d.id===e))return;a().recordGraphHistory("connect-nodes");const c=[...a().graphEdges,{id:lo(e,t,n,r),source:e,target:t,sourceHandle:n,targetHandle:r}];o({graphNodes:De(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function jh(e,t,n,r){const o=r().graphNodes.find(h=>h.id===e);if(!o)return;const a=o.data.referenceImages??[],l=r().referenceLimit-a.length;if(l<=0){r().showToast(O("toast.refLimitExceeded"),!0);return}const c=t.slice(0,Math.max(0,l)),d=c.filter(Pr),m=c.filter(h=>!Pr(h)),p=(await Promise.all(m.map(async h=>{try{return await Os(h,{preserveTransparency:oc(h)})}catch(x){return console.warn("[addNodeReferences] compress failed",x),null}}))).filter(h=>!!h);if(p.length>0){const h=r().activeSessionId;n({graphNodes:r().graphNodes.map(x=>{if(x.id!==e)return x;const S=[...x.data.referenceImages??[],...p].slice(0,r().referenceLimit);return oo(h,e,S),{...x,data:{...x.data,referenceImages:S}}})}),r().scheduleGraphSave()}d.length>0&&r().showToast(O("toast.refHeicUnsupported"),!0),m.length-p.length>0&&r().showToast(O("toast.refTooLarge"),!0),t.length>l&&r().showToast(O("toast.refLimitExceeded"),!0)}function Zc(e,t,n,r){r().graphNodes.find(a=>a.id===e)&&(n({graphNodes:r().graphNodes.map(a=>{if(a.id!==e)return a;const i=a.data.referenceImages??[];if(i.length>=r().referenceLimit)return a;const l=[...i,t];return oo(r().activeSessionId,e,l),{...a,data:{...a.data,referenceImages:l}}})}),r().scheduleGraphSave())}async function Ch(e,t,n,r,o){const a=o().graphNodes.find(l=>l.id===e);if(!a)return;if((a.data.referenceImages??[]).length>=o().referenceLimit){o().showToast(O("toast.refLimitExceeded"),!0);return}let i;try{i=tt(t)||tt(n)?await sn(t):await zn(t,n||"node-reference.png")}catch{o().showToast(O("toast.currentImageLoadFailed"),!0);return}Zc(e,i,r,o)}function Ah(e,t,n,r){n({graphNodes:r().graphNodes.map(o=>{if(o.id!==e)return o;const a=(o.data.referenceImages??[]).filter((i,l)=>l!==t);return oo(r().activeSessionId,e,a),{...o,data:{...o.data,referenceImages:a}}})}),r().scheduleGraphSave()}function Th(e,t,n){Us(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const Za=10;function Qc(e,t){return t?t.filename&&e.filename===t.filename?!0:e.image===t.image:!1}function Ph(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(t=>!!t)}function Ft(e){return e.filter(t=>!t.canvasVersion)}function st(e,t){if(!t)return null;const n=Ft(e);if(!t.canvasVersion)return n.find(a=>Qc(a,t))??null;const r=Ph(t);return n.find(a=>a.filename?r.includes(a.filename):!1)??null}function Rh(e,t){const n=Ft(e),r=st(e,t);return n.findIndex(o=>Qc(o,r))}function Mh(e,t,n){const r=Ft(e);if(r.length===0)return null;if(n==="first")return r[0]??null;if(n==="last")return r[r.length-1]??null;const o=Rh(e,t);if(o<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-Za:Za,l=Math.max(0,Math.min(r.length-1,o+i));return r[l]??null}const a=n==="previous"?o-1:o+1;return r[a]??null}function ed(e,t){const n=Ft(e),r=n.findIndex(o=>o.filename===t);return r<0?null:n[r+1]??n[r-1]??null}function Te(e){return e.filename||e.image}function In(e){return!e.canvasVersion}function wr(e){const t=new Set;return e.filter(n=>{const r=Te(n);return t.has(r)?!1:(t.add(r),!0)})}const td=72,Qa=10;function nd(e,t){const n=e.sequenceIndex??Number.MAX_SAFE_INTEGER,r=t.sequenceIndex??Number.MAX_SAFE_INTEGER;return n!==r?n-r:(e.createdAt??0)-(t.createdAt??0)}function Lh(e){return e<=1?1:e===2?2:4}function rd(e){const t=new Set,n=new Map,r=[];for(const o of e){if(!In(o))continue;if(o.sequenceId){const i=`sequence:${o.sequenceId}`;let l=n.get(o.sequenceId);l||(l={type:"sequence",key:i,sequenceId:o.sequenceId,items:[]},n.set(o.sequenceId,l),r.push(l)),l.items.push(o);continue}const a=Te(o);t.has(a)||(t.add(a),r.push({type:"image",key:a,item:o}))}for(const o of n.values())o.items.sort(nd);return r}function od(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Te(e):null}function So(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function Oh(e,t,n,r,o=td){const a=rd(e).slice(0,o);if(a.length===0)return null;const i=a[0],l=a[a.length-1];if(!i||!l)return null;if(n==="first")return So(i);if(n==="last")return So(l);const c=od(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const m=n==="pagePrevious"?-Qa:n==="pageNext"?Qa:n==="previous"?-1:1,u=Math.max(0,Math.min(a.length-1,d+m));if(u===d)return null;const p=a[u];return p?So(p):null}const sd={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},Fh={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},Dh={default:sd,"prompt-studio":Fh};function $n(e,t){return Dh[e]??sd}function Gh(e,t){return $n(e).promptBuilderSurface!=="off"}const zh="history:";function ad(e,t,n){if(!t||n||!t.startsWith(zh)||!(t in e))return e;const r={...e};return delete r[t],r}function Uh(e){const t=e.multimodePreviewFlightId;return t?t.startsWith("history:")?t.slice(8):e.multimodeSequences[t]?.sequenceId??null:null}async function $h(e,t){const n=t().historyNextCursor;if(!(!n||t().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const r=await en({limit:Ve,cursor:n}),o=r.items.map(Gn);e(a=>{const i=new Set(a.history.map(c=>c.filename??c.image)),l=o.filter(c=>{const d=c.filename??c.image;return i.has(d)?!1:(i.add(d),!0)});return{history:[...a.history,...l],historyNextCursor:r.nextCursor,historyLoadingOlder:!1,loadedHistoryRetainLimit:Math.max(a.loadedHistoryRetainLimit,a.history.length+l.length)}})}catch{e({historyLoadingOlder:!1}),t().showToast(O("gallery.loadOlderFailed"),!0)}}}async function qh(e,t){try{const n=await en({limit:Ve,favoritesOnly:!0}),r=n.items.map(Gn);e(o=>{const a=uc(o.history,r);return{history:a,favoriteHistoryNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(o.loadedHistoryRetainLimit,a.length),galleryFavorites:new Set([...Array.from(o.galleryFavorites),...r.filter(i=>i.filename).map(i=>i.filename)])}})}catch{t().showToast(O("gallery.loadOlderFailed"),!0)}}async function Hh(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await en({limit:Ve,cursor:n,favoritesOnly:!0}),o=r.items.map(Gn);e(a=>{const i=uc(a.history,o);return{history:i,favoriteHistoryNextCursor:r.nextCursor,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:Math.max(a.loadedHistoryRetainLimit,i.length),galleryFavorites:new Set([...Array.from(a.galleryFavorites),...o.filter(l=>l.filename).map(l=>l.filename)])}})}catch{e({favoriteHistoryLoadingOlder:!1}),t().showToast(O("gallery.loadOlderFailed"),!0)}}}function Vh(e,t,n){const r=Date.now(),o=n().history,a=e.canvasVersion?st(o,e)??Ft(o)[0]??null:st(o,e)??e;it(a?.filename??null);const i=$n(n().workspaceProfile).restoreComposerFromHistory,l=n().prompt,c=n().insertedPrompts,d=l.trim()!==""||c.length>0,m=i&&a&&!d?lp(a):{},u=n().multimodePreviewFlightId,p=u?n().multimodeSequences[u]:null,h=p&&a&&p.images.some(x=>x.filename===a.filename);t(x=>({currentImage:a,lastHistorySelectedAt:r,unseenGeneratedCount:0,multimodePreviewFlightId:h?u:null,multimodeSequences:ad(x.multimodeSequences,u,!!h),...m}))}function Kh(e,t,n){const r=Date.now(),o=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(nd);if(o.length===0)return;const a=`history:${e}`,i=Math.max(o.length,...o.map(d=>d.sequenceTotalRequested??0)),l=o.length,c=o[0]?.sequenceStatus==="empty"?"empty":l>=i?"complete":"partial";it(null),t(d=>({currentImage:null,lastHistorySelectedAt:r,unseenGeneratedCount:0,canvasOpen:!1,multimodePreviewFlightId:a,multimodeSequences:{...ad(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:o,partials:[],status:c}}}))}function Bh(e,t,n){const r=n(),o=$n(r.workspaceProfile);if(r.uiMode==="classic"&&o.multimodeHistoryGrouping==="sequence"){const i=Oh(r.history,r.currentImage,e,Uh(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=Mh(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function Wh(e,t,n){const r=e.canvasVersion?st(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(O("gallery.deleteFailed"),!0);return}const o=r.filename,a=n().currentImage,l=(a?st(n().history,a)??a:null)?.filename===o,c=l?ed(n().history,o):a;try{await tl(o),t(d=>{const m=Rp(d.multimodeSequences,o),u=d.multimodePreviewFlightId&&!m[d.multimodePreviewFlightId]?null:d.multimodePreviewFlightId;return{history:d.history.filter(p=>p.filename!==o),currentImage:c,multimodePreviewFlightId:u,multimodeSequences:m,trashPending:null}}),l&&it(c?.filename??null),n().showToast(O("gallery.movedToSystemTrash",{filename:o}))}catch(d){console.error("[history] trash failed",d),n().showToast(O("gallery.deleteFailed"),!0)}}async function Jh(e,t,n){const r=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion&&!!d.filename);if(r.length===0){n().showToast(O("gallery.deleteFailed"),!0);return}if(!window.confirm(O("history.deleteSequenceConfirm",{count:r.length})))return;const a=new Set(r.map(d=>d.filename).filter(d=>!!d)),i=n().currentImage,l=!!(i?.filename&&a.has(i.filename)),c=n().multimodePreviewFlightId===`history:${e}`||n().multimodePreviewFlightId===e;try{for(const d of a)await tl(d);t(d=>{const m={...d.multimodeSequences};return delete m[`history:${e}`],delete m[e],{history:d.history.filter(u=>!u.filename||!a.has(u.filename)),currentImage:l?null:d.currentImage,multimodePreviewFlightId:c?null:d.multimodePreviewFlightId,multimodeSequences:m,trashPending:null}}),l&&it(null),n().showToast(O("history.sequenceDeleted",{count:a.size}))}catch(d){console.error("[history] sequence trash failed",d),n().showToast(O("gallery.deleteFailed"),!0)}}async function Yh(e,t){const n=t().trashPending;if(n)try{await $u(n.filename,n.trashId),t().addHistoryItem(n.item),e({trashPending:null})}catch(r){console.error("[history] restore failed",r),t().showToast(O("gallery.restoreFailed"),!0)}}async function Xh(e,t,n){const r=e.canvasVersion?st(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(O("gallery.deleteFailed"),!0);return}const o=r.filename;if(!window.confirm(O("result.permanentDeleteConfirm",{filename:o})))return;const i=n().currentImage,c=(i?st(n().history,i)??i:null)?.filename===o,d=c?ed(n().history,o):i;try{await Uu(o),t(m=>({history:m.history.filter(u=>u.filename!==o),currentImage:d,trashPending:m.trashPending?.filename===o?null:m.trashPending})),c&&it(d?.filename??null),n().showToast(O("gallery.permanentDeleted",{filename:o}))}catch(m){console.error("[history] permanent delete failed",m),n().showToast(O("gallery.deleteFailed"),!0)}}function Zh(e,t,n){const r=n(),o=r.history.filter(i=>i.filename!==e),a=r.currentImage&&r.currentImage.filename===e?null:r.currentImage;t({history:o,currentImage:a}),a===null&&it(null)}function Qh(e,t,n){const r=n(),o={...e,createdAt:e.createdAt||Date.now()},a=cc(r.history,o),i=dc(o,a),l=lc(r.history,i);t({history:no([i,...l],r.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(r.loadedHistoryRetainLimit,Math.min(r.history.length+1,r.loadedHistoryRetainLimit+1))})}async function eg(e,t,n){if(!e.type||!/^image\/(png|jpeg|webp)$/.test(e.type))return n().showToast(O("toast.localImportInvalid"),!0),null;try{const r=await Ou(e);return n().addHistoryItem(r),t({currentImage:r,unseenGeneratedCount:0}),r.filename&&it(r.filename),n().showToast(O("toast.localImportSuccess")),r}catch{return n().showToast(O("toast.localImportFailed"),!0),null}}function tg(e,t){(async()=>{try{const n=await en({limit:Ve}),r=n.items.map(Gn);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Ve}),r.length>0){const o=Jl(),a=o?r.find(c=>c.filename===o):null,i=Ft(r),l=(a?st(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(Ve,r.length)}),l?.filename!==o&&it(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function id(e,t){try{const{sessions:n}=await Hu();if(e({sessions:n}),!t().activeSessionId){const o=yp(),a=o?n.some(i=>i.id===o):!1;o&&a?await t().switchSession(o):await t().createAndSwitchSession(O("session.firstGraph"))}}catch(n){console.warn("[sessions] load failed:",n),t().showToast(O("modal.sessionInitialLoadFailed"),!0),window.confirm(O("modal.sessionInitialLoadRetry"))&&await id(e,t)}}async function ng(e,t,n){if(e!==n().activeSessionId){try{await n().flushGraphSave("switch-session")}catch(r){console.warn("[sessions] switch blocked by save failure:",r),t({sessionLoading:!1}),n().showToast(O("modal.sessionSwitchSaveFailed"),!0);return}t({sessionLoading:!0});try{const{session:r}=await nl(e),{graphNodes:o,graphEdges:a,graphVersion:i}=vc(r);t({activeSessionId:e,activeSessionGraphVersion:i,graphNodes:o,graphEdges:a,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),Ls(e),await n().reconcileGraphPending().catch(()=>{})}catch(r){console.warn("[sessions] switch failed:",r),t({sessionLoading:!1}),n().showToast(O("toast.sessionLoadFailed"),!0)}}}async function rg(e,t){const n=t().activeSessionId;if(!n)return;if(t().graphNodes.filter(o=>o.data?.pendingRequestId&&(o.data.status==="pending"||o.data.status==="reconciling")).length>0){let o=[];try{o=(await Zi({kind:"node",sessionId:n})).jobs}catch{o=[]}const a=new Map(o.map(d=>[d.requestId,d.phase])),i=Date.now(),l=1e4,c=t().graphNodes.map(d=>{const m=d.data?.pendingRequestId;if(!m||d.data.status!=="pending"&&d.data.status!=="reconciling")return d;if(a.has(m)){const h=a.get(m)??null;return{...d,data:{...d.data,status:"reconciling",pendingPhase:h}}}const u=d.data.pendingStartedAt??0;if(u&&i-u<l)return{...d,data:{...d.data,status:"reconciling"}};const p=!!d.data.imageUrl||!!d.data.serverNodeId;return{...d,data:{...d.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:p?"ready":"stale",error:p?void 0:O("session.assetAbortedError")}}});e({graphNodes:c})}await wc(t,e).catch(()=>{})}async function og(e,t,n){e==null&&(e=O("session.untitled"));try{const{session:r}=await Vu(e);t({sessions:[r,...n().sessions],activeSessionId:r.id,activeSessionGraphVersion:r.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),Ls(r.id)}catch(r){console.warn("[sessions] create failed:",r),n().showToast(O("toast.sessionCreateFailed"),!0)}}async function sg(e,t,n){const r=n().activeSessionId;if(r)try{await Ku(r,e),t({sessions:n().sessions.map(o=>o.id===r?{...o,title:e,updatedAt:Date.now()}:o)})}catch{n().showToast(O("toast.sessionRenameFailed"),!0)}}async function ag(e,t,n){try{await Bu(e);const r=n().sessions.filter(o=>o.id!==e);t({sessions:r}),n().activeSessionId===e&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),Ls(null),r.length>0?await n().switchSession(r[0].id):await n().createAndSwitchSession(O("session.firstGraph")))}catch{n().showToast(O("toast.sessionDeleteFailed"),!0)}}function ig(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),n.imageToolModel=e.provider==="api"&&Is(t.imageToolModel)?t.imageToolModel:null,n.quality=Lt(e.provider,n.imageToolModel,Xl(t.quality)?t.quality:e.quality),Zl(t.format)&&(n.format=t.format),Ql(t.moderation)&&(n.moderation=t.moderation),(t.promptMode==="auto"||t.promptMode==="direct")&&(n.promptMode=t.promptMode),t.model&&gm(t.model)&&(n.imageModel=t.model);const o=bp(t.size);return o.preset&&(n.sizePreset=o.preset),o.preset==="custom"&&o.w&&o.h&&(n.customW=ot(o.w,e.customW),n.customH=ot(o.h,e.customH)),n}function qn(e,t){return Ks(e,t)}function Ys(e){const t=/^data:(image\/(?:png|jpeg|webp));/i.exec(e)?.[1]?.toLowerCase();return t==="image/png"||t==="image/jpeg"||t==="image/webp"?t:null}function ld(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function Xs(e,t){return qn(t,(n,r)=>{const o=[...n.trayItems];let a=n.retiredTags;const i=new Set(o.map(d=>d.tag)),l=[];let c=n.nextAttachmentOrdinal;for(const d of e){if(!Hs(o,r))break;const m=Tc(c,i),u=ld(d,m.tag);o.push(u),l.push(u),i.add(u.tag),a=Vs(a,u.tag),c=m.nextAttachmentOrdinal}return l.length===0?{result:l}:{result:l,patch:{trayItems:o,nextAttachmentOrdinal:c,retiredTags:a,providerUrlReference:null}}})}function lg(e,t,n){return Xs(e,t)}function co(e,t,n,r){const o=Ys(e);return o?Xs([{dataUrl:e,mimeType:o,origin:t}],n)[0]??null:null}function cg(e,t,n){co(e,"gallery",t)}async function dg(e,t,n){const r=n().activeReferenceLimit(),o=Math.max(0,r-n().trayItems.length),a=e.slice(0,o),i=a.filter(Pr),l=a.filter(u=>!Pr(u)),d=(await Promise.all(l.map(async u=>{try{const p=await Os(u,{preserveTransparency:oc(u)}),h=Ys(p);return h?{dataUrl:p,mimeType:h,originalName:u.name,byteSize:u.size,origin:"file"}:null}catch(p){return console.warn("[addReferences] compress failed",p),null}}))).filter(u=>u!==null),m=Xs(d,t);i.length>0&&n().showToast(O("toast.refHeicUnsupported"),!0),l.length-d.length>0&&n().showToast(O("toast.refTooLarge"),!0),(e.length>o||d.length>m.length)&&n().showToast(O("toast.refLimitExceeded"),!0)}async function ug(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let o="";try{o=await Gs(e);const a=await Ju({filename:e.name,dataUrl:o});return a.metadata?(n({metadataRestore:{filename:e.name,image:o,metadata:a.metadata,source:a.source??"xmp",targetNodeId:t}}),!0):!1}catch{return r().showToast(O("metadata.readFailed"),!0),!1}}function mg(e,t){const n=t().metadataRestore;if(!n)return;const r=ig(t(),n.metadata);if(te({imageToolModel:r.imageToolModel,quality:r.quality}),r.imageModel&&Bl(r.imageModel),n.targetNodeId&&typeof r.prompt=="string"){const o=r.prompt;e({...r,metadataRestore:null,graphNodes:t().graphNodes.map(a=>a.id===n.targetNodeId?{...a,data:{...a.data,prompt:o}}:a)}),t().scheduleGraphSave()}else e({...r,metadataRestore:null});t().showToast(O("metadata.applied"))}function Zs(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function Qs(e,t){t.length!==e.length&&te({insertedPrompts:t})}function cd(e,t,n){const r=n().insertedPrompts;qn(t,o=>{const a=o.trayItems.find(c=>c.tokenId===e);if(!a)return{result:void 0};const i=o.trayItems.filter(c=>c.tokenId!==e),l={trayItems:i,retiredTags:so(o.retiredTags,[a])};if(a.kind==="attachment"){const c=Un({trayItems:i}).length===0;l.canvasReferenceImage=a.source.dataUrl===o.canvasReferenceImage?null:o.canvasReferenceImage,c&&(l.insertedPrompts=Zs(o),l.videoContinuityLineage=null)}return{result:void 0,patch:l}}),Qs(r,n().insertedPrompts)}function pg(e,t,n){const r=Un(n())[e];r&&cd(r.tokenId,t,n)}function fg(e,t){const n=t().insertedPrompts;qn(e,r=>{const o=Un(r);return{result:void 0,patch:{trayItems:r.trayItems.filter(i=>i.kind!=="attachment"),retiredTags:so(r.retiredTags,o),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Zs(r),providerUrlReference:null}}}),Qs(n,t().insertedPrompts)}function hg(e,t){const n=t().insertedPrompts;qn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Zs(r),providerUrlReference:null}})),Qs(n,t().insertedPrompts)}function gg(e,t,n){const r=Un(e).filter(d=>d.source.dataUrl===n.dataUrl||d.source.dataUrl===e.canvasReferenceImage),o=new Set(r.map(d=>d.tokenId)),a=e.trayItems.filter(d=>!o.has(d.tokenId));if(!Hs(a,t))return{result:!1};const i=Tc(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=ld(n,i.tag),c=Vs(so(e.retiredTags,r),l.tag);return{result:!0,patch:{trayItems:[l,...a],nextAttachmentOrdinal:i.nextAttachmentOrdinal,retiredTags:c,canvasReferenceImage:n.dataUrl,providerUrlReference:null}}}async function yg(e,t,n,r){let o;try{o=await zn(r??e.image,e.filename||"canvas-version-reference.png")}catch{throw n().showToast(O("toast.currentImageLoadFailed"),!0),new Error("canvas_reference_attach_failed")}const a=Ys(o);if(!a){n().showToast(O("toast.currentImageLoadFailed"),!0);return}if(!qn(t,(l,c)=>gg(l,c,{dataUrl:o,mimeType:a,originalName:e.filename||"canvas-version-reference.png",origin:"canvas"}))){n().showToast(O("toast.refSlotFull"),!0);return}n().showToast(O("canvas.version.usingAsReference"))}function dd(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function vg(e,t){const n=t().currentImage;if(!n){t().showToast(O("toast.noCurrentImageForRef"),!0);return}if(t().trayItems.length>=t().activeReferenceLimit()){t().showToast(O("toast.refSlotFull"),!0);return}let r;try{r=await zn(dd(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(O("toast.currentImageLoadFailed"),!0);return}if(!co(r,"gallery",e)){t().showToast(O("toast.refSlotFull"),!0);return}t().showToast(O("toast.addedCurrentAsRef"))}async function bg(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(O("toast.refSlotFull"),!0);return}let r;try{r=await zn(dd(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(O("toast.currentImageLoadFailed"),!0);return}if(!co(r,"gallery",t)){n().showToast(O("toast.refSlotFull"),!0);return}n().showToast(O("toast.addedCurrentAsRef"))}function Hn(e){const{provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e();return dt({provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:o,comfyVideoWorkflow:a})}function Vn(e,t,n,r){const o=tc();o[e.provider]={...o[e.provider],...Ta(e)};const a={...o[t.provider],...Ta(t)};r&&delete a[r],o[t.provider]=a,_p(o),Ep(t),n(i=>{const l=t.provider==="api"?i.imageToolModel:null,c=Lt(t.provider,l,i.quality);return te({imageToolModel:l,quality:c}),{...t,imageToolModel:l,quality:c}})}function xg(e,t,n){const r=Hn(n);if(e===r.provider)return;const o=Rt(e)?tc()[e]:void 0,a=Cm(r,e,o);Vn(r,a,t)}function Sg(e,t,n){const r=Hn(n),o=dt({provider:jm(r.provider,e),imageModel:e,videoModelSelected:!1});Vn(r,o,t)}function Ig(e,t,n){const r=Hn(n),o=dt({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:Ot(e)||rt});Vn(r,o,t)}function wg(e,t,n){const r=Hn(n),o=dt({...r,provider:"comfy",comfyWorkflow:e,comfyVideoWorkflow:null});Vn(r,o,t,e===null?"image":void 0)}function _g(e,t,n){const r=Hn(n),o=dt({...r,provider:"comfy",comfyVideoWorkflow:e,videoModelSelected:!1});Vn(r,o,t,e===null?"video":void 0)}function Eg(e,t,n){const r=n.data?.parentServerNodeId;if(r){const a=e.find(i=>i.data?.serverNodeId===r);if(a)return a}const o=t.find(a=>a.target===n.id);return o?e.find(a=>a.id===o.source):void 0}function Ng(e){if(e.providerUrlReference)return 1;if(e.uiMode==="node"){const t=e.graphNodes??[],n=t.find(a=>a.selected),r=n?.data?.referenceImages?.length??0;return r>0?r:n&&Eg(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const kg=1e4;let Mn=[];async function ea(e){const t=await $("/api/mcp/providers",{signal:e});return Mn=Array.isArray(t.providers)?t.providers:[],Mn}function jg(e){return Ji("/api/mcp/providers",e)}function Cg(e,t){return Ji(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function Ag(){return Mn}async function d0(e){const t=window.open("about:blank",`ima2_mcp_${e}`);try{const n=await $(`/api/mcp/providers/${encodeURIComponent(e)}/connect`,{method:"POST"}),r=n.status.authorizationUrl;if(r){if(!t)throw new Error("MCP_POPUP_BLOCKED");t.location.href=r}else t?.close();return n.status}catch(n){throw t?.close(),n}}async function u0(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function m0(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function ud(e,t){const r=(await $(`/api/mcp/providers/${encodeURIComponent(e)}/models`,{signal:t})).models;return{image:Array.isArray(r?.image)?r.image:[],video:Array.isArray(r?.video)?r.video:[]}}function Tg(e,t){if(typeof e.filename!="string"||typeof e.url!="string"||e.mediaType!=="image"&&e.mediaType!=="video")return null;const n=e.model;return{requestId:t,filename:e.filename,url:e.url,mediaType:e.mediaType,provider:typeof e.provider=="string"?e.provider:void 0,model:typeof n=="string"||n===null?n:void 0,createdAt:typeof e.createdAt=="number"?e.createdAt:void 0}}function Pg(e,t){let n=!1;const r=()=>n?!1:(n=!0,o(),a(),!0),o=Tt(e,null,(i,l)=>{if(i==="done"){const c=Tg(l,e);if(!c||!r())return;Promise.resolve(t.onDone(c)).catch(d=>{t.onError?.(d instanceof Error?d:new Error(String(d)))});return}i==="error"&&r()&&t.onError?.(nt(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Qt(()=>{if(!r())return;const i=new Error("MCP generation timed out");i.code="MCP_STREAM_TIMEOUT",t.onError?.(i)});return r}async function Rg(e,t){const n=e.requestId??`mcp_ui_${crypto.randomUUID()}`,r=Pg(n,t);try{const a=(await ea()).find(i=>i.id===e.provider);if(!a||a.status.state!=="connected"){const i=new Error("MCP provider is not connected");throw i.code=a?"MCP_NOT_CONNECTED":"MCP_PROVIDER_UNKNOWN",i}return await Br(),await $("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(o){throw r(),o}}function md(){const[e,t]=g.useState(()=>[...Mn]),[n,r]=g.useState(Mn.length===0),[o,a]=g.useState(null),i=g.useCallback(async()=>{try{const l=await ea();t([...l]),a(null)}catch(l){a(l instanceof Error?l:new Error(String(l)))}finally{r(!1)}},[]);return g.useEffect(()=>{i();const l=window.setInterval(()=>{i()},kg);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:o,refresh:i}}let Or=null;function pd(e){if(at(e).code==="JOB_TRACKING_TIMEOUT")return O("toast.jobTrackingTimeout");const t=e,n=t.code??t.message??"";return n.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")||t.message?.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")?O("mcp.errorUnsupportedInput"):n==="MCP_END_FRAME_REQUIRES_START"?O("mcp.errorEndRequiresStart"):n==="INVALID_MCP_REFERENCES"?O("mcp.errorInvalidReferences"):n==="INVALID_START_FRAME"?O("mcp.errorInvalidFrame"):n.startsWith("INVALID_MCP_TEMP_REFERENCE")||n==="MCP_TEMP_REFERENCES_FAILED"?O("mcp.errorTempReferences"):O(n==="MCP_NOT_CONNECTED"||n==="MCP_PROVIDER_UNKNOWN"?"mcp.selectionUnavailable":"mcp.generateFailed")}async function Mg(e){const t=e.references.filter(a=>a.dataUrl);if(t.length===0)return{selection:e,batchId:null};const n=await $("/api/mcp/temp-references",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({images:t.map(a=>({dataUrl:a.dataUrl,...a.tag?{tag:a.tag}:{}}))})});if(n.files.length!==t.length)throw new Error("MCP_TEMP_REFERENCES_FAILED");let r=0;const o=e.references.map(a=>a.dataUrl?{filename:n.files[r++].filename,...a.tag?{tag:a.tag}:{}}:a);return{selection:{...e,references:o},batchId:n.batchId}}async function Lg(e){try{await $(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function Og(e,t,n){let r=()=>{};const o=new Promise(i=>{r=i});if(await Rg(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(pd(i),!0),r()}}),!n){await t().reconcileInflight(),t().startInFlightPolling();return}let a=null;try{await t().reconcileInflight(),t().startInFlightPolling()}catch(i){a=i}if(await o,a)throw a}async function Fg(e){const t=e();if((t.mcpProvider?Ag().find(c=>c.id===t.mcpProvider):void 0)?.executable===!1){e().showToast(O("mcp.higgsfieldLocked"),!0);return}const r=On(t.prompt,t.insertedPrompts);if(!r)return;const o=t.mcpReferenceSelection??Be();if(ep(o)){e().showToast(O("mcp.referenceTagInvalid"),!0);return}const a=t.selectedElementIds??[];if(t.mcpCharacterElementId&&a.length>0){e().showToast(O("mcp.characterSlotConflictHint"),!0);return}const i=a.map(c=>t.assets.find(d=>d.id===c)).flatMap(c=>{const d=c?.metadata?.refs;if(!Array.isArray(d))return[];const m=c?.name?Vl(c.name):null;return d.filter(u=>typeof u=="string").map(u=>({filename:u,...m?{tag:m}:{}}))}).slice(0,3);let l=null;try{const c=await Mg(o);l=c.batchId;const d=ap({mcpProvider:t.mcpProvider,mcpModel:t.mcpModel,mcpMediaKind:t.mcpMediaKind,mcpRatio:t.mcpRatio,mcpParameters:t.mcpParameters,mcpInputRoles:t.mcpInputRoles??[],mcpReferenceSelection:c.selection,currentImageFilename:t.currentImage?.filename??null,mcpCharacterElementId:t.mcpCharacterElementId??null,...i.length>0?{elementReferences:i}:{}},r,`mcp_ui_${crypto.randomUUID()}`);if(!d)return;await Og(d,e,!!l)}catch(c){e().showToast(pd(c),!0)}finally{l&&await Lg(l)}}function cn(e){Dn(null,null,"image"),te({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Be(),mcpCharacterElementId:null,...Or?{generate:Or}:{}})}function uo(e,t,n,r=null,o){if(!e){cn(t);return}Or||(Or=n().generate);const a=n().mcpProvider===e?n().mcpModel??r:r,i=o??n().mcpMediaKind??"image",l=n().mcpProvider!==e;Dn(e,a,i),te({count:1,multimode:!1,...l?{mcpRatio:null,mcpParameters:{}}:{}}),t({mcpProvider:e,mcpModel:a,mcpMediaKind:i,...l?{mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Be()}:{},count:1,multimode:!1,generate:()=>Fg(n)})}function Dg(e,t,n){Dn(n().mcpProvider??null,e,n().mcpMediaKind??"image"),te({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Be()})}function Gg(e,t,n,r,o){const a=np(o);let i=o?Rs(o.inputRoles,r().mcpReferenceSelection):Be();const l=r().currentImage;o?.inputRoles.includes("start_image")&&!i.startFrameFilename&&l?.filename&&!xe(l)&&(i={...i,startFrameFilename:l.filename}),Dn(r().mcpProvider??null,e,t),te({mcpRatio:a.ratio,mcpParameters:a.parameters}),n({mcpModel:e,mcpMediaKind:t,mcpRatio:a.ratio,mcpParameters:a.parameters,mcpInputRoles:o?[...o.inputRoles]:[],mcpReferenceSelection:i})}function zg(e,t,n){(n().mcpMediaKind??"image")!==e&&(Dn(n().mcpProvider??null,null,e),te({mcpRatio:null,mcpParameters:{}}),t({mcpMediaKind:e,mcpModel:null,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Be()}))}function Ug(e,t){te({mcpRatio:e}),t({mcpRatio:e})}function $g(e,t,n,r){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))return;const o={...r().mcpParameters??{}};t===null?delete o[e]:o[e]=t,te({mcpParameters:o}),n({mcpParameters:o})}function qg(e,t,n){const r=Rs(n().mcpInputRoles??[],Ps(e)),o=n().mcpReferenceSelection??Be();Hl(o,r)||t({mcpReferenceSelection:r})}function Hg(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},o=$l(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??Be(),i=Rs(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!rp(r,o),d=!Hl(a,i);!c&&!d&&!l||(c&&te({mcpRatio:o.ratio,mcpParameters:o.parameters}),t({...c?{mcpRatio:o.ratio,mcpParameters:o.parameters}:{},mcpInputRoles:[...e.inputRoles],mcpReferenceSelection:i}))}function Vg(e,t){const n=wp();n.provider&&(uo(n.provider,e,t,n.model,n.kind),te({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function Kg(e,t,n){cn(t),xg(e,t,n)}function Bg(e,t,n){n().provider!=="api"&&(e=null);const r=Lt(n().provider,e,n().quality);te({imageToolModel:e,quality:r}),t({imageToolModel:e,quality:r})}function Wg(e,t,n){e=Lt(n().provider,n().imageToolModel,e),te({quality:e}),t({quality:e})}function Jg(e,t){te({sizePreset:e}),t({sizePreset:e})}function Yg(e,t,n,r){const o=ot(e,r().customW),a=ot(t,r().customH);te({customW:o,customH:a}),n({customW:o,customH:a})}function Xg(e,t){te({grokAspectRatio:e}),t({grokAspectRatio:e})}function Zg(e,t){te({grokResolution:e}),t({grokResolution:e})}function Qg(e,t){te({format:e}),t({format:e})}function ey(e,t){te({moderation:e}),t({moderation:e})}function ty(e,t,n){cn(t),Sg(e,t,n)}function ny(e,t,n){cn(t),Ig(e,t,n)}function ry(e,t,n){cn(t),wg(e,t,n)}function oy(e,t,n){cn(t),_g(e,t,n)}function sy(e){return Ng(e())}function ay(e,t){pp(e),t({reasoningEffort:e})}function iy(e,t){gp(e),t({webSearchEnabled:e})}function ly(e,t){const n=En(e);te({count:n}),t({count:n})}function cy(e,t,n){if(e&&n().uiMode!=="classic")return;te({multimode:e});const r=n();t({multimode:e,multimodeSequences:e?r.multimodeSequences:{},multimodePreviewFlightId:e?r.multimodePreviewFlightId:null})}function dy(e,t){const n=En(e);te({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function uy(e,t){te({promptMode:e}),t({promptMode:e})}function my(e,t){te({prompt:e}),t({prompt:e})}function py(e,t){te({negativePrompt:e}),t({negativePrompt:e})}function fy(e,t,n,r){const o={...r().naiOptionOverrides,[e]:t};Wl(o),n({naiOptionOverrides:o})}function hy(e){Wl({}),e({naiOptionOverrides:{}})}function gy(e){const{provider:t,sizePreset:n,customW:r,customH:o,grokAspectRatio:a,grokResolution:i}=e();return t==="grok"||t==="grok-api"?`grok:${a}:${i}`:n==="custom"?`${r}x${o}`:n}const Io="starred";async function yy(e,t){const r=(await t.getAssets({kind:null,folderId:null,tag:null,q:"",filePath:e.filename,limit:1})).assets[0];if(r?.tags.includes(Io))return"noop";if(r)return await t.updateAsset(r.id,{tags:[...new Set([...r.tags,Io])]}),"tagged";const o=xe({...e,image:e.image??""})?"video":"image";return await t.createAsset({filePath:e.filename,kind:o,name:e.prompt?.trim().slice(0,80)||e.filename,tags:[Io],metadata:{origin:"star",mediaType:o}}),"created"}function vy(e,t){t(n=>{const r=n.insertedPrompts.some(i=>i.id===e.id),o={...e,placement:e.placement==="after"?"after":"before"},a=r?n.insertedPrompts:[...n.insertedPrompts,o];return te({insertedPrompts:a}),{insertedPrompts:a}})}function by(e,t){t(n=>{const r=n.insertedPrompts.filter(o=>o.id!==e);return te({insertedPrompts:r}),{insertedPrompts:r,videoContinuityLineage:e.startsWith("video-continuity:")?null:n.videoContinuityLineage}})}function xy(e,t,n){n(r=>{const o=r.insertedPrompts.filter(p=>p.placement!=="after"),a=r.insertedPrompts.filter(p=>p.placement==="after"),i=[...o.map(p=>({kind:"prompt",prompt:p})),{kind:"main"},...a.map(p=>({kind:"prompt",prompt:p}))],l=i.findIndex(p=>p.kind==="prompt"&&p.prompt.id===e);if(l<0)return{};const c=t==="up"?l-1:l+1;if(c<0||c>=i.length)return{};const[d]=i.splice(l,1);i.splice(c,0,d);const m=i.findIndex(p=>p.kind==="main"),u=i.filter(p=>p.kind==="prompt").map((p,h)=>({...p.prompt,placement:h<m?"before":"after"}));return te({insertedPrompts:u}),{insertedPrompts:u}})}function Sy(e){te({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function Iy(e){e({promptLibraryLoading:!0});try{const t=await Yu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function wy(e,t,n){try{await Xu(e),await n().loadPromptLibrary(),n().showToast(O("promptLibrary.saved"))}catch(r){console.error("[PromptLibrary] save failed",r),n().showToast(O("promptLibrary.saveFailed"),!0)}}async function _y(e,t,n){try{await Zu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function Ey(e,t,n){try{await Qu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function Ny(e,t,n){try{const r=[];for(const a of e){if(!/\.(txt|md|markdown)$/i.test(a.name))continue;const i=await a.text();if(!i.trim())continue;const l=a.name.replace(/\.(txt|md|markdown)$/i,"");r.push({name:l.trim()||O("promptLibrary.untitled"),text:i.trim(),tags:[]})}if(r.length===0){n().showToast(O("promptLibrary.importNoValidFiles"),!0);return}const o=await em({prompts:r});await n().loadPromptLibrary(),n().showToast(O("promptLibrary.imported",{count:o.promptsImported}))}catch(r){console.error("[PromptLibrary] import failed",r),n().showToast(O("promptLibrary.importFailed"),!0)}}async function ky(e,t,n){const r=e.filename;if(!r)return null;let o;try{o=(await Du(r)).isFavorite,t(i=>{const l=new Set(i.galleryFavorites);return o?l.add(r):l.delete(r),{galleryFavorites:l}}),t(i=>({history:i.history.map(l=>l.filename===r?{...l,isFavorite:o}:l),currentImage:i.currentImage?.filename===r?{...i.currentImage,isFavorite:o}:i.currentImage}))}catch(a){return console.error("[GalleryFavorite] toggle failed",a),n().showToast(O("gallery.favoriteFailed"),!0),null}if(!o)return o;try{await yy({...e,filename:r},{getAssets:ys,createAsset:Yr,updateAsset:rl})!=="noop"&&n().showToast(O("assets.starSaved"))}catch(a){console.error("[GalleryFavorite] asset sync failed",a),n().showToast(O("assets.starSaveFailed"),!0)}return o}async function jy(e,t,n){if(e){jc(e),t(r=>{const o=r.inFlight.map(a=>a.id===e?{...a,phase:"canceling"}:a);return Pe(o),{inFlight:o}});try{await Ae(e),n().startInFlightPolling()}catch{n().showToast(O("toast.cancelFailed"),!0)}}}function Cy(e,t){const n=ic(),r=Jl(),o=nc(),a=to(),i=rn();e(l=>{const c=r?l.history.find(p=>p.filename===r)??null:null,d=c?st(l.history,c):null,m=Ft(l.history)[0]??null,u=l.currentImage?.canvasVersion?st(l.history,l.currentImage)??m:l.currentImage;return{inFlight:n,activeGenerations:n.length,...o,imageToolModel:o.provider==="api"?i.imageToolModel??null:null,quality:Lt(o.provider,i.imageToolModel,i.quality??l.quality),videoDuration:a.duration,videoResolution:a.resolution,videoAspectRatio:a.aspectRatio,currentImage:r&&u?.filename!==r?d??u:u}}),n.length>0&&t().startInFlightPolling()}function Ay(e,t){t(n=>({history:e.filename?n.history.some(r=>r.filename===e.filename)?n.history.map(r=>r.filename===e.filename?e:r):no([e,...n.history],n.loadedHistoryRetainLimit+1):n.history,loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,Math.min(n.history.length+1,n.loadedHistoryRetainLimit+1))}))}function Ty(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function Py(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(xl,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function Ry(e,t){try{localStorage.setItem(ks,e)}catch{}t({galleryScope:e})}function My(e,t){try{localStorage.setItem(kl,e),localStorage.setItem(ks,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function Ly(e,t){const n=e==="card-news"&&!Tl?"classic":e;try{localStorage.setItem(Sl,n)}catch{}t({uiMode:n})}function Oy(e,t){try{localStorage.setItem(Il,e)}catch{}t({historyStripLayout:e})}function Fy(e,t,n){const r=Date.now(),o={message:e,error:t,id:r+Math.random(),createdAt:r};n(a=>({toast:o,toastLog:[...a.toastLog,o].slice(-50)}))}function Dy(e,t){t(n=>{const r=n.toastLog.filter(o=>o.id!==e);return{toastLog:r,toast:n.toast?.id===e?r[r.length-1]??null:n.toast}})}function Gy(e,t,n){const r=Date.now(),o={code:e,cardKey:t?.cardKey,cta:t?.cta,fallbackMessage:t?.fallbackMessage,id:r+Math.random(),createdAt:r};n(a=>({errorCard:o,errorCardLog:[...a.errorCardLog,o]}))}function zy(e,t){t(n=>{if(e==null)return{errorCard:null,errorCardLog:[]};const r=n.errorCardLog.filter(o=>o.id!==e);return{errorCardLog:r,errorCard:n.errorCard?.id===e?r[r.length-1]??null:n.errorCard}})}function Uy(e,t,n){t({graphNodes:De(e,n().graphEdges)}),n().scheduleGraphSave()}function $y(e,t,n){t({graphEdges:e,graphNodes:De(n().graphNodes,e)}),n().scheduleGraphSave()}function qy(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:Nn(t().graphNodes,[])}})}function Hy(e,t,n,r){n({graphNodes:kp(r().graphNodes,r().graphEdges,e,t)})}function Vy(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(O("nodeBatch.stopQueued")))}function Ky(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function By(e,t,n){t({canvasExportBackground:e}),Kl(e,n().canvasExportMatteColor)}function Wy(e,t,n){t({canvasExportMatteColor:e}),Kl(n().canvasExportBackground,e)}const ut=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let wo=0;async function fd(e){const{folders:t}=await vs();e({assetsFolders:t})}const ta=fd;async function na(e,t,n){const r=e!==!1;if(!r&&n().assetsLoading)return;const o=++wo;t({assetsLoading:!0,...r?{assetsLoadError:!1}:{}});try{const a=n().assetsFilters,i=await ys({...a,cursor:r?null:n().assetsCursor}),l=r?await Promise.all([vs(),bs()]):null;if(o!==wo)return;t(c=>({assets:r?i.assets:[...c.assets,...i.assets.filter(d=>!c.assets.some(m=>m.id===d.id))],assetsCursor:i.nextCursor,assetsLoading:!1,...l?{assetsFolders:l[0].folders,assetsTags:l[1].tags}:{}}))}catch(a){ut(a),o===wo&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function Jy(e,t){!t().assetsCursor||t().assetsLoading||await na(!1,e,t)}function ei(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),na(!0,t,n)}async function Yy(e,t,n){if(!e.filename)return!1;const r=Object.fromEntries(Object.entries({prompt:e.prompt,provider:e.provider,model:e.model,mediaType:e.mediaType,requestId:e.requestId,sessionId:e.sessionId,createdAt:e.createdAt}).filter(([,o])=>o!==void 0));try{const o=n().selectedProjectId??void 0,{asset:a}=await Yr({filePath:e.filename,kind:xe(e)?"video":"image",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:o,tags:[],metadata:r}),i=n().assetsFilters;return(!i.kind||i.kind===a.kind)&&!i.tag&&!(i.q||"").trim()&&!i.folderId&&t(c=>({assets:[a,...c.assets.filter(d=>d.id!==a.id)]})),!0}catch(o){return ut(o),!1}}async function Xy(e,t,n){try{const{asset:r}=await rl(e,t);let o=null;try{o=(await bs()).tags}catch(a){ut(a)}return n(a=>{const i=a.assetsFilters.tag;return{assets:i&&!r.tags.includes(i)?a.assets.filter(c=>c.id!==e):a.assets.map(c=>c.id===e?r:c),...o?{assetsTags:o}:{}}}),!0}catch(r){return ut(r),!1}}async function Zy(e,t){try{return await rm(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return ut(n),!1}}async function Qy(e,t,n){try{return await om({name:e,parentId:t}),await ta(n),!0}catch(r){return ut(r),!1}}async function ev(e,t,n){try{return await ol(e,{name:t}),await ta(n),!0}catch(r){return ut(r),!1}}async function tv(e,t,n){try{return await ol(e,{parentId:t}),await ta(n),!0}catch(r){return ut(r),!1}}async function nv(e,t){try{await sm(e);const[{folders:n},{tags:r}]=await Promise.all([vs(),bs()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return ut(n),!1}}function rv(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(ym(e.imageModel)||vm(e.imageModel)))return e.imageModel}async function hd(e,t,n){if(!e.filename)return;const r=n();try{await Yr({filePath:e.filename,kind:"image",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:r.selectedProjectId??void 0,tags:[],metadata:{source:"asset-gen",backgroundPreset:e.backgroundPreset??r.assetGenBackground,prompt:e.prompt,provider:e.provider,requestId:e.requestId}}),t(o=>({assetGenSaveFailures:o.assetGenSaveFailures.filter(a=>a!==e.requestId)}))}catch{t(o=>({assetGenSaveFailures:o.assetGenSaveFailures.includes(e.requestId??"")?o.assetGenSaveFailures:[...o.assetGenSaveFailures,e.requestId??""]}))}}async function ov(e,t,n){const r=n().assetGenItems.find(o=>o.requestId===e);r&&(r.mediaType==="video"?await gd(r,t,n):await hd(r,t,n))}async function sv(e,t,n,r){const o=n(),a=o.assetGenPrompt.trim(),i=await gs({prompt:a,provider:"grok",duration:o.assetGenVideoDuration,resolution:o.assetGenVideoResolution,aspectRatio:o.assetGenVideoAspect,requestId:e,backgroundPreset:o.assetGenBackground},{},{signal:r.signal}),l={image:i.url,url:i.url,filename:i.filename,mediaType:"video",video:i.video??null,prompt:a,provider:"grok",requestId:i.requestId??e,elapsed:i.elapsed,backgroundPreset:o.assetGenBackground,createdAt:Date.now()};await bt(l,t,n,{autoSelectStartedAt:Date.now()}),t(c=>({assetGenItems:[l,...c.assetGenItems]})),await gd(l,t,n),n().showToast(O("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function gd(e,t,n){if(!e.filename)return;const r=n();try{await Yr({filePath:e.filename,kind:"video",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:r.selectedProjectId??void 0,tags:[],metadata:{source:"asset-gen",backgroundPreset:e.backgroundPreset??r.assetGenBackground,prompt:e.prompt,provider:e.provider,requestId:e.requestId}}),t(o=>({assetGenSaveFailures:o.assetGenSaveFailures.filter(a=>a!==e.requestId)}))}catch{t(o=>({assetGenSaveFailures:o.assetGenSaveFailures.includes(e.requestId??"")?o.assetGenSaveFailures:[...o.assetGenSaveFailures,e.requestId??""]}))}}async function av(e,t){const n=t(),r=n.assetGenPrompt.trim();if(!r)return;const o=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,a=new AbortController;an(o,a);const i=Date.now(),l=[...n.inFlight,{id:o,prompt:r,startedAt:i}];Pe(l),e({assetGenLastError:null,activeGenerations:n.activeGenerations+1,inFlight:l}),t().startInFlightPolling();try{if(n.assetGenKind==="video"){await sv(o,e,t,a);return}const c={prompt:r,quality:n.quality,size:"1024x1024",format:"png",moderation:n.moderation,provider:n.assetGenProvider,n:1,model:rv(n),requestId:o,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await el(c,{signal:a.signal}),m=as(d)?d.images[0]:null,u={image:m?m.image:d.image,filename:m?m.filename:d.filename,reasoningEffort:d.reasoningEffort,prompt:r,elapsed:d.elapsed,provider:d.provider,providerUrl:(m?m.providerUrl:d.providerUrl)??null,usage:d.usage,requestId:d.requestId??o,quality:d.quality,size:d.size,model:d.model??null,backgroundPreset:n.assetGenBackground,createdAt:(m?m.createdAt:d.createdAt)??Date.now()};await bt(u,e,t,{autoSelectStartedAt:i}),e(p=>({assetGenItems:[u,...p.assetGenItems]})),await hd(u,e,t),t().showToast(O("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!on(c)){const d=We(c,t()),m=d.code==="JOB_TRACKING_TIMEOUT"?d.message:c instanceof Error?c.message:String(c);e({assetGenLastError:m})}}finally{const c=t().inFlight.filter(d=>d.id!==o);Pe(c),ln(o),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function iv(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function un(e){te({presetIds:e})}const lv=e=>({selectedPresetIds:rn().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return un(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(o=>o!==t);return un(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(o=>o!==t):[...n.selectedPresetIds,t];return un(r),{selectedPresetIds:r}}),clearPresets:()=>{un([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=iv(t);un(n),e({selectedPresetIds:n})}});function cv(){return{name:"",characterId:"",description:"",style:"",baseAssetId:"",cell:{width:256,height:256,safeMarginX:8,safeMarginY:8},chroma:{preset:"green",hex:"#00ff00"},states:[{key:"idle",frames:4,fps:8,loop:!0,action:"idle"}]}}const Kn=(e,t="POST",n)=>({method:t,signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),dv=e=>$("/api/sprite-recipes",{signal:e}),uv=(e,t)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),mv=(e,t)=>$("/api/sprite-recipes",Kn(e,"POST",t)),pv=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,Kn(t,"PATCH",n)),fv=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Kn({...t,async:!0},"POST",n)),hv=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Kn({assetId:t},"POST",n)),gv=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Kn({...t,async:!0},"POST",n)),Jt=new Map,Bn=e=>e instanceof Error?e.message:String(e),yd=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function yv(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await dv();e({spriteRecipes:n.map(yd)}),t().activeSpriteRecipeId&&await ra(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:Bn(n)})}finally{e({spriteRecipeLoading:!1})}}async function ra(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await uv(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:Bn(r)})}finally{t({spriteRecipeLoading:!1})}}async function vv(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await pv(n.activeSpriteRecipeId,n.spriteRecipeDraft):await mv(n.spriteRecipeDraft);return e(o=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[yd(r.recipe),...o.spriteRecipes.filter(a=>a.id!==r.recipe.id)]})),r.recipe.id}catch(n){return e({spriteRecipeError:Bn(n)}),null}finally{e({spriteRecipeSaving:!1})}}function vd(e,t,n){Jt.get(e)?.(),Jt.set(e,Tt(e,null,(r,o)=>wv({event:r,data:{...o,requestId:e}},t,n)))}function oa(e){Jt.get(e)?.(),Jt.delete(e)}function bd(e,t){return at(e).code==="JOB_TRACKING_TIMEOUT"?We(e,t()).message:Bn(e)}async function bv(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{vd(r,e,t),await Br(),await fv(n,{requestId:r,async:!0})}catch(o){oa(r),e({spriteRecipeError:bd(o,t),spriteRecipeGenerating:!1})}}async function xv(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:o}=await hv(r,e);t({activeSpriteRecipe:o,spriteRecipeDraft:o,spriteRecipeDirty:!1})}catch(o){t({spriteRecipeError:Bn(o)})}finally{t({spriteRecipeGenerating:!1})}}}async function Sv(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const o=crypto.randomUUID();try{vd(o,t,n),await Br(),await gv(r,{requestId:o,stateKeys:e,async:!0})}catch(a){oa(o),t({spriteRecipeError:bd(a,n),spriteRecipeGenerating:!1})}}async function Iv(e,t,n){Jt.get(e)?.(),Jt.delete(e),t({spriteRecipeGenerating:!1})}function wv(e,t,n){const r=e.data.stateKey,o=e.data.url??e.data.image??e.data.previewUrl;if(r&&o&&t(a=>({spritePartialPreviews:{...a.spritePartialPreviews,[r]:o}})),(e.event==="error"||e.event==="done")&&oa(String(e.data.requestId??"")),e.event==="error"){const a=String(e.data.message??"Generation failed"),i=nt(e.data,a),l=at(i).code==="JOB_TRACKING_TIMEOUT"?We(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&ra(a,t)}}function _v(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const Ce=rn(),tr=to(),nr=nc(),f=Wi((e,t,n)=>({...lv(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:cv(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>yv(e,t),selectSpriteRecipe:r=>ra(r,e),updateSpriteRecipeDraft:r=>_v(r,e),saveSpriteRecipe:()=>vv(e,t),generateSpriteAnchor:()=>bv(e,t),approveSpriteAnchor:r=>xv(r,e,t),generateSpriteRows:r=>Sv(r,e,t),cancelSpriteJob:r=>Iv(r,e),assetsFolders:[],assetsTags:[],assetsLoading:!1,assetsLoadError:!1,assetsCursor:null,assetsFilters:{kind:null,folderId:null,tag:null,q:""},assetGenPrompt:"",assetGenBackground:"chroma-green",assetGenProvider:nr.provider==="grok"||nr.provider==="grok-api"?nr.provider:"oauth",assetGenKind:"image",assetGenVideoDuration:5,assetGenVideoResolution:"720p",assetGenVideoAspect:"1:1",setAssetGenVideoDuration:r=>e({assetGenVideoDuration:r}),setAssetGenVideoResolution:r=>e({assetGenVideoResolution:r}),setAssetGenVideoAspect:r=>e({assetGenVideoAspect:r}),assetGenItems:[],assetGenSaveFailures:[],assetGenLastError:null,setAssetGenLastError:r=>e({assetGenLastError:r}),keyingTarget:null,setKeyingTarget:r=>e({keyingTarget:r}),vectorizeTarget:null,setVectorizeTarget:r=>e({vectorizeTarget:r}),spriteCuratorTarget:null,setCuratorTarget:r=>e({spriteCuratorTarget:r}),addAssetGenDerivedItem:r=>e(o=>r.filename&&o.assetGenItems.some(a=>a.filename===r.filename)?{}:{assetGenItems:[r,...o.assetGenItems]}),selectedProjectId:null,setSelectedProject:r=>{e({selectedProjectId:r}),ei({folderId:r},e,t)},loadAssetFolders:()=>fd(e),retryAssetGenSave:r=>ov(r,e,t),setAssetGenPrompt:r=>e({assetGenPrompt:r}),setAssetGenBackground:r=>e({assetGenBackground:r}),setAssetGenProvider:r=>e(o=>({assetGenProvider:r,...(r==="grok"||r==="grok-api")&&o.assetGenBackground==="transparent"?{assetGenBackground:"chroma-green"}:{}})),setAssetGenKind:r=>e({assetGenKind:r}),generateAssetGen:()=>av(e,t),loadAssets:r=>na(r,e,t),loadMoreAssets:()=>Jy(e,t),setAssetsFilters:r=>ei(r,e,t),saveToAssets:r=>Yy(r,e,t),updateAssetItem:(r,o)=>Xy(r,o,e),deleteAssetItem:r=>Zy(r,e),createAssetFolder:(r,o)=>Qy(r,o,e),renameAssetFolder:(r,o)=>ev(r,o,e),moveAssetFolder:(r,o)=>tv(r,o,e),deleteAssetFolder:r=>nv(r,e),...nr,imageToolModel:Ce.imageToolModel??null,quality:Ce.quality??"medium",sizePreset:Ce.sizePreset??"1024x1024",customW:Ce.customW??1920,customH:Ce.customH??1088,grokAspectRatio:Ce.grokAspectRatio??"1:1",grokResolution:Ce.grokResolution??"1k",format:Ce.format??"png",moderation:Ce.moderation??"low",count:Ce.count??1,multimode:Ce.multimode??!1,multimodeMaxImages:Ce.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:Ce.promptMode??"auto",prompt:Ce.prompt??"",negativePrompt:Ce.negativePrompt??"",naiOptionOverrides:fp(),naiServerDefaults:null,insertedPrompts:Ce.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:Be(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:Fs,activeReferenceLimit:()=>kc({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>kf(t().trayItems),workspaceProfile:(()=>{try{return localStorage.getItem("ima2.workspaceProfile")==="prompt-studio"?"prompt-studio":"default"}catch{return"default"}})(),promptBuilderOpen:!1,storyboardActive:!1,promptLibraryOpen:!1,promptLibrary:{prompts:[],folders:[]},promptLibraryLoading:!1,galleryFavorites:new Set,browserId:Yi(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:$a().mode,canvasExportMatteColor:$a().matteColor,syncCapabilities:()=>Op(e),addTrayAttachments:async r=>lg(r,e),addTrayAttachmentDataUrl:(r,o)=>co(r,o,e),addTrayElement:r=>Ir(r,e),addElementFromMention:r=>Ir(r.id,e,t,r),syncElementCatalog:r=>Oc(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>cd(r,e,t),clearTray:()=>hg(e,t),addElementId:r=>{Ir(r,e)},removeElementId:r=>Af(r,e),addReferences:r=>dg(r,e,t),addReferenceDataUrl:r=>cg(r,e),metadataRestore:null,readDroppedImageMetadata:(r,o=null)=>ug(r,o,e,t),applyMetadataRestore:()=>mg(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>Ty(e,t),removeReference:r=>pg(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>fg(e,t),attachCanvasVersionReference:(r,o)=>yg(r,e,t,o),useCurrentAsReference:()=>vg(e,t),useImageAsReference:r=>bg(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>jy(r,e,t),startInFlightPolling:()=>{uh(e,t)},reconcileInflight:async()=>{await mh(e,t)},syncFromStorage:()=>Cy(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>Ay(r,e),addGeneratedHistoryItem:async r=>{await bt(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:Ve,loadOlderHistory:async()=>$h(e,t),loadFavoriteHistory:async()=>qh(e,t),loadOlderFavoriteHistory:async()=>Hh(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:cp(),toggleRightPanel:()=>Py(e,t),composeSheetOpen:!1,composeSheetTab:"prompt",openComposeSheet:(r="prompt")=>e({composeSheetOpen:!0,composeSheetTab:r}),setComposeSheetTab:r=>e({composeSheetTab:r}),closeComposeSheet:()=>e({composeSheetOpen:!1}),galleryOpen:!1,openGallery:()=>e(r=>({galleryOpen:!0,galleryScope:r.galleryDefaultScope})),closeGallery:()=>e({galleryOpen:!1}),galleryScope:Ua(ks),galleryDefaultScope:Ua(kl),setGalleryScope:r=>Ry(r,e),setGalleryDefaultScope:r=>My(r,e),reasoningEffort:mp(),webSearchEnabled:hp(),settingsOpen:!1,activeSettingsSection:"providers",readinessPopupOpen:!1,openSettings:(r="providers")=>e({settingsOpen:!0,activeSettingsSection:r}),closeSettings:()=>e({settingsOpen:!1}),toggleSettings:()=>e(r=>({settingsOpen:!r.settingsOpen,activeSettingsSection:r.settingsOpen?r.activeSettingsSection:"providers"})),setActiveSettingsSection:r=>e({activeSettingsSection:r}),openReadinessPopup:()=>e({readinessPopupOpen:!0}),closeReadinessPopup:()=>e({readinessPopupOpen:!1}),uiMode:dp(),setUIMode:r=>Ly(r,e),historyStripLayout:up(),setHistoryStripLayout:r=>Oy(r,e),locale:uu(),setLocale:r=>{du(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const o=t();e({graphHistoryPast:Zp(o.graphHistoryPast,xo(o.graphNodes,o.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),o=Qp(r.graphHistoryPast,xo(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Wa(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),o=ef(r.graphHistoryPast,xo(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Wa(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>Uy(r,e,t),setGraphEdges:r=>$y(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>Nh(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>qy(e,t),selectAllGraphNodes:()=>{e({graphNodes:Nn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,o)=>Hy(r,o,e,t),clearNodeSelection:()=>{e({graphNodes:Nn(t().graphNodes,[])})},cancelNodeBatch:()=>Vy(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await id(e,t)},async switchSession(r){await ng(r,e,t)},async reconcileGraphPending(){await rg(e,t)},async createAndSwitchSession(r){await og(r,e,t)},async renameCurrentSession(r){await sg(r,e,t)},async deleteSessionById(r){await ag(r,e,t)},scheduleGraphSave(){Ec(t,e)},async flushGraphSave(r="manual"){await Wp(t,e,r)},addRootNode:()=>yh(e,t),createRootNodeFromHistoryItem:r=>vh(r,e,t),addChildNode:r=>bh(r,e,t),addSiblingNode:r=>xh(r,e,t),updateNodePrompt:(r,o)=>wh(r,o,e,t),addNodeReferences:async(r,o)=>jh(r,o,e,t),addNodeReferenceDataUrl:(r,o)=>Zc(r,o,e,t),addNodeReferenceFromUrl:async(r,o,a)=>Ch(r,o,a,e,t),removeNodeReference:(r,o)=>Ah(r,o,e,t),clearNodeReferences:r=>Th(r,e,t),duplicateBranchRoot:r=>Ih(r,e,t),generateNode:r=>Xf(r,e,t),generateNodeInPlace:r=>Zf(r,e,t),generateNodeVariation:(r,o)=>Qf(r,o,e,t),runGenerateNode:(r,o)=>eh(r,o,e,t),async runGenerateNodeInPlace(r,o={}){return Rf(r,o,e,t,Pe)},async runNodeBatch(r){await Mf(r,e,t)},deleteNode:r=>_h(r,e,t),deleteNodes:r=>Eh(r,e,t),addChildNodeAt:(r,o,a)=>Sh(r,o,a,e,t),connectNodes:(r,o,a,i)=>kh(r,o,a,i,e,t),setProvider:r=>Kg(r,e,t),setImageToolModel:r=>Bg(r,e,t),setQuality:r=>Wg(r,e,t),setSizePreset:r=>Jg(r,e),setCustomSize:(r,o)=>Yg(r,o,e,t),setGrokAspectRatio:r=>Xg(r,e),setGrokResolution:r=>Zg(r,e),setFormat:r=>Qg(r,e),setModeration:r=>ey(r,e),setImageModel:r=>ty(r,e,t),videoDuration:tr.duration,videoResolution:tr.resolution,videoSingleRefMode:tr.singleRefMode,videoAspectRatio:tr.aspectRatio,videoReferenceVoices:[],videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>ny(r,e,t),setComfyWorkflow:r=>ry(r,e,t),setComfyVideoWorkflow:r=>oy(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),yn({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),yn({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),yn({aspectRatio:r})},toggleVideoReferenceVoice:r=>{const o=t().videoReferenceVoices,a=o.includes(r)?o.filter(i=>i!==r):o.length>=3?o:[...o,r];e({videoReferenceVoices:a})},setVideoSingleRefMode:r=>{e({videoSingleRefMode:r}),yn({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>sy(t),runVideoGenerate:async r=>{await th(r,e,t)},animateImage:async(r,o)=>nh(r,o,e,t),setReasoningEffort:r=>ay(r,e),setWebSearchEnabled:r=>iy(r,e),setCount:r=>ly(r,e),setMultimode:r=>cy(r,e,t),setMultimodeMaxImages:r=>dy(r,e),setPromptMode:r=>uy(r,e),setPrompt:r=>my(r,e),setNegativePrompt:r=>py(r,e),setNaiOption:(r,o)=>fy(r,o,e,t),resetNaiOptions:()=>hy(e),insertPromptToComposer:r=>vy(r,e),removeInsertedPromptFromComposer:r=>by(r,e),moveInsertedPromptInComposer:(r,o)=>xy(r,o,e),clearInsertedPrompts:()=>Sy(e),selectHistory:r=>Vh(r,e,t),showHistorySequence:r=>Kh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>Bh(r,e,t),trashHistoryItem:async r=>Wh(r,e,t),trashHistorySequence:async r=>Jh(r,e,t),restorePendingTrash:async()=>Yh(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>Xh(r,e,t),removeFromHistory:r=>Zh(r,e,t),addHistoryItem:r=>Qh(r,e,t),importLocalImageToHistory:async r=>eg(r,e,t),getResolvedSize:()=>gy(t),generate:()=>Wf(e,t),async generateMultimode(r){await Gf(r,e,t)},cancelMultimode:()=>Jf(e,t),async runGenerate(r){await zf(r,e,t)},confirmCustomSizeAdjustment:()=>Yf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){tg(e)},showToast:(r,o=!1)=>Fy(r,o,e),dismissToast:r=>Dy(r,e),showErrorCard:(r,o)=>Gy(r,o,e),dismissErrorCard:r=>zy(r,e),setWorkspaceProfile(r){e({workspaceProfile:r});try{localStorage.setItem("ima2.workspaceProfile",r)}catch{}},togglePromptBuilder(){e(r=>({promptBuilderOpen:!r.promptBuilderOpen}))},toggleStoryboard(){e(r=>({storyboardActive:!r.storyboardActive}))},setPromptLibraryOpen(r){e({promptLibraryOpen:r})},togglePromptLibrary(){e(r=>({promptLibraryOpen:!r.promptLibraryOpen}))},loadPromptLibrary:()=>Iy(e),savePromptToLibrary:r=>wy(r,e,t),deletePromptFromLibrary:r=>_y(r,e,t),togglePromptFavorite:r=>Ey(r,e,t),importPromptsToLibrary:r=>Ny(r,e,t),toggleGalleryFavorite:r=>ky(r,e,t),openCanvas:()=>e({canvasOpen:!0,canvasZoom:1,canvasPanX:0,canvasPanY:0}),closeCanvas:()=>e({canvasOpen:!1}),setCanvasZoom:r=>e({canvasZoom:Math.max(.5,Math.min(3,r))}),resetCanvasZoom:()=>e({canvasZoom:1,canvasPanX:0,canvasPanY:0}),setCanvasPan:(r,o)=>Ky(r,o,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>By(r,e,t),setCanvasExportMatteColor:r=>Wy(r,e,t)})),Ev=/^[\p{L}\p{N}_-]$/u,Nv=new Set([" "," ","(","["]);function kv(e,t){const n=Math.max(0,Math.min(t,e.length));let r=n;for(;r>0&&e[r-1]!=="@"&&e[r-1]!==`
|
|
7
|
+
`;){if(!Ev.test(e[r-1]))return null;r-=1}if(r===0||e[r-1]!=="@")return null;const o=r-1,a=e[o-1];return a!==void 0&&!Nv.has(a)&&a!==`
|
|
8
|
+
`?null:{start:o,end:n,query:e.slice(r,n)}}function qe({title:e,help:t,items:n,value:r,onChange:o,className:a}){const i=g.useRef(null),l=c=>{if(c.key!=="ArrowLeft"&&c.key!=="ArrowRight")return;const d=n.filter(h=>!h.disabled);if(d.length===0)return;const m=d.findIndex(h=>h.value===r),u=c.key==="ArrowRight"?1:-1,p=d[(m+u+d.length)%d.length];c.preventDefault(),o(p.value),i.current?.querySelector(`[data-value="${p.value}"]`)?.focus()};return s.jsxs("div",{className:`option-group${a?` ${a}`:""}`,children:[e?s.jsx("div",{className:"section-title",children:e}):null,s.jsx("div",{className:"option-row",role:"group",ref:i,onKeyDown:l,children:n.map(c=>s.jsxs("button",{type:"button","data-value":c.value,className:`option-btn${c.value===r?" active":""}`,style:c.color?{color:c.color}:void 0,disabled:c.disabled,"aria-pressed":c.value===r,onClick:()=>o(c.value),children:[c.label,c.sub?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:c.sub})]}):null]},c.value))}),t?s.jsx("p",{className:"option-help",children:t}):null]})}var mo=mu();function jv(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Cv=(e,t)=>{if(e&&e.length>0){const r=e.filter(o=>o.items.length>0);return{flat:r.flatMap(o=>[...o.items]),rendered:r}}const n=t??[];return{flat:[...n],rendered:[{items:n}]}},ti=(e,t,n)=>{if(t==="first"){const r=e.findIndex(o=>!o.disabled);return r>=0?r:n}for(let r=e.length-1;r>=0;r-=1)if(!e[r]?.disabled)return r;return n};function Me({items:e,groups:t,value:n,onChange:r,ariaLabel:o,ariaDescribedBy:a,className:i,id:l,disabled:c,portal:d=!1,triggerLabel:m,triggerSub:u,placeholder:p,title:h}){const x=g.useId(),S=g.useRef(null),b=g.useRef(null),v=g.useRef(null),[y,w]=g.useState(!1),[I,_]=g.useState({top:0,left:0,width:200,maxHeight:260}),{flat:N,rendered:j}=Cv(t,e),L=N.length===0,[q,A]=g.useState(()=>Math.max(0,N.findIndex(F=>F.value===n))),G=g.useRef({buffer:"",at:0}),C=N.find(F=>F.value===n),T=F=>`${x}-opt-${F}`,k=F=>F.searchText?F.searchText:typeof F.label=="string"?F.label:F.value,R=F=>{const ee=Date.now(),J=G.current;J.buffer=ee-J.at>1e3?F:J.buffer+F,J.at=ee;const me=J.buffer.toLowerCase(),ye=J.buffer.length===1?q+1:q;for(let ie=0;ie<N.length;ie+=1){const ke=(ye+ie+N.length)%N.length,le=N[ke];if(!(!le||le.disabled)&&k(le).toLowerCase().startsWith(me)){A(ke);return}}};g.useEffect(()=>{if(!y)return;const F=ee=>{const J=ee.target;J instanceof Node&&(S.current?.contains(J)||v.current?.contains(J)||w(!1))};return document.addEventListener("pointerdown",F),()=>document.removeEventListener("pointerdown",F)},[y]),g.useLayoutEffect(()=>{if(!d||!y)return;const F=b.current?.getBoundingClientRect();if(F){const ye=Math.max(0,window.innerWidth-24),ie=Math.min(300,ye,Math.max(190,F.width)),ke=Math.max(12,window.innerWidth-ie-12),le=Math.min(Math.max(12,F.left),ke),Ie=window.innerHeight-F.bottom-12,je=F.top-12,Re=Ie>=160||Ie>=je?"down":"up",ce=Math.max(0,Re==="down"?Ie:je),be=Math.min(420,ce),z=8+N.length*44,ve=v.current?.scrollHeight??z,P=Math.min(ve,be);_({top:Re==="down"?F.bottom+4:Math.max(12,F.top-P-4),left:le,width:ie,maxHeight:be})}const ee=()=>w(!1),J=me=>{jv(me,v.current)&&w(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,y]),g.useEffect(()=>{y&&v.current?.querySelector(`[data-index="${q}"]`)?.scrollIntoView({block:"nearest"})},[y,q]);const B=()=>{L||(A(Math.max(0,N.findIndex(F=>F.value===n))),w(!0))};g.useEffect(()=>{L&&(w(!1),A(0))},[L]);const se=F=>{let ee=q;for(let J=0;J<N.length&&(ee=(ee+F+N.length)%N.length,!!N[ee]?.disabled);J+=1);A(ee)},oe=F=>{const ee=N[F];!ee||ee.disabled||(r(ee.value),w(!1),b.current?.focus())},ae=F=>{if(!y){["Enter"," ","ArrowDown","ArrowUp"].includes(F.key)&&(F.preventDefault(),B());return}if(F.key==="Escape")F.preventDefault(),w(!1);else if(F.key==="ArrowDown")F.preventDefault(),se(1);else if(F.key==="ArrowUp")F.preventDefault(),se(-1);else if(F.key==="Home")F.preventDefault(),A(ti(N,"first",q));else if(F.key==="End")F.preventDefault(),A(ti(N,"last",q));else if(F.key==="Enter"||F.key===" "){if(F.key===" "&&Date.now()-G.current.at<=1e3&&G.current.buffer){F.preventDefault(),R(" ");return}F.preventDefault(),oe(q)}else F.key==="Tab"?w(!1):F.key.length===1&&!F.metaKey&&!F.ctrlKey&&!F.altKey&&(F.preventDefault(),R(F.key))};let ge=-1;const D=y&&!L?s.jsx("ul",{className:`ctl-select__list${d?" ctl-select__list--portal":""}`,role:"listbox",id:x,ref:v,style:d?{position:"fixed",top:I.top,left:I.left,width:I.width,maxHeight:I.maxHeight}:void 0,children:j.map((F,ee)=>s.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[F.label?s.jsx("div",{className:"ctl-select__group-label",children:F.label}):null,s.jsx("ul",{role:"group","aria-label":typeof F.label=="string"?F.label:void 0,className:"ctl-select__group-items",children:F.items.map(J=>{ge+=1;const me=ge;return s.jsxs("li",{role:"option",id:T(me),"data-index":me,"aria-selected":J.value===n,"aria-disabled":J.disabled||void 0,title:J.title,className:`ctl-select__item${J.value===n?" is-selected":""}${me===q?" is-active":""}${J.disabled?" is-disabled":""}${J.stacked?" is-stacked":""}`,onPointerEnter:()=>A(me),onClick:()=>oe(me),children:[s.jsx("span",{className:"ctl-select__item-label",children:J.label}),J.sub?s.jsx("span",{className:"ctl-select__item-sub",children:J.sub}):null]},J.value)})})]},`g-${ee}`))}):null;return s.jsxs("div",{className:`ctl-select${i?` ${i}`:""}`,ref:S,children:[s.jsxs("button",{type:"button",id:l,ref:b,className:`ctl-select__trigger${y?" is-open":""}`,role:"combobox","aria-haspopup":"listbox","aria-expanded":y,"aria-controls":y?x:void 0,"aria-activedescendant":y&&N[q]?T(q):void 0,"aria-label":o,"aria-describedby":a,disabled:c||L,title:h,onClick:()=>y?w(!1):B(),onKeyDown:ae,children:[s.jsx("span",{className:"ctl-select__value",children:m??C?.label??p??""}),u??C?.sub?s.jsx("span",{className:"ctl-select__value-sub",children:u??C?.sub}):null,s.jsx("svg",{className:"ctl-select__caret",width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:s.jsx("path",{d:"M2 3.5 5 6.5 8 3.5",fill:"none",stroke:"currentColor",strokeWidth:"1.4"})})]}),D?d?mo.createPortal(D,document.body):D:null]})}function Av({checked:e,onChange:t,label:n,ariaLabel:r,className:o,disabled:a,id:i}){return s.jsxs("button",{type:"button",id:i,role:"switch","aria-checked":e,"aria-label":r,disabled:a,className:`ctl-toggle${e?" is-on":""}${o?` ${o}`:""}`,onClick:()=>t(!e),children:[s.jsx("span",{className:"ctl-toggle__track","aria-hidden":"true",children:s.jsx("span",{className:"ctl-toggle__thumb"})}),n?s.jsx("span",{className:"ctl-toggle__label",children:n}):null]})}function xd({selected:e,onSelect:t,onRemove:n,removeLabel:r,disabled:o,className:a,children:i,title:l}){return s.jsxs("span",{className:`ctl-chip${e?" is-selected":""}${o?" is-disabled":""}${a?` ${a}`:""}`,children:[s.jsx("button",{type:"button",className:"ctl-chip__body","aria-pressed":t?e:void 0,disabled:o,title:l,onClick:t,children:i}),n?s.jsx("button",{type:"button",className:"ctl-chip__remove","aria-label":r,disabled:o,onClick:n,children:s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8","aria-hidden":"true",children:s.jsx("path",{d:"M1 1l6 6M7 1L1 7",stroke:"currentColor",strokeWidth:"1.3"})})}):null]})}function sa({className:e,children:t,ariaLabel:n}){return s.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":n,children:t})}function Tv(){return s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:s.jsx("path",{d:"m12 2.75 2.78 5.63 6.22.9-4.5 4.39 1.06 6.2L12 16.94 6.44 19.87l1.06-6.2L3 9.28l6.22-.9L12 2.75Z"})})}function Sd({active:e,label:t,variant:n,busy:r=!1,onToggle:o}){const a=c=>{c.stopPropagation()},i=c=>{c.stopPropagation()},l=c=>{(c.key==="Enter"||c.key===" ")&&c.stopPropagation()};return s.jsx("button",{type:"button",className:`favorite-star favorite-star--${n}${e?" is-active":""}`,title:t,"aria-label":t,"aria-pressed":e,"aria-busy":r||void 0,disabled:r,onPointerDown:a,onDoubleClick:i,onKeyDown:l,onClick:c=>{c.stopPropagation(),o()},children:s.jsx(Tv,{})})}function Pv(){return s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:s.jsx("path",{d:"M4 20h4l10-10a2.5 2.5 0 0 0-3.5-3.5L4.5 16.5 4 20Z",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinejoin:"round"})})}const ni=12,Rv=240;function Mv(e,t){const n=getComputedStyle(e),r=document.createElement("div");["boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","textIndent","textAlign","wordSpacing","tabSize"].forEach(d=>{r.style[d]=n[d]}),r.style.cssText+=";position:fixed;visibility:hidden;white-space:pre-wrap;overflow-wrap:break-word;top:0;left:-9999px;",r.textContent=e.value.slice(0,t);const a=document.createElement("span");a.textContent=e.value.slice(t)||".",r.append(a),document.body.append(r);const i=r.getBoundingClientRect(),l=a.getBoundingClientRect();r.remove();const c=e.getBoundingClientRect();return new DOMRect(c.left+l.left-i.left-e.scrollLeft,c.top+l.top-i.top-e.scrollTop,1,l.height||parseFloat(n.lineHeight)||16)}function Lv(e,t){const n=Mv(e,t),r=window.innerHeight-n.bottom,o=r<Rv?"top":"bottom",a=o==="bottom"?r:n.top;return{left:Math.max(ni,Math.min(n.left,window.innerWidth-332)),top:o==="bottom"?n.bottom+6:Math.max(ni,n.top-Math.min(320,a-8)),placement:o,maxHeight:Math.max(120,Math.min(320,a-12))}}function Ov(){return window.matchMedia("(max-width: 640px)").matches}function Fv({open:e,textareaRef:t,composingRef:n,caret:r,query:o,elements:a,ariaLabel:i,emptyLabel:l,kindLabel:c,onSelect:d,onClose:m,onActiveChange:u}){const p=g.useId(),[h,x]=g.useState(0),[S,b]=g.useState(null),[v,y]=g.useState(!1),w=g.useRef(null),I=g.useMemo(()=>{const L=o.trim().toLocaleLowerCase();return L?a.filter(q=>[q.name,...q.tags??[]].some(A=>A.toLocaleLowerCase().includes(L))):a},[a,o]),_=L=>{x(L),u?.(L)},N=()=>{const L=I[h];L&&d(L)};if(g.useLayoutEffect(()=>{if(!e||!t.current)return;const L=()=>{if(!t.current){m();return}y(Ov()),b(Lv(t.current,r))},q=()=>requestAnimationFrame(L);return L(),window.addEventListener("resize",q),t.current.addEventListener("scroll",q),()=>{window.removeEventListener("resize",q),t.current?.removeEventListener("scroll",q)}},[e,t,r,m]),g.useEffect(()=>{_(0)},[o,I.length]),g.useEffect(()=>{if(!e)return;const L=t.current;if(!L)return;L.setAttribute("aria-controls",p),L.setAttribute("aria-expanded","true");const q=A=>{if(document.activeElement===L&&!(n?.current||A.isComposing||A.keyCode===229)&&!(A.key==="Enter"&&(A.ctrlKey||A.metaKey))){if(A.key==="Escape"){A.preventDefault(),m("escape");return}A.key==="ArrowDown"||A.key==="ArrowUp"?(A.preventDefault(),_((h+(A.key==="ArrowDown"?1:-1)+I.length)%Math.max(1,I.length))):A.key==="Home"?(A.preventDefault(),_(0)):A.key==="End"?(A.preventDefault(),_(Math.max(0,I.length-1))):A.key==="Enter"?I.length&&(A.preventDefault(),N()):A.key==="Tab"&&I.length&&N()}};return L.addEventListener("keydown",q),()=>{L.removeAttribute("aria-controls"),L.removeAttribute("aria-expanded"),L.removeAttribute("aria-activedescendant"),L.removeEventListener("keydown",q)}},[e,t,n,p,h,I,m]),g.useEffect(()=>{const L=t.current,q=I[h];L&&q&&L.setAttribute("aria-activedescendant",`${p}-${q.id}`)},[h,I,p,t]),g.useEffect(()=>{w.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!S||typeof document>"u")return null;const j=s.jsx("section",{className:`element-mention-menu${v?" is-mobile":""}`,style:v?void 0:{left:S.left,top:S.top,maxHeight:S.maxHeight},"aria-label":i,children:s.jsx("ul",{id:p,className:"element-mention-menu__list",role:"listbox",ref:w,children:I.length?I.map((L,q)=>s.jsxs("li",{id:`${p}-${L.id}`,role:"option","aria-selected":q===h,className:`element-mention-menu__option${q===h?" is-active":""}`,onPointerEnter:()=>_(q),onMouseDown:A=>{A.preventDefault(),d(L)},children:[L.thumbnail?s.jsx("img",{src:L.thumbnail,alt:"",className:"element-mention-menu__thumbnail"}):s.jsx("span",{className:"element-mention-menu__thumbnail is-empty","aria-hidden":"true"}),s.jsxs("span",{className:"element-mention-menu__copy",children:[s.jsx("strong",{children:L.name}),s.jsx("small",{children:c(L.kind)})]})]},L.id)):s.jsx("li",{className:"element-mention-menu__empty",role:"presentation",children:l})})});return mo.createPortal(j,document.body)}function Dv(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function Gv(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??Dv(e.source.referenceFilenames[0])}function zv({items:e,limit:t,onRemove:n,onAdd:r}){const{t:o}=V(),a=e.length>t,i=e.length>=t;return s.jsxs("div",{className:"composer__tray-wrap",children:[s.jsxs("div",{className:"composer__tray",role:"list","aria-label":o("prompt.trayAria",{count:e.length,max:t}),children:[e.map((l,c)=>{const d=Gv(l);return s.jsxs("div",{className:"composer__tray-slot",role:"listitem","aria-label":`@${l.tag}, ${c+1}/${t}`,children:[s.jsxs("span",{className:"composer__tray-thumbnail",children:[d?s.jsx("img",{src:d,alt:"",loading:"lazy",decoding:"async"}):s.jsx("span",{className:"composer__tray-thumbnail-empty","aria-hidden":"true",children:"@"}),s.jsx("button",{type:"button",className:"composer__tray-remove",onClick:()=>n(l.tokenId),"aria-label":`${o("prompt.refRemoveAria",{n:c+1})}: @${l.tag}`,children:"×"})]}),s.jsxs("span",{className:"composer__tray-tag",title:`@${l.tag}`,children:["@",l.tag]})]},l.tokenId)}),s.jsx("button",{type:"button",className:"composer__tray-slot composer__tray-slot--add",onClick:r,disabled:i,"aria-label":o("prompt.attachTitle"),title:o("prompt.attachTitle"),children:s.jsx("span",{"aria-hidden":"true",children:"+"})})]}),a?s.jsx("p",{className:"composer__ref-warning",role:"alert",children:o("prompt.refOverProviderLimit",{max:t,excess:e.length-t})}):null]})}function Uv({kind:e="character"}){const t={character:"M8 8a3 3 0 1 0 0-6 3 3 0 0 0 0 6Zm-5 6c.4-2.2 2.2-3.5 5-3.5s4.6 1.3 5 3.5",product:"M3 5.5 8 2l5 3.5v6L8 15l-5-3.5v-6ZM3 5.5 8 9l5-3.5M8 9v6",style:"m3 11 5-8 5 8-5 2-5-2Zm5-8v10",scene:"M2 13 6.5 8l3 3 2-2 2.5 4H2ZM2 3h12v12H2z",reference:"M2 3h12v10H2zM2 10l3.5-3.5 3 3L11 7l3 3"};return s.jsx("svg",{className:"element-mention-chip__kind",viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:t[e]})})}function $v({elementId:e,name:t,kind:n,thumbnail:r,missing:o,ariaLabel:a,unavailableLabel:i,removeLabel:l,onRemove:c,onOpen:d}){return s.jsxs("span",{className:`element-mention-chip${o?" is-missing":""}`,"data-element-id":e,children:[s.jsxs("button",{type:"button",className:"element-mention-chip__body",onClick:()=>d?.(e),"aria-label":a,children:[r?s.jsx("img",{className:"element-mention-chip__thumbnail",src:r,alt:""}):s.jsx("span",{className:"element-mention-chip__thumbnail is-empty","aria-hidden":"true"}),o?s.jsx("span",{className:"element-mention-chip__warning","aria-label":i,children:"!"}):s.jsx(Uv,{kind:n}),s.jsx("span",{className:"element-mention-chip__name",children:t})]}),s.jsx("button",{type:"button",className:"element-mention-chip__remove",onClick:()=>c(e),"aria-label":l,children:s.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:s.jsx("path",{d:"m4 4 8 8m0-8-8 8"})})})]})}const qv=new Set(["character","product","style","scene"]);function Hv(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&qv.has(t)?t:"character"}function Vv(e){if(!e)return;const t=e.metadata?.refs,n=Array.isArray(t)?t.find(r=>typeof r=="string"&&r.length>0):void 0;return n?`/generated/${n.split("/").map(encodeURIComponent).join("/")}`:void 0}function Kv(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),o=new Set(n);return Pc({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:Hv(i),thumbnail:Vv(i)??a.source.thumbnailUrl,missing:o.has(a.source.elementId)||t!==null&&!i}})}function Bv(e){const t=Kv(e.items,e.assets,e.missingElementIds);return t.length===0?null:s.jsx(sa,{ariaLabel:e.selectedLabel,children:t.map(n=>{const r=e.kindLabel(n.kind);return s.jsx($v,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const Wv=["boxSizing","width","height","overflowX","overflowY","borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth","paddingTop","paddingRight","paddingBottom","paddingLeft","fontFamily","fontSize","fontWeight","fontStyle","letterSpacing","lineHeight","textTransform","textIndent","textAlign","wordSpacing","tabSize","whiteSpace","overflowWrap","wordBreak"];function Jv({prompt:e,retiredTags:t,textareaRef:n}){const{t:r}=V(),o=g.useRef(null),a=g.useRef(null),[i,l]=g.useState([]),c=g.useMemo(()=>Nf(e).filter(m=>Object.prototype.hasOwnProperty.call(t,m.tag)),[e,t]),d=g.useMemo(()=>[...new Set(c.map(m=>`@${m.tag}`))],[c]);return g.useLayoutEffect(()=>{const m=n.current,u=o.current,p=a.current?.firstChild;if(!m||!u||!(p instanceof Text)){l([]);return}const h=()=>{const S=getComputedStyle(m);Wv.forEach(y=>{u.style[y]=S[y]}),u.scrollTop=m.scrollTop,u.scrollLeft=m.scrollLeft;const b=u.getBoundingClientRect(),v=[];for(const y of c){const w=document.createRange();w.setStart(p,y.start),w.setEnd(p,y.end),Array.from(w.getClientRects()).forEach((I,_)=>{v.push({key:`${y.start}-${y.end}-${_}`,left:I.left-b.left+u.scrollLeft,top:I.top-b.top+u.scrollTop,width:I.width,height:I.height})})}l(v)};h(),m.addEventListener("scroll",h,{passive:!0});const x=new ResizeObserver(h);return x.observe(m),()=>{m.removeEventListener("scroll",h),x.disconnect()}},[n,e,c]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:o,className:"composer__prompt-mirror","aria-hidden":"true",children:[s.jsx("span",{ref:a,children:e}),i.map(m=>s.jsx("span",{className:"dead-tag",style:m},m.key))]}),s.jsx("span",{className:"sr-only",role:"status","aria-live":"polite","aria-atomic":"true",children:d.length>0?r("prompt.deadTagStatus",{tags:d.join(", ")}):""})]})}async function po(e){const t=f.getState(),n=xe(e),r=!!e.prompt;if(t.clearReferences(),t.setPrompt(r&&!n?e.prompt:""),n){const o=e.url||e.image,a=await sn(o);t.addReferenceDataUrl(a);const i=$c(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(Kf(i)),e.videoSeries?.topic&&t.setVideoTopic(e.videoSeries.topic),t.videoModelSelected||t.selectVideoModel("grok-imagine-video-1.5")}else await t.useImageAsReference(e);return{ok:!0,isVideo:n,hasPrompt:r}}async function Id(e){const t=await po(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const Yv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:po,continueFromItemAsUrl:Id},Symbol.toStringTag,{value:"Module"}));function Xv({text:e,mode:t,onClose:n}){const{t:r}=V(),o=f(x=>x.savePromptToLibrary),[a,i]=g.useState(e.slice(0,30)),[l,c]=g.useState(e),[d,m]=g.useState(""),[u,p]=g.useState(!1),h=async()=>{l.trim()&&(p(!0),await o({name:a.trim()||l.slice(0,30),text:l.trim(),tags:d.split(",").map(x=>x.trim()).filter(Boolean),mode:t||void 0}),p(!1),n())};return s.jsxs("div",{className:"save-prompt-popover",onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:"save-prompt-popover__header",children:[s.jsx("span",{children:r("promptLibrary.saveTitle")}),s.jsx("button",{className:"save-prompt-popover__close",onClick:n,"aria-label":r("common.close"),children:"×"})]}),s.jsxs("div",{className:"save-prompt-popover__body",children:[s.jsxs("label",{children:[r("promptLibrary.name"),s.jsx("input",{type:"text",value:a,onChange:x=>i(x.target.value),placeholder:l.slice(0,30)})]}),s.jsxs("label",{children:[r("promptLibrary.content"),s.jsx("textarea",{value:l,onChange:x=>c(x.target.value),placeholder:r("common.enterPrompt"),rows:4,autoFocus:!0})]}),s.jsxs("label",{children:[r("promptLibrary.tags"),s.jsx("input",{type:"text",value:d,onChange:x=>m(x.target.value),placeholder:"cta, product, summer"})]})]}),s.jsx("div",{className:"save-prompt-popover__footer",children:s.jsx("button",{onClick:h,disabled:u||!l.trim(),className:"save-prompt-popover__save",children:r(u?"common.saving":"promptLibrary.save")})})]})}function Zv({variant:e="label"}){const{t}=V(),n=f(a=>a.webSearchEnabled),r=f(a=>a.setWebSearchEnabled),o=t(n?"settings.webSearch.on":"settings.webSearch.off");return e==="label"?s.jsx(Av,{checked:n,onChange:r,label:o,className:"web-search-toggle web-search-toggle--label"}):s.jsx("button",{type:"button",className:`${e==="compact"?"composer__tool ":""}web-search-toggle web-search-toggle--${e}${n?" is-active":""}`,onClick:()=>r(!n),"aria-pressed":n,"aria-label":o,title:o,children:e==="compact"?s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M2 12h20"}),s.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 0 20"}),s.jsx("path",{d:"M12 2a15.3 15.3 0 0 0 0 20"})]}):s.jsx("span",{children:o})})}function Qv({canAddMore:e,onAttach:t}){const{t:n}=V(),r=f(S=>S.prompt),o=f(S=>S.currentImage),a=f(S=>S.videoModelSelected),i=f(S=>S.selectVideoModel),l=f(S=>S.setImageModel),c=f(S=>S.promptMode),d=f(S=>S.setPromptMode),m=f(S=>S.storyboardActive),u=f(S=>S.toggleStoryboard),[p,h]=g.useState(!1),x=c==="direct";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"composer__hint-row",children:s.jsx("span",{className:"composer__hint",children:n("prompt.hint")})}),s.jsxs("div",{className:"composer__toolbar",children:[s.jsx("button",{type:"button",className:"composer__tool",onClick:t,disabled:!e,title:n("prompt.attachTitle"),"aria-label":n("prompt.attachTitle"),children:s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),s.jsx("button",{type:"button",className:"composer__tool",onClick:()=>o&&void po(o).catch(()=>{}),disabled:!o||!e,title:n("prompt.continueTitle"),children:n("prompt.continue")}),s.jsx("button",{type:"button",className:`composer__tool${a?" composer__tool--on":""}`,onClick:()=>{a?l(kr):i("grok-imagine-video-1.5")},title:n("prompt.videoToggleTitle"),"aria-label":n("prompt.videoToggleTitle"),"aria-pressed":!!a,children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("polygon",{points:"23 7 16 12 23 17 23 7"}),s.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2",ry:"2"})]})}),s.jsx("button",{type:"button",className:`composer__tool${x?" composer__tool--on":""}`,onClick:()=>d(x?"auto":"direct"),title:n("prompt.directModeTitle"),"aria-label":n("prompt.directModeTitle"),"aria-pressed":x,children:s.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"})}),s.jsx(Zv,{variant:"compact"}),s.jsxs("div",{className:"composer__tool-wrap",children:[s.jsx("button",{type:"button",className:"composer__tool composer__tool--full",onClick:()=>h(S=>!S),disabled:!r.trim(),title:n("promptLibrary.saveTitle"),"aria-label":n("promptLibrary.saveTitle"),children:n("prompt.savePrompt")}),p&&s.jsx(Xv,{text:r,mode:c,onClose:()=>h(!1)})]})]}),s.jsx("div",{className:"composer__storyboard-row",children:s.jsx("button",{type:"button",className:`composer__tool composer__tool--storyboard${m?" composer__tool--on":""}`,onClick:u,title:n("prompt.storyboardTitle"),"aria-pressed":m,children:n("prompt.storyboard")})})]})}function ri(e){return e?Array.from(e).flatMap(t=>{if(t.kind!=="file"||!t.type.startsWith("image/"))return[];const n=t.getAsFile();return n?[n]:[]}):[]}function eb(e){const{maxRefs:t,trayItemCount:n,captureAttachmentCaret:r,addFilesAtCaret:o}=e,{t:a}=V(),i=async(c,d)=>{const m=Math.max(0,t-n);if(m===0){f.getState().showToast(a("toast.refLimitTrayFull",{max:t}),!0);return}const u=c.slice(0,m),p=await o(u,d,!1);c.length>u.length&&f.getState().showToast(a("toast.refLimitPartial",{added:p,total:c.length,max:t}),!1)},l=c=>{const d=ri(c.clipboardData?.items??null);d.length!==0&&(c.preventDefault(),i(d,r()))};return g.useEffect(()=>{const c=d=>{const m=d.target;if(["INPUT","TEXTAREA"].includes(m?.tagName??"")||m?.isContentEditable)return;const u=ri(d.clipboardData?.items??null);u.length!==0&&(d.preventDefault(),i(u,f.getState().prompt.length))};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[o,t,a,n]),l}const wd="grok-imagine-video",tb="grok-imagine-video-1.5",_d=new Set([tb,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function nb(e){return e.type.startsWith("audio/")}function rb(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function ob(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,o=typeof r=="string"&&_d.has(r),a=r===wd;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(nb(i)){r?o?n.audios.push(i):n.rejected.push({file:i,reason:"audio-needs-15"}):n.rejected.push({file:i,reason:"audio-needs-video-model"});continue}if(rb(i)){a?n.videos.length>0?n.rejected.push({file:i,reason:"video-single-only"}):n.videos.push(i):n.rejected.push({file:i,reason:"video-needs-base"});continue}n.rejected.push({file:i,reason:"not-media"})}return n}function sb(e){const t=e.videoModelSelected;return typeof t=="string"&&_d.has(t)?"image/*,audio/*":t===wd?"image/*,video/mp4":"image/*"}function ab(e,t){switch(e){case"audio-needs-video-model":return t("prompt.rejectAudioNeedsVideoModel");case"audio-needs-15":return t("prompt.rejectAudioNeeds15");case"video-needs-base":return t("prompt.rejectVideoNeedsBase");case"video-single-only":return t("prompt.rejectVideoSingleOnly");case"not-media":return t("prompt.rejectNotMedia")}}function ib({onImages:e}){const{t}=V(),n=f(o=>o.videoModelSelected),r=f(o=>o.showToast);return o=>{if(o.length===0)return;const a=ob(o,{videoModelSelected:n});a.images.length>0&&e(a.images),a.audios.length>0&&r(t("prompt.audioUsePresetVoice"),!0),a.videos.length>0&&r(t("prompt.videoUseCliForEdit"),!0);for(const i of new Set(a.rejected.map(l=>l.reason)))r(ab(i,t),!0)}}function lb({variant:e,onSubmit:t}){const n=f(d=>d.provider),r=f(d=>d.negativePrompt),o=f(d=>d.setNegativePrompt),a=g.useRef(!1),{t:i}=V();if(g.useLayoutEffect(()=>{n!=="nai"&&(a.current=!1)},[n]),n!=="nai")return null;const l=`negative-prompt-${e}`,c=`${l}-hint`;return s.jsxs("div",{className:`negative-prompt negative-prompt--${e}`,children:[s.jsx("label",{className:"negative-prompt__label",htmlFor:l,children:i("nai.negativePrompt.label")}),s.jsx("textarea",{id:l,className:`negative-prompt__textarea${e==="home"?" home-prompt__textarea":""}`,rows:5,value:r,placeholder:i("nai.negativePrompt.placeholder"),"aria-describedby":c,onCompositionStart:()=>{a.current=!0},onCompositionEnd:()=>{a.current=!1},onChange:d=>o(d.target.value),onKeyDown:d=>{d.key!=="Enter"||!(d.metaKey||d.ctrlKey)||d.defaultPrevented||a.current||d.nativeEvent.isComposing||d.nativeEvent.keyCode===229||(d.preventDefault(),t())}}),s.jsx("p",{id:c,className:"negative-prompt__hint",children:i("nai.negativePrompt.hint",{count:r.length})})]})}const _o="tray:";function Eo(e){return`${e.start}:${e.end}:${e.query}`}function cb(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):Ir(e.id,f.setState,f.getState,e)}function db(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):Oc(e,f.setState,f.getState)}function ub(e){const t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function aa({variant:e="sidebar"}){const t=f(E=>E.prompt),n=f(E=>E.setPrompt),r=f(E=>E.provider),o=f(E=>E.insertedPrompts),a=f(E=>E.removeInsertedPromptFromComposer),i=f(E=>E.moveInsertedPromptInComposer),l=f(E=>E.generate),c=f(E=>E.selectedPresetIds),d=f(E=>E.removePreset),m=f(E=>E),u=m.addElementId,p=m.elementCatalog??null,h=m.missingElementIds??[],[x,S]=g.useState([]),b=E=>{const W=x.find(Q=>Q.id===E);return W?cb(W):(u?.(E),null)};g.useEffect(()=>{let E=!1;return vf().then(W=>{E||(S(W),db(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{E=!0}},[]);const{t:v}=V(),y=f(E=>E.trayItems),w=f(E=>E.retiredTags),I=f(E=>E.removeTrayItem),_=f(E=>E.activeReferenceLimit()),N=f(E=>E.providerUrlReference),j=f(E=>E.setProviderUrlReference),L=f(E=>E.addReferences),q=f(E=>E.addReferenceDataUrl),A=f(E=>E.useImageAsReference),G=f(E=>E.readDroppedImageMetadata),C=f(E=>E.videoModelSelected),T=g.useRef(null),k=g.useRef(null),R=g.useRef(null),[B,se]=g.useState(!1),[oe,ae]=g.useState(null),ge=g.useRef(!1),D=g.useRef(null),F=g.useRef(null),ee=f(E=>E.promptMode),J=f(Bf),me=f(E=>E.multimodeMaxImages),ye=ee==="direct",ie=r==="nai",ke=o.filter(E=>E.placement!=="after"),le=o.filter(E=>E.placement==="after"),Ie=[...ke.map(E=>E.id),"__main_prompt__",...le.map(E=>E.id)],je=y.length<_,Re=J?y.length>0?v("multimode.promptPlaceholderWithRefs"):v("multimode.promptPlaceholder"):y.length>0?v("prompt.placeholderWithRefs"):v("prompt.placeholder"),ce=()=>{h.length>0||l()},be=()=>k.current?.selectionStart??f.getState().prompt.length,z=(E,W)=>{const Q=f.getState().trayItems.filter(H=>H.kind==="attachment"&&!E.has(H.tokenId));if(Q.length===0)return 0;const we=f.getState().prompt,M=Math.max(0,Math.min(W,we.length)),Y=Q.map(H=>`@${H.tag} `).join("");n(`${we.slice(0,M)}${Y}${we.slice(M)}`);const _e=M+Y.length;return requestAnimationFrame(()=>k.current?.setSelectionRange(_e,_e)),Q.length},ve=(E,W)=>{const Q=`@${E} `,we=f.getState().prompt,M=`${we.slice(0,W.start)}${Q}${we.slice(W.end)}`,Y=W.start+Q.length;n(M),requestAnimationFrame(()=>k.current?.setSelectionRange(Y,Y))},P=(E,W)=>{if(ge.current)return;const Q=kv(E,W);ae(Q&&Eo(Q)!==F.current?Q:null)},ne=async(E,W,Q)=>{if(E.length===0)return 0;const we=new Set(f.getState().trayItems.map(M=>M.tokenId));try{return Q&&E.length===1&&await G(E[0])?0:(await L(E),z(we,W))}catch{return 0}},de=async E=>{const W=R.current??be();R.current=null,await ne(E,W,!0)},K=ib({onImages:E=>{de(E)}}),U=()=>{je&&(R.current=be(),T.current?.click())},X=async(E,W)=>{const Q=new Set(f.getState().trayItems.map(we=>we.tokenId));try{const we=E.url||E.image;if(!we)return;const M={image:we,url:E.url,filename:E.filename};if(xe(M)){const Y=await sn(we);Y&&q(Y)}else await A(M);z(Q,W)}catch{}},re=E=>{E.preventDefault(),se(!1);const W=E.dataTransfer.getData("application/ima2-ref");if(W){try{const Q=JSON.parse(W);X(Q,be())}catch{}return}K(Array.from(E.dataTransfer.files))},Oe=E=>{E.preventDefault(),B||se(!0)},ze=E=>{E.currentTarget.contains(E.relatedTarget)||se(!1)},Gt=eb({maxRefs:_,trayItemCount:y.length,captureAttachmentCaret:be,addFilesAtCaret:ne}),Je=g.useRef(null),pt=g.useRef(e);g.useLayoutEffect(()=>{const E=k.current;if(!E)return;(Je.current===null||pt.current!==e)&&(Je.current=ub(window.getComputedStyle(E).maxHeight)??0,pt.current=e),E.style.height="auto";const W=Je.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ft=(E,W)=>{const Q=Ie.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<Ie.length-1},xt=E=>s.jsxs("div",{className:"composer__prompt-chip",title:E.name,children:[s.jsx("span",{className:"composer__prompt-chip-plus","aria-hidden":"true",children:"+"}),s.jsx("span",{className:"composer__prompt-chip-title",children:E.name}),s.jsxs("div",{className:"composer__prompt-chip-actions",children:[s.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>i(E.id,"up"),disabled:!ft(E.id,"up"),"aria-label":v("prompt.moveBlockUp",{name:E.name}),title:v("prompt.moveBlockUp",{name:E.name}),children:"^"}),s.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>i(E.id,"down"),disabled:!ft(E.id,"down"),"aria-label":v("prompt.moveBlockDown",{name:E.name}),title:v("prompt.moveBlockDown",{name:E.name}),children:"v"}),s.jsx("button",{type:"button",className:"composer__prompt-chip-remove",onClick:()=>a(E.id),"aria-label":v("promptLibrary.removeInserted",{name:E.name}),children:"x"})]})]},E.id);return s.jsxs("div",{className:`composer composer--${e}${B?" composer--drag":""}${ye?" composer--direct":""}${J?" composer--multimode":""}${ye&&J?" composer--combined-modes":""}`,role:"group","aria-label":J?v("multimode.composerAriaLabel",{count:me}):v("prompt.label"),onDrop:re,onDragOver:Oe,onDragLeave:ze,onPaste:Gt,children:[s.jsxs("div",{className:"composer__header",children:[s.jsx("span",{className:"section-title composer__label",children:v("prompt.label")}),s.jsxs("div",{className:"composer__header-meta",children:[J&&s.jsx("span",{className:"composer__mode-badge",children:v("multimode.composerBadge",{count:me})}),ye&&s.jsx("span",{className:"composer__direct-badge",children:v("prompt.directModeActive")}),N&&s.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>j(null),title:v("prompt.urlRefActiveTitle"),"aria-label":v("prompt.urlRefClear"),children:[s.jsx("span",{className:"composer__url-ref-dot","aria-hidden":"true"}),v("prompt.urlRefActive")]}),y.length>0&&s.jsx("span",{className:"composer__count",children:v("prompt.refCount",{count:y.length,max:_})})]})]}),s.jsx(zv,{items:y,limit:_,onRemove:I,onAdd:U}),ke.length>0&&s.jsx("div",{className:"composer__prompt-chips",children:ke.map(xt)}),c.length>0&&s.jsx(sa,{ariaLabel:v("home.selectedPresets"),children:c.map(E=>{const W=Gc(E);return W?s.jsx(xd,{onRemove:()=>d(E),removeLabel:v("common.removeNamed",{name:W.name}),children:W.name},E):null})}),s.jsx(Bv,{items:y,assets:p,missingElementIds:h,selectedLabel:v("element.selected"),unavailableLabel:v("common.elementUnavailable"),kindLabel:E=>v(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),mentionLabel:(E,W,Q)=>Q?v("element.unavailableAria",{name:E}):v("element.mentionAria",{name:E,kind:W}),removeLabel:E=>v("element.removeAria",{name:E}),onRemove:E=>m.removeElementId?.(E)}),s.jsxs("div",{className:`composer__prompt-panes${ie?" composer__prompt-panes--dual":""}`,children:[s.jsxs("div",{className:"composer__prompt-pane",children:[ie?s.jsx("label",{className:"composer__prompt-pane-label",htmlFor:`positive-prompt-${e}`,children:v("nai.positivePrompt.label")}):null,s.jsxs("div",{className:"composer__prompt-stack",children:[s.jsx(Jv,{prompt:t,retiredTags:w,textareaRef:k}),s.jsx("textarea",{id:`positive-prompt-${e}`,ref:k,className:"prompt-area composer__textarea",value:t,placeholder:ie?v("nai.positivePrompt.placeholder"):Re,"aria-describedby":ie?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{ge.current=!0,ae(null)},onCompositionEnd:E=>{ge.current=!1,D.current=E.currentTarget.value,queueMicrotask(()=>{D.current=null}),P(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{F.current=null,n(E.target.value),D.current!==E.target.value&&P(E.target.value,E.target.selectionStart)},onClick:E=>P(E.currentTarget.value,E.currentTarget.selectionStart),onKeyDown:E=>{if(!(ge.current||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229)){if(E.key==="Escape"&&oe){E.preventDefault(),F.current=Eo(oe),ae(null);return}if(E.key==="Enter"&&(E.metaKey||E.ctrlKey)){if(E.defaultPrevented)return;E.preventDefault(),ce()}}}})]}),ie?s.jsx("p",{id:`positive-prompt-${e}-hint`,className:"composer__prompt-hint",children:v("nai.positivePrompt.hint",{count:t.length})}):null]}),s.jsx(lb,{variant:"classic",onSubmit:ce})]}),s.jsx(Fv,{open:oe!==null,textareaRef:k,composingRef:ge,caret:oe?.end??0,query:oe?.query??"",elements:[...y.filter(E=>E.kind==="attachment").map(E=>({id:`${_o}${E.tokenId}`,name:E.tag,kind:"reference",thumbnail:E.source.dataUrl})),...x.map(E=>{const W=Cc(E);return{id:E.id,name:E.name,kind:typeof E.metadata?.elementKind=="string"?E.metadata.elementKind:"character",thumbnail:W?`/generated/${W.split("/").map(encodeURIComponent).join("/")}`:void 0,tags:E.tags}})],ariaLabel:v("common.elementSuggestions"),emptyLabel:v("common.noMatchingElements"),kindLabel:E=>v(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),onSelect:E=>{const W=ss(f.getState().trayItems,E.id);if(E.id.startsWith(_o)){const we=E.id.slice(_o.length),M=f.getState().trayItems.find(Y=>Y.tokenId===we);M&&oe&&ve(M.tag,oe),ae(null);return}if(b?.(E.id),W){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),ae(null);return}const Q=ss(f.getState().trayItems,E.id);!Q||!oe||(ve(Q.tag,oe),ae(null))},onClose:E=>{E==="escape"&&oe&&(F.current=Eo(oe)),ae(null)}}),le.length>0&&s.jsxs("div",{className:"composer__prompt-chips composer__prompt-chips--after",children:[s.jsx("span",{className:"composer__prompt-chips-label",children:v("prompt.afterBlocks")}),le.map(xt)]}),s.jsx(Qv,{canAddMore:je,onAttach:U}),B&&s.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:v("prompt.dropHere",{max:_})}),s.jsx("input",{ref:T,type:"file",accept:sb({videoModelSelected:C}),multiple:!0,hidden:!0,onChange:E=>{const W=Array.from(E.target.files??[]);W.length>0?K(W):R.current=null,E.target.value=""}})]})}function ia(){const e=f(l=>l.activeGenerations),t=f(l=>l.generate),n=f(l=>l.openReadinessPopup),r=f(l=>l.missingElementIds??[]),{t:o}=V(),a=e>0,i=r.length>0;return s.jsxs("div",{className:"generate-row",children:[s.jsxs("button",{type:"button",className:`generate-btn foil-hover${a?" generate-btn--active":""}`,disabled:i,title:i?o("toast.missingElements"):void 0,onClick:()=>{t()},children:[o("generate.button"),a?s.jsx("span",{className:"generate-btn__count","aria-label":o("generate.buttonLoading",{n:e}),children:e}):null]}),s.jsx("button",{type:"button",className:"generate-row__readiness",onClick:n,title:o("readiness.openTitle"),"aria-label":o("readiness.openTitle"),children:"?"})]})}function Ed(e,t=28){const n=e.trim().replace(/\s+/g," ");return n.length>t?`${n.slice(0,t)}...`:n}function la(e={}){const t=f(i=>i.inFlight),n=f(i=>i.cancelInFlightJob),r=f(i=>i.videoProgress),{t:o}=V(),a={queued:o("inflight.queued"),planning:o("inflight.planning"),streaming:o("inflight.streaming"),decoding:o("inflight.decoding"),canceling:o("inflight.canceling")};return t.length===0?null:"panelId"in e?s.jsx(fb,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o,variant:e.variant,panelId:e.panelId}):s.jsx(mb,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o})}function mb(e){return s.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>s.jsx(pb,{f:t,...e},t.id))})}function pb({f:e,phaseLabels:t,videoProgress:n,cancelInFlightJob:r,t:o}){const a=e.phase?t[e.phase]??e.phase:o("inflight.queued"),l=e.prompt.trim().replace(/\s+/g," ")||o("inflight.noPrompt");return s.jsxs("li",{className:"in-flight-item","data-phase":e.phase??"queued",title:l,"aria-label":`${a}: ${l}`,children:[s.jsx("span",{className:"in-flight-prompt",children:Ed(e.prompt)}),s.jsx("span",{className:"in-flight-phase",children:e.kind==="video"&&n!=null&&n>0?`${Math.round(n*100)}%`:a}),s.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{r(e.id)},disabled:e.phase==="canceling","aria-label":o("inflight.cancelAria",{prompt:l}),title:o("common.cancel"),children:"×"}),s.jsx("span",{className:"in-flight-spinner","aria-hidden":"true","data-motion-essential":!0})]})}function fb(e){const t=e.jobs.filter(o=>o.kind==="video"||o.kind==="mcp-video"),n=t.length===1?t[0]?.id:null,r=e.videoProgress!=null&&e.videoProgress>=0&&e.videoProgress<=1?e.videoProgress:null;return s.jsx("ul",{id:e.panelId,className:`in-flight-list in-flight-list--${e.variant}`,children:e.jobs.map(o=>s.jsx(hb,{f:o,determinateVideoId:n,validVideoProgress:r,...e},o.id))})}function hb({f:e,determinateVideoId:t,validVideoProgress:n,phaseLabels:r,cancelInFlightJob:o,t:a}){const i=e.phase?r[e.phase]??e.phase:a("inflight.queued"),c=e.prompt.trim().replace(/\s+/g," ")||a("inflight.noPrompt"),d=e.kind==="video"||e.kind==="mcp-video",m=yb(e)??vb(e.kind,a),u=e.id===t&&n!=null?Math.round(n*100):null;return s.jsxs("li",{className:"in-flight-rich-item","data-phase":e.phase??"queued",title:c,"aria-label":`${m}, ${i}: ${c}`,children:[s.jsx("span",{className:`in-flight-placeholder${d?" in-flight-placeholder--video":""}`,"aria-hidden":"true",children:s.jsx(bb,{video:d})}),s.jsxs("span",{className:"in-flight-rich-copy",children:[s.jsx("span",{className:"in-flight-rich-title",children:m}),s.jsx("span",{className:"in-flight-rich-prompt",title:c,children:Ed(e.prompt,54)}),s.jsxs("span",{className:"in-flight-rich-status",children:[s.jsx("span",{className:"in-flight-phase",children:u==null?i:`${i} · ${u}%`}),s.jsx(gb,{progressPercent:u,phaseLabel:i,t:a})]})]}),s.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{o(e.id)},disabled:e.phase==="canceling","aria-label":a("inflight.cancelAria",{prompt:c}),title:a("common.cancel"),children:"×"})]})}function gb({progressPercent:e,phaseLabel:t,t:n}){return s.jsx("span",{className:`in-flight-progress${e==null?" in-flight-progress--indeterminate":""}`,role:"progressbar","data-motion-essential":!0,"aria-label":e==null?t:n("inflight.progressAria",{n:e}),"aria-valuemin":e==null?void 0:0,"aria-valuemax":e==null?void 0:100,"aria-valuenow":e??void 0,children:s.jsx("span",{style:e==null?void 0:{width:`${e}%`}})})}function yb(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function vb(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function bb({video:e}){return s.jsxs("svg",{viewBox:"0 0 24 24",focusable:"false",children:[s.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),e?s.jsx("path",{d:"m10 9 5 3-5 3Z"}):s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"9",cy:"9",r:"1.5"}),s.jsx("path",{d:"m5.5 17 4.2-4 2.7 2.4 2.2-2 3.9 3.6"})]})]})}const oi="(max-width: 800px)";function mt(){const[e,t]=g.useState(()=>typeof window<"u"?window.matchMedia(oi).matches:!1);return g.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(oi),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const xb=10,ht=12;function Sb({anchorRef:e,panelId:t,focusOnOpen:n,onRequestClose:r,onPointerEnter:o,onPointerLeave:a}){const{t:i}=V(),l=g.useRef(null),c=g.useRef(null),d=g.useRef(null),[m,u]=g.useState({left:ht,top:ht,caretTop:24}),[p,h]=g.useState(!1);g.useLayoutEffect(()=>{const b=()=>{const w=e.current,I=l.current;if(!w||!I)return;const _=w.getBoundingClientRect(),N=w.closest(".sidebar")?.getBoundingClientRect(),j=I.getBoundingClientRect(),L=N?N.right:_.right,q=Math.max(ht,window.innerWidth-j.width-ht),A=Math.max(ht,window.innerHeight-j.height-ht),G=Math.min(Math.max(L+xb,ht),q),C=Math.min(Math.max(_.bottom-j.height,ht),A),T=Math.min(Math.max(_.top+_.height/2-C,16),j.height-16);u({left:G,top:C,caretTop:T}),h(!0)},v=()=>{d.current!=null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(b)};b(),window.addEventListener("resize",v),window.addEventListener("scroll",v,!0);const y=new ResizeObserver(v);return e.current&&y.observe(e.current),l.current&&y.observe(l.current),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0),y.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),g.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),g.useEffect(()=>{const b=y=>{const w=y.target;w&&(e.current?.contains(w)||l.current?.contains(w))||r(!1)},v=y=>{y.key==="Escape"&&(y.preventDefault(),r(!0))};return document.addEventListener("pointerdown",b,!0),document.addEventListener("keydown",v),()=>{document.removeEventListener("pointerdown",b,!0),document.removeEventListener("keydown",v)}},[e,r]);const x=`${t}-title`,S={left:m.left,top:m.top,"--inflight-caret-top":`${m.caretTop}px`};return mo.createPortal(s.jsxs("div",{ref:l,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":x,"data-positioned":p,style:S,onPointerEnter:o,onPointerLeave:a,children:[s.jsxs("header",{className:"inflight-popup__header",children:[s.jsx("h2",{ref:c,id:x,tabIndex:-1,children:i("inflight.title")}),s.jsx("button",{type:"button",className:"inflight-popup__close","aria-label":i("common.close"),title:i("common.close"),onClick:()=>r(!0),children:s.jsx("span",{"aria-hidden":"true",children:"×"})})]}),s.jsx(la,{variant:"popup",panelId:t}),s.jsx("footer",{className:"inflight-popup__footer",children:i("inflight.footerHint")})]}),document.body)}const Ib=180,wb=180;function Nd({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const o=f(A=>A.inFlight.length),a=mt(),{t:i}=V(),[l,c]=g.useState("closed"),[d,m]=g.useState(!1),u=g.useRef(null),p=g.useRef(null),h=g.useRef(null),x=e==="inline"?n:l!=="closed",S=()=>{p.current!=null&&window.clearTimeout(p.current),h.current!=null&&window.clearTimeout(h.current),p.current=null,h.current=null};if(g.useEffect(()=>S,[]),g.useLayoutEffect(()=>{if(o!==0)return;const A=document.activeElement;x&&A instanceof HTMLElement&&A.closest(".inflight-popup")&&u.current?.focus(),S(),c("closed"),m(!1),e==="inline"&&n&&r?.(!1)},[o,n,r,x,e]),o===0&&!(o===0&&e==="popup"&&x)||e==="popup"&&a)return null;const v=()=>window.matchMedia("(hover: hover) and (pointer: fine)").matches,y=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=null},w=()=>{e!=="popup"||l==="pinned"||!v()||(y(),p.current!=null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>c("hover"),Ib))},I=()=>{p.current!=null&&window.clearTimeout(p.current),p.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),wb))},_=A=>{S(),c("closed"),m(!1),A&&u.current?.focus()},N=A=>{if(e==="inline"){r?.(!n);return}if(S(),l==="pinned"){_(!1);return}m(A.detail===0),c("pinned")},j=A=>{A.pointerType==="mouse"&&w()},L=o>99?"99+":String(o),q=x?"inflight.badgeClose":"inflight.badgeOpen";return s.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:j,onPointerLeave:I,children:[s.jsxs("button",{ref:u,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:N,"aria-live":"polite","aria-expanded":x,"aria-controls":t,"aria-haspopup":e==="popup"?"dialog":void 0,"aria-label":i(q,{n:o}),title:i(q,{n:o}),children:[s.jsx("span",{className:"inflight-badge__spinner","aria-hidden":"true"}),s.jsx("span",{className:"inflight-badge__count","aria-hidden":"true",children:L})]}),e==="popup"&&x?s.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&x?s.jsx(Sb,{anchorRef:u,panelId:t,focusOnOpen:d,onRequestClose:_,onPointerEnter:y,onPointerLeave:I}):null]})}function _b(){const{t:e}=V(),t=f(p=>p.sessions),n=f(p=>p.activeSessionId),r=f(p=>p.switchSession),o=f(p=>p.createAndSwitchSession),a=f(p=>p.renameCurrentSession),i=f(p=>p.deleteSessionById),[l,c]=g.useState(!1),d=t.find(p=>p.id===n),m=()=>{const p=window.prompt(e("session.renamePrompt"),d?.title??e("session.newSession"));p&&p.trim()&&a(p.trim())},u=(p,h)=>{window.confirm(e("session.deleteConfirm",{title:h}))&&i(p)};return s.jsxs("div",{className:"session-picker",children:[s.jsxs("div",{className:"session-picker-row",children:[s.jsxs("button",{type:"button",className:"session-current",onClick:()=>c(p=>!p),title:e("session.switchTitle"),children:[s.jsx("span",{className:"session-title",children:d?.title??e("session.loading")}),s.jsx("span",{className:"session-caret",children:l?"▴":"▾"})]}),s.jsx("button",{type:"button",className:"session-btn",onClick:()=>{o(e("session.newSession"))},title:e("session.newSessionTitle"),children:"+"}),s.jsx("button",{type:"button",className:"session-btn",onClick:m,title:e("session.renameTitle"),disabled:!d,children:s.jsx(Pv,{})})]}),l&&s.jsxs("ul",{className:"session-list",children:[t.map(p=>s.jsxs("li",{className:p.id===n?"is-active":"",children:[s.jsxs("button",{type:"button",className:"session-item",onClick:()=>{c(!1),r(p.id)},children:[s.jsx("span",{className:"session-item-title",children:p.title}),s.jsx("span",{className:"session-item-count",children:p.nodeCount})]}),s.jsx("button",{type:"button",className:"session-del",onClick:()=>u(p.id,p.title),title:e("session.deleteTitle"),children:"×"})]},p.id)),t.length===0&&s.jsx("li",{className:"session-empty",children:e("session.empty")})]})]})}function p0(){return $("/api/comfy/workflows")}function f0(e){return $("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function h0(e){return $("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function g0(e){return $("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function y0(e){return $(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Eb(e){return kb(await $("/api/models",e?{signal:e}:{}))}function Nb(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function wn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function vn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function si(e){if(!vn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return wn();const t={id:e.id,label:e.label};for(const n of["description","lockReason"])if(e[n]!==void 0){if(typeof e[n]!="string")return wn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return wn();t.executable=e.executable}return t}function kb(e){return!vn(e)||e.ok!==!0||!vn(e.lanes)?wn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!vn(n)||!Nb(n.status)||!vn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return wn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(si),video:n.models.video.map(si)}};return[t,r]}))}const kd={phase:"idle",catalog:null,observedAt:null,error:null},yt=new Set;let Ln=kd,Fr=0,gt=null,rr=null;const ai=()=>{da()};function ca(){return Ln}function bn(e){Ln=e;for(const t of[...yt])yt.has(t)&&t()}function No(e,t){return e===Fr&>===t&&!t.signal.aborted&&yt.size>0}function jb(e){const t=e;return t?.status===401||t?.status===403?"app-auth":t?.code==="MODEL_CATALOG_INVALID"?"invalid":"request"}async function da(){const e=++Fr;if(gt?.abort(),gt=null,yt.size===0){bn(kd);return}const t=new AbortController;if(gt=t,bn({...Ln,phase:"loading",error:null}),!!No(e,t))try{const n=await Eb(t.signal);No(e,t)&&bn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){No(e,t)&&bn({...Ln,phase:"error",error:jb(n)})}finally{e===Fr&>===t&&(gt=null)}}function Cb(e){const t=yt.size===0;return yt.add(e),t&&(typeof window<"u"&&(rr=window,rr.addEventListener("focus",ai)),da()),()=>{!yt.delete(e)||yt.size>0||(++Fr,gt?.abort(),gt=null,rr?.removeEventListener("focus",ai),rr=null,bn({...Ln,phase:"idle",error:null}))}}function Wn(){return{...g.useSyncExternalStore(Cb,ca),refresh:da}}function Vt(e){return e.executable!==!1&&!e.description?.endsWith("(offline)")}function Ct(e,t){const n=e.catalog?.comfy,r=n?.models??{image:[],video:[]},o=t?.comfyVideoWorkflow?"video":"image",a=t?.comfyVideoWorkflow||t?.comfyWorkflow||null,i=a?r[o].find(p=>p.id===a):void 0,l=Ss.comfy,c=r.image.some(Vt)||r.video.some(Vt),d=e.phase==="ready"&&n?.status==="ready"&&c,m=!!(d&&i&&Vt(i)&&(o==="video"?l.video.supported:l.generate.supported)),u=p=>({code:p,laneAvailable:d,selectedAvailable:m,selected:a?{id:a,kind:o,label:i?.label??a}:null,imageCount:r.image.length,videoCount:r.video.length});return e.phase==="idle"||e.phase==="loading"?u("loading"):e.phase==="error"?u("error"):!n||n.status==="key-missing"||n.status==="locked"?u("unavailable"):a&&!i?u("selected-missing"):r.image.length+r.video.length===0?u("empty"):n.status==="disconnected"?u("disconnected"):i?.executable===!1?u("selected-locked"):i?.description?.endsWith("(offline)")?u("selected-offline"):u(c?a?m?"ready":"unavailable":"choose":"unavailable")}const Ab={unavailable:"comfy.display.unavailable",empty:"comfy.display.empty",disconnected:"comfy.statusOffline",choose:"comfy.display.chooseWorkflow","selected-missing":"comfy.display.selectedMissing","selected-offline":"comfy.display.selectedOffline","selected-locked":"comfy.display.selectedLocked",ready:"comfy.display.available"};function Yt(e,t){return e.code==="loading"?t.catalog?"comfy.display.refreshing":"comfy.display.loading":e.code==="error"?t.error==="app-auth"?"comfy.display.appAccessRequired":"comfy.display.loadFailed":Ab[e.code]}const jd=[{value:"oauth",label:"GPT"},{value:"api",label:"GPT API"},{value:"grok",label:"Grok"},{value:"grok-api",label:"xAI API"},{value:"agy",label:"agy"},{value:"gemini-api",label:"Gem API"},{value:"atlascloud",label:"Atlas"},{value:"minimax",label:"MiniMax"},{value:"nai",label:"NovelAI"},{value:"comfy",label:"ComfyUI"}],ii=new Map(jd.map(e=>[e.value,e.label])),Tb=new Set(["runway","higgsfield"]),or="mcp:",sr="core:",ko="effort:",jo=gl,mn=Wt;function Pb(e){uo(e,f.setState,f.getState)}function Rb(e){Dg(e,f.setState,f.getState)}function Mb(e,t,n){Gg(e,t,f.setState,f.getState,n)}const Co={image:[],video:[]};function Ao(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Lb(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function Cd({compact:e=!1}={}){const{t}=V(),n=f(P=>P.provider),r=f(P=>P.imageModel),o=f(P=>P.videoModelSelected),a=f(P=>P.mcpProvider??null),i=f(P=>P.mcpModel??null),l=f(P=>P.mcpMediaKind??"image"),c=f(P=>P.setProvider),d=f(P=>P.setImageModel),m=f(P=>P.selectVideoModel),u=f(P=>P.setComfyWorkflow),p=f(P=>P.comfyWorkflow),h=f(P=>P.setComfyVideoWorkflow),x=f(P=>P.comfyVideoWorkflow),S=f(P=>P.setReasoningEffort),b=f(P=>P.reasoningEffort),{providers:v,loading:y,error:w}=md(),[I,_]=g.useState(Co),[N,j]=g.useState(!1),[L,q]=g.useState(0),[A,G]=g.useState(!1),C=Wn(),T=C.catalog??{},k=T.comfy?.models??{image:[],video:[]};g.useEffect(()=>{Vg(f.setState,f.getState)},[]);const R=a?v.find(P=>P.id===a)??null:null,B=!!(R?.enabled&&R.status.state==="connected");g.useEffect(()=>{if(!a||!B){_(Co),j(!1);return}const P=new AbortController;return G(!0),j(!1),ud(a,P.signal).then(ne=>{if(P.signal.aborted)return;_(ne);const de=f.getState(),U=(de.mcpMediaKind==="video"?ne.video:ne.image).find(X=>X.id===de.mcpModel);U&&Hg(U.capabilities,f.setState,f.getState)}).catch(ne=>{ne.name!=="AbortError"&&(P.signal.aborted||(_(Co),j(!0)))}).finally(()=>{P.signal.aborted||G(!1)}),()=>P.abort()},[a,B,L]);const se=g.useMemo(()=>v.filter(P=>P.enabled&&P.status.state==="connected"),[v]),oe=a?`${or}${a}`:`${sr}${n}`,ae=bm(n).filter(P=>P.providerHint===void 0||P.providerHint===n),ge=n==="comfy"?k.image.map(P=>({id:P.id,label:P.description?.endsWith("(offline)")?`${P.label} — ${t("comfy.statusOffline")}`:P.label,disabled:C.phase!=="ready"||T.comfy?.status!=="ready"||!Vt(P),reason:P.lockReason})):[],D=n==="comfy"?k.video.map(P=>({id:P.id,label:P.description?.endsWith("(offline)")?`${P.label} — ${t("comfy.statusOffline")}`:P.label,reason:P.lockReason,disabled:C.phase!=="ready"||T.comfy?.status!=="ready"||!Vt(P)})):[],F=Em({provider:n,imageModel:r,videoModel:o,comfyWorkflow:p,comfyVideoWorkflow:x}),ee=a?i?Xn(l,i):"":F,J=!a&&(n==="oauth"||n==="api")&&!o,me=!!(i&&(I.image.some(P=>P.id===i)||I.video.some(P=>P.id===i))),ye=R?.executable===!1?R.lockReason??t("mcp.higgsfieldLocked"):null,ie=a?R?R.status.state!=="connected"?t("mcp.disconnectedSelection"):R.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,ke=P=>{if(P.startsWith(sr)){const K=P.slice(sr.length);if(!ii.has(K))return;c(K);return}const ne=P.slice(or.length),de=v.find(K=>K.id===ne);!de||de.status.state!=="connected"||Pb(ne)},le=P=>{const ne=f.getState();if(ne.provider!==n||(ne.mcpProvider??null)!==a)return;const de=ca();if(ne.mcpProvider){if(P.startsWith(mn))return;const K=sp(P);if(K){const X=(K.kind==="video"?I.video:I.image).find(re=>re.id===K.model);Mb(K.model,K.kind,X?.capabilities)}else Rb(P||null);return}if(ne.provider==="comfy"){const K=P.startsWith(mn),U=K?P.slice(mn.length):P;if(!Ct(de,K?{comfyVideoWorkflow:U}:{comfyWorkflow:U}).selectedAvailable)return;K?h(U):u(U||null);return}if(!P.startsWith(mn)){if(P.startsWith(ko)){S(P.slice(ko.length));return}if(P.startsWith(jo)){m(P.slice(jo.length));return}d(P)}},Ie=Object.keys(T).filter(P=>!Tb.has(P)),je=Ie.length>0?Ie:jd.map(P=>P.value);je.includes("comfy")||je.push("comfy");const Re=[{label:t("mcp.coreProviders"),items:je.map(P=>{const ne=T[P],de=ii.get(P),K=ne?Lb(ne.status,t):null;return{value:`${sr}${P}`,label:de??Ao(P),...K?{sub:K}:{},...ne?.reason?{title:ne.reason}:{},...de?{}:{disabled:!0}}})}];se.length>0&&Re.push({label:t("mcp.connectedProviders"),items:se.map(P=>({value:`${or}${P.id}`,label:Ao(P.id),sub:P.executable===!1?t("mcp.locked"):void 0}))}),a&&!se.some(P=>P.id===a)&&Re.push({items:[{value:`${or}${a}`,label:Ao(a),sub:t("mcp.unavailable"),disabled:!0}]});const ce=[];if(a)i&&!me&&ce.push({items:[{value:Xn(l,i),label:i}]}),ce.push({label:t("mcp.imageModels"),items:I.image.map(P=>({value:Xn("image",P.id),label:P.label}))}),ce.push({label:t("mcp.videoModels"),items:I.video.map(P=>({value:Xn("video",P.id),label:P.label}))});else{const P=T[n]?.models.video.length??0,ne=(n==="grok"||n==="grok-api")&&P>0;ce.push({label:t("mcp.imageModels"),items:n==="comfy"?ge.map(K=>({value:K.id,label:K.label,sub:K.reason,...K.disabled?{disabled:!0}:{}})):ae.map(K=>({value:K.value,label:K.shortLabel}))}),n==="comfy"&&D.length>0&&ce.push({label:t("mcp.videoModels"),items:D.map(K=>({value:`${mn}${K.id}`,label:K.label,stacked:!0,...K.reason?{sub:t("comfy.videoCatalogShort"),title:K.reason}:{},...K.disabled?{disabled:!0}:{}}))}),(ne||o)&&ce.push({label:t("mcp.videoModels"),items:Im.map(K=>({value:`${jo}${K.value}`,label:K.shortLabel}))}),J&&ce.push({label:t("sidebar.reasoningLabel"),items:Xo.map(K=>({value:`${ko}${K.value}`,label:K.shortLabel,sub:K.value===b?"●":void 0}))});const de=new Set(ce.flatMap(K=>K.items.map(U=>U.value)));F&&!de.has(F)&&ce.unshift({items:[{value:F,label:F.includes(":")?F.split(":").slice(1).join(":"):F,title:t("mcp.unavailable"),...n==="comfy"?{disabled:!0}:{}}]})}const be=Xo.find(P=>P.value===b),z=n==="comfy"&&!a?Ct(C,{comfyWorkflow:p,comfyVideoWorkflow:x}):null,ve=z?t(Yt(z,C)):null;return s.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[s.jsx(Me,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:Re,value:oe,onChange:ke,ariaLabel:t("mcp.providerLabel"),title:ie??t("mcp.providerLabel"),triggerSub:"",portal:!0}),s.jsx(Me,{id:"sidebar-generation-model",className:"gen-provider-model__select gen-provider-model__select--model",groups:ce,value:ee,onChange:le,ariaLabel:t("mcp.modelLabel"),title:ie??t("mcp.modelLabel"),disabled:!!ie,placeholder:a?t(A?"mcp.loadingModels":"mcp.chooseModel"):n==="comfy"?t("mcp.chooseModel"):void 0,triggerSub:J&&be?be.shortLabel:void 0,portal:!0}),ie||ye||w||N||ve?s.jsx("span",{className:z?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:z&&ve?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:ve}),C.phase==="error"?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{C.refresh()},children:t("comfy.display.refresh")}):null]}):ie??ye??(N?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>q(P=>P+1),children:t("mcp.modelsLoadFailed")}):t(y?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function Ad(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function _n(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(Ad):[]}}async function Dt(e,t){const n=await Se(e,t),r=await n.json().catch(()=>({}));if(!n.ok){const o=r,a=typeof o.error=="string"?o.error:o.error?.message||`Request failed: ${n.status}`,i=new Error(a);throw typeof o.error!="string"&&(i.code=o.error?.code),i}return r}function Ob(){return Dt("/api/cardnews/image-templates")}function Fb(){return Dt("/api/cardnews/role-templates")}async function Db(e){const t=await Dt("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:_n(t.plan)}}function Gb(e){return Dt("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function zb(e){return Dt(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function Ub(e){const n=(await Dt(`/api/cardnews/cards/${encodeURIComponent(e.card.id)}/regenerate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,cards:[e.card]})})).cards.find(r=>r.id===e.card.id);if(!n)throw new Error("Regenerated card not found");return{card:n}}function li(e){return Dt(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:_n(t.plan)}))}function $b(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function qb(e){return e[0]?.id||"academy-lesson-square"}function Hb(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function Vb(e){return Math.round(e/16)*16}function Dr(e){return Math.min(Cs,Math.max(1024,Vb(e)))}function ci(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Dr(e.customW)}x${Dr(e.customH)}`}function Td(e){if(e){if(typeof e=="string")return e;if(typeof e=="object"&&"message"in e){const t=e.message;return typeof t=="string"?t:void 0}return String(e)}}function Kb(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?Td(t.error)||O("cardNews.error"):void 0}}function Bb(e){return new Promise(t=>setTimeout(t,e))}function To(e,t){const n=new Map(t.cards.map(r=>[r.id,r]));return{...e,cards:e.cards.map(r=>{const o=n.get(r.id);return o?{...r,...o,textFields:Array.isArray(o.textFields)?o.textFields:r.textFields,status:o.status||r.status,error:Td(o.error)}:r})}}const Ee=Wi((e,t)=>({templates:[],roleTemplates:[],activePlan:null,selectedCardId:null,selectedTextFieldId:null,topic:"",audience:"",goal:"",contentBrief:"",imageTemplateId:"academy-lesson-square",roleTemplateId:"mid-5",outputSizePreset:"2048x2048",customW:2048,customH:2048,loading:!1,generating:!1,error:null,draftError:null,plannerMeta:null,async hydrate(){if(!(t().loading||t().templates.length>0)){e({loading:!0,error:null});try{const[n,r]=await Promise.all([Ob(),Fb()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:qb(n.templates),roleTemplateId:Hb(r.templates),loading:!1})}catch(n){e({loading:!1,error:n instanceof Error?n.message:String(n)})}}},setBriefField(n,r){e({[n]:r})},setImageTemplate(n){e({imageTemplateId:n})},setRoleTemplate(n){e({roleTemplateId:n})},setOutputSizePreset(n){e({outputSizePreset:n})},setCustomSize(n,r){e({customW:Dr(n),customH:Dr(r)})},async draft(){const n=t();e({loading:!0,error:null,draftError:null});try{const{plan:r,planner:o}=await Db({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:ci(n)});e({activePlan:_n(r),selectedCardId:r.cards[0]?.id||null,selectedTextFieldId:null,plannerMeta:o||null,loading:!1})}catch(r){const o=r instanceof Error?r.message:String(r);e({loading:!1,draftError:o,error:o})}},updateCard(n,r){e(o=>({activePlan:o.activePlan?{...o.activePlan,cards:o.activePlan.cards.map(a=>a.id===n?{...a,...r}:a)}:null}))},updateTextField(n,r,o){e(a=>({activePlan:a.activePlan?{...a.activePlan,cards:a.activePlan.cards.map(i=>i.id!==n||i.locked?i:{...i,textFields:i.textFields.map(l=>l.id===r?{...l,...o,source:o.source||"user"}:l)})}:null}))},addTextField(n,r){e(o=>({activePlan:o.activePlan?{...o.activePlan,cards:o.activePlan.cards.map(a=>a.id===n&&!a.locked?{...a,textFields:[...a.textFields,{...r,source:"user"}]}:a)}:null,selectedTextFieldId:r.id}))},removeTextField(n,r){e(o=>({activePlan:o.activePlan?{...o.activePlan,cards:o.activePlan.cards.map(a=>a.id===n&&!a.locked?{...a,textFields:a.textFields.filter(i=>i.id!==r)}:a)}:null,selectedTextFieldId:o.selectedTextFieldId===r?null:o.selectedTextFieldId}))},selectCard(n){e({selectedCardId:n,selectedTextFieldId:null})},selectTextField(n){e({selectedTextFieldId:n})},getGenerationSummary(){const n=t().activePlan?.cards||[];return{total:n.length,done:n.filter(r=>r.status==="generated").length,queued:n.filter(r=>r.status==="queued").length,generating:n.filter(r=>r.status==="generating").length,errors:n.filter(r=>r.status==="error").length,skipped:n.filter(r=>r.locked||r.status==="skipped").length}},async generateSet(){const n=t();if(!n.activePlan)return;const r=f.getState();e({generating:!0,error:null,activePlan:{...n.activePlan,cards:n.activePlan.cards.map(o=>o.locked?{...o,status:"skipped"}:{...o,status:"queued",error:void 0})}});try{const o=t().activePlan||n.activePlan;let i=await Gb({...o,size:ci(n),quality:r.quality,moderation:r.moderation,model:r.imageModel,sessionId:r.activeSessionId});for(e(c=>({activePlan:c.activePlan?To(c.activePlan,i):c.activePlan}));["queued","running"].includes(i.status);)await Bb(900),i=await zb(i.jobId),e(c=>({activePlan:c.activePlan?To(c.activePlan,i):c.activePlan}));const l=await li(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?_n(l.plan):c.activePlan?To(c.activePlan,i):c.activePlan,selectedTextFieldId:null})),r.showToast(O("cardNews.generated",{count:i.generated}))}catch(o){const a=o instanceof Error?o.message:String(o);e(i=>({generating:!1,error:a,activePlan:i.activePlan?{...i.activePlan,cards:i.activePlan.cards.map(l=>l.status==="queued"||l.status==="generating"?{...l,status:"error",error:a}:l)}:i.activePlan}))}},async retryCard(n){const o=t().activePlan,a=o?.cards.find(l=>l.id===n);if(!o||!a||a.locked||!["draft","error"].includes(a.status))return;const i=f.getState();e({error:null,activePlan:{...o,cards:o.cards.map(l=>l.id===n?{...l,status:"generating",error:void 0}:l)}});try{const{card:l}=await Ub({setId:o.setId,card:a,quality:i.quality,moderation:i.moderation,model:i.imageModel});e(c=>({activePlan:c.activePlan?{...c.activePlan,cards:c.activePlan.cards.map(d=>d.id===n?Kb(d,Ad(l)):d)}:c.activePlan}))}catch(l){const c=l instanceof Error?l.message:String(l);e(d=>({error:c,activePlan:d.activePlan?{...d.activePlan,cards:d.activePlan.cards.map(m=>m.id===n?{...m,status:"error",error:c}:m)}:d.activePlan}))}},async loadSet(n){e({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:r}=await li(n);e({activePlan:_n(r),selectedCardId:r.cards[0]?.id||null,selectedTextFieldId:null,loading:!1})}catch(r){e({loading:!1,error:r instanceof Error?r.message:String(r)})}}}));function Wb(){const{t:e}=V(),t=Ee(I=>I.hydrate),n=Ee(I=>I.topic),r=Ee(I=>I.audience),o=Ee(I=>I.goal),a=Ee(I=>I.contentBrief),i=Ee(I=>I.outputSizePreset),l=Ee(I=>I.customW),c=Ee(I=>I.customH),d=Ee(I=>I.setBriefField),m=Ee(I=>I.setOutputSizePreset),u=Ee(I=>I.setCustomSize),p=Ee(I=>I.draft),h=Ee(I=>I.loading),x=Ee(I=>I.generating),S=Ee(I=>I.draftError),b=Ee(I=>I.generateSet),v=Ee(I=>I.activePlan),y=v?.cards||[],w={total:y.length,done:y.filter(I=>I.status==="generated").length};return g.useEffect(()=>{t()},[t]),s.jsxs("section",{className:"card-news-composer","aria-label":e("cardNews.composer"),children:[s.jsx("div",{className:"card-news-composer__head",children:s.jsxs("div",{children:[s.jsx("div",{className:"section-title",children:e("cardNews.composer")}),s.jsx("p",{children:e("cardNews.composerHint")})]})}),s.jsxs("label",{className:"card-news-field",children:[s.jsx("span",{children:e("cardNews.topic")}),s.jsx("input",{value:n,placeholder:e("cardNews.topicPlaceholder"),onChange:I=>d("topic",I.target.value)})]}),s.jsxs("label",{className:"card-news-field",children:[s.jsx("span",{children:e("cardNews.audience")}),s.jsx("input",{value:r,placeholder:e("cardNews.audiencePlaceholder"),onChange:I=>d("audience",I.target.value)})]}),s.jsxs("label",{className:"card-news-field",children:[s.jsx("span",{children:e("cardNews.goal")}),s.jsx("input",{value:o,placeholder:e("cardNews.goalPlaceholder"),onChange:I=>d("goal",I.target.value)})]}),s.jsxs("label",{className:"card-news-field",children:[s.jsx("span",{children:e("cardNews.brief")}),s.jsx("textarea",{value:a,placeholder:e("cardNews.briefPlaceholder"),onChange:I=>d("contentBrief",I.target.value)})]}),s.jsxs("div",{className:"card-news-field",children:[s.jsx("span",{children:e("cardNews.outputSize")}),s.jsx("div",{className:"card-news-size-row",role:"group","aria-label":e("cardNews.outputSize"),children:["1024x1024","2048x2048","custom"].map(I=>s.jsx("button",{type:"button",className:`option-btn${i===I?" active":""}`,onClick:()=>m(I),children:I==="custom"?e("cardNews.customSize"):I==="1024x1024"?"1024²":"2048²"},I))}),i==="custom"?s.jsxs("div",{className:"card-news-custom-size",children:[s.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:l,onChange:I=>u(Number.parseInt(I.target.value,10)||l,c),"aria-label":e("size.width")}),s.jsx("span",{children:"×"}),s.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:c,onChange:I=>u(l,Number.parseInt(I.target.value,10)||c),"aria-label":e("size.height")})]}):null]}),s.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{p()},disabled:h||!n.trim(),children:[h?s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,e(h?"cardNews.drafting":"cardNews.draft")]}),S?s.jsx("div",{className:"card-news-error",role:"alert",children:S}):null,h?s.jsxs("div",{className:"card-news-inline-status",role:"status",children:[s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}),s.jsx("span",{children:e("cardNews.drafting")})]}):null,s.jsxs("button",{type:"button",className:"composer__tool card-news-generate-btn",onClick:()=>{b()},disabled:!v||x||v.cards.every(I=>I.locked),children:[x?s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,x?e("cardNews.progress.generating",{done:w.done,total:w.total}):e("cardNews.batchGenerate")]})]})}function Xt({className:e}){return s.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function Jb({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=Te(e),c=xe(e),d=m=>{m.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?jn(e):{image:e.url||e.image,filename:e.filename})),m.dataTransfer.effectAllowed="copy"};return s.jsxs("div",{className:"sidebar-history__item",children:[s.jsx("button",{ref:m=>o(l,m),type:"button",className:`sidebar-history__thumb${t?" active":""}${c?" sidebar-history__thumb--video":""}`,onClick:()=>a(e),"aria-label":n,title:e.prompt??"",draggable:!0,onDragStart:d,children:c?s.jsxs(s.Fragment,{children:[e.thumb?s.jsx("img",{src:e.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Xt,{}),s.jsx("span",{className:"sidebar-history__play-badge","aria-hidden":"true",children:"▶"})]}):s.jsx("img",{src:e.thumb||e.url||e.image,alt:"",loading:"lazy",decoding:"async"})}),s.jsx("button",{type:"button",className:"sidebar-history__delete",onClick:m=>{m.preventDefault(),m.stopPropagation(),i(e)},"aria-label":r,title:r,children:"x"})]})}function Yb({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=Lh(e.items.length);return s.jsxs("div",{className:"sidebar-history__item",children:[s.jsxs("button",{ref:c=>o(e.key,c),type:"button",className:`sidebar-history__sequence${t?" active":""}`,onClick:()=>a(e.sequenceId),"aria-label":n,children:[s.jsx("span",{className:`sidebar-history__sequence-grid count-${l}`,"aria-hidden":"true",children:Array.from({length:l}).map((c,d)=>{const m=e.items[d];return m&&xe(m)&&!m.thumb?s.jsx(Xt,{},Te(m)):m?s.jsx("img",{src:m.thumb||m.url||m.image,alt:"",loading:"lazy",decoding:"async"},Te(m)):s.jsx("span",{className:"sidebar-history__sequence-placeholder"},`sequence-placeholder-${e.sequenceId}-${d}`)})}),s.jsx("span",{className:"sidebar-history__sequence-badge",children:e.items.length})]}),s.jsx("button",{type:"button",className:"sidebar-history__delete",onClick:c=>{c.preventDefault(),c.stopPropagation(),i(e.sequenceId)},"aria-label":r,title:r,children:"x"})]})}const di="ima2.sidebarHistoryCollapsed";function ui(){const{t:e}=V();return s.jsx("div",{className:"sidebar-history__item",children:s.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--skeleton","aria-label":e("common.generating")})})}function Xb({count:e}){const t=Math.min(e,4);return s.jsx("div",{className:"sidebar-history__item",children:s.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--collection-skeleton",children:Array.from({length:t},(n,r)=>s.jsx("div",{className:"sidebar-collection-mini sidebar-collection-mini--skeleton"},r))})})}function Zb(){const e=f(v=>v.history),t=f(v=>v.currentImage),n=f(v=>v.selectHistory),r=f(v=>v.showHistorySequence),o=f(v=>v.trashHistoryItem),a=f(v=>v.trashHistorySequence),i=f(v=>v.inFlight),l=f(v=>v.multimodeSequences),c=f(v=>{const y=v.multimodePreviewFlightId;return y?y.startsWith("history:")?y.slice(8):v.multimodeSequences[y]?.sequenceId??null:null}),d=f(v=>v.openGallery),m=g.useRef({}),[u,p]=g.useState(()=>{try{return localStorage.getItem(di)==="1"}catch{return!1}}),{t:h}=V(),x=od(t,c),S=g.useMemo(()=>rd(e).slice(0,td),[e]);g.useEffect(()=>{!x||u||m.current[x]?.scrollIntoView({block:"nearest",inline:"nearest"})},[x,u,S]),g.useEffect(()=>{try{localStorage.setItem(di,u?"1":"0")}catch{}},[u]);const b=(v,y)=>{m.current[v]=y};return s.jsxs("section",{className:`sidebar-history${u?" sidebar-history--collapsed":""}`,"aria-label":h("history.recentTitle"),children:[s.jsxs("div",{className:"sidebar-history__header",children:[s.jsx("span",{className:"section-title",children:h("history.recentTitle")}),s.jsxs("div",{className:"sidebar-history__header-actions",children:[s.jsx("button",{type:"button",className:"sidebar-history__gallery-button",onClick:d,"aria-label":h("history.galleryCard"),title:h("history.openGalleryTitle"),children:s.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),s.jsx("button",{type:"button",className:"sidebar-history__toggle",onClick:()=>p(v=>!v),title:h(u?"history.expandRecent":"history.collapseRecent"),"aria-expanded":!u,children:h(u?"history.expandRecentShort":"history.collapseRecentShort")})]})]}),u?null:s.jsxs("div",{className:"sidebar-history__grid",children:[i.map(v=>{const y=l[v.id];if(v.kind==="multimode"&&y){const w=[s.jsx(Xb,{count:y.requested},`coll-sk-${v.id}`)];for(let I=0;I<y.requested;I++)y.images[I]||w.push(s.jsx(ui,{},`sk-${v.id}-${I}`));return w}return s.jsx(ui,{},`sk-${v.id}`)}),S.length===0&&i.length===0?s.jsx("button",{type:"button",className:"sidebar-history__empty",onClick:d,children:h("history.emptyRecent")}):null,S.map(v=>v.type==="sequence"?s.jsx(Yb,{entry:v,active:x===v.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteSequenceAria",{count:v.items.length}),setRef:b,onSelect:r,onDelete:y=>{a(y)}},v.key):s.jsx(Jb,{item:v.item,active:x===v.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteImageAria"),setRef:b,onSelect:n,onDelete:y=>{o(y)}},v.key))]})]})}function Fe(){return typeof window>"u"?null:window.ima2Desktop??null}function Qb(){return Fe()?.platform==="darwin"}function Pd(){return Fe()?.platform==="win32"}function ex(){if(typeof window>"u"||!Fe())return 1;const{outerWidth:e,innerWidth:t}=window;if(!e||!t)return 1;const n=e/t;return Number.isFinite(n)&&n>.2&&n<5?Math.round(n*1e3)/1e3:1}function tx(){if(typeof window>"u"||!Fe())return()=>{};const e=document.documentElement,t=()=>e.style.setProperty("--chrome-zoom",String(ex()));return t(),window.addEventListener("resize",t),()=>{window.removeEventListener("resize",t),e.style.removeProperty("--chrome-zoom")}}function nx(){return typeof window>"u"?"":window.location.host}const rx="sidebar-inflight-panel";function ox(){const{t:e}=V(),t=f(d=>d.uiMode),n=f(d=>d.workspaceProfile),r=f(d=>d.referenceImages),o=f(d=>d.clearReferences),a=mt(),i=t==="agent"&&nn?"agent":t==="node"&&tn?"node":t==="assets"?"assets":t==="asset-gen"?"asset-gen":"classic",l=$n(n),c=!a&&i==="classic"&&l.composerPlacement==="bottom"&&l.multimodeHistoryGrouping==="sequence";return s.jsxs(s.Fragment,{children:[s.jsx(sx,{}),i==="classic"?c?s.jsx(s.Fragment,{children:s.jsx(Zb,{})}):s.jsxs(s.Fragment,{children:[s.jsx(aa,{}),s.jsxs("div",{className:"sidebar-generate-with-inflight",children:[s.jsx(ia,{}),s.jsx(Nd,{variant:"popup",panelId:rx})]})]}):i==="card-news"?s.jsx(s.Fragment,{children:s.jsx(Wb,{})}):i==="node"?s.jsxs(s.Fragment,{children:[s.jsx(_b,{}),r.length>0?s.jsxs("div",{className:"node-mode-ref-warning",role:"status",children:[s.jsx("strong",{children:e("node.classicRefsParkedTitle")}),s.jsx("span",{children:e("node.classicRefsParkedBody")}),s.jsx("button",{type:"button",onClick:o,children:e("node.clearParkedRefs")})]}):null,s.jsx("div",{className:"sidebar__node-hint",children:e("sidebar.nodeModeHint")}),s.jsx(la,{})]}):null]})}function sx(){const e=mt(),t=Fe();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"logo",children:[s.jsx(Kr,{className:"logo-mark"}),s.jsxs("div",{className:"logo-copy",children:[s.jsx("div",{className:"logo-title",children:"ima2"}),s.jsx("div",{className:"logo-title logo-title--gen",children:"gen"}),t?s.jsx("div",{className:"logo-host",children:nx()}):null]})]}),s.jsxs("div",{className:"sidebar-controls",children:[s.jsx(ix,{}),s.jsx(Cd,{compact:e})]})]})}function ax(){return s.jsx("aside",{className:"sidebar",id:"app-sidebar",children:s.jsx("div",{className:"sidebar__scroll",children:s.jsx(ox,{})})})}function ix(){const{t:e}=V(),t=f(i=>i.togglePromptLibrary),n=f(i=>i.promptLibraryOpen),r=f(i=>i.rightPanelOpen),o=f(i=>i.toggleRightPanel),a=()=>{!n&&!r&&o(),t()};return s.jsx("button",{type:"button",className:"settings-button",onClick:a,title:e("promptLibrary.title"),"aria-label":e("promptLibrary.title"),children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})})}const lx=1024,cx=1024,dx="blank-canvas.png";function mi(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function ux(e){const t=mi(e?.width,lx),n=mi(e?.height,cx),r=document.createElement("canvas");r.width=t,r.height=n;const o=r.getContext("2d");if(!o)throw new Error("blank_canvas_context_unavailable");o.fillStyle="#ffffff",o.fillRect(0,0,r.width,r.height);const a=await new Promise((i,l)=>{r.toBlob(c=>{c?i(c):l(new Error("blank_canvas_blob_unavailable"))},"image/png")});return new File([a],dx,{type:"image/png"})}const ar=1024;function mx(e){const t=/^(\d+)x(\d+)$/.exec(e);if(!t)return{width:ar,height:ar};const n=Number.parseInt(t[1]??"",10),r=Number.parseInt(t[2]??"",10);return!Number.isFinite(n)||!Number.isFinite(r)||n<=0||r<=0?{width:ar,height:ar}:{width:n,height:r}}function px(){const e=f(c=>c.importLocalImageToHistory),t=f(c=>c.openCanvas),n=f(c=>c.showToast),r=f(c=>c.getResolvedSize),{t:o}=V(),[a,i]=g.useState(!1),l=g.useCallback(async()=>{if(!a){i(!0);try{const c=mx(r()),d=await ux(c);await e(d)&&t()}catch{n(o("canvas.blank.failed"),!0)}finally{i(!1)}}},[a,r,e,t,n,o]);return{creatingBlankCanvas:a,createBlankCanvas:l}}function fx(e,t){return{image:e.url,url:e.url,providerUrl:e.providerUrl,filename:e.filename,mediaType:"video",prompt:e.prompt,userPrompt:e.userPrompt,revisedPrompt:e.revisedPrompt,provider:e.provider,model:e.model,format:"mp4",elapsed:e.elapsed,usage:e.usage??void 0,webSearchCalls:e.webSearchCalls,video:e.video,videoSeries:null,videoContinuity:e.videoContinuity,videoLineage:e.videoLineage,requestId:e.requestId,createdAt:e.createdAt,sessionId:null}}async function hx(e,t){try{const n=await Se("/api/video/extend",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw nt(r,`Request failed: ${n.status}`);if(n.status!==202||r.requestId!==e.requestId||r.sourceVideoId!==e.sourceVideoId||r.workflow!=="last-frame-i2v")throw new Error("Video extension returned an invalid acceptance response")}catch(n){throw n instanceof Error?n:new Error(String(n))}}function gx(e,t){const n=he();return ue()?Promise.reject(et(n-1)):(Pt(),new Promise((r,o)=>{let a=!1,i=()=>{},l=()=>{};const c=p=>{a||(a=!0,i(),l(),t.removeEventListener("abort",m),p())},d=()=>{Ae(e.requestId).catch(()=>{})},m=()=>c(()=>{d(),o(new DOMException("Aborted","AbortError"))});if(l=Tt(e.requestId,null,(p,h)=>{p==="done"?c(()=>r(h)):p==="error"&&c(()=>o(nt(h,"Video extension failed")))}),i=Qt(()=>c(()=>{d(),o(new Error("Video extension stream timed out"))})),t.aborted)return m();t.addEventListener("abort",m,{once:!0}),Br().then(()=>{if(n!==he())throw et(n);if(ue())throw et(n-1);return hx(e,t)}).catch(p=>c(()=>o(p)))}))}let It={source:null,status:"idle"},pn=null,pi=0;const ls=new Set;function ir(e,t){It={source:e,status:t};for(const n of ls)n()}const Ut={getSnapshot:()=>It,subscribe(e){return ls.add(e),()=>{ls.delete(e)}},select(e){It.status!=="pending"&&It.source!==e&&ir(e,"idle")},start(e){if(It.status==="pending"||It.source===e.sourceVideoId&&It.status==="tracking-expired")return null;const t=new AbortController;return pn=t,pi=he(),ir(e.sourceVideoId,"pending"),gx(e,t.signal).then(n=>(pn=null,ir(e.sourceVideoId,"idle"),n),n=>{pn=null;const r=at(n).code,o=n instanceof DOMException&&n.name==="AbortError";throw ir(e.sourceVideoId,o||r==="LAN_TOKEN_REQUIRED"?"idle":r==="JOB_TRACKING_TIMEOUT"?"tracking-expired":"error"),n})},cancel(){pn?.abort()},releaseView(){!ue()&&pi===he()&&pn?.abort()}};async function yx(e,t){const n=await fetch("/api/video/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw nt(r,`Request failed: ${n.status}`);if(typeof r.url!="string"||typeof r.filename!="string")throw new Error("Video edit returned no saved artifact");return{requestId:String(r.requestId??""),url:r.url,filename:r.filename,duration:typeof r.duration=="number"?r.duration:null,model:String(r.model??"")}}const vx=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),Kt=[];function bx(e){return Kt.length>0&&Kt[Kt.length-1]===e}function Ge(e,t,n={}){const r=g.useRef(null),o=g.useRef(t);o.current=t;const a=g.useId(),{trap:i=!0,autoFocus:l=!0,restoreFocus:c=!0}=n;return g.useEffect(()=>{if(!e)return;Kt.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,m=r.current,u=()=>Array.from(m?.querySelectorAll(vx)??[]).filter(b=>!b.hidden&&b.getAttribute("aria-hidden")!=="true");l&&window.requestAnimationFrame(()=>{(m?.querySelector("[data-modal-initial-focus]")??u()[0]??m)?.focus()});const p=b=>typeof c=="function"?c(b):c,h=b=>{if(!bx(a))return;if(b.key==="Escape"){b.preventDefault(),o.current("escape");return}if(!i||b.key!=="Tab")return;const v=u();if(v.length===0){b.preventDefault(),m?.focus();return}const y=v[0],w=v[v.length-1];b.shiftKey&&document.activeElement===y?(b.preventDefault(),w.focus()):!b.shiftKey&&document.activeElement===w&&(b.preventDefault(),y.focus())};document.addEventListener("keydown",h);let x="programmatic";const S=o.current;return o.current=b=>{x=b??"programmatic",S(b)},()=>{const b=Kt.indexOf(a);b!==-1&&Kt.splice(b,1),document.removeEventListener("keydown",h),p(x)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const xx={oauth:"GPT OAuth / Codex login",api:"GPT API key",grok:"Grok OAuth","grok-api":"Grok API key",agy:"Antigravity Gemini CLI","gemini-api":"Gemini API / Vertex",atlascloud:"Atlas Cloud API",minimax:"MiniMax API",nai:"NovelAI API"};function Sx(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function ua(e){return Sx(e)?String(e):null}function Ix(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function fi(e){return e?e.replace("x","×"):null}function wx(e){if(e==null)return null;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Z(e,t,n,r={}){const o=ua(n);o&&e.push({label:t,value:o,...r})}function Po(e,t,n,r={}){typeof n!="number"||n<=0||Z(e,t,n,r)}function _x(e,t,n){const r=wx(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function Ex(e){if(!e.sequenceId)return null;const t=[e.sequenceIndex!=null&&e.sequenceTotalReturned!=null?`${e.sequenceIndex+1}/${e.sequenceTotalReturned}`:null,e.sequenceTotalRequested!=null?`requested ${e.sequenceTotalRequested}`:null,e.sequenceStatus??null].filter(Boolean);return t.length?`${e.sequenceId} (${t.join(", ")})`:e.sequenceId}function Nx(e){return e?xx[e]??e:null}function kx(e){return e.trim().replace(/\s+/g," ")}function lr(e,t,n,r){const o=ua(r);if(!o)return;const a=kx(o);!a||t.has(a)||(t.add(a),e.push({label:n,value:o,copyValue:o,pre:!0}))}function hi(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function gi(e,t,n){const r=e?.[t];if(!r||typeof r!="object"||Array.isArray(r))return null;const o=r[n];return typeof o=="number"&&Number.isFinite(o)?o:null}function jx(e){const t=["metadata-modal__row"];return e.pre&&t.push("metadata-modal__row--pre"),e.compact&&t.push("metadata-modal__row--compact"),t.join(" ")}function Cx({item:e,onClose:t,onCopy:n}){const{t:r,locale:o}=V(),a=Ge(!0,t),i=g.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=Nx(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),fi(e.size),e.elapsed!=null?`${e.elapsed}s`:null,e.usage?.total_tokens!=null?`${e.usage.total_tokens} ${r("metadata.fields.tokens").toLowerCase()}`:null].filter(w=>!!w),m=[],u=[];Z(u,r("metadata.fields.provider"),c,{compact:!0}),Z(u,r("metadata.fields.model"),e.model,{compact:!0}),Z(u,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Z(u,r("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),u.length&&m.push({title:r("metadata.sections.provider"),fields:u,compact:!0});const p=[];Z(p,r("metadata.fields.quality"),e.quality,{compact:!0}),Z(p,r("metadata.fields.size"),fi(e.size),{compact:!0}),Z(p,r("metadata.fields.format"),e.format,{compact:!0}),Z(p,r("metadata.fields.moderation"),e.moderation,{compact:!0}),Z(p,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Z(p,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Z(p,r("metadata.fields.kind"),e.kind,{compact:!0}),Z(p,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),p.length&&m.push({title:r("metadata.sections.settings"),fields:p,compact:!0});const h=[];Z(h,r("metadata.fields.elapsed"),e.elapsed!=null?`${e.elapsed}s`:null,{compact:!0}),Z(h,r("metadata.fields.totalTokens"),e.usage?.total_tokens,{compact:!0}),Z(h,r("metadata.fields.inputTokens"),hi(e.usage,"input_tokens"),{compact:!0}),Po(h,r("metadata.fields.cachedTokens"),gi(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),hi(e.usage,"output_tokens"),{compact:!0}),Po(h,r("metadata.fields.reasoningTokens"),gi(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),Po(h,r("metadata.fields.webSearchCalls"),e.webSearchCalls,{compact:!0}),e.usage?.grok_cost_usd_ticks!=null&&Z(h,r("metadata.fields.grokCostTicks"),e.usage.grok_cost_usd_ticks,{compact:!0}),h.length&&m.push({title:r("metadata.sections.usage"),fields:h,compact:!0});const x=[];Z(x,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Z(x,r("metadata.fields.createdAt"),Ix(e.createdAt,o)),Z(x,r("metadata.fields.sessionId"),e.sessionId),Z(x,r("metadata.fields.nodeId"),e.nodeId),Z(x,r("metadata.fields.parentNodeId"),e.parentNodeId),Z(x,r("metadata.fields.clientNodeId"),e.clientNodeId),Z(x,r("metadata.fields.refsCount"),e.refsCount),Z(x,r("metadata.fields.sequence"),Ex(e)),Z(x,r("metadata.fields.setId"),e.setId),Z(x,r("metadata.fields.cardId"),e.cardId),x.length&&m.push({title:r("metadata.sections.lineage"),fields:x});const S=[];Z(S,r("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),Z(S,r("metadata.fields.videoResolution"),e.video?.resolution),Z(S,r("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),Z(S,r("metadata.fields.videoRequestedModel"),e.video?.requestedModel),Z(S,r("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),Z(S,r("metadata.fields.videoModelFallback"),e.video?.modelFallback),Z(S,r("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:ua(e.video?.xaiVideoRequestId)??void 0}),Z(S,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),S.length&&m.push({title:r("metadata.sections.video"),fields:S});const b=[];Z(b,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Z(b,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Z(b,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Z(b,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Z(b,r("metadata.fields.latestContinuityPrompt"),l?.revisedPrompt,{copyValue:l?.revisedPrompt,pre:!0}),b.length&&m.push({title:r("metadata.sections.videoContinuity"),fields:b});const v=[],y=new Set;return lr(v,y,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),lr(v,y,r("metadata.fields.revisedPrompt"),e.revisedPrompt),lr(v,y,r("metadata.fields.prompt"),e.prompt),lr(v,y,r("metadata.fields.composerPrompt"),e.composerPrompt),_x(v,r("metadata.fields.insertedPrompts"),e.composerInsertedPrompts),v.length&&m.push({title:r("metadata.sections.prompts"),fields:v}),s.jsx("div",{className:"modal-backdrop metadata-modal-backdrop",onClick:t,children:s.jsxs("section",{ref:a,className:"modal metadata-modal",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-modal-title",onClick:w=>w.stopPropagation(),children:[s.jsxs("header",{className:"metadata-modal__header",children:[s.jsxs("div",{children:[s.jsx("h3",{id:"metadata-modal-title",children:r("metadata.title")}),s.jsx("p",{children:[e.mediaType??r("metadata.asset"),e.filename].filter(Boolean).join(" · ")}),d.length?s.jsx("div",{className:"metadata-modal__summary","aria-label":r("metadata.summary"),children:d.map(w=>s.jsx("span",{children:w},w))}):null]}),s.jsx("button",{type:"button",className:"metadata-modal__close",onClick:t,"aria-label":r("common.close"),children:"×"})]}),s.jsxs("div",{className:"metadata-modal__body",children:[m.map(w=>s.jsxs("section",{className:w.compact?"metadata-modal__section metadata-modal__section--compact":"metadata-modal__section",children:[s.jsx("h4",{children:w.title}),s.jsx("dl",{children:w.fields.map(I=>s.jsxs("div",{className:jx(I),children:[s.jsx("dt",{children:I.label}),s.jsxs("dd",{children:[I.pre?s.jsx("pre",{children:I.value}):s.jsx("span",{children:I.value}),I.copyValue?s.jsx("button",{type:"button",onClick:()=>n(I.copyValue),"aria-label":r("metadata.copyField",{label:I.label}),children:r("metadata.copy")}):null]})]},`${w.title}:${I.label}`))})]},w.title)),s.jsxs("details",{className:"metadata-modal__raw",children:[s.jsx("summary",{children:r("metadata.rawJson")}),s.jsx("div",{className:"metadata-modal__raw-actions",children:s.jsx("button",{type:"button",onClick:()=>n(i),children:r("metadata.copyRaw")})}),s.jsx("pre",{children:i})]})]})]})})}function Ax(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function Rd(e,t){return e==="video"&&Object.values(t).some(n=>n!==void 0)?"video upscale takes no parameters":t.scaleFactor!==void 0&&![2,4,8,16].includes(t.scaleFactor)?"scaleFactor must be 2, 4, 8, or 16":t.scaleFactor!==void 0&&t.scaleFactor>2&&t.flavor!==void 0&&t.flavor!=="sublime"?"scaleFactor above 2 requires flavor sublime":null}function Tx(e,t){const n=Ax(e);if(!n||Rd(n,t))return null;const r=n==="image"?"upscale-image":"upscale-video",o=Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0));return{action:r,files:[e],...Object.keys(o).length>0?{parameters:o}:{}}}const Px=[2,4,8,16],Rx=["sublime","photo","photo_denoiser"];function Mx({pending:e,onSubmit:t,onClose:n}){const{t:r}=V(),o=Ge(!0,n,{trap:!1,restoreFocus:v=>v!=="outsidePointer"}),[a,i]=g.useState(2),[l,c]=g.useState(""),[d,m]=g.useState(10),[u,p]=g.useState(10),[h,x]=g.useState(30),S={scaleFactor:a,...l?{flavor:l}:{},sharpen:d,smartGrain:u,ultraDetail:h},b=Rd("image",S);return s.jsxs("div",{ref:o,className:"upscale-popover",role:"dialog","aria-label":r("result.upscaleTitle"),children:[s.jsx("div",{className:"option-row",role:"group","aria-label":"scaleFactor",children:Px.map(v=>s.jsxs("button",{type:"button",className:`option-btn${a===v?" active":""}`,"aria-pressed":a===v,onClick:()=>i(v),children:[v,"x"]},v))}),s.jsxs("label",{className:"upscale-popover__field",children:[s.jsx("span",{children:r("result.upscaleFlavor")}),s.jsxs("select",{value:l,onChange:v=>c(v.target.value),children:[s.jsx("option",{value:"",children:r("result.upscaleFlavorAuto")}),Rx.map(v=>s.jsx("option",{value:v,children:v},v))]})]}),[["sharpen",d,m],["smartGrain",u,p],["ultraDetail",h,x]].map(([v,y,w])=>s.jsxs("label",{className:"upscale-popover__field",children:[s.jsxs("span",{children:[v," ",s.jsx("output",{children:y})]}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:y,onChange:I=>w(Number(I.target.value))})]},v)),b?s.jsx("p",{className:"element-detail__error",role:"alert",children:b}):null,s.jsxs("div",{className:"upscale-popover__actions",children:[s.jsx("button",{type:"button",className:"action-btn action-btn--primary",disabled:e||!!b,onClick:()=>t(S),children:r(e?"inflight.streaming":"result.upscaleStart")}),s.jsx("button",{type:"button",className:"action-btn",onClick:n,children:r("common.cancel")})]})]})}const Lx="canvas-mode-context",Ox="Canvas Mode",yi=36e5,Fx=["Canvas Mode context:","The user edited or annotated the reference image on a canvas.","If the image is a blank white canvas or paper with user-drawn strokes, treat those strokes as source content and preserve/complete them.","If the image is an existing picture with circles, arrows, sticky notes, handwritten marks, or memo notes over it, treat those marks as edit instructions. Apply the instruction, then remove the marks from the final image unless explicitly asked to keep them.","Infer the intended edit from the canvas marks and memo text. Preserve unrelated image content."].join(`
|
|
9
|
+
`);function Dx({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=V(),r=f(U=>U.currentImage),o=f(U=>U.showToast),a=f(U=>U.insertPromptToComposer),i=f(U=>U.createRootNodeFromHistoryItem),l=f(U=>U.trashHistoryItem),c=f(U=>U.saveToAssets),d=f(U=>U.permanentlyDeleteHistoryItemByClick),m=f(U=>U.canvasOpen),u=f(U=>U.openCanvas),[p,h]=g.useState(!1),[x,S]=g.useState(!1),b=g.useSyncExternalStore(Ut.subscribe,Ut.getSnapshot),[v,y]=g.useState("idle"),[w,I]=g.useState(!1),[_,N]=g.useState(!1),[j,L]=g.useState(!1),[q,A]=g.useState(!1),G=g.useRef(null);g.useEffect(()=>{let U=!0;return ea().then(X=>{U&&A(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{U=!1}},[]);const C=async U=>{if(!T?.filename||j)return;const X=Tx(T.filename,U);if(!X){o(n("result.upscaleInvalid"),!0);return}L(!0);try{await $("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),N(!1),o(n("result.upscaleStarted"))}catch{o(n("result.upscaleFailed"),!0)}finally{L(!1)}};g.useEffect(()=>Ut.releaseView,[]);const T=e??r,k=T?.filename??null;g.useEffect(()=>{Ut.select(k)},[k]);const R=b.status==="pending"||b.source===k?b.status:"idle";if(!T)return null;const B=xe(T),se=B?T.url||T.image:"",oe=!!T.filename,ae=!!T.filename&&!B,ge=B&&!!T.filename,F=!!((T.provider==="grok"||T.provider==="grok-api")&&!B&&T.providerUrl&&T.createdAt&&Date.now()-T.createdAt<yi),ee=async()=>{if(!(!T.filename||x)){S(!0);try{await f.getState().animateImage(T.filename,T.prompt??void 0)&&o(n("toast.animateDone"))}catch(U){const X=U instanceof Error?U.message:n("toast.animateFailed");o(X,!0)}finally{S(!1)}}},J=async()=>{if(!T.filename||R==="pending"||R==="tracking-expired")return;const U=`vext_${crypto.randomUUID()}`;try{const X=Ut.start({requestId:U,sourceVideoId:T.filename,prompt:T.prompt?.trim()||void 0,provider:T.provider==="grok-api"?"grok-api":"grok",model:T.model??void 0});if(!X)return;const re=await X;f.getState().addHistoryItem(fx(re,T)),o(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Oe=at(X).code;Oe==="JOB_TRACKING_TIMEOUT"||Oe==="LAN_TOKEN_REQUIRED"?We(X,f.getState()):re||o(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},me=()=>Ut.cancel(),ye=async()=>{if(!T.filename||v==="pending")return;const U=window.prompt(n("result.editVideoPrompt"))?.trim();if(!U)return;const X=new AbortController;G.current=X,y("pending");try{const re=await yx({videoUrl:T.filename,prompt:U,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...T,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:U,userPrompt:U,model:re.model||"grok-imagine-video",format:"mp4"}),y("idle"),o(n("toast.animateDone"))}catch(re){const Oe=re instanceof DOMException&&re.name==="AbortError";y(Oe?"idle":"error"),Oe||o(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{G.current===X&&(G.current=null)}},ie=()=>G.current?.abort(),ke=()=>{const U=document.createElement("a");U.href=T.image,U.download=T.filename||"generated.png",U.click()},le=async U=>{const re=await(await fetch(U)).blob();let Oe;if(re.type==="image/png")Oe=re;else{const ze=new Image;ze.crossOrigin="anonymous";const Gt=URL.createObjectURL(re);await new Promise((pt,ft)=>{ze.onload=()=>pt(),ze.onerror=ft,ze.src=Gt});const Je=document.createElement("canvas");Je.width=ze.naturalWidth,Je.height=ze.naturalHeight,Je.getContext("2d").drawImage(ze,0,0),URL.revokeObjectURL(Gt),Oe=await new Promise((pt,ft)=>Je.toBlob(xt=>xt?pt(xt):ft(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Oe})])},Ie=async()=>{try{if(B){const U=await sn(se);await le(U)}else await le(T.image);o(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{o(n("toast.copyFailed"),!0)}},je=async()=>{try{const U=await gc(se);await le(U),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},Re=async()=>{try{const U=await yc(se);await le(U),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},ce=async()=>{if(T.prompt)try{await navigator.clipboard.writeText(T.prompt),o(n("toast.promptCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},be=async U=>{try{await navigator.clipboard.writeText(U),o(n("toast.metadataCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},z=async()=>{let U={ok:!1,isVideo:!1,hasPrompt:!1};try{U=await po(T)}catch{}m&&e&&a({id:Lx,name:Ox,text:Fx});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),o(n(U.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ve=async()=>{if(B||!T.providerUrl||!T.createdAt||Date.now()-T.createdAt>=yi){o(n("toast.continueAsUrlExpired"),!0);return}try{await Id(T)}catch{}const U=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');U&&(U.focus(),U.setSelectionRange(U.value.length,U.value.length)),o(n("toast.continueAsUrlStarted"))},P=async()=>{if(!(!T.filename||p)){h(!0);try{const U=await qu({filename:T.filename});o(n("toast.comfyExported",{filename:U.uploadedFilename}))}catch(U){const X=U instanceof Error?U.code:void 0;o(n(X==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":X==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":X==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{h(!1)}}},ne=()=>{i(T),o(n("toast.nodeRootCreated"))},de=async()=>{try{await l(T)}finally{t?.()}},K=async()=>{try{await d(T)}finally{t?.()}};return s.jsxs("div",{className:"result-actions",children:[s.jsx("button",{type:"button",className:"action-btn",onClick:ke,children:n("result.download")}),s.jsx("button",{type:"button",className:`action-btn${B?" action-btn--frame":""}`,onClick:Ie,children:n(B?"result.copyLastFrame":"result.copyImage")}),B&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:je,children:n("result.copyFirstFrame")}),s.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:Re,children:n("result.copyMidFrame")})]}),s.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ce()},children:n("result.copyPrompt")}),s.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const U=await c(T);o(n(U?"chain.savedToAssets":"chain.saveToAssetsFailed"),!U)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),s.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:z,title:n("result.continueHereTitle"),children:n("result.continueHere")}),F&&s.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ve()},title:n("result.continueAsUrlTitle"),children:n("result.continueAsUrl")}),ae&&s.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ee()},disabled:x,title:n("result.animateTitle"),children:n(x?"result.animating":"result.animate")}),q&&T.filename&&(B?s.jsx("button",{type:"button",className:"action-btn",disabled:j,onClick:()=>{C({})},title:n("result.upscaleTitle"),children:n(j?"inflight.streaming":"result.upscale")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",disabled:j,onClick:()=>N(U=>!U),title:n("result.upscaleTitle"),children:n("result.upscale")}),_?s.jsx(Mx,{pending:j,onSubmit:U=>{C(U)},onClose:()=>N(!1)}):null]})),ge&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",onClick:J,disabled:R==="pending"||R==="tracking-expired","aria-busy":R==="pending",title:n(R==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:R==="pending"?n("inflight.streaming"):R==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),R==="pending"&&s.jsx("button",{type:"button",className:"action-btn",onClick:me,children:n("common.cancel")}),s.jsx("button",{type:"button",className:"action-btn",onClick:ye,disabled:v==="pending","aria-busy":v==="pending",title:n("result.editVideoTitle"),children:n(v==="pending"?"inflight.streaming":v==="error"?"gallery.retry":"result.editVideo")}),v==="pending"&&s.jsx("button",{type:"button",className:"action-btn",onClick:ie,children:n("common.cancel")})]}),s.jsx("button",{type:"button",className:"action-btn",onClick:ne,title:n("result.firstNodeTitle"),children:n("result.firstNode")}),s.jsx("button",{type:"button",className:"action-btn",onClick:()=>I(!0),title:n("result.infoTitle"),children:n("result.info")}),!m&&s.jsx("button",{type:"button",className:"action-btn",onClick:u,title:n("canvas.open"),"aria-label":n("canvas.openAria"),children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:s.jsx("path",{d:"M4 4h8v8M12 4l-8 8"})})}),T.filename&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{de()},title:n("result.deleteTitle"),children:n("result.delete")}),s.jsxs("details",{className:"result-actions__more",children:[s.jsx("summary",{className:"action-btn",children:n("result.more")}),s.jsxs("div",{className:"result-actions__menu",children:[oe&&s.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{P()},title:n("result.sendToComfyUITitle"),disabled:p,children:n("result.sendToComfyUI")}),s.jsx("button",{type:"button",className:"result-actions__menu-item result-actions__danger-item",onClick:()=>{K()},children:n("result.permanentDelete")})]})]})]}),w&&s.jsx(Cx,{item:T,onClose:()=>I(!1),onCopy:U=>{be(U)}})]})}const Gx=["auto","flat","detailed","mono"],ct={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function zx(e,t){const n=`/generated/${encodeURIComponent(t)}`;return{...e,image:n,url:n,filename:t,mediaType:"image",kind:"edit",requestId:`derived:${t}`,createdAt:Date.now(),providerUrl:null}}function Ux(e){return`${Math.round(e/1024)}KB`}function $x(){const{t:e}=V(),t=f(G=>G.vectorizeTarget),n=f(G=>G.setVectorizeTarget),r=f(G=>G.addAssetGenDerivedItem),o=f(G=>G.selectedProjectId),a=f(G=>G.showToast),i=g.useRef(null),l=g.useRef(t?.filename??null);l.current=t?.filename??null;const c=g.useCallback(()=>{i.current?.abort(),i.current=null,n(null)},[n]),d=Ge(!!t,c),[m,u]=g.useState("auto"),[p,h]=g.useState(ct.colorPrecision),[x,S]=g.useState(ct.filterSpeckle),[b,v]=g.useState(ct.cornerThreshold),[y,w]=g.useState(!1),[I,_]=g.useState(null),[N,j]=g.useState(null);g.useEffect(()=>{i.current?.abort(),i.current=null,w(!1),_(null),j(null)},[t?.filename]),g.useEffect(()=>()=>i.current?.abort(),[]);const L=g.useCallback(()=>{if(!t?.filename||y)return;const G=t.filename,C=new AbortController;i.current=C,w(!0),_(null),nm({source:G,preset:m,...p!==ct.colorPrecision?{colorPrecision:p}:{},...x!==ct.filterSpeckle?{filterSpeckle:x}:{},...b!==ct.cornerThreshold?{cornerThreshold:b}:{},projectId:o,signal:C.signal}).then(T=>{if(!(i.current!==C||l.current!==G)){if(!T.filePath)throw new Error(e("vectorize.saveError"));j({filePath:T.filePath,pathCount:T.pathCount,bytes:T.bytes}),r(zx(t,T.filePath)),a(e("vectorize.saved"))}}).catch(T=>{if(T instanceof DOMException&&T.name==="AbortError"||i.current!==C||l.current!==G)return;const k=T instanceof Error?T.message:e("vectorize.saveError");_(k),a(k,!0)}).finally(()=>{i.current!==C||l.current!==G||(i.current=null,w(!1))})},[t,y,m,p,x,b,o,r,a,e]);if(!t)return null;const q=t.url||t.image,A=N?`/generated/${encodeURIComponent(N.filePath)}`:null;return s.jsx("div",{className:"assetgen-popup-backdrop",onClick:c,children:s.jsxs("div",{ref:d,className:"keying-panel vectorize-panel",role:"dialog","aria-modal":"true","aria-label":e("vectorize.title"),onClick:G=>G.stopPropagation(),children:[s.jsxs("header",{className:"keying-panel__head",children:[s.jsx("h2",{children:e("vectorize.title")}),s.jsx("span",{className:"keying-panel__hint",children:e("vectorize.hint")})]}),s.jsxs("div",{className:"keying-panel__compare","aria-busy":y,children:[s.jsxs("figure",{className:"keying-panel__preview",children:[s.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.original")}),s.jsx("div",{className:"keying-panel__stage keying-panel__stage--original",children:s.jsx("img",{src:q??"",alt:e("vectorize.originalAlt")})})]}),s.jsxs("figure",{className:"keying-panel__preview",children:[s.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.result")}),s.jsx("div",{className:"keying-panel__stage",children:A?s.jsx("img",{src:A,alt:e("vectorize.resultAlt")}):s.jsx("span",{className:"keying-panel__loading",role:"status",children:e(y?"vectorize.running":"vectorize.idle")})})]})]}),s.jsx("div",{className:"keying-panel__modes",role:"group","aria-label":e("vectorize.preset"),children:Gx.map(G=>s.jsx("button",{type:"button",className:m===G?"is-active":"","aria-pressed":m===G,onClick:()=>u(G),children:e(`vectorize.preset_${G}`)},G))}),N?s.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(N.pathCount),size:Ux(N.bytes)})}):null,s.jsxs("details",{className:"keying-panel__advanced",children:[s.jsx("summary",{children:e("vectorize.advanced")}),s.jsxs("div",{className:"keying-panel__controls",children:[s.jsxs("label",{children:[e("vectorize.colorPrecision")," ",s.jsx("output",{children:p}),s.jsx("input",{type:"range",min:1,max:8,value:p,onChange:G=>h(Number(G.target.value))})]}),s.jsxs("label",{children:[e("vectorize.filterSpeckle")," ",s.jsx("output",{children:x}),s.jsx("input",{type:"range",min:0,max:32,value:x,onChange:G=>S(Number(G.target.value))})]}),s.jsxs("label",{children:[e("vectorize.cornerThreshold")," ",s.jsx("output",{children:b}),s.jsx("input",{type:"range",min:0,max:180,value:b,onChange:G=>v(Number(G.target.value))})]}),s.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(ct.colorPrecision),S(ct.filterSpeckle),v(ct.cornerThreshold)},children:e("vectorize.reset")})]})]}),s.jsxs("footer",{className:"keying-panel__actions",children:[I?s.jsx("span",{className:"keying-panel__save-error",role:"alert",children:I}):null,s.jsx("button",{type:"button",className:"assetgen-generate",disabled:y||!t.filename,onClick:L,children:e(y?"vectorize.running":"vectorize.run")}),A?s.jsx("a",{className:"assetgen-popup__close",href:A,download:N?.filePath,children:e("vectorize.download")}):null,s.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function qx({prompt:e,onCopy:t}){const{t:n}=V(),r=o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())};return s.jsx("div",{className:"result-prompt",onClick:t,onKeyDown:r,role:"button",tabIndex:0,title:n("result.copyPrompt"),"aria-label":n("result.copyPrompt"),children:s.jsx("span",{className:"result-prompt__text",children:e})})}function Hx(){const e=f(p=>{const h=p.multimodePreviewFlightId;return h?p.multimodeSequences[h]??null:null}),t=f(p=>p.cancelMultimode),n=f(p=>{const h=p.multimodePreviewFlightId;return!!(h&&(p.activeFlightIds.has(h)||p.inFlight.some(x=>x.id===h)))}),r=f(p=>p.selectHistory),o=f(p=>p.currentImage),a=f(p=>p.openCanvas),{t:i}=V(),l=p=>{r(p)},c=p=>{r(p),a()};if(!e)return null;const d=new Map,m=e.partials.filter(p=>p.index==null);for(const p of e.partials)p.index!=null&&d.set(p.index,p);const u=Array.from({length:e.requested},(p,h)=>{const x=e.images[h],S=d.get(h)??(x?void 0:m.shift());return{index:h,image:x,partial:S}});return s.jsxs("section",{className:"multimode-sequence","aria-live":"polite",children:[s.jsxs("div",{className:"multimode-sequence__header",children:[s.jsxs("div",{children:[s.jsx("div",{className:"multimode-sequence__title",children:i("multimode.sequenceTitle")}),s.jsx("div",{className:"multimode-sequence__meta",children:i("multimode.sequenceProgress",{returned:e.returned,requested:e.requested})})]}),n?s.jsx("button",{type:"button",className:"secondary-btn",onClick:t,children:i("multimode.cancel")}):null]}),s.jsx("div",{className:`multimode-sequence__grid count-${Math.min(e.requested,4)}`,children:u.map(({index:p,image:h,partial:x})=>{const S=h&&o?.filename&&h.filename===o.filename;return s.jsxs("article",{className:`multimode-sequence__slot${h?" done":""}${S?" active":""}`,onClick:h?()=>l(h):void 0,onDoubleClick:h?()=>c(h):void 0,role:h?"button":void 0,tabIndex:h?0:void 0,onKeyDown:h?b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l(h))}:void 0,children:[s.jsx("div",{className:"multimode-sequence__badge",children:i("multimode.stageLabel",{index:p+1})}),h?s.jsx("img",{src:h.url??h.image,alt:i("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):x?s.jsx("img",{src:x.image,alt:i("multimode.partialAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):e.status==="pending"||e.status==="complete"?s.jsx("div",{className:"multimode-sequence__skeleton"}):s.jsx("div",{className:"multimode-sequence__empty",children:e.status==="error"?i("multimode.error"):e.status==="empty"?i("multimode.empty"):e.status==="canceled"?i("multimode.canceled"):e.status==="partial"?i("multimode.notReturned"):i("multimode.generating")})]},h?.filename??p)})})]})}function Vx({zoom:e,minZoom:t,maxZoom:n,onZoomIn:r,onZoomOut:o,onReset:a,labels:i}){return s.jsxs("div",{className:"viewer-controls","aria-label":i.controls,onPointerDown:l=>l.stopPropagation(),onDoubleClick:l=>l.stopPropagation(),onWheel:l=>l.stopPropagation(),children:[s.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),o()},disabled:e<=t,"aria-label":i.zoomOut,children:"-"}),s.jsxs("button",{type:"button",className:"viewer-control-btn viewer-control-btn--label",onClick:l=>{l.stopPropagation(),a()},"aria-label":i.reset,children:[Math.round(e*100),"%"]}),s.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),r()},disabled:e>=n,"aria-label":i.zoomIn,children:"+"})]})}function _r(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function Kx(e,t,n,r){if(!e)return!1;const o=t.find(a=>a.filename===e);return o?!!o.isFavorite:r!==void 0?r:n.has(e)}function v0(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const Et=1,Md=5,cr=.22;function Bx(e){return Math.min(Md,Math.max(Et,e))}function Wx(e){const[t,n]=g.useState(1),[r,o]=g.useState({x:0,y:0}),[a,i]=g.useState(null),l=g.useRef(0),c=g.useRef(null),d=g.useCallback(()=>{cancelAnimationFrame(l.current),l.current=0,c.current=null,n(1),o({x:0,y:0}),i(null)},[]);g.useEffect(()=>{d()},[d,e]),g.useEffect(()=>()=>{cancelAnimationFrame(l.current)},[]);const m=g.useCallback(b=>{n(v=>{const y=Bx(v+b);return y<=Et?(o({x:0,y:0}),Et):Number(y.toFixed(2))})},[]),u=g.useCallback(b=>{b.preventDefault(),m(b.deltaY<0?cr:-cr)},[m]),p=g.useCallback(()=>{if(t>Et){d();return}n(2)},[d,t]),h=g.useCallback(b=>{t<=Et||b.button!==0||(b.preventDefault(),b.currentTarget.setPointerCapture(b.pointerId),i({pointerId:b.pointerId,startX:b.clientX,startY:b.clientY,baseX:r.x,baseY:r.y}))},[r.x,r.y,t]),x=g.useCallback(b=>{if(!a||a.pointerId!==b.pointerId)return;const v={x:a.baseX+b.clientX-a.startX,y:a.baseY+b.clientY-a.startY};c.current=v,cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{o(v),c.current=null})},[a]),S=g.useCallback(b=>{!a||a.pointerId!==b.pointerId||(cancelAnimationFrame(l.current),l.current=0,c.current&&(o(c.current),c.current=null),i(null),b.currentTarget.releasePointerCapture(b.pointerId))},[a]);return{zoom:t,pan:r,reset:d,zoomIn:()=>m(cr),zoomOut:()=>m(-cr),handleWheel:u,handleDoubleClick:p,handlePointerDown:h,handlePointerMove:x,handlePointerUp:S}}const Jx=g.lazy(()=>Le(()=>import("./index-CUMOJ4Vx.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function Yx(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Xx(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function Zx(e){const t=e.url??e.image;if(!e.canvasVersion||!e.canvasMergedAt||t.startsWith("data:"))return t;const n=t.includes("?")?"&":"?";return`${t}${n}canvasMergedAt=${e.canvasMergedAt}`}function cs(){const e=f(D=>D.currentImage),t=f(D=>D.importLocalImageToHistory),n=f(D=>{const F=D.multimodePreviewFlightId;return F?D.multimodeSequences[F]??null:null}),r=f(D=>D.selectHistoryShortcutTarget),o=f(D=>D.trashHistoryItem),a=f(D=>D.permanentlyDeleteHistoryItemByShortcut),i=f(D=>D.markGeneratedResultsSeen),l=f(D=>D.activeGenerations),c=f(D=>D.canvasOpen),d=f(D=>D.openCanvas),m=f(D=>D.showToast),u=f(D=>D.history),p=f(D=>D.galleryFavorites),h=f(D=>D.toggleGalleryFavorite),{t:x}=V(),[S,b]=g.useState(!1),[v,y]=g.useState(null),{creatingBlankCanvas:w,createBlankCanvas:I}=px(),_=g.useRef(null),N=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,j=Wx(N),L=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),m(x("toast.promptCopied")))},q=D=>{if(D.key==="Delete"||D.key==="Backspace"){if(!e||D.target!==D.currentTarget||_r(D.target))return;if(D.preventDefault(),D.shiftKey){a(e);return}o(e);return}D.key!=="ArrowLeft"&&D.key!=="ArrowRight"&&D.key!=="Home"&&D.key!=="End"||D.target===D.currentTarget&&(_r(D.target)||(D.preventDefault(),D.key==="ArrowLeft"?r("previous"):D.key==="ArrowRight"?r("next"):D.key==="Home"?r("first"):D.key==="End"&&r("last")))},A=D=>{_r(D.target)||(i(),D.currentTarget.focus())},G=g.useCallback(()=>{window.requestAnimationFrame(()=>_.current?.focus())},[]),C=async()=>{const D=e?.filename;if(!(!e||!D||v===D)){y(D);try{await h(e)}finally{y(F=>F===D?null:F)}}},T=g.useCallback(D=>{Array.from(D.dataTransfer.types).includes("Files")&&(D.preventDefault(),b(F=>F||!0))},[]),k=g.useCallback(D=>{D.currentTarget.contains(D.relatedTarget)||b(!1)},[]),R=g.useCallback(async D=>{if(!Array.from(D.dataTransfer.types).includes("Files"))return;D.preventDefault(),b(!1);const F=Array.from(D.dataTransfer.files).filter(ee=>/^image\/(png|jpeg|webp)$/.test(ee.type));F.length!==0&&await t(F[0])},[t]);if(c&&e)return s.jsxs(s.Fragment,{children:[s.jsx(g.Suspense,{fallback:s.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:s.jsx(Jx,{currentImage:e})}),s.jsx($x,{})]});const B=Yx(e?.quality),se=Xx(e?.size),oe=pl(e?.model,e?.provider),ae=e?Zx(e):null,ge=Kx(e?.filename,u,p,e?.isFavorite);return s.jsxs("main",{className:`canvas${S?" canvas--drop-active":""}`,onDragOver:T,onDragLeave:k,onDrop:R,children:[S?s.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:s.jsx("span",{className:"canvas__drop-hint",children:x("canvas.drop.hint")})}):null,s.jsx("div",{className:`progress-bar${l>0?" active":""}`}),n?s.jsx(Hx,{}):e&&ae?s.jsxs("div",{ref:_,className:"result-container visible",tabIndex:0,onMouseDown:A,onKeyDown:q,"aria-label":x("canvas.imageViewerAria"),children:[s.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${j.zoom>Et?" canvas-annotation-frame--zoomed":""}`,onWheel:j.handleWheel,onDoubleClick:j.handleDoubleClick,onPointerDown:j.handlePointerDown,onPointerMove:j.handlePointerMove,onPointerUp:j.handlePointerUp,onPointerCancel:j.handlePointerUp,children:[e.filename?s.jsx(Sd,{variant:"result",active:ge,busy:v===e.filename,label:x(ge?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:C}):null,xe(e)?s.jsxs(s.Fragment,{children:[s.jsx("video",{className:"result-img",src:ae,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${j.pan.x}px, ${j.pan.y}px) scale(${j.zoom})`}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify(jn(e))),D.dataTransfer.effectAllowed="copy"},title:x("canvas.dragToComposer"),"aria-label":x("canvas.dragToComposer"),children:x("canvas.dragHint")})]}):s.jsxs(s.Fragment,{children:[s.jsx("img",{className:"result-img",src:ae,alt:x("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${j.pan.x}px, ${j.pan.y}px) scale(${j.zoom})`},onDoubleClick:D=>{D.stopPropagation(),d()}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),D.dataTransfer.effectAllowed="copy"},title:x("canvas.dragToComposer"),"aria-label":x("canvas.dragToComposer"),children:x("canvas.dragHint")})]}),s.jsx(Vx,{zoom:j.zoom,minZoom:Et,maxZoom:Md,onZoomIn:j.zoomIn,onZoomOut:j.zoomOut,onReset:j.reset,labels:{controls:x("viewer.controls"),zoomIn:x("viewer.zoomIn"),zoomOut:x("viewer.zoomOut"),reset:x("viewer.reset")}})]}),s.jsx("div",{className:"result-meta",children:(xe(e)?[e.elapsed!=null?`${e.elapsed}s`:null,e.video?.duration?`${e.video.duration}s clip`:null,e.video?.resolution??null,e.video?.aspectRatio??null,qc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?x("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Pm(e.reasoningEffort),B,se,oe]).filter(D=>!!D).join(" · ")}),s.jsx(Dx,{onAfterDeleteFocus:G}),e.prompt?s.jsx(qx,{prompt:e.prompt,onCopy:L}):null]}):e?null:s.jsxs("div",{className:"canvas__blank-entry",children:[s.jsx("div",{className:"canvas__blank-sheet","aria-hidden":!0}),s.jsxs("div",{className:"canvas__blank-copy",children:[s.jsx("strong",{children:x("canvas.blank.title")}),s.jsx("span",{children:x("canvas.blank.subtitle")})]}),s.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{I()},disabled:w,children:x(w?"canvas.blank.creating":"canvas.blank.create")})]})]})}function Qx(){return s.jsxs("div",{className:"classic-workspace",children:[s.jsx("div",{className:"classic-workspace__stage",children:s.jsx(cs,{})}),s.jsxs("div",{className:"classic-workspace__dock",children:[s.jsx(aa,{variant:"bottom"}),s.jsx(ia,{})]})]})}const Ld="ima2.customSizeSlots";function eS(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.id=="string"&&typeof t.w=="number"&&typeof t.h=="number"&&typeof t.updatedAt=="number"}function tS(){try{const e=localStorage.getItem(Ld);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?Ht(t.filter(eS)):[]}catch{return[]}}function nS(e){try{localStorage.setItem(Ld,JSON.stringify(Ht(e)))}catch{}}function rS(e,t,n){return Zr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function fn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function oS(){const e=f(R=>R.sizePreset),t=f(R=>R.setSizePreset),n=f(R=>R.customW),r=f(R=>R.customH),o=f(R=>R.setCustomSize),{t:a}=V(),[i,l]=g.useState(String(n)),[c,d]=g.useState(String(r)),[m,u]=g.useState(e==="custom"),[p,h]=g.useState(()=>tS()),[x,S]=g.useState(null),[b,v]=g.useState("free"),y=e==="custom",w=As(i,c,n,r),I=Ym().filter(R=>R.value==="auto");g.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),g.useEffect(()=>{y||(u(!1),S(null))},[y]);function _(R){h(R),nS(R)}function N(){const R=ot(i,n),B=ot(c,r);o(R,B),l(String(R)),d(String(B))}function j(R){R.key==="Enter"&&(R.preventDefault(),N())}function L(){t("custom"),u(!0),S(p.length>=qt?p[0]?.id??null:null)}function q(R){t(R),R!=="custom"&&(u(!1),S(null))}function A(R){t("custom"),o(R.w,R.h),l(String(R.w)),d(String(R.h)),u(!1),S(R.id)}function G(R){v(R.id);const B=qm(R);B&&(l(String(B.w)),d(String(B.h)))}function C(){const R=rS(w.w,w.h,b),B=p.length>=qt&&x?Vm(p,x,R):Hm(p,R);_(B),t("custom"),o(w.w,w.h),l(String(w.w)),d(String(w.h)),S(R.id),u(!1)}const T=w.reasons.length>0?w.reasons.map(R=>a(`size.adjustedReasons.${R}`)).join(", "):a("size.noAdjustment"),k=w.reasons.includes("maxPixels")&&w.requestedW===w.requestedH&&w.w===w.h?a("size.squareMaxHint",{size:`${La}×${La}`}):null;return s.jsxs("div",{className:"option-group size-picker",children:[s.jsx("div",{className:"section-title",children:a("size.title")}),s.jsx(qe,{title:"",items:fn(Km),value:e,onChange:q}),s.jsx(qe,{title:"",items:fn(Bm),value:e,onChange:q}),s.jsx(qe,{title:"",items:fn(Wm),value:e,onChange:q}),s.jsx(qe,{title:"",items:fn(Jm),value:e,onChange:q}),s.jsxs("div",{className:"option-row size-picker__quick-row",children:[fn(I).map(R=>s.jsxs("button",{type:"button",className:`option-btn${e===R.value?" active":""}`,onClick:()=>q(R.value),children:[R.label,R.sub?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:R.sub})]}):null]},R.value)),s.jsxs("button",{type:"button",className:`option-btn${y?" active":""}`,onClick:L,children:[a("size.customPlus"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:a("size.customSub")})]})]}),p.length>0?s.jsx("div",{className:"option-row size-picker__slot-row",children:p.map(R=>s.jsxs("button",{type:"button",className:`option-btn size-picker__slot${y&&n===R.w&&r===R.h?" active":""}`,onClick:()=>A(R),children:[R.w,"×",R.h,s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:R.ratio||a("size.customSlot")})]},R.id))}):null,m?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"size-picker__ratio-row",children:Um.map(R=>s.jsx("button",{type:"button",className:`size-picker__ratio${b===R.id?" active":""}`,onClick:()=>G(R),children:R.id==="free"?a("size.ratioFree"):R.label},R.id))}),s.jsxs("div",{className:"option-row size-picker__custom-row",children:[s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:i,onChange:R=>l(R.target.value.replace(/\D/g,"")),onBlur:N,onKeyDown:j,placeholder:a("size.width")}),s.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:c,onChange:R=>d(R.target.value.replace(/\D/g,"")),onBlur:N,onKeyDown:j,placeholder:a("size.height")})]}),s.jsxs("div",{className:"size-picker__preview",children:[s.jsx("span",{children:a("size.normalizedPreview")}),s.jsx("strong",{children:$m(w.w,w.h)})]}),s.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:T}),k?s.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:k}):null,p.length>=qt?s.jsxs("div",{className:"size-picker__replace-row",children:[s.jsx("span",{children:a("size.replaceCustomSlot")}),p.map(R=>s.jsxs("button",{type:"button",className:`size-picker__replace${x===R.id?" active":""}`,onClick:()=>S(R.id),children:[R.w,"×",R.h]},R.id))]}):null,s.jsx("button",{type:"button",className:"size-picker__save",onClick:C,children:p.length>=qt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),s.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const Ro=[1,2,4];function sS(){const e=f(y=>y.count),t=f(y=>y.setCount),n=f(y=>y.uiMode),r=f(y=>y.multimode),o=f(y=>y.multimodeMaxImages),a=f(y=>y.setMultimodeMaxImages),{t:i}=V(),l=n==="classic"&&r,c=l?o:e,d=l?a:t,[m,u]=g.useState(!Ro.includes(c)),[p,h]=g.useState(String(c));g.useEffect(()=>{u(!Ro.includes(c)),h(String(c))},[l,c]);function x(y=p){const w=es(Number.parseInt(y,10));d(w),h(String(w))}function S(y){u(!1),h(String(y)),d(y)}function b(y){const w=es(c+y);u(!0),h(String(w)),d(w)}function v(y){y.key==="Enter"&&(y.preventDefault(),x())}return s.jsxs("div",{className:"option-group count-picker",children:[s.jsx("div",{className:"section-title",children:i(l?"multimode.maxStages":"count.title")}),s.jsxs("div",{className:"option-row",children:[Ro.map(y=>s.jsx("button",{type:"button",className:`option-btn${c===y&&!m?" active":""}`,onClick:()=>S(y),children:y},y)),s.jsx("button",{type:"button",className:`option-btn${m?" active":""}`,onClick:()=>{u(y=>!y),h(String(c))},children:i("count.customPlus")})]}),m?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"count-picker__custom",children:[s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>b(-1),"aria-label":i("count.decrease"),children:"-"}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"count-picker__input",value:p,onChange:y=>h(y.target.value.replace(/\D/g,"")),onBlur:()=>x(),onKeyDown:v,"aria-label":i("count.customLabel")}),s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>b(1),"aria-label":i("count.increase"),children:"+"})]}),s.jsx("p",{className:"option-help",children:c>=5?i(l?"multimode.highCountHint":"count.highCountHint"):i(l?"multimode.minMaxHint":"count.minMaxHint")})]}):null]})}const aS={low:{"1024x1024":.006,"1024x1536":.005,"1536x1024":.005,"1024x1360":.005,"1360x1024":.005,"1024x1824":.006,"1824x1024":.006,"2048x2048":.012,"2048x1152":.009,"1152x2048":.009,"3840x2160":.023,"2160x3840":.023,auto:.006},medium:{"1024x1024":.053,"1024x1536":.041,"1536x1024":.041,"1024x1360":.041,"1360x1024":.041,"1024x1824":.05,"1824x1024":.05,"2048x2048":.106,"2048x1152":.08,"1152x2048":.08,"3840x2160":.2,"2160x3840":.2,auto:.053},high:{"1024x1024":.211,"1024x1536":.165,"1536x1024":.165,"1024x1360":.165,"1360x1024":.165,"1024x1824":.2,"1824x1024":.2,"2048x2048":.422,"2048x1152":.32,"1152x2048":.32,"3840x2160":.8,"2160x3840":.8,auto:.211}},iS={512:.045,"1K":.067,"2K":.101,"4K":.151},lS={512:.134,"1K":.134,"2K":.134,"4K":.24};function cS(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function dS(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),o=cS(r),i=t==="nano-banana-pro"?lS:iS;return i[o]??i["1K"]??.003}function uS(e,t,n,r){return n==="gemini-api"?dS(t,r):aS[e]?.[t]??0}function mS(){const{t:e}=V(),t=f(h=>h.provider),n=f(h=>h.quality),r=f(h=>h.multimode),o=f(h=>h.multimodeMaxImages),i=f(h=>h.getResolvedSize)(),l=f(h=>h.imageModel),c=f(h=>h.imageToolModel),d=t==="oauth"||t==="grok"||t==="agy",m=uS(n,i,t,l),u=t==="api"&&c?e("imageToolModel.costUnavailable"):d?e("cost.free"):r?e("cost.multimodeApprox",{amount:(m*o).toFixed(3),count:o}):e("cost.approx",{amount:m.toFixed(3)}),p=d?"var(--green)":void 0;return s.jsxs("div",{className:"cost-estimate",children:[s.jsx("span",{children:e("cost.label")}),s.jsx("span",{className:"price",style:p?{color:p}:void 0,children:u})]})}const Gr="ima2:oauth-changed",pS=3e3,fS=15e3;function Od(){const[e,t]=g.useState(null);return g.useEffect(()=>{let n=!1,r=null;const o=async()=>{r&&clearTimeout(r),r=null;try{const i=await gu();if(n)return;t(i),i.status==="starting"?r=setTimeout(o,pS):i.status!=="ready"&&(r=setTimeout(o,fS))}catch{n||t(null)}},a=()=>{o()};return window.addEventListener(Gr,a),o(),()=>{n=!0,window.removeEventListener(Gr,a),r&&clearTimeout(r)}},[]),e}function hS(){const[e,t]=g.useState(null),[n,r]=g.useState(!1);return g.useEffect(()=>{let o=!1;return yu().then(a=>{o||t(a)}).catch(()=>{o||r(!0)}),()=>{o=!0}},[]),{data:e,error:n}}function Fd(){const[e,t]=g.useState(null);return g.useEffect(()=>{if(ue())return;const n=he();let r=!1,o=null,a=0;const i=async()=>{o&&(clearTimeout(o),o=null);const d=++a;if(!(r||ue()||n!==he()))try{const m=await Se("/api/grok/status");if(r||d!==a)return;const u=await m.json();if(r||d!==a||ue()||n!==he())return;t(u),u.status!=="ready"&&(o=setTimeout(i,1e4))}catch{if(r||d!==a)return;t({status:"offline"}),o=setTimeout(i,1e4)}},l=()=>{i()},c=()=>{r=!0,o&&clearTimeout(o),window.removeEventListener(Nt,c),window.removeEventListener(Gr,l)};return window.addEventListener(Nt,c),window.addEventListener(Gr,l),i(),c},[]),e}function Dd(){const[e,t]=g.useState(null),[n,r]=g.useState(null),o=g.useRef(!1),a=g.useCallback(async()=>{if(!o.current||ue())return;const i=he();try{const c=await(await Se("/api/keys/status")).json();if(!o.current||ue()||i!==he())return;t(c),r(null)}catch(l){if(!o.current||ue()||i!==he())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return g.useEffect(()=>{if(ue())return;o.current=!0;let i=!1,l=null;const c=async()=>{await a(),i||(l=setInterval(a,3e4))},d=()=>{o.current=!1,i=!0,l&&clearInterval(l),window.removeEventListener(Nt,d)};return window.addEventListener(Nt,d),c(),d},[a]),{data:e,error:n,mutate:a}}function Gd(){const{t:e}=V(),t=Od(),{data:n}=hS(),r=Fd(),{data:o}=Dd(),a=t?.status==="ready";let i=e("provider.oauthNotReady"),l;t?.status==="auth_required"?(i=e("provider.codexLoginRequired"),l=e("provider.codexLoginHint")):t?.status==="starting"?i=e("provider.oauthStarting"):t||(i=e("provider.serverUnreachable"));const c=n?.apiKeyValid===!0,d=r?.status==="ready",m=r?r.status==="offline"?e("provider.grokOffline"):r.status==="no_image_model"?e("provider.grokNoImageModel"):r.status==="error"?e("provider.grokNotReady"):"":e("provider.grokNotReady"),u=o?.xai?.valid===!0,p=o?.gemini?.valid===!0||o?.vertex?.valid===!0,h=o?.atlascloud?.valid===!0,x=o?.minimax?.valid===!0,S=o?.nai?.valid===!0,b=Wn(),v=Ct(b,null);return{oauth:{ok:a,reason:i,hint:l},api:{ok:c,reason:c?"":e("provider.apiInvalid")},grok:{ok:d,reason:m,hint:d?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:u,reason:u?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:p,reason:p?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:h,reason:h?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:x,reason:x?"":e("provider.minimaxApiKeyRequired")},nai:{ok:S,reason:S?"":e("provider.naiApiKeyRequired")},comfy:{ok:v.laneAvailable,reason:e(v.laneAvailable?"comfy.display.available":Yt(v,b)),hint:e("comfy.display.chooseWorkflow")}}}function gS({open:e,providerLabel:t,reason:n,hint:r,onClose:o}){const{t:a}=V(),i=Ge(e,o);if(!e)return null;const l=a("apiDisabled.title",{provider:t});return s.jsx("div",{className:"modal-backdrop",onClick:o,role:"presentation",children:s.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-label":l,tabIndex:-1,onClick:c=>c.stopPropagation(),children:[s.jsx("div",{className:"modal__title",children:l}),s.jsxs("div",{className:"modal__body",children:[s.jsx("p",{children:n}),r?s.jsx("p",{className:"modal__hint",children:r}):null]}),s.jsx("div",{className:"modal__actions",children:s.jsx("button",{type:"button",className:"modal__btn",onClick:o,"data-modal-initial-focus":!0,children:a("common.ok")})})]})})}const dr="core:",Mo="mcp:",yS={oauth:{value:"oauth",provider:"GPT",method:"OAuth"},api:{value:"api",provider:"GPT",method:"API"},grok:{value:"grok",provider:"Grok",method:"OAuth"},"grok-api":{value:"grok-api",provider:"Grok",method:"API"},agy:{value:"agy",provider:"Gemini",method:"agy"},"gemini-api":{value:"gemini-api",provider:"Gemini",method:"API"},atlascloud:{value:"atlascloud",provider:"Atlas Cloud",method:"API"},minimax:{value:"minimax",provider:"MiniMax",method:"API"},nai:{value:"nai",provider:"NovelAI",method:"API"},comfy:{value:"comfy",provider:"ComfyUI",method:"local"}},Lo=xs.map(e=>yS[e]);function Oo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Fo({tone:e}){return s.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function vi(e){return e.enabled?e.status.state==="connected"?e.executable===!1?"warn":"ok":e.status.state==="connecting"||e.status.state==="auth_required"?"warn":"bad":"bad"}function Do({mcpProviders:e}){const{t}=V(),n=f(A=>A.provider),r=f(A=>A.mcpProvider??null),o=f(A=>A.setProvider),a=Gd(),i=Wn(),l=f(A=>A.comfyWorkflow),c=f(A=>A.comfyVideoWorkflow),d=Ct(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),m=n==="comfy"&&!r,u=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[p,h]=g.useState(null),x=A=>{const G=a[A.value];return A.value==="comfy"?m?t(Yt(d,i)):G.reason:G.ok?t("provider.statusReady"):G.reason},S=A=>A.enabled?A.status.state==="connected"?A.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):A.status.state==="connecting"?t("mcp.connecting"):A.status.state==="auth_required"?t("provider.statusAuthRequired"):A.status.state==="offline"||A.status.state==="error"?t(`mcp.status.${A.status.state}`):t("provider.statusDisconnected"):t("mcp.disabledProvider"),b=[{label:t("mcp.coreProviders"),items:Lo.map(A=>{const G=a[A.value];return{value:`${dr}${A.value}`,searchText:`${A.provider} ${A.value==="comfy"?t("comfy.display.localMethod"):A.method}`,label:s.jsxs("span",{className:"provider-option",children:[s.jsx(Fo,{tone:A.value==="comfy"&&m?u:G.ok?"ok":"bad"}),s.jsxs("span",{children:[A.provider," ",A.value==="comfy"?t("comfy.display.localMethod"):A.method]})]}),sub:x(A)}})}],v=e.filter(A=>A.enabled).map(A=>({value:`${Mo}${A.id}`,searchText:Oo(A.id),label:s.jsxs("span",{className:"provider-option",children:[s.jsx(Fo,{tone:vi(A)}),s.jsx("span",{children:Oo(A.id)})]}),sub:S(A)}));v.length>0&&b.push({label:"MCP",items:v});const y=r?`${Mo}${r}`:`${dr}${n}`,w=r?null:Lo.find(A=>A.value===n)??null,I=r?e.find(A=>A.id===r)??null:null,_=w?.value==="comfy",N=_?t(Yt(d,i)):w?x(w):I?S(I):t("provider.statusDisconnected"),j=_?u:w?a[w.value].ok?"ok":"bad":I?vi(I):"bad",L=w?w.value==="comfy"?t("comfy.display.localMethod"):w.method:"MCP",q=A=>{if(A.startsWith(dr)){const T=A.slice(dr.length);if(!Rt(T))return;const k=Lo.find(B=>B.value===T),R=a[T];if(T==="comfy"){o(T);return}if(!R.ok){h({label:k?`${k.provider} ${k.method}`:T,reason:R.reason,hint:R.hint});return}o(T);return}const G=A.slice(Mo.length),C=e.find(T=>T.id===G);if(!C||!C.enabled||C.status.state!=="connected"){h({label:Oo(G),reason:!C||!C.enabled?t("mcp.disabledProvider"):C.status.state==="disconnected"?t("mcp.disconnectedSelection"):S(C)});return}uo(G,f.setState,f.getState)};return s.jsxs("div",{className:"option-group provider-status-select","data-testid":"provider-status-select",children:[s.jsx("div",{className:"section-title",children:t("provider.authTitle")}),s.jsx(Me,{groups:b,value:y,onChange:q,triggerSub:_?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),s.jsxs("div",{className:"provider-status-line","data-tone":j,role:"status","aria-live":"polite",children:[s.jsx(Fo,{tone:j}),s.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),s.jsx("span",{className:"provider-status-line__value",children:N})]}),_&&i.observedAt!==null?s.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,_&&d.code==="selected-missing"&&i.catalog?.comfy?.status==="disconnected"?s.jsx("p",{className:"provider-helper",children:t("comfy.statusOffline")}):null,s.jsxs("div",{className:"provider-auth-chip",title:t(_?"comfy.display.localMethod":"provider.authMethodTitle"),children:[s.jsx("span",{children:L}),j!=="bad"&&!_?s.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),s.jsx(gS,{open:!!p,providerLabel:p?.label??"",reason:p?.reason??"",hint:p?.hint,onClose:()=>h(null)})]})}const vS=[{value:"1:1",label:"1:1"},{value:"3:2",label:"3:2"},{value:"2:3",label:"2:3"},{value:"4:3",label:"4:3"},{value:"3:4",label:"3:4"},{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"2:1",label:"2:1"},{value:"1:2",label:"1:2"},{value:"auto",label:"Auto"}],bS=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function xS(){const{t:e}=V(),t=f(a=>a.grokAspectRatio),n=f(a=>a.grokResolution),r=f(a=>a.setGrokAspectRatio),o=f(a=>a.setGrokResolution);return s.jsxs("div",{className:"option-group grok-size-picker",children:[s.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")}),s.jsx("div",{className:"grok-size-picker__aspects",children:vS.map(a=>s.jsx("button",{type:"button",className:`option-btn grok-size-picker__aspect${t===a.value?" active":""}`,onClick:()=>r(a.value),children:a.label},a.value))}),s.jsx("div",{className:"section-title",style:{marginTop:8},children:e("size.grokResolutionTitle")}),s.jsx("div",{className:"grok-size-picker__resolutions",children:bS.map(a=>s.jsx("button",{type:"button",className:`option-btn grok-size-picker__res${n===a.value?" active":""}`,onClick:()=>o(a.value),children:a.label},a.value))})]})}function SS(){const{t:e}=V(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")}),s.jsx(Me,{ariaLabel:e("quality.grokModelTitle"),items:ul.map(r=>({value:r.value,label:e(r.fullLabelKey)})),value:t,onChange:n,portal:!0})]})}function zd({values:e,value:t,defaultValue:n,onChange:r,allowAuto:o=!1,disabled:a,ariaLabel:i}){const{t:l}=V(),c=g.useId();if(e.length===0)return null;const d=t??n??e[0],m=e.reduce((x,S,b)=>Math.abs(S-d)<Math.abs(e[x]-d)?b:x,0),u=t===null,p=e[0],h=e[e.length-1];return s.jsxs("div",{className:`ctl-duration${u?" is-auto":""}${a?" is-disabled":""}`,children:[s.jsxs("div",{className:"ctl-duration__head",children:[s.jsx("output",{htmlFor:c,className:"ctl-duration__value",children:u?`${l("size.autoLabel")} · ${e[m]}s`:`${e[m]}s`}),o?s.jsx("button",{type:"button",className:`option-btn ctl-duration__auto${u?" active":""}`,"aria-pressed":u,disabled:a,onClick:()=>r(null),children:l("size.autoLabel")}):null]}),s.jsx("input",{id:c,type:"range",className:"ctl-duration__range",min:0,max:e.length-1,step:1,value:m,disabled:a,"aria-label":i,"aria-valuetext":`${e[m]}s`,onChange:x=>r(e[Number(x.target.value)]??e[0])}),s.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[s.jsxs("span",{children:[p,"s"]}),s.jsxs("span",{children:[h,"s"]})]})]})}const bi=3;function IS(){const{t:e}=V(),t=f(u=>u.videoModelSelected),n=f(u=>u.videoReferenceVoices),r=f(u=>u.toggleVideoReferenceVoice),[o,a]=g.useState([]),[i,l]=g.useState("");g.useEffect(()=>{let u=!0;return Xi().then(p=>{u&&a(p.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{u=!1}},[]);const c=Ot(t)===rt,d=n.length>=bi,m=()=>{const u=i.trim();!u||d||n.includes(u)||(r(u),l(""))};return o.length===0&&n.length===0?null:s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("video.voiceSection")}),s.jsx("div",{className:"composer__hint",children:c?e("video.voiceLimit",{max:bi}):e("video.voiceNeeds15")}),s.jsx("div",{className:"option-row",role:"group","aria-label":e("video.voiceSection"),children:o.map(u=>{const p=n.includes(u);return s.jsxs("button",{type:"button",className:`option-btn${p?" active":""}`,"aria-pressed":p,disabled:!c||!p&&d,onClick:()=>r(u),children:[u,p?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:`<AUDIO_${n.indexOf(u)}>`})]}):null]},u)})}),s.jsx("input",{type:"text",className:"text-input",value:i,disabled:!c||d,placeholder:e("video.voiceCustomPlaceholder"),onChange:u=>l(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),m())},onBlur:m,"aria-label":e("video.voiceCustomPlaceholder")})]})}const wS=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],_S=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),xi=[3,5,8,10,12,15],ES=[{value:_s,label:"Grok V",sub:"Fast"},{value:rt,label:"Grok V1.5",sub:"HD"}];function NS(){const{t:e}=V(),t=f(k=>k.videoModelSelected),n=f(k=>k.selectVideoModel),r=f(k=>k.activeVideoRefCount()),o=f(k=>k.videoSingleRefMode),a=f(k=>k.setVideoSingleRefMode),i=f(k=>k.videoDuration),l=f(k=>k.setVideoDuration),c=f(k=>k.videoResolution),d=f(k=>k.setVideoResolution),m=f(k=>k.videoAspectRatio),u=f(k=>k.setVideoAspectRatio),p=f(k=>k.videoTopic),h=f(k=>k.setVideoTopic),x=f(k=>k.showToast),S=f(k=>k.videoContinuityLineage),b=f(k=>k.selectedPresetIds),v=f(k=>k.removePreset),y=b.map(k=>Gc(k)).filter(k=>k?.category==="camera-motion"),w=_m(r,o),I=Aa(t,w),_=qc(S),N=go(t,"1080p",w),j=go(rt,"1080p",w),L=wS.map(k=>k.value==="1080p"?{...k,disabled:!j}:k);g.useEffect(()=>{go(t,c,w)||d("720p")},[w,c,d,t]),g.useEffect(()=>{i!==null&&i>I&&l(I)},[i,I,l]);const q=k=>{const R=Aa(k,w);i!==null&&i>R&&x(e("video.durationClampedToModel",{seconds:R})),n(k)},A=k=>{if(k==="1080p"){if(!j)return;N||n(rt)}d(k)},[G,C]=g.useState(null);g.useEffect(()=>{Se("/api/config/grok-planner").then(k=>k.json()).then(C).catch(()=>{})},[]);const T=async k=>{const R=G?.model;C(B=>B?{...B,model:k}:null);try{const B=await Se("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:k})});if(!B.ok)throw new Error(`HTTP ${B.status}`)}catch(B){if(C(se=>se&&R?{...se,model:R}:se),B?.code==="LAN_TOKEN_REQUIRED")return;x(e("video.plannerUpdateFailed"),!0)}};return s.jsxs("div",{className:"right-panel-settings video-controls",children:[s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")??"Model"}),s.jsx("div",{className:"option-row",children:ES.map(k=>s.jsxs("button",{type:"button",className:`option-btn${t===k.value?" active":""}`,onClick:()=>q(k.value),children:[k.label,s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:k.sub})]},k.value))})]}),s.jsxs("div",{className:"provider-compat-note",role:"note",children:[s.jsx("strong",{children:e("video.modeLabel")}),s.jsx("span",{children:e(`video.mode.${w}`,{n:r})})]}),_?s.jsxs("div",{className:"provider-compat-note",role:"note",children:[s.jsx("strong",{children:e("common.continuity")}),s.jsx("span",{children:_})]}):null,s.jsx(IS,{}),y.length>0&&s.jsx(sa,{ariaLabel:e("video.selectedCameraPresets"),children:y.map(k=>s.jsx(xd,{onRemove:()=>v(k.id),removeLabel:e("common.removeNamed",{name:k.name}),children:k.name},k.id))}),s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("video.seriesTopicTitle")??"시리즈 주제"}),s.jsx("input",{type:"text",className:"video-topic-input",placeholder:e("video.seriesTopicPlaceholder")??"예: 한국 여행 브이로그",value:p,onChange:k=>h(k.target.value)})]}),s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("video.durationTitle")}),s.jsx(zd,{values:xi.filter(k=>k<=I),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??xi[0])})]}),r===1&&s.jsx(qe,{title:e("video.singleRefTitle"),help:e("video.singleRefHelp"),items:[{value:"image-to-video",label:e("video.singleRef.source")},{value:"reference-to-video",label:e("video.singleRef.reference")}],value:o,onChange:a}),s.jsx(qe,{title:e("video.resolutionTitle"),help:j?void 0:e("video.resolution1080Help"),items:L,value:c,onChange:A}),s.jsx(qe,{title:e("video.aspectTitle"),items:_S,value:m,onChange:u}),G&&s.jsx("div",{className:"video-controls__pills",children:s.jsx(Me,{className:"video-controls__pill",items:G.options.map(k=>({value:k,label:k})),value:G.model,onChange:k=>{T(k)},ariaLabel:e("video.plannerModelTitle")})}),s.jsxs("details",{className:"provider-compat-details",style:{marginTop:8},children:[s.jsx("summary",{children:e("common.activePrompt")}),s.jsx("p",{children:Lr})]})]})}const Si=e=>Symbol.iterator in e,Ii=e=>"entries"in e,wi=(e,t)=>{const n=e instanceof Map?e:new Map(e.entries()),r=t instanceof Map?t:new Map(t.entries());if(n.size!==r.size)return!1;for(const[o,a]of n)if(!r.has(o)||!Object.is(a,r.get(o)))return!1;return!0},kS=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let o=n.next(),a=r.next();for(;!o.done&&!a.done;){if(!Object.is(o.value,a.value))return!1;o=n.next(),a=r.next()}return!!o.done&&!!a.done};function jS(e,t){return Object.is(e,t)?!0:typeof e!="object"||e===null||typeof t!="object"||t===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(t)?!1:Si(e)&&Si(t)?Ii(e)&&Ii(t)?wi(e,t):kS(e,t):wi({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function CS(e){const t=gn.useRef(void 0);return n=>{const r=e(n);return jS(t.current,r)?t.current:t.current=r}}const AS=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function TS(){const{t:e}=V(),t=f(CS(Mp)),n=f(m=>m.setNaiOption),r=f(m=>m.resetNaiOptions),o=f(m=>m.imageModel),a=f(m=>m.setImageModel),i=f(m=>m.sizePreset),l=f(m=>m.setSizePreset),c=ts(o),d=t.seed===null?"":String(t.seed);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"option-group nai-controls",children:[s.jsx("div",{className:"section-title",children:e("nai.panel.modelTitle")}),s.jsx(Me,{items:ml.map(m=>({value:m.value,label:m.shortLabel})),value:o,onChange:m=>{ts(m)||(n("straightAlpha",!1),n("qualityPresetId","standard")),a(m)},ariaLabel:e("nai.panel.modelTitle")})]}),s.jsxs("div",{className:"option-group nai-controls",children:[s.jsx("div",{className:"section-title",children:e("nai.panel.sizeTitle")}),s.jsx("div",{className:"option-row",children:AS.map(m=>s.jsxs("button",{type:"button",className:`option-btn${i===m.value?" active":""}`,onClick:()=>l(m.value),children:[m.label==="nai.size.portrait"?e("nai.size.portrait"):m.label==="nai.size.landscape"?e("nai.size.landscape"):e("nai.size.square"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:m.value.replace("x","×")})]},m.value))})]}),s.jsxs("div",{className:"option-group nai-controls",children:[s.jsx("div",{className:"section-title",children:e("nai.panel.samplingTitle")}),s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.sampler")}),s.jsx(Me,{items:Ll.map(m=>({value:m,label:m})),value:t.sampler,onChange:m=>n("sampler",m),ariaLabel:e("nai.field.sampler")})]}),s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.noiseSchedule")}),s.jsx(Me,{items:Ol.map(m=>({value:m,label:m})),value:t.noiseSchedule,onChange:m=>n("noiseSchedule",m),ariaLabel:e("nai.field.noiseSchedule")})]}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[s.jsx("input",{type:"checkbox",checked:t.autoSmea,onChange:m=>n("autoSmea",m.target.checked)}),s.jsx("span",{children:e("nai.field.autoSmea")})]}),s.jsx("p",{className:"option-help",children:e("nai.help.autoSmea")}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[s.jsx("span",{children:e("nai.field.steps")}),s.jsx("input",{type:"range",min:Cr.min,max:Cr.max,step:1,value:t.steps,onChange:m=>n("steps",Number(m.target.value))}),s.jsx("output",{children:t.steps})]}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[s.jsx("span",{children:e("nai.field.scale")}),s.jsx("input",{type:"range",min:Ar.min,max:Ar.max,step:.1,value:t.scale,onChange:m=>n("scale",Number(m.target.value))}),s.jsx("output",{children:t.scale.toFixed(1)})]}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[s.jsx("span",{children:e("nai.field.cfgRescale")}),s.jsx("input",{type:"range",min:Tr.min,max:Tr.max,step:.01,value:t.cfgRescale,onChange:m=>n("cfgRescale",Number(m.target.value))}),s.jsx("output",{children:t.cfgRescale.toFixed(2)})]}),s.jsx("p",{className:"option-help",children:e("nai.help.cfgRescale")}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[s.jsx("input",{type:"checkbox",checked:t.decrisper,onChange:m=>n("decrisper",m.target.checked)}),s.jsx("span",{children:e("nai.field.decrisper")})]}),s.jsx("p",{className:"option-help",children:e("nai.help.decrisper")})]}),s.jsxs("div",{className:"option-group nai-controls",children:[s.jsx("div",{className:"section-title",children:e("nai.panel.presetTitle")}),s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.ucPreset")}),s.jsx(Me,{items:Fl.map(m=>({value:m,label:e(`nai.ucPreset.${m}`)})),value:t.ucPresetId,onChange:m=>n("ucPresetId",m),ariaLabel:e("nai.field.ucPreset")})]}),c?s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.qualityPreset")}),s.jsx(Me,{items:Dl.map(m=>({value:m,label:e(`nai.qualityPreset.${m}`)})),value:t.qualityPresetId,onChange:m=>n("qualityPresetId",m),ariaLabel:e("nai.field.qualityPreset")})]}):null]}),s.jsxs("div",{className:"option-group nai-controls",children:[s.jsx("div",{className:"section-title",children:e("nai.panel.outputTitle")}),s.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[s.jsx("input",{type:"checkbox",checked:t.varietyPlus,onChange:m=>n("varietyPlus",m.target.checked)}),s.jsx("span",{children:e("nai.field.varietyPlus")})]}),s.jsx("p",{className:"option-help",children:e("nai.help.varietyPlus")}),c?s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[s.jsx("input",{type:"checkbox",checked:t.straightAlpha,onChange:m=>n("straightAlpha",m.target.checked)}),s.jsx("span",{children:e("nai.field.straightAlpha")})]}),s.jsx("p",{className:"option-help",children:e("nai.help.straightAlpha")})]}):null,s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.seed")}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:d,placeholder:e("nai.field.seedRandom"),onChange:m=>{const u=m.target.value.replace(/\D/g,"");n("seed",u===""?null:Math.min(Number(u),Gl))}})]}),s.jsx("p",{className:"option-help",children:e("nai.help.seed")})]}),s.jsx("div",{className:"option-group nai-controls",children:s.jsx("button",{type:"button",className:"option-btn",onClick:r,children:e("nai.resetDefaults")})})]})}const PS="",Ud=3;function _i(e,t,n,r){const o=[],a=new Set;for(const i of[t,...e])!i?.filename||a.has(i.filename)||xe(i)!==r||r&&!/\.(?:mp4|mov)$/i.test(i.filename)||(a.add(i.filename),o.push({filename:i.filename,current:i===t}));for(const i of n){const l=i.filePath,c=r?i.kind==="video":i.kind==="image"||i.kind==="element",d=r?/\.(?:mp4|mov)$/i.test(l??""):/\.(?:png|jpe?g|webp)$/i.test(l??"");!l||!c||!d||a.has(l)||(a.add(l),o.push({filename:l,current:!1,label:i.name||l,source:i.kind==="element"?"element":"asset"}))}return o}function RS(e,t){return e[t]??null}function $d(e,t,n){const r=!t||e.some(o=>o.filename===t);return[{value:PS,label:n("mcp.referenceNone")},...r?[]:[{value:t,label:t,sub:n("mcp.referenceMissing")}],...e.map(o=>({value:o.filename,label:o.label??o.filename,sub:o.current?n("mcp.referenceCurrent"):o.source?n(`mcp.referenceSource.${o.source}`):void 0}))]}function Go({id:e,label:t,value:n,candidates:r,disabled:o,title:a,help:i,onChange:l,t:c}){return s.jsxs("div",{className:"mcp-reference-slot",children:[s.jsx("label",{className:"mcp-reference-slot__label",htmlFor:e,children:t}),s.jsx(Me,{id:e,items:$d(r,n??"",c),value:n??"",onChange:l,ariaLabel:t,placeholder:c("mcp.referenceSelect"),disabled:o,title:a,portal:!0}),i?s.jsx("p",{className:"option-help",children:i}):null]})}function MS({index:e,images:t,selection:n,disabled:r,onChange:o,t:a}){const i=RS(n.references,e),l=new Set(n.references.filter((x,S)=>S!==e).map(x=>x.filename)),c=i?.dataUrl?{filename:i.filename,current:!1,label:i.displayName??a("mcp.referenceLocalFallback"),source:"local"}:null,d=[...c?[c]:[],...t.filter(x=>!l.has(x.filename))],m=x=>{const S=[...n.references];x?S[e]={filename:x,...i?.tag?{tag:i.tag}:{}}:S.splice(e,1),o({...n,references:S})},u=x=>{if(!i)return;const S=[...n.references],{tag:b,...v}=i;S[e]={...v,...x?{tag:x}:{}},o({...n,references:S})},p=!!(i?.tag&&!Ts(i.tag)),h=`mcp-reference-tag-error-${e}`;return s.jsxs("div",{className:"mcp-reference-slot__reference",children:[s.jsx(Me,{items:$d(d,i?.filename??"",a),value:i?.filename??"",onChange:m,ariaLabel:a("mcp.imageReferenceAria",{index:e+1}),placeholder:a("mcp.referenceSelect"),disabled:r,portal:!0}),s.jsxs("div",{children:[s.jsx("input",{type:"text",value:i?.tag??"",onChange:x=>u(x.target.value),"aria-label":a("mcp.referenceTagAria",{index:e+1}),placeholder:a("mcp.referenceTagPlaceholder"),"aria-invalid":p,"aria-describedby":p?h:void 0,maxLength:32,disabled:r||!i}),p?s.jsx("p",{id:h,className:"settings-row__microcopy",role:"alert",children:a("mcp.referenceTagInvalid")}):null]})]})}function LS({selection:e,disabled:t,onChange:n,t:r}){const o=g.useRef(null),[a,i]=g.useState(null),l=e.references.length>=Ud,c=async d=>{const m=d.target.files?.[0];if(d.target.value="",!!m){if(!/^image\/(?:png|jpeg|webp)$/i.test(m.type)){i(r("mcp.referenceLocalInvalidType"));return}try{const u=await Gs(m),p=`local:${globalThis.crypto.randomUUID()}`;n({...e,references:[...e.references,{filename:p,displayName:m.name,dataUrl:u}]}),i(null)}catch{i(r("mcp.referenceLocalReadFailed"))}}};return s.jsxs("div",{children:[s.jsx("input",{ref:o,className:"sr-only",type:"file",accept:"image/png,image/jpeg,image/webp",onChange:d=>{c(d)},disabled:t||l}),s.jsx("button",{type:"button",className:"option-btn",onClick:()=>o.current?.click(),disabled:t||l,children:r("mcp.referenceAttachLocal")}),s.jsx("p",{className:"option-help",children:r("mcp.referenceAttachHelp")}),a?s.jsx("p",{className:"settings-row__microcopy",role:"alert",children:a}):null]})}function OS({images:e,selection:t,disabled:n,onChange:r,t:o}){return s.jsxs("div",{className:"mcp-reference-slot",children:[s.jsx("div",{className:"mcp-reference-slot__label",children:o("mcp.imageReferencesLabel")}),Array.from({length:Ud},(a,i)=>s.jsx(MS,{index:i,images:e,selection:t,disabled:n,onChange:r,t:o},i)),s.jsx(LS,{selection:t,disabled:n,onChange:r,t:o})]})}function FS({inputRoles:e,disabled:t}){const{t:n}=V(),r=f(u=>u.history),o=f(u=>u.currentImage),a=f(u=>u.assets),i=f(u=>u.mcpReferenceSelection)??Be(),l=g.useMemo(()=>_i(r,o,a,!1),[r,o,a]),c=g.useMemo(()=>_i(r,o,a,!0),[r,o,a]),d=u=>qg(u,f.setState,f.getState),m=i.startFrameFilename?void 0:n("mcp.endFrameNeedsStart");return s.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?s.jsx(Go,{id:"mcp-start-frame",label:n("mcp.startFrameLabel"),value:i.startFrameFilename,candidates:l,disabled:t,t:n,onChange:u=>d({...i,startFrameFilename:u||null,...u?{}:{endFrameFilename:null}})}):null,e.includes("end_image")?s.jsx(Go,{id:"mcp-end-frame",label:n("mcp.endFrameLabel"),value:i.endFrameFilename,candidates:l,disabled:t||!i.startFrameFilename,title:m,help:m,t:n,onChange:u=>d({...i,endFrameFilename:u||null})}):null,e.includes("image_references")?s.jsx(OS,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?s.jsx(Go,{id:"mcp-video-reference",label:n("mcp.videoReferenceLabel"),value:i.referenceVideoFilename,candidates:c,disabled:t,t:n,help:n("mcp.videoReferenceCostNote"),onChange:u=>d({...i,referenceVideoFilename:u||null})}):null]})}function DS(e){return Array.isArray(e)&&e.includes("image_references")}function GS(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function b0(e,t){return t.mode!=="trained-id"||!Array.isArray(t.trainedFromRefs)?!1:t.trainedFromRefs.length!==e.length?!0:t.trainedFromRefs.some((n,r)=>e[r]!==n)}function x0(e){return e.length>3}function zS({inputRoles:e,disabled:t}){const{t:n}=V(),r=f(d=>d.assets),o=f(d=>d.mcpCharacterElementId??null),a=f(d=>d.selectedElementIds??[]);if(!DS(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=GS({mentionElementIds:a,characterElementId:o})==="conflict",c=!!t||a.length>0;return s.jsxs("div",{className:"mcp-character-slot","data-testid":"mcp-character-slot",children:[s.jsx("div",{className:"section-title",children:n("mcp.characterSlotLabel")}),s.jsxs("select",{value:o??"",disabled:c,"aria-label":n("mcp.characterSlotLabel"),title:a.length>0?n("mcp.characterSlotConflictHint"):void 0,onChange:d=>f.setState({mcpCharacterElementId:d.target.value||null}),children:[s.jsx("option",{value:"",children:n("mcp.characterSlotNone")}),i.map(d=>s.jsx("option",{value:d.id,children:d.name},d.id))]}),l?s.jsx("p",{className:"option-help",role:"alert",children:n("mcp.characterSlotConflictHint")}):null]})}const Ei=new Set(["duration","resolution","quality","mode"]);function Ni(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ma(e){return e.options&&e.options.length>0?Ni(e.options):e.type==="boolean"?[!0,!1]:e.type!=="number"||e.min===void 0||e.max===void 0?[]:Number.isInteger(e.min)&&Number.isInteger(e.max)&&e.max-e.min<=20?Array.from({length:e.max-e.min+1},(t,n)=>e.min+n):Ni([e.min,...e.default!==void 0?[e.default]:[],e.max])}function ki(e,t){return{duration:t("mcp.durationLabel"),resolution:t("mcp.resolutionLabel"),quality:t("mcp.qualityLabel"),mode:t("mcp.modeLabel"),generateAudio:t("mcp.audioLabel"),generate_audio:t("mcp.audioLabel"),sound:t("mcp.audioLabel")}[e]??e.replace(/_/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function US(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function $S(e){return[...ma(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function qS({parameter:e,value:t,disabled:n,onChange:r}){const{t:o}=V();if(e.name==="duration"&&e.type==="number"){const l=$S(e);if(l.length>1){const c=ki(e.name,o);return s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:c}),s.jsx(zd,{values:l,value:typeof t=="number"?t:null,defaultValue:typeof e.default=="number"?e.default:void 0,allowAuto:!e.required,disabled:n,ariaLabel:c,onChange:r})]})}}const a=ma(e);if(a.length===0)return null;const i=ki(e.name,o);return s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:i}),s.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i,children:[e.required?null:s.jsx("button",{type:"button",className:`option-btn${t===void 0?" active":""}`,"aria-pressed":t===void 0,disabled:n,onClick:()=>r(null),children:o("size.autoLabel")}),a.map(l=>s.jsx("button",{type:"button",className:`option-btn${t===l?" active":""}`,"aria-pressed":t===l,disabled:n,onClick:()=>r(l),title:e.description,children:US(l,o)},`${typeof l}:${String(l)}`))]})]})}function ji({entries:e,parameters:t,disabled:n,onParameter:r}){return s.jsx(s.Fragment,{children:e.map(o=>s.jsx(qS,{parameter:o,value:t[o.name],disabled:n,onChange:a=>r(o.name,a)},o.name))})}function HS({entry:e,ratio:t,parameters:n,disabled:r,onRatio:o,onParameter:a}){const{t:i}=V(),l=e.capabilities.aspectRatios.filter(p=>p!=="auto"),c=e.capabilities.parameters.filter(p=>ma(p).length>0),d=c.filter(p=>Ei.has(p.name)),m=c.filter(p=>!Ei.has(p.name)),u=e.capabilities.inputRoles.some(p=>p==="start_image"||p==="end_image"||p==="image_references"||p==="video_references");return s.jsxs("div",{className:"mcp-model-presets","data-capability-source":e.capabilities.source,children:[l.length>0?s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:i("mcp.aspectRatioLabel")}),s.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i("mcp.aspectRatioLabel"),children:[s.jsx("button",{type:"button",className:`option-btn${t===null?" active":""}`,"aria-pressed":t===null,disabled:r,onClick:()=>o(null),children:i("size.autoLabel")}),l.map(p=>s.jsx("button",{type:"button",className:`option-btn${t===p?" active":""}`,"aria-pressed":t===p,disabled:r,onClick:()=>o(p),children:p},p))]})]}):null,s.jsx(ji,{entries:d,parameters:n,disabled:r,onParameter:a}),u?s.jsxs("div",{className:"mcp-tool-inputs",children:[s.jsx("div",{className:"section-title",children:i("mcp.toolInputsLabel")}),s.jsx(FS,{inputRoles:e.capabilities.inputRoles,disabled:r}),s.jsx(zS,{inputRoles:e.capabilities.inputRoles,disabled:r})]}):null,m.length>0?s.jsxs("details",{className:"mcp-advanced-presets",children:[s.jsx("summary",{children:i("mcp.advancedPresetsLabel")}),s.jsx(ji,{entries:m,parameters:n,disabled:r,onParameter:a})]}):null,l.length===0&&c.length===0?s.jsx("p",{className:"option-help",children:i("mcp.providerDefaultsHelp")}):null]})}const ur={image:[],video:[]},VS={};function KS(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function BS({record:e}){const{t}=V(),n=f(w=>w.mcpProvider??null),r=f(w=>w.mcpModel??null),o=f(w=>w.mcpMediaKind??"image"),a=f(w=>w.mcpRatio??null),l=f(w=>w.mcpParameters)??VS,[c,d]=g.useState(ur),[m,u]=g.useState("idle"),[p,h]=g.useState(0),x=e?.executable===!1,S=e?.status.state==="connected";if(g.useEffect(()=>{if(!n||!S){d(ur),u("idle");return}const w=new AbortController;return d(ur),u("loading"),ud(n,w.signal).then(I=>{w.signal.aborted||(d(I),u("ready"))}).catch(I=>{I.name!=="AbortError"&&(w.signal.aborted||(d(ur),u("error")))}),()=>w.abort()},[n,S,p]),!n)return null;const b=o==="video"?c.video:c.image,v=b.find(w=>w.id===r)??null,y=w=>zg(w,f.setState,f.getState);return s.jsxs("div",{className:"mcp-generation-controls","data-testid":"mcp-generation-controls",children:[s.jsxs("div",{className:"option-group",children:[s.jsxs("div",{className:"section-title mcp-generation-controls__header",children:[s.jsxs("span",{children:[KS(n)," · MCP"]}),s.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>uo(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),S?null:s.jsx("p",{className:"option-help",children:t("mcp.disconnectedSelection")}),x?s.jsx("p",{className:"option-help",children:t("mcp.higgsfieldLocked")}):null]}),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"option-group",children:s.jsxs("div",{className:"option-row",children:[s.jsx("button",{type:"button",className:`option-btn${o==="image"?" active":""}`,"aria-pressed":o==="image",onClick:()=>y("image"),children:t("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${o==="video"?" active":""}`,"aria-pressed":o==="video",onClick:()=>y("video"),children:t("grokMode.video")})]})}),s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:t("mcp.modelSectionTitle")}),m==="loading"?s.jsx("p",{className:"option-help",role:"status",children:t("mcp.loadingModels")}):m==="error"?s.jsxs("div",{className:"mcp-catalog-state",role:"alert",children:[s.jsx("span",{children:t("mcp.modelsLoadFailed")}),s.jsx("button",{type:"button",className:"settings-action-btn",onClick:()=>h(w=>w+1),children:t("mcp.retryModels")})]}):m==="ready"&&b.length===0?s.jsx("p",{className:"option-help",children:t("mcp.noModels")}):v?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mcp-selected-model",children:[s.jsx("strong",{children:v.label}),v.description?s.jsx("span",{children:v.description}):null]}),s.jsx(HS,{entry:v,ratio:a,parameters:l,disabled:x,onRatio:w=>Ug(w,f.setState),onParameter:(w,I)=>$g(w,I,f.setState,f.getState)})]}):s.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function WS(e,t,n,r){const o=e.catalog?.comfy,a=e.phase==="ready"&&o?.status==="ready",i=[];for(const l of["image","video"])i.push({label:r(l==="image"?"comfy.kindImage":"comfy.kindVideo"),items:(o?.models[l]??[]).map(c=>({value:l==="video"?`${Wt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!Vt(c),title:c.executable===!1?r("comfy.display.selectedLocked"):c.description?.endsWith("(offline)")?r("comfy.display.selectedOffline"):void 0}))});return n&&!i.some(l=>l.items.some(c=>c.value===n))&&i.unshift({items:[{value:n,label:t.selected?.id??n,disabled:!0,title:r("comfy.display.selectedMissing")}]}),i}function JS(e,t){const n=f.getState();if(n.provider!=="comfy"||n.mcpProvider||n.provider!==t.provider||(n.mcpProvider??null)!==t.mcpProvider)return;const r=e.startsWith(Wt),o=r?e.slice(Wt.length):e;Ct(ca(),r?{comfyVideoWorkflow:o}:{comfyWorkflow:o}).selectedAvailable&&(r?n.setComfyVideoWorkflow(o):n.setComfyWorkflow(o))}function YS(){const{t:e}=V(),t=g.useId(),n=`${t}-status`,r=`${t}-workflow`,o=f(h=>h.provider),a=f(h=>h.mcpProvider??null),i=f(h=>h.comfyWorkflow),l=f(h=>h.comfyVideoWorkflow),c=f(h=>h.openSettings),d=Wn(),m=Ct(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),u=l?`${Wt}${l}`:i??"",p=WS(d,m,u,e);return o!=="comfy"||a?null:s.jsxs("div",{className:"option-group comfy-generation-controls","data-testid":"comfy-generation-controls","aria-busy":d.phase==="loading",children:[s.jsx("label",{className:"section-title",htmlFor:r,children:e("comfy.workflowsTitle")}),s.jsxs("p",{id:n,className:"option-help",children:[e(Yt(m,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),s.jsx(Me,{id:r,groups:p,value:u,onChange:h=>JS(h,{provider:o,mcpProvider:a}),ariaLabel:e("comfy.display.chooseWorkflow"),ariaDescribedBy:n,placeholder:e("comfy.display.chooseWorkflow"),portal:!0}),m.selected?s.jsxs("p",{className:"option-help",children:[e(m.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage"),": ",m.selected.label,s.jsx("br",{}),s.jsx("code",{children:m.selected.id})]}):null,s.jsx("p",{className:"option-help",children:e("comfy.display.controlsHelp")}),s.jsxs("div",{className:"option-row",children:[s.jsx("button",{type:"button",className:"option-btn",onClick:()=>{d.refresh()},children:e("comfy.display.refresh")}),s.jsx("button",{type:"button",className:"option-btn",onClick:()=>c("providers"),children:e("comfy.display.manage")})]})]})}const XS=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],mr=[{value:"1:1",label:"1:1"},{value:"2:3",label:"2:3"},{value:"3:2",label:"3:2"},{value:"3:4",label:"3:4"},{value:"4:3",label:"4:3"},{value:"4:5",label:"4:5"},{value:"5:4",label:"5:4"},{value:"9:16",label:"9:16"},{value:"16:9",label:"16:9"},{value:"21:9",label:"21:9"}],ZS=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],zr={"1:1":{512:"512x512","1K":"1024x1024","2K":"2048x2048","4K":"4096x4096"},"2:3":{512:"424x632","1K":"848x1264","2K":"1696x2528","4K":"3392x5056"},"3:2":{512:"632x424","1K":"1264x848","2K":"2528x1696","4K":"5056x3392"},"3:4":{512:"448x600","1K":"896x1200","2K":"1792x2400","4K":"3584x4800"},"4:3":{512:"600x448","1K":"1200x896","2K":"2400x1792","4K":"4800x3584"},"4:5":{512:"464x576","1K":"928x1152","2K":"1856x2304","4K":"3712x4608"},"5:4":{512:"576x464","1K":"1152x928","2K":"2304x1856","4K":"4608x3712"},"9:16":{512:"384x688","1K":"768x1376","2K":"1536x2752","4K":"3072x5504"},"16:9":{512:"688x384","1K":"1376x768","2K":"2752x1536","4K":"5504x3072"},"21:9":{512:"792x168","1K":"1584x672","2K":"3168x1344","4K":"6336x2688"}};function QS(e){for(const[t,n]of Object.entries(zr))for(const[r,o]of Object.entries(n))if(o===e)return{ratio:t,res:r};return null}function eI(e,t){const n=e/t;let r="1:1",o=1/0;const a=[...Object.keys(zr),"1:8","8:1","1:4","4:1"];for(const c of a){const[d,m]=c.split(":").map(Number),u=Math.abs(n-d/m);u<o&&(o=u,r=c)}const i=Math.max(e,t),l=i<=512?"512":i<=1024?"1K":i<=2048?"2K":"4K";return{ratio:r,res:l}}function qd(){const{t:e}=V(),t=f(z=>z.provider),n=f(z=>z.imageToolModel),r=f(z=>z.setImageToolModel),o=f(z=>z.quality),a=f(z=>z.setQuality),i=f(z=>z.format),l=f(z=>z.setFormat),c=f(z=>z.moderation),d=f(z=>z.setModeration),m=f(z=>z.multimode),u=f(z=>z.setMultimode),p=f(z=>z.imageModel),h=f(z=>z.setImageModel),x=f(z=>z.selectVideoModel),S=f(z=>z.sizePreset),b=f(z=>z.customW),v=f(z=>z.customH),y=f(z=>z.setSizePreset),w=f(z=>z.setCustomSize),I=f(z=>z.uiMode),_=f(z=>z.videoModelSelected),N=f(z=>z.mcpProvider??null),{providers:j}=md(),L=I==="classic",q=t==="grok"||t==="grok-api",A=t==="agy",G=t==="gemini-api",C=A||G,T=t==="nai",k=t==="comfy",R=q||C||T,B=S==="custom"?`${b}x${v}`:"1024x1024",se=G&&S==="auto",oe=G&&!se?QS(B):null,ae=oe??{ratio:"",res:""},ge=G&&!se&&S==="custom"&&!oe,D=p==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[F,ee]=g.useState(!1),[J,me]=g.useState(String(b)),[ye,ie]=g.useState(String(v)),ke=(z,ve)=>{const P=zr[z||"1:1"]?.[ve||"1K"]||"1024x1024",[ne,de]=P.split("x").map(Number);ee(!1),y("custom"),w(ne,de)},le=()=>{const z=Number(J),ve=Number(ye);!Number.isFinite(z)||!Number.isFinite(ve)||z<=0||ve<=0||(y("custom"),w(z,ve),ee(!1))},Ie=[{value:"low",label:e("quality.lowLabel"),sub:e("quality.lowSub")},{value:"medium",label:e("quality.mediumLabel"),sub:e("quality.mediumSub")},{value:"high",label:e("quality.highLabel"),sub:e("quality.highSub")},...t==="api"&&n?[{value:"xhigh",label:e("quality.xhighLabel")},{value:"max",label:e("quality.maxLabel")}]:[]],je=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],Re=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],ce=q?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:A?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:G?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:T?{title:e("nai.compatTitle"),body:e("nai.compatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},be=z=>{z==="video"?x("grok-imagine-video"):h(p)};return N?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Do,{mcpProviders:j}),s.jsx(BS,{record:j.find(z=>z.id===N)??null})]}):k?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Do,{mcpProviders:j}),s.jsx(YS,{})]}):s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Do,{mcpProviders:j}),s.jsxs("details",{className:"provider-compat-details",children:[s.jsx("summary",{children:ce.title}),s.jsx("p",{children:ce.body})]}),q&&s.jsx("div",{className:"option-group grok-mode-toggle",children:s.jsxs("div",{className:"option-row",children:[s.jsx("button",{type:"button",className:`option-btn${_?"":" active"}`,onClick:()=>be("image"),children:e("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>be("video"),children:e("grokMode.video")})]})}),_?s.jsx(NS,{}):s.jsxs(s.Fragment,{children:[A?null:q?s.jsxs(s.Fragment,{children:[s.jsx(SS,{}),s.jsx(xS,{})]}):T?s.jsx(TS,{}):G?s.jsxs(s.Fragment,{children:[s.jsx(qe,{title:e("quality.grokModelTitle"),items:Re,value:D,onChange:h}),s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")||"Aspect Ratio"}),[mr.slice(0,3),mr.slice(3,6),mr.slice(6,8),mr.slice(8)].map((z,ve)=>s.jsx("div",{className:"option-row",children:z.map(P=>s.jsx("button",{type:"button",className:`option-btn${ae.ratio===P.value?" active":""}`,onClick:()=>ke(P.value,ae.res),children:P.label},P.value))},ve))]}),s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("size.grokResolutionTitle")||"Resolution"}),s.jsx("div",{className:"gemini-resolution-grid",children:ZS.map(z=>s.jsxs("button",{type:"button",className:`option-btn${ae.res===z.value?" active":""}`,onClick:()=>ke(ae.ratio,z.value),children:[s.jsx("span",{children:z.label}),s.jsx("br",{}),s.jsx("small",{children:zr[ae.ratio]?.[z.value]?.replace("x","×")||""})]},z.value))})]}),s.jsxs("div",{className:"option-group",children:[s.jsxs("div",{className:"option-row",children:[s.jsxs("button",{type:"button",className:`option-btn${se?" active":""}`,onClick:()=>{ee(!1),y("auto")},children:[e("size.autoLabel"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:e("size.autoSub")})]}),s.jsxs("button",{type:"button",className:`option-btn${ge||F?" active":""}`,onClick:()=>ee(z=>!z),children:[e("size.customPlus"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),F?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"option-row size-picker__custom-row",children:[s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:J,onChange:z=>me(z.target.value.replace(/\D/g,"")),placeholder:e("size.width")}),s.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:ye,onChange:z=>ie(z.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(J)>0&&Number(ye)>0?s.jsxs("div",{className:"size-picker__preview",children:[s.jsx("span",{children:e("size.normalizedPreview")}),s.jsx("strong",{children:(()=>{const z=eI(Number(J),Number(ye));return`${z.ratio} · ${z.res}`})()})]}):null,s.jsx("button",{type:"button",className:"size-picker__save",onClick:le,children:e("settings.apiKeys.save")})]}):null]})]}):s.jsxs(s.Fragment,{children:[t==="api"&&s.jsxs("div",{className:"option-group",children:[s.jsx("div",{className:"section-title",children:e("imageToolModel.title")}),s.jsx(Me,{ariaLabel:e("imageToolModel.title"),items:[{value:"",label:e("imageToolModel.default")},...al],value:n??"",onChange:z=>r(z||null),portal:!0})]}),s.jsx(qe,{className:Ie.length>3?"quality-options-expanded":"",title:e("quality.title"),items:Ie,value:o,onChange:a}),s.jsx(oS,{})]}),R?null:s.jsxs(s.Fragment,{children:[s.jsx(qe,{title:e("format.title"),items:XS,value:i,onChange:l}),s.jsx(qe,{title:e("moderation.title"),items:je,value:c,onChange:d}),s.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),L&&!C&&!T&&s.jsx("div",{className:"option-group multimode-toggle",children:s.jsxs("button",{type:"button",className:`multimode-toggle__button${m?" active":""}`,"aria-pressed":m,title:e("multimode.tooltip"),onClick:()=>u(!m),children:[s.jsx("span",{children:e("multimode.label")}),s.jsx("span",{children:e("multimode.shortHint")})]})}),C||T?null:s.jsx(sS,{}),T?null:s.jsx(mS,{})]})]})}const tI=g.lazy(()=>Le(()=>import("./PromptLibraryPanel-v7hIoYy-.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),nI=g.lazy(()=>Le(()=>import("./PromptBuilderPanel-C1DLHD9Q.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),rI=g.lazy(()=>Le(()=>import("./GenerationRequestLogPanel-D6jO_fXj.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.GenerationRequestLogPanel})));function oI(){const e=f(v=>v.rightPanelOpen),t=f(v=>v.toggleRightPanel),n=f(v=>v.promptLibraryOpen),r=f(v=>v.setPromptLibraryOpen),o=f(v=>v.promptBuilderOpen),a=f(v=>v.togglePromptBuilder),i=f(v=>v.workspaceProfile),{t:l}=V(),[c,d]=g.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);g.useEffect(()=>{if(typeof window>"u")return;const v=window.matchMedia("(max-width: 800px)"),y=()=>d(v.matches);return v.addEventListener("change",y),()=>v.removeEventListener("change",y)},[]);const[m,u]=g.useState(!1),p=Gh(i)&&!c,h=c?e:!0,x=Ge(c&&e,t),S=m?"log":o&&p?"builder":n?"library":"settings",b=v=>{u(v==="log"),v==="builder"?(o||a(),n&&r(!1)):v==="library"?(o&&a(),n||r(!0)):(o&&a(),n&&r(!1))};return s.jsxs(s.Fragment,{children:[c&&e?s.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":l("panel.closeSettings"),onClick:t}):null,s.jsx("aside",{ref:x,className:`right-panel${e?"":" collapsed"}${c&&h?" drawer-open":""}`,"aria-label":l("panel.detailSettings"),"aria-modal":c&&e?"true":void 0,role:c&&e?"dialog":void 0,tabIndex:c?-1:void 0,children:s.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!e,children:[s.jsxs("div",{className:"right-panel-tabs",role:"tablist","aria-label":l("panel.detailSettings"),children:[p?s.jsx("button",{type:"button",role:"tab","aria-selected":S==="builder","aria-controls":"right-panel-tab-builder",title:l("promptBuilder.title"),className:`right-panel-tabs__button${S==="builder"?" active":""}`,onClick:()=>b("builder"),children:l("promptBuilder.title")}):null,s.jsx("button",{type:"button",role:"tab","aria-selected":S==="log","aria-controls":"right-panel-tab-log",title:l("generationLog.title"),className:`right-panel-tabs__button${p?"":" right-panel-tabs__button--full"}${S==="log"?" active":""}`,onClick:()=>b("log"),children:l("generationLog.title")}),s.jsx("button",{type:"button",role:"tab","aria-selected":S==="library","aria-controls":"right-panel-tab-library",title:l("promptLibrary.title"),className:`right-panel-tabs__button right-panel-tabs__button--full${S==="library"?" active":""}`,onClick:()=>b("library"),children:l("promptLibrary.title")}),s.jsx("button",{type:"button",role:"tab","aria-selected":S==="settings","aria-controls":"right-panel-tab-settings",title:l("panel.detailSettings"),className:`right-panel-tabs__button right-panel-tabs__button--full${S==="settings"?" active":""}`,onClick:()=>b("settings"),children:l("panel.detailSettings")})]}),S==="builder"&&p?s.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:s.jsx(g.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(nI,{variant:"sidebar"})})}):S==="library"?s.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:s.jsx(g.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(tI,{variant:"embedded"})})}):S==="log"?s.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:s.jsx(g.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(rI,{})})}):s.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:s.jsx(qd,{})})]})})]})}function sI(e){const t=e.currentTarget;if(t.scrollWidth<=t.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const r=t.scrollLeft<=0,o=t.scrollLeft+t.clientWidth>=t.scrollWidth-1,a=e.deltaY<0,i=e.deltaY>0;a&&r||i&&o||(e.preventDefault(),t.scrollLeft+=e.deltaY)}function aI({id:e}){const{t}=V();return s.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function iI({id:e,count:t}){const{t:n}=V(),r=Math.min(t,4);return s.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":n("history.generatingCollection",{count:t}),children:Array.from({length:r},(o,a)=>s.jsx("div",{className:"collection-mini collection-mini--skeleton"},a))},`coll-${e}`)}function lI({sequenceId:e,images:t}){const n=f(l=>l.showHistorySequence),o=f(l=>l.multimodePreviewFlightId)===`history:${e}`,a=t.slice(0,4),{t:i}=V();return s.jsx("button",{type:"button",className:`history-thumb history-thumb--collection${o?" active":""}`,onClick:()=>n(e),"aria-label":i("common.imageCollection",{n:t.length}),children:a.map((l,c)=>!l.thumb&&(tt(l.url)||tt(l.image))?s.jsx(Xt,{className:"collection-mini"},c):s.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function cI(e){const t=g.useRef(null),n=g.useRef(new Map),[r,o]=g.useState(()=>new Set);g.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const i=new IntersectionObserver(l=>{const c=l.filter(d=>d.isIntersecting);c.length!==0&&o(d=>{const m=new Set(d);for(const u of c){const p=u.target.dataset.historyLazyKey;p&&m.add(p)}return m})},{root:e,rootMargin:"0px 200% 0px 200%"});t.current=i;for(const l of n.current.values())i.observe(l);return()=>{i.disconnect(),t.current=null}},[e]);const a=g.useCallback((i,l)=>{const c=n.current.get(i);c&&c!==l&&t.current?.unobserve(c),l?(n.current.set(i,l),t.current?.observe(l)):n.current.delete(i)},[]);return{visibleKeys:r,register:a,supported:typeof IntersectionObserver<"u"}}function dI(){const e=f(y=>y.history),t=f(y=>y.currentImage),n=f(y=>y.historyStripLayout),r=f(y=>y.selectHistory),o=f(y=>y.openGallery),a=f(y=>y.inFlight),i=f(y=>y.multimodeSequences),l=g.useRef({}),[c,d]=g.useState(null),m=cI(c),{t:u}=V(),p=t?Te(t):null,h=g.useMemo(()=>wr(e.filter(In)),[e]),x=g.useMemo(()=>{const y=[];for(const w of a){const I=i[w.id];if(w.kind==="multimode"&&I){y.push({type:"collection-skeleton",id:w.id,count:I.requested});for(let _=0;_<I.requested;_++)I.images[_]||y.push({type:"skeleton",id:`${w.id}_${_}`,count:1})}else y.push({type:"skeleton",id:w.id,count:1})}return y},[a,i]),{completedSequences:S,sequenceFirstKeys:b}=g.useMemo(()=>{const y=new Map,w=new Set;for(const I of h)if(I.sequenceId&&(I.sequenceTotalRequested??0)>1){y.has(I.sequenceId)||w.add(Te(I));const _=y.get(I.sequenceId)||[];_.push(I),y.set(I.sequenceId,_)}return{completedSequences:y,sequenceFirstKeys:w}},[h]);g.useEffect(()=>{p&&l.current[p]?.scrollIntoView({block:"nearest",inline:"nearest"})},[p,h]);const v=(y,w)=>{const I=m.supported?m.visibleKeys.has(y):!0;return s.jsx("div",{ref:_=>{l.current[y]=_,m.register(y,_)},className:"history-thumb","data-history-lazy-key":y,"aria-hidden":I?void 0:!0,style:{padding:0,overflow:"hidden"},children:I?w:null},y)};return s.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:sI,"data-layout":n,children:[s.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:o,"aria-label":u("history.openGalleryAria"),title:u("history.openGalleryTitle"),children:s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),x.map(y=>y.type==="collection-skeleton"?s.jsx(iI,{id:y.id,count:y.count},`coll-${y.id}`):s.jsx(aI,{id:y.id},y.id)),h.map(y=>{const w=Te(y),I=p===w;if(y.sequenceId&&S.has(y.sequenceId)&&b.has(w)){const _=S.get(y.sequenceId);return[v(`coll-${y.sequenceId}`,s.jsx(lI,{sequenceId:y.sequenceId,images:_})),..._.map(N=>{const j=Te(N),L=p===j;return xe(N)?v(j,s.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${L?" active":""}`,onClick:()=>r(N),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify(jn(N))),q.dataTransfer.effectAllowed="copy"},children:[N.thumb?s.jsx("img",{src:N.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Xt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):v(j,s.jsx("img",{src:N.thumb||N.url||N.image,alt:"",className:`history-thumb history-thumb--fade-in${L?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(N),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:N.url||N.image,filename:N.filename})),q.dataTransfer.effectAllowed="copy"}}))})]}return y.sequenceId&&S.has(y.sequenceId)&&!b.has(w)?null:xe(y)?v(w,s.jsxs("div",{className:`history-thumb history-thumb--video${I?" active":""}`,onClick:()=>r(y),draggable:!0,onDragStart:_=>{_.dataTransfer.setData("application/ima2-ref",JSON.stringify(jn(y))),_.dataTransfer.effectAllowed="copy"},children:[y.thumb?s.jsx("img",{src:y.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Xt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):v(w,s.jsx("img",{src:y.thumb||y.url||y.image,alt:"",className:`history-thumb${I?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(y),draggable:!0,onDragStart:_=>{_.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:y.url||y.image,filename:y.filename})),_.dataTransfer.effectAllowed="copy"}}))})]})}const Ci=3e3;function uI(){const{t:e}=V(),t=f(d=>d.toastLog),n=f(d=>d.errorCardLog),r=f(d=>d.dismissToast),o=f(d=>d.dismissErrorCard),[a,i]=g.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),l=g.useRef(new Map);g.useEffect(()=>{const d=()=>i(document.visibilityState==="visible");return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),window.addEventListener("blur",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d),window.removeEventListener("blur",d)}},[]),g.useEffect(()=>{const d=l.current,m=new Set([...t.map(u=>`toast-${u.id}`),...n.map(u=>`error-card-${u.id}`)]);for(const[u,p]of d)(!m.has(u)||!a)&&(clearTimeout(p),d.delete(u));if(a){for(const u of t){const p=`toast-${u.id}`;if(d.has(p))continue;const h=setTimeout(()=>{d.delete(p),r(u.id)},Ci);d.set(p,h)}for(const u of n){const p=`error-card-${u.id}`;if(d.has(p))continue;const h=setTimeout(()=>{d.delete(p),o(u.id)},Ci);d.set(p,h)}}},[o,r,n,a,t]),g.useEffect(()=>()=>{for(const d of l.current.values())clearTimeout(d);l.current.clear()},[]);const c=[...t.map(d=>({kind:"toast",id:d.id,key:`toast-${d.id}`,message:d.message,error:d.error,createdAt:d.createdAt,cta:void 0,cardKey:void 0})),...n.map(d=>{const m=Xe[d.code],u=d.cardKey??m?.cardKey??"errorCard.unknown",p=e(`${u}.title`),h=e(`${u}.body`),x=d.cta??m?.cta;return{kind:"error-card",id:d.id,key:`error-card-${d.id}`,message:d.fallbackMessage?`${p}: ${h} ${d.fallbackMessage}`:`${p}: ${h}`,error:!0,createdAt:d.createdAt,cta:x,cardKey:u}})].sort((d,m)=>d.createdAt-m.createdAt).slice(-5);return c.length===0?null:s.jsx("div",{className:"toast-stack","aria-live":"polite","aria-relevant":"additions removals",children:c.map(d=>{const m=["toast","visible",d.error?"error":"",d.error?"toast--card":""].filter(Boolean).join(" ");return s.jsxs("div",{className:m,role:d.error?"alert":"status",children:[s.jsx("span",{className:"toast__message",children:d.message}),d.kind==="error-card"&&(d.cta==="reauth"||d.cta==="reload")?s.jsx("button",{type:"button",className:"toast__cta",onClick:()=>{d.cta==="reauth"&&f.getState().openSettings("providers"),d.cta==="reload"&&window.location.reload()},children:e(`${d.cardKey??"errorCard.unknown"}.cta`)}):null,s.jsx("button",{type:"button",className:"toast__dismiss","aria-label":e("common.dismiss"),onClick:()=>d.kind==="error-card"?o(d.id):r(d.id),children:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:s.jsx("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round"})})})]},d.key)})})}const mI=10*6e4;function pI(e){return!e||e.surface!=="npm"||!e.enabled||!e.available||!e.latestVersion?{kind:"hidden"}:{kind:"npm",version:e.latestVersion,command:e.command,releaseUrl:e.releaseUrl}}function Ai(e){if(!e?.active||!e.availableVersion)return{kind:"hidden"};const{phase:t}=e;return t!=="available"&&t!=="downloading"&&t!=="downloaded"&&t!=="error"?{kind:"hidden"}:{kind:"desktop",version:e.availableVersion,phase:t,progress:e.progress}}function fI(){return $("/api/update/badge")}async function hI(e){await $("/api/update/dismiss",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:e})})}async function gI(){return(await $("/api/update/notice",{method:"POST"})).updatedTo}const fo={kind:"hidden"},xn=new Set;let He=fo,zo=null,Hd=null,Ti=null,Vd=!1,ds=null;function Ur(e){He=e.kind==="npm"&&e.version===Hd?fo:e;for(const t of xn)t()}function yI(){const e=Fe();let t=!0,n=0;const r=e?.onUpdateState?.(o=>{t&&(n++,Ur(Ai(o)))});return e?.getUpdateState?.().then(o=>{t&&n===0&&Ur(Ai(o))}).catch(()=>{}),()=>{t=!1,r?.()}}function vI(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;return t.surface!=="npm"||typeof t.enabled!="boolean"||typeof t.available!="boolean"||typeof t.currentVersion!="string"||typeof t.command!="string"||t.latestVersion!==null&&typeof t.latestVersion!="string"||t.releaseUrl!==null&&typeof t.releaseUrl!="string"||t.noticePending!==void 0&&typeof t.noticePending!="boolean"?null:e}function Pi(e){Ur(pI(e)),e.noticePending===!0&&(Vd=!0,ds?.(),ds=null)}function bI(){let e=!0,t=!1;const n=async()=>{if(!(!e||t)){t=!0;try{const a=await fI();e&&Pi(a)}catch{}finally{t=!1}}};let r=null;const o=Nu(a=>{if(!e)return;const i=vI(a);i&&(r===null&&(r=setInterval(()=>{n()},mI)),Pi(i))});return()=>{e=!1,o(),r!==null&&clearInterval(r)}}function xI(e){return xn.add(e),xn.size===1&&(zo=Fe()?.getUpdateState?yI():bI()),()=>{xn.delete(e),xn.size===0&&(zo?.(),zo=null)}}function SI(){return He}function II(){return fo}async function wI(){if(He.kind!=="npm")return;const e=He.version;try{await hI(e),Hd=e,He.kind==="npm"&&He.version===e&&Ur(fo)}catch(t){console.warn("[update] dismissal failed",t)}}async function _I(){if(!(He.kind!=="desktop"||He.phase!=="available"&&He.phase!=="error"))try{await Fe()?.downloadUpdate?.()}catch(e){console.warn("[update] download failed",e)}}async function EI(){if(!(He.kind!=="desktop"||He.phase!=="downloaded"))try{await Fe()?.installUpdate?.()}catch(e){console.warn("[update] install failed",e)}}function NI(){return Ti??=(async()=>{try{const e=Fe();return e?.getUpdateState?await e.claimUpdateNotice?.()??null:(Vd||await new Promise(t=>{ds=t}),await gI())}catch{return null}})(),Ti}const kI={dismiss:()=>{wI()},download:()=>{_I()},install:()=>{EI()}};function Kd(){return{view:g.useSyncExternalStore(xI,SI,II),...kI}}function jI(){return s.jsxs("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16V8m-4 4 4-4 4 4"})]})}function CI(e,t){const n=e.kind==="npm"?"available":{available:"download",downloading:"downloading",downloaded:"ready",error:"retry"}[e.phase];return t(`update.${n}`,{version:e.version,progress:e.kind==="desktop"?e.progress??0:0})}function AI(e,t,n,r){g.useEffect(()=>{if(!e)return;const o=i=>{i.target instanceof Node&&!t.current?.contains(i.target)&&r()},a=i=>{i.key==="Escape"&&(i.preventDefault(),r(),n.current?.focus())};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",a),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",a)}},[e,t,n,r])}function TI({view:e,id:t,dismiss:n}){const{t:r}=V(),o=g.useRef(null);g.useEffect(()=>{o.current?.focus()},[]);const a=async()=>{try{await navigator.clipboard.writeText(e.command),f.getState().showToast(r("update.copied"),!1)}catch(i){console.warn("[update] copy failed",i)}};return s.jsxs("div",{id:t,className:"update-popover",role:"dialog","aria-labelledby":`${t}-title`,children:[s.jsx("h2",{id:`${t}-title`,children:r("update.popoverTitle",{version:e.version})}),s.jsx("p",{children:r("update.runCommand")}),s.jsx("code",{children:e.command}),s.jsxs("div",{className:"update-popover__actions",children:[s.jsx("button",{type:"button",ref:o,onClick:()=>{a()},children:r("update.copy")}),e.releaseUrl?s.jsx("a",{href:e.releaseUrl,target:"_blank",rel:"noopener noreferrer",children:r("update.whatsNew")}):null,s.jsx("button",{type:"button",onClick:n,children:r("update.dismiss")})]})]})}function Bd({variant:e="strip",trailing:t=!1,top:n}){const{view:r,dismiss:o,download:a,install:i}=Kd(),{t:l}=V(),c=g.useId(),d=g.useRef(null),m=g.useRef(null),[u,p]=g.useState(null),h=g.useCallback(()=>p(null),[]),x=r.kind==="npm"&&u===r.version;if(AI(x,d,m,h),r.kind==="hidden")return null;const S=CI(r,l),b=r.kind==="desktop"&&r.phase==="downloading",v=()=>{r.kind==="npm"?p(x?null:r.version):r.phase==="downloaded"?i():b||a()},y=t?" sidebar-top__btn--trailing":"";return s.jsxs("span",{ref:d,className:`update-indicator-anchor update-indicator-anchor--${e}${y}`,style:e==="floating"?{top:n}:void 0,children:[s.jsxs("button",{type:"button",ref:m,className:`sidebar-top__btn update-indicator update-indicator--${e}${y}`,"aria-label":S,title:S,"aria-disabled":b||void 0,onClick:v,"aria-haspopup":r.kind==="npm"?"dialog":void 0,"aria-expanded":r.kind==="npm"?x:void 0,"aria-controls":x?c:void 0,children:[s.jsx(jI,{}),s.jsx("span",{className:"update-indicator__dot","aria-hidden":"true"}),e==="floating"?s.jsx("span",{"aria-hidden":"true",children:b?`${r.progress??0}%`:`v${r.version}`}):null]}),x&&r.kind==="npm"?s.jsx(TI,{view:r,id:c,dismiss:o}):null]})}let Ri=!1;function PI(e,t,n){const[r,o]=g.useState();return g.useLayoutEffect(()=>{const a=e&&!t?document.querySelector(".mobile-app-bar"):null;if(!a){o(void 0);return}const i=()=>o(a.getBoundingClientRect().bottom+10);i();const l=new ResizeObserver(i);return l.observe(a),()=>l.disconnect()},[e,t,n]),r}function RI(){Kd();const e=mt(),t=f(o=>o.settingsOpen),n=f(o=>o.uiMode),r=PI(e,t,n);return g.useEffect(()=>{let o=!0;return NI().then(a=>{!o||!a||Ri||(Ri=!0,f.getState().showToast(O("update.updatedTo",{version:a}),!1))}),()=>{o=!1}},[]),e&&!t?s.jsx(Bd,{variant:"floating",top:r}):null}function MI(){return null}function LI(e,t="en"){if(!e)return"earlier";const n=new Date(e);if(Number.isNaN(n.getTime()))return"earlier";const o=Math.floor((new Date().getTime()-n.getTime())/864e5);return o===0?"today":o===1?"yesterday":o<7?"thisWeek":new Intl.DateTimeFormat(t,{year:"numeric",month:"short",day:"numeric"}).format(n)}function OI(e,t,n){async function r(i){if(i.setId)try{await Ee.getState().loadSet(i.setId),f.getState().setUIMode("card-news"),e()}catch{t(n("gallery.openCardNewsSetFailed"),!0)}}async function o(i,l){if(l.stopPropagation(),!i.setId)return;const c=`generated/cardnews/${i.setId}`;try{await navigator.clipboard?.writeText(c),t(n("gallery.cardNewsPathCopied"))}catch{t(n("toast.copyFailed"),!0)}}function a(i,l){l.stopPropagation(),i.setId&&window.open($b(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:o,handleDownloadCardNewsManifest:a}}const FI=["ArrowLeft","ArrowRight","Home","End"];function DI(){return g.useCallback(e=>{if(!FI.includes(e.key))return;const t=e.currentTarget,n=Array.from(t.querySelectorAll("[role='tab']")).filter(l=>!l.hasAttribute("disabled"));if(n.length===0)return;e.preventDefault();const r=document.activeElement,o=r?n.indexOf(r):-1,a=e.key==="Home"?0:e.key==="End"?n.length-1:o<0?0:(o+(e.key==="ArrowRight"?1:-1)+n.length)%n.length,i=n[a];i?.focus(),i?.click()},[])}function Uo({className:e,ariaLabel:t,tabs:n,value:r,onChange:o}){const a=DI(),i=n.find(c=>c.value===r),l=i&&!i.disabled?i.value:n.find(c=>!c.disabled)?.value;return s.jsx("div",{className:e,role:"tablist","aria-label":t,onKeyDown:a,children:n.map(c=>s.jsx("button",{type:"button",role:"tab","aria-selected":c.value===r,tabIndex:c.value===l?0:-1,className:c.value===r?"active":"",onClick:()=>o(c.value),disabled:c.disabled,children:c.label},c.value))})}function GI({item:e,onOpen:t,onCopyPath:n,onDownloadManifest:r}){const{t:o}=V(),i=e.cards?.find(l=>l.headline)?.headline||e.headline||o("gallery.cardNewsSet");return s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>t(e),title:i,children:[e.image?s.jsx("img",{src:e.image,alt:i,loading:"lazy"}):null,s.jsxs("div",{className:"gallery__caption",children:[s.jsx("small",{children:o("gallery.cardNewsSet")}),s.jsx("span",{className:"gallery__caption-text",children:i})]}),s.jsx("div",{className:"gallery-card-news-strip",children:(e.cards||[]).slice(0,5).map((l,c)=>s.jsxs("span",{children:[l.url?s.jsx("img",{src:l.url,alt:l.headline??"",loading:"lazy"}):null,s.jsx("em",{children:l.cardOrder??c+1})]},`${l.url}-${c}`))})]}),s.jsxs("div",{className:"gallery-card-news-actions",children:[s.jsx("span",{children:o("gallery.cardNewsCount",{n:e.cards?.length??0})}),s.jsx("button",{type:"button",onClick:()=>t(e),children:o("gallery.openCardNewsSet")}),s.jsx("button",{type:"button",onClick:l=>n(e,l),children:o("gallery.copyCardNewsSetPath")}),s.jsx("button",{type:"button",onClick:l=>r(e,l),children:o("gallery.downloadCardNewsManifest")})]})]})}const zI=[{id:"animate",labelKey:"chain.animate",available:e=>!!e.filename&&!xe(e)},{id:"edit",labelKey:"chain.edit",available:e=>!!e.filename&&!xe(e)},{id:"useAsRef",labelKey:"chain.useAsRef",available:e=>!!(e.image||e.url)},{id:"rebake",labelKey:"chain.rebake",available:e=>!!(e.prompt||e.filename)},{id:"saveToAssets",labelKey:"chain.saveToAssets",available:e=>!!e.filename},{id:"saveAsElement",labelKey:"chain.saveAsElement",available:e=>!!e.filename&&!xe(e)}];async function UI(e,t,n,r){const o=n();switch(e){case"animate":{if(!t.filename)return;try{await o.animateImage(t.filename,t.prompt??void 0)&&o.showToast(r("toast.animateDone"))}catch(a){o.showToast(a instanceof Error?a.message:r("toast.animateFailed"),!0)}break}case"edit":{o.selectHistory(t),o.openCanvas();break}case"useAsRef":{const a=t.url||t.image;if(!a)return;try{const l=await(await Se(a)).blob(),c=new File([l],t.filename||"reference.png",{type:l.type});await o.addReferences([c]),o.showToast(r("chain.refAdded"))}catch(i){if(i?.code==="LAN_TOKEN_REQUIRED")return;o.showToast(r("chain.refFailed"),!0)}break}case"rebake":{try{const{continueFromItem:i}=await Le(async()=>{const{continueFromItem:c}=await Promise.resolve().then(()=>Yv);return{continueFromItem:c}},void 0),l=await i(t);o.showToast(r(l.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))}catch{o.showToast(r("toast.forkFailed"),!0)}const a=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');a&&(a.focus(),a.setSelectionRange(a.value.length,a.value.length));break}case"saveToAssets":{try{const a=await o.saveToAssets(t);o.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{o.showToast(r("chain.saveToAssetsFailed"),!0)}break}case"saveAsElement":{try{const a=await o.saveAsElement?.(t);o.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{o.showToast(r("chain.saveToAssetsFailed"),!0)}break}}}function $I(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function qI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function HI(e){return{modelLabel:pl(e.model,e.provider),derivation:$I(e),sourceLabel:qI(e)}}function VI(e){return!e.modelLabel&&!e.derivation}function KI({view:e,size:t="sm"}){const{t:n}=V();return VI(e)?null:s.jsxs("span",{className:`provenance-chip provenance-chip--${t}`,children:[e.modelLabel?s.jsx("span",{className:"provenance-chip__model",children:e.modelLabel}):null,e.derivation?s.jsx("span",{className:"provenance-chip__derivation",children:n(`provenance.${e.derivation}`)}):null]})}function BI({id:e}){switch(e){case"animate":return s.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})});case"edit":return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),s.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]});case"useAsRef":return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),s.jsx("polyline",{points:"17 8 12 3 7 8"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]});case"rebake":return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]});case"saveToAssets":return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),s.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),s.jsx("path",{d:"M10 12h4"})]})}}function WI({item:e,active:t,itemRef:n,onSelect:r,onDelete:o,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=g.useMemo(()=>zI.filter(u=>u.available(e)),[e]),d=g.useCallback(async(u,p)=>{p.stopPropagation(),await UI(u,e,()=>{const h=f.getState();return{animateImage:h.animateImage,openCanvas:h.openCanvas,selectHistory:h.selectHistory,addReferences:h.addReferences,showToast:h.showToast,saveToAssets:h.saveToAssets}},l)},[e,l]),m=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(xe(e)?jn(e):{image:e.url||e.image,filename:e.filename})),u.dataTransfer.effectAllowed="copy"};return s.jsxs("div",{ref:n,className:`gallery__tile-wrap${t?" gallery__tile-wrap--active":""}${e.isFavorite?" gallery__tile-wrap--favorite":""}`,children:[s.jsxs("button",{type:"button",className:`gallery__tile${t?" gallery__tile--active":""}`,onClick:()=>r(e),title:e.prompt??"",draggable:!0,onDragStart:m,children:[xe(e)?s.jsxs("div",{className:"gallery__tile-video-wrap",children:[e.thumb?s.jsx("img",{src:e.thumb,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async",className:"gallery__tile-video"}):s.jsx(Xt,{className:"gallery__tile-video"}),s.jsx("span",{className:"gallery__play-badge","aria-hidden":"true",children:"▶"})]}):s.jsx("img",{src:e.thumb||e.image,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),e.prompt&&s.jsx("div",{className:"gallery__caption",children:s.jsx("span",{className:"gallery__caption-text",children:e.prompt})})]}),c.length>0?s.jsx("div",{className:"gallery__chain-overlay",role:"group","aria-label":l("chain.ariaLabel"),children:c.map(u=>s.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:p=>{d(u.id,p)},title:l(u.labelKey),"aria-label":l(u.labelKey),children:s.jsx(BI,{id:u.id})},u.id))}):null,e.filename&&a&&s.jsx(Sd,{variant:"gallery",active:!!e.isFavorite,busy:i,label:e.isFavorite?l("gallery.unfavoriteAria"):l("gallery.favoriteAria"),onToggle:()=>a(e)}),e.filename&&s.jsx("button",{type:"button",className:"gallery__delete",onClick:u=>o(e,u),title:l("gallery.deleteTitle"),"aria-label":l("gallery.deleteAria"),children:"×"}),s.jsx(KI,{view:HI(e)})]})}function JI(e){return typeof e=="object"?e.key:e}function YI(e,t){const n=e.length;return new Proxy(e,{get(r,o,a){if(typeof o=="string"){const i=o.charCodeAt(0);if(i>=48&&i<=57){const l=+o;if(Number.isInteger(l)&&l>=0&&l<n){let c=r[l];if(typeof c!="object"){const d=t[l*2];c=r[l]={index:l,key:c,start:d,size:t[l*2+1],end:d+t[l*2+1],lane:0}}return c}}if(o==="length")return n}return Reflect.get(r,o,a)}})}function $t(e,t,n){let r=n.initialDeps??[],o,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((d,m)=>r[m]!==d))&&(r=l,o=t(...l),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(o),a=!1),o}return i.updateDeps=l=>{r=l},i}function Mi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const Li=(e,t)=>Math.abs(e-t)<1.01,XI=(e,t,n)=>{let r;return Object.assign(function(...o){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,o),n)},{cancel:()=>{e.clearTimeout(r)}})};let hn;const $o=()=>{if(hn!==void 0)return hn;if(typeof navigator>"u")return hn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return hn=!0;const e=navigator.maxTouchPoints;return hn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Oi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},ZI=e=>e,QI=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,o=new Array(r);for(let a=0;a<r;a++)o[a]=t+a;return o},ew=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const o=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(o(Oi(n)),!r.ResizeObserver)return()=>{};const a=new r.ResizeObserver(i=>{const l=()=>{const c=i[0];if(c?.borderBoxSize){const d=c.borderBoxSize[0];if(d){o({width:d.inlineSize,height:d.blockSize});return}}o(Oi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},$r={passive:!0},tw=typeof window>"u"?!0:"onscrollend"in window,nw=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const o=e.targetWindow;if(!o)return;const a=e.options.useScrollendEvent&&tw;let i=0;const l=a?null:XI(o,()=>t(n(r),!1),e.options.isScrollingResetDelay),c=u=>()=>{i=n(r),l?.(),t(i,u)},d=c(!0),m=c(!1);return r.addEventListener("scroll",d,$r),a&&r.addEventListener("scrollend",m,$r),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",m),l?.cancel()}},rw=(e,t)=>nw(e,t,n=>{const{horizontal:r,isRtl:o}=e.options;return r?n.scrollLeft*(o&&-1||1):n.scrollTop}),ow=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),o=n.options.getItemKey(r);return n.itemSizeCache.get(o)??n.options.estimateSize(r)}if(t?.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}if(!t){const r=n.indexFromElement(e),o=n.options.getItemKey(r),a=n.itemSizeCache.get(o);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},sw=(e,{adjustments:t=0,behavior:n},r)=>{var o,a;(a=(o=r.scrollElement)==null?void 0:o.scrollTo)==null||a.call(o,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},aw=sw;function iw(e,t,n,r){if(t===0)return!1;const o=r(0),a=new Set;let i=0;for(;i<e;){const c=n(i);if(c===o)break;a.add(c),i++}const l=e-i;if(l===0||l>=t)return!1;for(let c=0;c<l;c++)if(r(c)!==n(i+c))return!1;for(let c=l;c<t;c++)if(a.has(r(c)))return!1;return!0}class lw{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache=new Map,this.itemSizeCacheVersion=0,this.laneAssignments=new Map,this.pendingMin=null,this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.pendingScrollAnchor=null,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._intendedScrollOffset=null,this._clampedAdjustment=null,this.elementsCache=new Map,this.now=()=>{var n,r,o;return((o=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:o.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(o=>{o.forEach(a=>{const i=()=>{const l=a.target,c=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);for(const[d,m]of this.elementsCache)if(m===l){this.elementsCache.delete(d);break}return}this.isIndexInRange(c)&&this.shouldMeasureDuringScroll(c)&&this.resizeItem(c,this.options.measureElement(l,a,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(i):i()})}));return{disconnect:()=>{var o;(o=r())==null||o.disconnect(),n=null},observe:o=>{var a;return(a=r())==null?void 0:a.observe(o,{box:"border-box"})},unobserve:o=>{var a;return(a=r())==null?void 0:a.unobserve(o)}}})(),this.range=null,this.setOptions=n=>{var r;const o={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:ZI,rangeExtractor:QI,onChange:()=>{},measureElement:ow,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,anchorTo:"start",followOnAppend:!1,scrollEndThreshold:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",useCachedMeasurements:!1};for(const u in n){const p=n[u];p!==void 0&&(o[u]=p)}const a=this.options;let i=null,l=null,c=!1;if(a!==void 0&&a.enabled&&o.enabled&&o.anchorTo==="end"&&this.scrollElement!==null){const u=a.count,p=o.count,h=this.getMeasurements(),x=((r=this._singleLaneMeasurements)==null?void 0:r.items)??h,S=I=>JI(x[I]),b=u>0?S(0):null,v=u>0?S(u-1):null;if(p!==u||u>0&&p>0&&(o.getItemKey(0)!==b||o.getItemKey(p-1)!==v)){c=!0;const I=u>0?this.getVirtualItemForOffset(this.getScrollOffset())??h[0]:null;I&&(i=[I.key,this.getScrollOffset()-I.start]);const _=o.followOnAppend===!0?"auto":o.followOnAppend||null;_&&p>0&&this.isAtEnd(a.scrollEndThreshold)&&(u===0||o.getItemKey(p-1)!==v)&&(p>u||iw(u,p,S,o.getItemKey))&&(l=_)}}this.options=o,c&&(this.pendingMin=0,this.itemSizeCacheVersion++);let d=!1,m=0;if(i&&this.scrollOffset!==null){const[u,p]=i,h=this.getMeasurements(),{count:x,getItemKey:S}=this.options;let b=0;for(;b<x&&S(b)!==u;)b++;if(b<x){const v=h[b];if(v){const y=Math.max(0,v.start+p);!l&&y!==this.scrollOffset&&(m=y-this.scrollOffset,this.scrollOffset=y,d=!0)}}}(d||l)&&(this.pendingScrollAnchor=[d?i[0]:null,d?i[1]:0,l,m])},this.notify=n=>{var r,o;(o=(r=this.options).onChange)==null||o.call(r,this,n)},this.maybeNotify=$t(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.isScrolling=!1,this.scrollDirection=null,this._iosDeferredAdjustment=0,this._iosTouching=!1,this._iosJustTouchEnded=!1,this._clampedAdjustment=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n,r;const o=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==o){if(this.cleanup(),!o){this.maybeNotify();return}if(this.scrollElement=o,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,l)=>{if(l&&this._intendedScrollOffset===null&&i===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(i-this._intendedScrollOffset)<1.5&&(i=this._intendedScrollOffset),this._intendedScrollOffset=null,this._clampedAdjustment!==null&&Math.abs(i-this._clampedAdjustment.maxAtWrite)>=1.5&&(this._clampedAdjustment=null),this.scrollAdjustments=0;const c=this.getScrollOffset();this.scrollDirection=l?c===i?this.scrollDirection:c<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=l,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const i=this.scrollElement,l=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},c=()=>{this._iosTouching=!1,!(!$o()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};i.addEventListener("touchstart",l,$r),i.addEventListener("touchend",c,$r),this.unsubs.push(()=>{i.removeEventListener("touchstart",l),i.removeEventListener("touchend",c),this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)})}this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}const a=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,a&&this.scrollElement&&this.options.enabled){const[i,l,c,d]=a;i!==null&&!c&&($o()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?d!==0&&(this._iosDeferredAdjustment+=d):((r=this.scrollState)==null?void 0:r.behavior)==="smooth"&&!Li(this.getScrollOffset()-d,this.scrollState.lastTargetOffset)||this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),c&&this.scrollToEnd({behavior:c})}this._retryClampedAdjustment()},this._retryClampedAdjustment=()=>{if(this._clampedAdjustment===null||!this.scrollElement||!this.options.enabled)return;const{target:n,maxAtWrite:r}=this._clampedAdjustment,o=this.getMaxScrollOffset();o>r+.5&&(this._clampedAdjustment=n>o+.5?{target:n,maxAtWrite:o}:null,this._scrollToOffset(n,{adjustments:void 0,behavior:void 0}))},this._flushIosDeferredIfReady=()=>{if(this._iosDeferredAdjustment===0||this.isScrolling||this._iosTouching||this._iosJustTouchEnded)return;const n=this.getScrollOffset(),r=this.getMaxScrollOffset();if(n<0||n>r)return;if(this._iosDeferredAdjustment<0&&n>=r-1){this._iosDeferredAdjustment=0;return}const o=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=o,behavior:void 0})},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getMeasurementOptions=$t(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode,this.options.gap],(n,r,o,a,i,l,c,d)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMin=null,{count:n,paddingStart:r,scrollMargin:o,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d}),{key:!1}),this.isIndexInRange=n=>n>=0&&n<this.options.count,this.getMeasurements=$t(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:o,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d},m)=>{var u;const p=this.itemSizeCache;if(!i)return this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this._singleLaneMeasurements=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const h=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const y=n*2;let w=(u=this._singleLaneMeasurements)==null?void 0:u.flat;if(!w||w.length<y){const j=new Float64Array(y);w&&h>0&&j.set(w.subarray(0,h*2)),w=j}const I=h===0?new Array(n):this._singleLaneMeasurements.items.slice();let _;if(h===0)_=r+o;else{const j=h-1;_=w[j*2]+w[j*2+1]+d}for(let j=h;j<n;j++){const L=a(j);I[j]=L;const q=p.get(L),A=typeof q=="number"?q:this.options.estimateSize(j);w[j*2]=_,w[j*2+1]=A,_+=A+d}this._singleLaneMeasurements={flat:w,items:I};const N=YI(I,w);return this.measurementsCache=N,N}const x=this.measurementsCache.slice(0,h),S=new Array(l).fill(void 0),b=new Float64Array(l);let v=0;for(let y=0;y<h;y++){const w=x[y];w&&(S[w.lane]===void 0&&v++,S[w.lane]=y,b[w.lane]=w.end)}for(let y=h;y<n;y++){const w=a(y),I=this.laneAssignments.get(y);let _,N;const j=c==="estimate"||p.has(w);if(I!==void 0&&this.options.lanes>1){_=I;const G=S[_],C=G!==void 0?x[G]:void 0;N=C?C.end+d:r+o}else if(v===l){let G=0,C=b[0],T=S[0];for(let k=1;k<l;k++){const R=b[k];(R<C||R===C&&S[k]<T)&&(G=k,C=R,T=S[k])}_=G,N=C+d,j&&this.laneAssignments.set(y,_)}else _=y%this.options.lanes,N=r+o,j&&this.laneAssignments.set(y,_);const L=p.get(w),q=typeof L=="number"?L:this.options.estimateSize(y),A=N+q;x[y]={index:y,start:N,size:q,end:A,key:w,lane:_},S[_]===void 0&&v++,S[_]=y,b[_]=A}return this.measurementsCache=x,x},{key:!1,debug:()=>this.options.debug}),this.calculateRange=$t(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,o,a)=>n.length===0||r===0?(this.range=null,null):(this.range=dw(n,r,o,a,a===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=$t(()=>{let n=null,r=null;const o=this.calculateRange();return o&&(n=o.startIndex,r=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,o,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:r,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,o=n.getAttribute(r);return o?parseInt(o,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(o!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,o-a),l=Math.min(this.options.count-1,o+a);return n>=i&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((i,l)=>{i.isConnected||(this.observer.unobserve(i),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n);if(!this.isIndexInRange(r))return;const o=this.options.getItemKey(r),a=this.elementsCache.get(o);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(o,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var o,a,i;if(!this.isIndexInRange(n))return;let l,c,d;const m=(o=this._singleLaneMeasurements)==null?void 0:o.flat;if(this.options.lanes===1&&m!=null)d=this.options.getItemKey(n),c=m[n*2],l=m[n*2+1];else{const h=this.measurementsCache[n];if(!h)return;d=h.key,c=h.start,l=h.size}const u=this.itemSizeCache.get(d)??l,p=r-u;if(p!==0){const h=this.options.anchorTo==="end"&&((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,x=h?this.getTotalSize():0,S=this.getScrollOffset()+this.scrollAdjustments,v=!this.itemSizeCache.has(d)?c<S:c+u<=S&&this.scrollDirection!=="backward",y=((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:d,start:c,size:l,end:c+l,lane:0},p,this):v);(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(d,r),this.itemSizeCacheVersion++;let w=!1;h?w=this.applyScrollAdjustment(this.getTotalSize()-x):y&&(w=this.applyScrollAdjustment(p)),this.notify(w),this._retryClampedAdjustment()}},this.getVirtualItems=$t(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const o=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=r[l];o.push(c)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{var r;const o=this.getMeasurements();if(o.length===0)return;const a=(r=this._singleLaneMeasurements)==null?void 0:r.flat,i=this.options.lanes===1&&a!=null,l=Wd(0,o.length-1,i?c=>a[c*2]:c=>Mi(o[c]).start,n);return Mi(o[l])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getVirtualDistanceFromEnd=()=>Math.max(this.getTotalSize()-this.getSize()-this.getScrollOffset(),0),this.getDistanceFromEnd=()=>Math.max(this.getMaxScrollOffset()-this.getScrollOffset(),0),this.isAtEnd=(n=this.options.scrollEndThreshold)=>this.getDistanceFromEnd()<=n,this.getOffsetForAlignment=(n,r,o=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+a?"end":"start"),r==="center"?n+=(o-a)/2:r==="end"&&(n-=a);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getSize(),a=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=a+o-this.options.scrollPaddingEnd)r="end";else if(i.start<=a+this.options.scrollPaddingStart)r="start";else return[a,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?i.end+this.options.scrollPaddingEnd:i.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,i.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:o="auto"}={})=>{this._iosDeferredAdjustment=0;const a=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:o,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:o="auto"}={})=>{this._iosDeferredAdjustment=0,n=Math.max(0,Math.min(n,this.options.count-1));const a=this.getOffsetForIndex(n,r);if(!a)return;const[i,l]=a,c=this.now();this.scrollState={index:n,align:l,behavior:o,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const o=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.scrollToEnd=({behavior:n="auto"}={})=>{if(this.options.count>0){this.scrollToIndex(this.options.count-1,{align:"end",behavior:n});return}this.scrollToOffset(Math.max(this.getTotalSize()-this.getSize(),0),{behavior:n})},this.getTotalSize=()=>{var n,r;const o=this.getMeasurements();let a;if(o.length===0)a=this.options.paddingStart;else if(this.options.lanes===1){const i=o.length-1,l=(n=this._singleLaneMeasurements)==null?void 0:n.flat;l!=null?a=l[i*2]+l[i*2+1]:a=((r=o[i])==null?void 0:r.end)??0}else{const i=Array(this.options.lanes).fill(null);let l=o.length-1;for(;l>=0&&i.some(c=>c===null);){const c=o[l];i[c.lane]===null&&(i[c.lane]=c.end),l--}a=Math.max(...i.filter(c=>c!==null))}return Math.max(a-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const o of r)o&&this.itemSizeCache.has(o.key)&&n.push({index:o.index,key:o.key,start:o.start,size:o.size,end:o.end,lane:o.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:o})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:o,adjustments:r},this)},this.measure=()=>{this.pendingMin=null,this.itemSizeCache.clear(),this.laneAssignments.clear(),this.itemSizeCacheVersion++,this.notify(!1)},this.setOptions(t)}applyScrollAdjustment(t,n){if(t===0)return!1;if($o()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded))return this._iosDeferredAdjustment+=t,!1;{const r=this.getScrollOffset()+this.scrollAdjustments+t,o=this.scrollElement,a=o!==null&&("scrollHeight"in o||"document"in o)?this.getMaxScrollOffset():null;return this._clampedAdjustment=a!==null&&r>a+.5?{target:r,maxAtWrite:a}:null,this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=t,behavior:n}),this.scrollOffset!==null&&(this.scrollOffset+=this.scrollAdjustments,this.scrollOffset<0&&(this.scrollOffset=0),this.scrollAdjustments=0),!0}}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,o=r?r[0]:this.scrollState.lastTargetOffset,a=1,i=o!==this.scrollState.lastTargetOffset;if(!i&&Li(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==o&&this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(o-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=o,d||(this.scrollState.behavior="auto"),this._scrollToOffset(o,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const Wd=(e,t,n,r)=>{for(;e<=t;){const o=(e+t)/2|0,a=n(o);if(a<r)e=o+1;else if(a>r)t=o-1;else return o}return e>0?e-1:0};function cw(e,t,n){let r=0;for(;r<=t;){const o=(r+t)/2|0,a=e[o*2];if(a<n)r=o+1;else if(a>n)t=o-1;else return o}return r>0?r-1:0}function dw(e,t,n,r,o){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&o!==null){const d=cw(o,a,n);let m=d;const u=n+t;for(;m<a&&o[m*2]+o[m*2+1]<u;)m++;return{startIndex:d,endIndex:m}}let l=Wd(0,a,d=>e[d].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const d=Array(r).fill(0);for(;c<a&&d.some(u=>u<n+t);){const u=e[c];d[u.lane]=u.end,c++}const m=Array(r).fill(n+t);for(;l>=0&&m.some(u=>u>=n);){const u=e[l];m[u.lane]=u.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const qo=typeof document<"u"?g.useLayoutEffect:g.useEffect;function uw({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const o=g.useReducer(u=>u+1,0)[1],a=g.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=g.useRef(!1),l=u=>{const p=a.current;if(!p.enabled||!p.container)return;const h=u.getTotalSize();if(h!==p.lastSize){p.lastSize=h;const x=u.options.horizontal?"width":"height";p.container.style[x]=`${h}px`}},c=u=>{const p=a.current;if(!p.enabled||!p.container)return;l(u);const h=!!u.options.horizontal,x=p.mode==="transform",S=h?"left":"top",b=u.options.scrollMargin,v=u.getVirtualItems();for(const y of v){const w=y.start-b,I=u.elementsCache.get(y.key);I&&p.lastPositions.get(I)!==w&&(p.lastPositions.set(I,w),x?I.style.transform=h?`translate3d(${w}px, 0, 0)`:`translate3d(0, ${w}px, 0)`:I.style[S]=`${w}px`)}},d={...r,onChange:(u,p)=>{var h;const x=a.current;let S=!0;if(x.enabled){c(u);const b=u.range,v=x.prevRange;S=!v||v.isScrolling!==u.isScrolling||v.startIndex!==b?.startIndex||v.endIndex!==b?.endIndex,S&&(x.prevRange=b?{startIndex:b.startIndex,endIndex:b.endIndex,isScrolling:u.isScrolling}:null)}S&&(e&&p&&!i.current?mo.flushSync(o):o()),(h=r.onChange)==null||h.call(r,u,p)}},[m]=g.useState(()=>{const u=new lw(d),p=u.measureElement;return u.measureElement=h=>{i.current=!0;try{p(h)}finally{i.current=!1}},Object.assign(u,{containerRef:h=>{const x=a.current;if(x.container=h,x.lastSize=null,h&&x.enabled){const S=u.getTotalSize();x.lastSize=S;const b=u.options.horizontal?"width":"height";h.style[b]=`${S}px`}}})});return m.setOptions(d),qo(()=>m._didMount(),[]),qo(()=>(l(m),m._willUpdate())),qo(()=>{c(m)}),m}function mw(e){return uw({observeElementRect:ew,observeElementOffset:rw,scrollToFn:aw,...e})}const qr=170,Hr=10,Jd=36,pw=44;function fw(e){const t=Math.max(qr,e-Jd);return Math.max(1,Math.floor((t+Hr)/(qr+Hr)))}function hw(e,t){const n=Math.max(qr,e-Jd);return Math.max(qr,Math.floor((n-Hr*Math.max(0,t-1))/t))+Hr}function gw(e,t){const n=[];for(const[r,o]of e){n.push({type:"header",id:`h-${r}`,label:r,count:o.length});for(let a=0;a<o.length;a+=t)n.push({type:"items",id:`r-${r}-${a}`,items:o.slice(a,a+t)})}return n}function yw({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:o}){const a=g.useRef(null),[i,l]=g.useState(0),c=g.useMemo(()=>fw(i||960),[i]),d=g.useMemo(()=>hw(i||960,c),[i,c]),m=g.useMemo(()=>gw(e,c),[e,c]);g.useEffect(()=>{const p=a.current;if(!p)return;const h=()=>l(p.clientWidth);h();const x=new ResizeObserver(h);return x.observe(p),()=>x.disconnect()},[]);const u=mw({count:m.length,getScrollElement:()=>n,estimateSize:p=>m[p]?.type==="header"?pw:d,overscan:6});return g.useEffect(()=>{if(!t)return;const p=m.findIndex(h=>h.type==="items"&&h.items.some(x=>Te(x)===t));p>=0&&u.scrollToIndex(p,{align:"center"})},[m,t,u]),s.jsx("div",{ref:a,className:"gallery__virtual",style:{height:u.getTotalSize()},children:u.getVirtualItems().map(p=>{const h=m[p.index];return h?s.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${p.start}px)`},children:h.type==="header"?s.jsxs("header",{className:"gallery__group-header gallery__group-header--virtual",children:[s.jsx("span",{className:"gallery__group-label",children:r(h.label)}),s.jsx("span",{className:"gallery__group-count",children:h.count})]}):s.jsx("div",{className:"gallery__grid gallery__grid--virtual",children:h.items.map((x,S)=>o(x,h.id,S))})},h.id):null})})}function Fi({showSessions:e,favoritesOnly:t,query:n,historyNextCursor:r,favoriteHistoryNextCursor:o,historyLoadingOlder:a,favoriteHistoryLoadingOlder:i,onLoadOlder:l,onLoadOlderFavorites:c,t:d}){return e?s.jsx("div",{className:"gallery__load-more gallery__load-more--hint",children:d("gallery.sessionPaginationHint")}):n.trim()?null:t?o?s.jsx("div",{className:"gallery__load-more",children:s.jsx("button",{type:"button",onClick:c,disabled:i,children:d(i?"gallery.loadingOlderFavorites":"gallery.loadOlderFavorites")})}):null:r?s.jsx("div",{className:"gallery__load-more",children:s.jsx("button",{type:"button",onClick:l,disabled:a,children:d(a?"gallery.loadingOlder":"gallery.loadOlder")})}):null}function vw({groups:e,loose:t,favoritesOnly:n,galleryScope:r,setGalleryScope:o,renderTile:a,t:i}){return e.length===0&&t.length===0?s.jsx("div",{className:"gallery__empty",children:n?i("gallery.emptyFavorites"):r==="current-session"?s.jsxs(s.Fragment,{children:[s.jsx("p",{children:i("gallery.empty.currentSession")}),s.jsx("button",{type:"button",onClick:()=>o("all"),children:i("gallery.scope.all")})]}):i("gallery.emptySessions")}):s.jsxs(s.Fragment,{children:[e.map(l=>s.jsxs("section",{className:"gallery__group",children:[s.jsxs("header",{className:"gallery__group-header",children:[s.jsx("span",{className:"gallery__group-label",title:l.sessionId,children:l.title?l.displayLabel:i("gallery.sessionLabel",{name:l.displayLabel})}),s.jsx("span",{className:"gallery__group-count",children:l.items.length})]}),s.jsx("div",{className:"gallery__grid",children:l.items.map((c,d)=>a(c,l.sessionId,d))})]},l.sessionId)),t.length>0&&s.jsxs("section",{className:"gallery__group",children:[s.jsxs("header",{className:"gallery__group-header",children:[s.jsx("span",{className:"gallery__group-label",children:i("gallery.standalone")}),s.jsx("span",{className:"gallery__group-count",children:t.length})]}),s.jsx("div",{className:"gallery__grid",children:t.map((l,c)=>a(l,"loose",c))})]})]})}function bw({status:e,dismissed:t,onOpenFolder:n,onDismiss:r,t:o}){const a=e!=null&&e.state!=="ok"&&!t,i=e?.state==="recoverable"?"gallery.storageNoticeRecoverable":e?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return s.jsxs("div",{className:`gallery__storage-bar${a?" gallery__storage-bar--notice":""}`,children:[a?s.jsxs("div",{className:"gallery__storage-copy",children:[s.jsx("div",{className:"gallery__storage-title",children:o("gallery.storageNoticeTitle")}),s.jsx("div",{className:"gallery__storage-text",children:o(i)})]}):s.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:e?.generatedDirLabel??"~/.ima2/generated"}),s.jsxs("div",{className:"gallery__storage-actions",children:[s.jsx("button",{type:"button",className:"gallery__storage-button",onClick:n,title:o("gallery.openGeneratedDirTitle"),children:o("gallery.openGeneratedDir")}),a&&s.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:r,children:o("common.close")})]})]})}const Di="ima2.storageNoticeDismissed.0.09.23";function xw(e){const t=g.useRef(null),n=g.useRef(new Map),[r,o]=g.useState(()=>new Set);g.useEffect(()=>{if(!e||typeof IntersectionObserver>"u")return;const i=new IntersectionObserver(l=>{const c=l.filter(d=>d.isIntersecting);c.length!==0&&o(d=>{const m=new Set(d);for(const u of c){const p=u.target.dataset.galleryLazyKey;p&&m.add(p)}return m})},{root:e,rootMargin:"200% 0px"});t.current=i;for(const l of n.current.values())i.observe(l);return()=>{i.disconnect(),t.current=null}},[e]);const a=g.useCallback((i,l)=>{const c=n.current.get(i);c&&c!==l&&t.current?.unobserve(c),l?(n.current.set(i,l),t.current?.observe(l)):n.current.delete(i)},[]);return{visibleKeys:r,register:a,supported:typeof IntersectionObserver<"u"}}function Sw(){const{t:e,locale:t}=V(),n=f(M=>M.galleryOpen),r=f(M=>M.closeGallery),o=f(M=>M.history),a=f(M=>M.selectHistory),i=f(M=>M.currentImage),l=f(M=>M.trashHistoryItem),c=f(M=>M.showToast),d=f(M=>M.toggleGalleryFavorite),m=f(M=>M.galleryScope),u=f(M=>M.setGalleryScope),p=f(M=>M.historyNextCursor),h=f(M=>M.historyLoadingOlder),x=f(M=>M.favoriteHistoryNextCursor),S=f(M=>M.favoriteHistoryLoadingOlder),b=f(M=>M.loadOlderHistory),v=f(M=>M.loadFavoriteHistory),y=f(M=>M.loadOlderFavoriteHistory),w=f(Yp),[I,_]=g.useState(""),[N,j]=g.useState("date"),[L,q]=g.useState(!1),[A,G]=g.useState(()=>new Set),C=g.useRef(new Set),[T,k]=g.useState([]),[R,B]=g.useState([]),[se,oe]=g.useState(!1),[ae,ge]=g.useState(!1),[D,F]=g.useState(!1),[ee,J]=g.useState(0),[me,ye]=g.useState(null),[ie,ke]=g.useState(()=>{try{return localStorage.getItem(Di)==="1"}catch{return!1}}),le=g.useRef(null),Ie=g.useRef({}),[je,Re]=g.useState(null),ce=g.useRef(0),be=g.useRef({open:!1,selectedKey:null}),z=g.useMemo(()=>wr(o.filter(In)),[o]),ve=g.useCallback(M=>{le.current=M,Re(M)},[]),P=xw(je),ne=Ge(n,r);g.useEffect(()=>{n||_("")},[n]),g.useEffect(()=>{if(!n)return;let M=!1;return(async()=>{try{const Y=await Gu();M||ye(Y)}catch{M||ye({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{M=!0}},[n]),g.useEffect(()=>{if(!n||N!=="session")return;let M=!1;return k([]),B([]),oe(!0),ge(!1),F(!1),(async()=>{try{const Y=await Fu({limit:500,sessionId:m==="current-session"?w:void 0});if(M)return;F(Y.nextCursor!==null||Y.total>=500);const _e=H=>{const pe=H.kind,lt=pe==="classic"||pe==="edit"||pe==="generate"||pe==="card-news-card"||pe==="card-news-set"?pe:null,ga=H.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(H.filename??"");return{image:H.url,url:H.url,filename:H.filename,thumb:H.thumb??(ga?void 0:H.url),mediaType:H.mediaType,video:H.video??null,videoSeries:H.videoSeries??null,videoContinuity:H.videoContinuity??null,prompt:H.prompt??void 0,userPrompt:H.userPrompt??null,revisedPrompt:H.revisedPrompt??null,promptMode:H.promptMode??null,composerPrompt:H.composerPrompt??null,composerInsertedPrompts:H.composerInsertedPrompts??null,size:H.size??void 0,quality:H.quality??void 0,format:H.format,moderation:H.moderation??void 0,model:H.model??void 0,reasoningEffort:H.reasoningEffort,provider:H.provider,providerUrl:H.providerUrl??null,usage:H.usage,elapsed:H.elapsed??void 0,createdAt:H.createdAt,sessionId:H.sessionId??null,nodeId:H.nodeId??null,parentNodeId:H.parentNodeId??null,clientNodeId:H.clientNodeId??null,requestId:H.requestId??null,kind:lt,setId:H.setId??null,cardId:H.cardId??null,cardOrder:H.cardOrder??null,headline:H.headline??null,body:H.body??null,cards:H.cards,refsCount:H.refsCount??0,webSearchCalls:H.webSearchCalls??0,sequenceId:H.sequenceId??null,sequenceIndex:H.sequenceIndex??null,sequenceTotalRequested:H.sequenceTotalRequested??null,sequenceTotalReturned:H.sequenceTotalReturned??null,sequenceStatus:H.sequenceStatus??null,isFavorite:H.isFavorite??!1}};k(Y.sessions.map(H=>({sessionId:H.sessionId,title:H.title??null,label:H.label??null,displayLabel:H.title||H.label||H.sessionId.slice(0,8),items:wr(H.items.filter(In).map(_e))})).filter(H=>H.items.length>0)),B(wr(Y.loose.filter(In).map(_e)))}catch{M||ge(!0)}finally{M||oe(!1)}})(),()=>{M=!0}},[n,N,m,w,ee]),g.useEffect(()=>{!n||N==="session"||!L||v()},[n,N,L,v]);const de=g.useMemo(()=>{const M=I.trim().toLowerCase().normalize("NFC");return z.filter(Y=>L&&!Y.isFavorite?!1:M?(Y.prompt??"").toLowerCase().normalize("NFC").includes(M)||(Y.filename??"").toLowerCase().normalize("NFC").includes(M):!0)},[z,I,L]),K=g.useMemo(()=>L?T.map(M=>({...M,items:M.items.filter(Y=>Y.isFavorite)})).filter(M=>M.items.length>0):T,[T,L]),U=g.useMemo(()=>L?R.filter(M=>M.isFavorite):R,[R,L]),X=g.useMemo(()=>{const M=new Map;for(const Y of de){const _e=LI(Y.createdAt,t);M.has(_e)||M.set(_e,[]),M.get(_e).push(Y)}return Array.from(M.entries())},[de,t]),re=N==="session"?K.reduce((M,Y)=>M+Y.items.length,0)+U.length:de.length;g.useLayoutEffect(()=>{const M=i?Te(i):null;if(!n){be.current={open:!1,selectedKey:M};return}const Y=be.current,_e=!Y.open||Y.selectedKey!==M;be.current={open:!0,selectedKey:M};const H=M?Ie.current[M]:null;if(_e&&H){H.scrollIntoView({block:"center"});return}le.current&&(le.current.scrollTop=ce.current)},[n,i?.filename,i?.image,N,re,X.length,K.length,U.length]);async function Oe(M,Y){Y.stopPropagation();const _e=Te(M);await l(M),delete Ie.current[_e],window.requestAnimationFrame(()=>le.current?.focus())}async function ze(M){const Y=M.filename;if(!(!Y||C.current.has(Y))){C.current.add(Y),G(new Set(C.current));try{const _e=await d(M);if(_e===null)return;k(H=>H.map(pe=>({...pe,items:pe.items.map(lt=>lt.filename===Y?{...lt,isFavorite:_e}:lt)}))),B(H=>H.map(pe=>pe.filename===Y?{...pe,isFavorite:_e}:pe))}finally{C.current.delete(Y),G(new Set(C.current))}}}async function Gt(){try{await zu(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Je,handleCopyCardNewsSetPath:pt,handleDownloadCardNewsManifest:ft}=OI(r,c,e);function xt(){ke(!0);try{localStorage.setItem(Di,"1")}catch{}}if(!n)return null;const E=M=>M==="earlier"||M==="today"||M==="yesterday"||M==="thisWeek"?e(`gallery.${M}`):M,W=(M,Y,_e)=>{const H=i?.image===M.image,pe=Te(M),lt=zt=>{Ie.current[pe]=zt,P.register(pe,zt)};return(P.supported?P.visibleKeys.has(pe):!0)?M.kind==="card-news-set"?s.jsx("div",{ref:lt,className:"gallery__tile-wrap gallery-card-news-set",children:s.jsx(GI,{item:M,onOpen:zt=>{Je(zt)},onCopyPath:pt,onDownloadManifest:ft})},`${Y}-${pe}`):s.jsx(WI,{item:M,active:H,itemRef:lt,onSelect:zt=>{a(zt),r()},onDelete:Oe,onToggleFavorite:ze,favoriteBusy:!!(M.filename&&A.has(M.filename)),t:e},`${Y}-${pe}`):s.jsx("div",{ref:lt,className:"gallery__tile-wrap","data-gallery-lazy-key":pe,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Y}-${pe}`)},Q=N==="session",we=i?Te(i):null;return s.jsx("div",{className:"gallery-backdrop",onClick:r,role:"presentation",children:s.jsxs("div",{ref:ne,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:M=>M.stopPropagation(),children:[s.jsxs("div",{className:"gallery__header",children:[s.jsxs("div",{className:"gallery__title-row",children:[s.jsx("div",{className:"gallery__title",children:e("gallery.title")}),s.jsxs("div",{className:"gallery__meta",children:[e("gallery.total",{n:re}),I||L?e("gallery.totalFiltered",{n:z.length}):""]}),s.jsx(Uo,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:L?"favorites":"all",onChange:M=>q(M==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),s.jsx(Uo,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:N,onChange:j,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),s.jsx(Uo,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:m,onChange:u,tabs:[{value:"current-session",label:e("gallery.scope.current"),disabled:!w},{value:"all",label:e("gallery.scope.all")}]})]}),s.jsx("input",{type:"text",className:"gallery__search",...Q?{}:{"data-modal-initial-focus":!0},placeholder:e(Q?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:I,onChange:M=>_(M.target.value),disabled:Q}),s.jsx("button",{type:"button",className:"gallery__close",onClick:r,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),s.jsx(bw,{status:me,dismissed:ie,onOpenFolder:Gt,onDismiss:xt,t:e}),s.jsx("div",{className:"gallery__scroll",ref:ve,tabIndex:-1,onScroll:()=>{ce.current=le.current?.scrollTop??0},children:Q?se?s.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):ae?s.jsxs("div",{className:"gallery__empty",role:"alert",children:[s.jsx("span",{children:e("gallery.sessionLoadFailed")}),s.jsx("button",{type:"button",onClick:()=>J(M=>M+1),children:e("gallery.retry")})]}):s.jsxs(s.Fragment,{children:[D?s.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,s.jsx(vw,{groups:K,loose:U,favoritesOnly:L,galleryScope:m,setGalleryScope:u,renderTile:W,t:e}),s.jsx(Fi,{showSessions:Q,favoritesOnly:L,query:I,historyNextCursor:p,favoriteHistoryNextCursor:x,historyLoadingOlder:h,favoriteHistoryLoadingOlder:S,onLoadOlder:()=>{b()},onLoadOlderFavorites:()=>{y()},t:e})]}):de.length===0?s.jsx("div",{className:"gallery__empty",children:z.length===0?e("gallery.emptyAll"):e(L?"gallery.emptyFavorites":"gallery.noResults")}):s.jsxs(s.Fragment,{children:[s.jsx(yw,{dateGroups:X,selectedKey:we,scrollElement:je,localizeBucket:E,renderTile:W}),s.jsx(Fi,{showSessions:Q,favoritesOnly:L,query:I,historyNextCursor:p,favoriteHistoryNextCursor:x,historyLoadingOlder:h,favoriteHistoryLoadingOlder:S,onLoadOlder:()=>{b()},onLoadOlderFavorites:()=>{y()},t:e})]})})]})})}function Iw(e){return e.includes("ratio")?"sizeConfirm.reasonRatio":e.includes("maxPixels")||e.includes("pixels")?"sizeConfirm.reasonPixels":e.includes("minPixels")?"sizeConfirm.reasonMinPixels":e.includes("min")?"sizeConfirm.reasonMin":e.includes("maxEdge")||e.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function ww(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=V(),o=Ge(!!e,n);if(!e)return null;const a=`${e.requestedW}x${e.requestedH}`,i=`${e.adjustedW}x${e.adjustedH}`;return s.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:s.jsxs("div",{ref:o,className:"modal custom-size-confirm",role:"dialog","aria-modal":"true","aria-labelledby":"custom-size-confirm-title","aria-describedby":"custom-size-confirm-body",tabIndex:-1,children:[s.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:r("sizeConfirm.title")}),s.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[s.jsx("p",{children:r("sizeConfirm.body")}),s.jsxs("dl",{className:"size-confirm__pairs",children:[s.jsxs("div",{className:"size-confirm__pair",children:[s.jsx("dt",{children:r("sizeConfirm.requested")}),s.jsx("dd",{children:a})]}),s.jsxs("div",{className:"size-confirm__pair",children:[s.jsx("dt",{children:r("sizeConfirm.adjusted")}),s.jsx("dd",{children:i})]})]}),s.jsx("p",{className:"size-confirm__reason",children:r(Iw(e.reasons))})]}),s.jsxs("div",{className:"modal__actions",children:[s.jsx("button",{type:"button","data-modal-initial-focus":!0,className:"modal__btn modal__btn--secondary",onClick:n,children:r("sizeConfirm.cancel")}),s.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{t()},children:r("sizeConfirm.approve")})]})]})})}function pr(e){return e==null||e===""?"-":String(e)}function _w(){const{t:e}=V(),t=f(c=>c.metadataRestore),n=f(c=>c.applyMetadataRestore),r=f(c=>c.addMetadataRestoreAsReference),o=f(c=>c.cancelMetadataRestore),a=Ge(!!t,o);if(!t)return null;const i=t.metadata,l=i.userPrompt||i.prompt||i.revisedPrompt||"";return s.jsx("div",{className:"modal-backdrop metadata-restore-backdrop",role:"presentation",children:s.jsxs("div",{ref:a,className:"modal metadata-restore",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-restore-title",tabIndex:-1,children:[s.jsx("div",{id:"metadata-restore-title",className:"modal__title",children:e("metadata.restoreTitle")}),s.jsxs("div",{className:"modal__body metadata-restore__body",children:[s.jsx("p",{children:e("metadata.restoreBody")}),s.jsxs("div",{className:"metadata-restore__preview",children:[s.jsx("img",{src:t.image,alt:e("metadata.imageAlt")}),s.jsxs("div",{className:"metadata-restore__details",children:[s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.prompt")}),s.jsx("strong",{title:l,children:pr(l)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.size")}),s.jsx("strong",{children:pr(i.size)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.quality")}),s.jsx("strong",{children:pr(i.quality)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.model")}),s.jsx("strong",{children:pr(i.model)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.source")}),s.jsx("strong",{children:t.source==="png-comment"?e("metadata.sourcePngComment"):e("metadata.sourceXmp")})]})]})]})]}),s.jsxs("div",{className:"modal__actions",children:[s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:o,"data-modal-initial-focus":!0,children:e("common.cancel")}),s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:r,children:e("metadata.useAsReferenceOnly")}),s.jsx("button",{type:"button",className:"modal__btn",onClick:n,children:e("metadata.applySettings")})]})]})})}const Ew=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function At(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Bt(e){return!e||typeof e!="object"||Array.isArray(e)?At():e}function us(e){return typeof e!="string"||!e.trim()?At():e}function Yd(e){return e===void 0?{}:typeof e!="boolean"?At():{executable:e}}function Nw(e){const t=Bt(e),n=Bt(t.status);return typeof t.enabled!="boolean"||!Ew.has(n.state)?At():{id:us(t.id),enabled:t.enabled,...Yd(t.executable),status:{state:n.state}}}function Gi(e){return Array.isArray(e)?e.map(t=>{const n=Bt(t);return{id:us(n.id),label:us(n.label),...Yd(n.executable)}}):At()}function zi(e,t){const n=Bt(e);if(n.ok!==!0||!Array.isArray(n.providers))return At();const r=n.providers.map(Nw);if(t===null)return{providers:r,catalog:null};const o=Bt(t),a=Bt(o.models);return o.ok!==!0?At():{providers:r,catalog:{image:Gi(a.image),video:Gi(a.video)}}}function kw(e,t){const n=e.selection.provider===t.provider&&e.selection.model===t.model&&e.selection.kind===t.kind,r=(i,l=t.model)=>({...t,code:i,modelLabel:l,observedAt:n?e.observedAt:null});if(!n||e.phase==="loading")return r("loading");if(e.phase==="error")return r("error");const o=e.providers.find(i=>i.id===t.provider);if(!o)return r("missing");if(!o.enabled)return r("disabled");if(o.status.state!=="connected")return r("disconnected");if(o.executable===!1)return r("locked");if(t.model===null)return r("default",null);const a=e.catalog?.[t.kind].find(i=>i.id===t.model);return a?r(a.executable===!1?"model-locked":"ready",a.label||a.id):r("model-missing")}function jw(){const{t:e}=V(),t=f(m=>m.mcpProvider??""),n=f(m=>m.mcpModel??null),r=f(m=>m.mcpMediaKind??"image"),[o,a]=g.useState(0),[i,l]=g.useState({selection:{provider:t,model:n,kind:r},phase:"loading",observedAt:null,providers:[],catalog:null});if(g.useEffect(()=>{const m=new AbortController,u={provider:t,model:n,kind:r};return l({selection:u,phase:"loading",observedAt:null,providers:[],catalog:null}),t&&(async()=>{try{const h=await jg(m.signal),S=zi(h,null).providers.find(y=>y.id===t),b=S?.enabled&&S.status.state==="connected"&&S.executable!==!1&&n!==null?await Cg(t,m.signal):null,v=zi(h,b);m.signal.aborted||l({...v,selection:u,phase:"ready",observedAt:Date.now()})}catch{m.signal.aborted||l({selection:u,phase:"error",observedAt:null,providers:[],catalog:null})}})(),()=>m.abort()},[t,n,r,o]),!t)return null;const c=kw(i,{provider:t,model:n,kind:r}),d=`readiness.mcp.${c.code}`;return s.jsxs("div",{className:"provider-readiness__body","data-mcp-readiness":c.code,"aria-busy":c.code==="loading",children:[s.jsx("p",{role:"status","aria-live":"polite",children:s.jsx("strong",{children:e(d)})}),s.jsxs("dl",{className:"provider-readiness__facts",children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.provider")}),s.jsxs("dd",{children:[t," · MCP"]})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.model")}),s.jsx("dd",{style:{minWidth:0,overflowWrap:"anywhere"},children:c.modelLabel??e("readiness.mcp.default")})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colKind")}),s.jsx("dd",{children:e(r==="video"?"grokMode.video":"grokMode.image")})]})]}),c.observedAt!==null?s.jsx("small",{children:e("readiness.mcp.observed",{time:new Date(c.observedAt).toLocaleTimeString()})}):null,s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:()=>a(m=>m+1),children:e("readiness.mcp.refresh")})]})}const Ui={oauth:"GPT OAuth",api:"GPT API",grok:"Grok OAuth","grok-api":"Grok API",agy:"Gemini","gemini-api":"Gemini API",atlascloud:"Atlas Cloud",minimax:"MiniMax",nai:"NovelAI",comfy:"ComfyUI"};function Cw(){const{t:e}=V(),t=f(_=>_.readinessPopupOpen),n=f(_=>_.closeReadinessPopup),r=f(_=>_.openSettings),o=f(_=>_.provider),a=f(_=>_.mcpProvider??null),i=f(_=>_.imageModel),l=f(_=>_.reasoningEffort),c=f(_=>_.webSearchEnabled),d=f(_=>_.comfyWorkflow),m=f(_=>_.comfyVideoWorkflow),u=Gd(),p=Wn(),h=o==="grok",x=Ke.find(_=>_.value===i),S=Ge(t,n);if(!t)return null;const b=u[o],v=Ct(p,{comfyWorkflow:d,comfyVideoWorkflow:m}),y=o==="comfy"&&!a,w=y?v.selectedAvailable:b.ok,I=()=>{n(),r("providers")};return s.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:n,role:"presentation",children:s.jsxs("div",{ref:S,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:_=>_.stopPropagation(),children:[s.jsx("div",{id:"provider-readiness-title",className:"modal__title",children:e("readiness.title")}),s.jsxs("div",{className:"modal__body provider-readiness__body",children:[a?s.jsx(jw,{}):null,!a&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`provider-readiness__status${w?" is-ok":" is-blocked"}`,children:[s.jsx("span",{"aria-hidden":"true"}),s.jsx("strong",{children:e(y?Yt(v,p):w?"readiness.ready":"readiness.blocked")}),s.jsx("small",{children:y?e("comfy.display.controlsHelp"):w?e("readiness.readyBody"):b.reason})]}),!y&&b.hint?s.jsx("p",{className:"modal__hint",children:b.hint}):null,y?s.jsxs("dl",{className:"provider-readiness__facts",children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.provider")}),s.jsx("dd",{children:Ui.comfy})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.workflowsTitle")}),s.jsx("dd",{children:v.selected?.label??e("comfy.display.chooseWorkflow")})]}),v.selected?s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colId")}),s.jsx("dd",{children:v.selected.id})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colKind")}),s.jsx("dd",{children:e(v.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage")})]})]}):null,p.observedAt!==null?s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colStatus")}),s.jsx("dd",{children:e("comfy.display.lastChecked",{time:new Date(p.observedAt).toLocaleTimeString()})})]}):null]}):s.jsxs("dl",{className:"provider-readiness__facts",children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.provider")}),s.jsx("dd",{children:Ui[o]??"GPT API"})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.model")}),s.jsx("dd",{children:x?e(x.fullLabelKey):i})]}),h?s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.grokApi")}),s.jsx("dd",{children:e("readiness.grokApiBody")})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.reasoning")}),s.jsx("dd",{children:l})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.webSearch")}),s.jsx("dd",{children:e(c?"settings.webSearch.on":"settings.webSearch.off")})]})]})]})]})]}),s.jsxs("div",{className:"modal__actions",children:[s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:n,"data-modal-initial-focus":!0,children:e("common.close")}),s.jsx("button",{type:"button",className:"modal__btn",onClick:I,children:e(y?"comfy.display.manage":"readiness.openAccount")})]})]})})}function Aw(){try{return localStorage.getItem(Al)==="1"}catch{return!1}}function Ho({num:e,current:t,title:n,hint:r}){return s.jsxs("li",{className:t?"onboarding__step is-current":"onboarding__step","aria-current":t?"step":void 0,children:[s.jsx("span",{className:"onboarding__step-num","aria-hidden":"true",children:e}),s.jsxs("span",{children:[s.jsx("span",{className:"onboarding__step-title",children:n}),s.jsx("span",{className:"onboarding__step-hint",children:r})]})]})}function Vo({title:e,body:t,badge:n,primary:r,onChoose:o}){return s.jsxs("button",{type:"button",className:r?"onboarding__choice onboarding__choice--primary":"onboarding__choice",onClick:o,"data-modal-initial-focus":r?!0:void 0,children:[s.jsxs("span",{className:"onboarding__choice-head",children:[s.jsx("span",{children:e}),n?s.jsx("span",{className:"onboarding__badge",children:n}):null]}),s.jsx("span",{className:"onboarding__choice-body",children:t})]})}function Tw(){const{t:e}=V(),t=f(I=>I.openSettings),n=f(I=>I.settingsOpen),r=Od(),o=Fd(),{data:a}=Dd(),[i,l]=g.useState(Aw),[c,d]=g.useState(!1),m=r!==null&&o!==null&&a!=null,u=r?.status==="auth_required"||r?.status==="offline",p=o?.status==="offline"||o?.status==="error",h=a?!a.gemini?.configured&&!a.vertex?.configured:!1,S=!i&&!c&&!n&&(m&&u&&p&&h),b=()=>{try{localStorage.setItem(Al,"1")}catch{}l(!0)},v=()=>d(!0),y=()=>{b(),t("providers")},w=Ge(S,v);return S?s.jsx("div",{className:"modal-backdrop onboarding-backdrop",role:"presentation",onClick:I=>{I.target===I.currentTarget&&v()},children:s.jsxs("div",{ref:w,className:"modal onboarding",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[s.jsxs("section",{className:"onboarding__intro",children:[s.jsx(Kr,{className:"onboarding__mark"}),s.jsx("h2",{id:"onboarding-title",className:"onboarding__title",children:e("onboarding.title")}),s.jsx("p",{className:"onboarding__lead",children:e("onboarding.lead")}),s.jsxs("ol",{className:"onboarding__steps","aria-label":e("onboarding.stepsLabel"),children:[s.jsx(Ho,{num:1,current:!0,title:e("onboarding.steps.signIn.title"),hint:e("onboarding.steps.signIn.hint")}),s.jsx(Ho,{num:2,title:e("onboarding.steps.firstImage.title"),hint:e("onboarding.steps.firstImage.hint")}),s.jsx(Ho,{num:3,title:e("onboarding.steps.star.title"),hint:e("onboarding.steps.star.hint")})]})]}),s.jsxs("section",{className:"onboarding__pick",children:[s.jsxs("div",{className:"onboarding__choices",children:[s.jsx(Vo,{primary:!0,title:e("onboarding.choices.chatgpt.title"),body:e("onboarding.choices.chatgpt.body"),badge:e("onboarding.recommended"),onChoose:y}),s.jsx(Vo,{title:e("onboarding.choices.grok.title"),body:e("onboarding.choices.grok.body"),onChoose:y}),s.jsx(Vo,{title:e("onboarding.choices.apiKey.title"),body:e("onboarding.choices.apiKey.body"),onChoose:y})]}),s.jsxs("div",{className:"onboarding__footer",children:[s.jsx("p",{className:"onboarding__privacy",children:e("onboarding.privacy")}),s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:b,children:e("onboarding.skip")})]})]})]})}):null}const pa="/api/github/star",Pw="https://api.github.com/repos/lidge-ai/ima2-gen";function Rw(){return $(pa)}async function Mw(){return(await Se(pa,{method:"POST"})).ok}async function Lw(){await Se(`${pa}/dismiss`,{method:"POST"})}async function Ow(){try{const e=await fetch(Pw,{credentials:"omit",referrerPolicy:"no-referrer"});if(!e.ok)return null;const t=await e.json();return typeof t.stargazers_count=="number"?t.stargazers_count:null}catch{return null}}function Xd(e,t){return!e||e.mediaType==="video"?!1:typeof e.createdAt=="number"&&e.createdAt>=t}function Fw(e){const{status:t}=e;return!t||t.prompted||t.state==="starred"||e.settingsOpen||e.readinessOpen?!1:Xd(e.head,e.mountedAt)}const Dw=1800;function Gw(){const{t:e}=V(),t=f(N=>N.history[0]??null),n=f(N=>N.settingsOpen),r=f(N=>N.readinessPopupOpen),o=g.useRef(Date.now()),a=g.useRef(!1),[i,l]=g.useState(null),[c,d]=g.useState(!1),[m,u]=g.useState("ask"),[p,h]=g.useState(null),x=t?{createdAt:t.createdAt,mediaType:t.mediaType}:null,S=Xd(x,o.current);g.useEffect(()=>{a.current||!S||(a.current=!0,Rw().then(l).catch(()=>{}))},[S]),g.useEffect(()=>{c||!Fw({status:i,head:x,mountedAt:o.current,settingsOpen:n,readinessOpen:r})||(d(!0),Ow().then(h))},[i,t,n,r,c]),g.useEffect(()=>{if(m!=="thanks")return;const N=setTimeout(()=>d(!1),Dw);return()=>clearTimeout(N)},[m]);const b=()=>{d(!1),l(N=>N&&{...N,prompted:!0})},v=()=>{b(),m!=="thanks"&&Lw().catch(()=>{})},y=Ge(c,v);if(!c||!i)return null;const w=i.state!=="unauthenticated",I=async()=>{u("starring");const N=await Mw().catch(()=>!1);u(N?"thanks":"failed"),N&&l({...i,state:"starred",prompted:!0})},_=()=>{window.open(i.url,"_blank","noopener"),v()};return s.jsx("div",{className:"modal-backdrop star-prompt-backdrop",role:"presentation",children:s.jsxs("div",{ref:y,className:"modal star-prompt",role:"dialog","aria-modal":"true","aria-labelledby":"star-prompt-title",tabIndex:-1,children:[s.jsx(Kr,{className:"star-prompt__mark"}),s.jsx("div",{id:"star-prompt-title",className:"modal__title star-prompt__title",children:e(m==="thanks"?"starPrompt.thanks":"starPrompt.title")}),s.jsx("div",{className:"modal__body",children:s.jsx("p",{children:e("starPrompt.body")})}),s.jsxs("div",{className:"star-prompt__repo",children:[s.jsx("span",{children:i.repo}),p!==null?s.jsx("span",{className:"star-prompt__count",children:e("starPrompt.count",{count:p})}):null]}),m==="failed"?s.jsx("p",{className:"star-prompt__note",role:"alert",children:e("starPrompt.failed")}):null,s.jsxs("div",{className:"modal__actions star-prompt__actions",children:[w&&m!=="failed"?s.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{I()},disabled:m!=="ask","data-modal-initial-focus":!0,children:e(m==="starring"?"starPrompt.starring":"starPrompt.star")}):s.jsx("button",{type:"button",className:"modal__btn",onClick:_,"data-modal-initial-focus":!0,children:e("starPrompt.open")}),s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:v,children:e("starPrompt.notNow")})]}),s.jsx("p",{className:"star-prompt__note",children:e(w?"starPrompt.noteGh":"starPrompt.noteSignIn")})]})})}function zw(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=V(),[o,a]=g.useState(Date.now());return g.useEffect(()=>{if(!e)return;a(Date.now());const i=window.setInterval(()=>{const l=Date.now();a(l),l>=e.expiresAt&&n()},500);return()=>window.clearInterval(i)},[n,e]),e?s.jsxs("div",{className:"trash-undo-toast",children:[s.jsx("span",{children:r("gallery.deleted",{filename:e.filename})}),s.jsx("button",{type:"button",onClick:()=>{t()},children:r("gallery.undo")}),s.jsx("span",{className:"trash-undo-toast__timer",children:r("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((e.expiresAt-o)/1e3))})})]}):null}function Uw(){return s.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("line",{x1:"4",y1:"6",x2:"14",y2:"6"}),s.jsx("circle",{cx:"17",cy:"6",r:"2.2"}),s.jsx("line",{x1:"4",y1:"12",x2:"8",y2:"12"}),s.jsx("circle",{cx:"11",cy:"12",r:"2.2"}),s.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),s.jsx("line",{x1:"4",y1:"18",x2:"14",y2:"18"}),s.jsx("circle",{cx:"17",cy:"18",r:"2.2"})]})}function $w(){const e=f(d=>d.composeSheetOpen),t=f(d=>d.composeSheetTab),n=f(d=>d.openComposeSheet),r=f(d=>d.settingsOpen),o=f(d=>d.uiMode),{t:a}=V();if(!mt()||r||o==="home"||o==="card-news"||o==="agent"||o==="assets"||o==="asset-gen")return null;const l=e&&t==="controls",c=a("sheet.controlsOpen");return s.jsx("button",{type:"button",className:"mobile-settings-toggle","aria-expanded":l,"aria-controls":"mobile-generate-sheet","aria-label":c,title:c,onClick:()=>n("controls"),children:s.jsx(Uw,{})})}let Vr=null;function qw(e){Vr=e}function Hw(){const e=Vr;Vr=null,e?.isConnected&&e.focus()}function $i(){Vr=null}function Vw(){const{t:e}=V(),t=f(m=>m.openComposeSheet),n=f(m=>m.settingsOpen),r=f(m=>m.uiMode),o=r==="agent"&&nn?"agent":r==="node"&&tn?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=mt(),i=g.useRef(null),l=g.useRef(null),c=g.useRef(null),d=(m,u)=>{u.current&&qw(u.current),t(m==="library"?"library":m==="controls"?"controls":"prompt")};return!a||n||o!=="classic"?null:s.jsxs("header",{className:"mobile-app-bar",role:"banner",children:[s.jsxs("div",{className:"mobile-app-bar__brand",children:[s.jsx(Kr,{className:"logo-mark"}),s.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[s.jsx("span",{className:"mobile-app-bar__title",children:e("appBar.brand")}),s.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),s.jsxs("div",{className:"mobile-app-bar__actions",children:[s.jsx("button",{ref:i,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>d("library",i),"aria-label":e("promptLibrary.title"),title:e("promptLibrary.title"),children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),s.jsx("button",{ref:l,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>d("controls",l),"aria-label":e("appBar.controls"),title:e("appBar.controls"),children:s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),s.jsx("button",{ref:c,type:"button",className:"mobile-app-bar__generate",onClick:()=>d("prompt",c),"aria-label":e("appBar.generateAria"),title:e("appBar.generate"),style:{width:44,padding:0},children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),s.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]}),s.jsx("div",{className:"mobile-app-bar__selection",children:s.jsx(Cd,{compact:!0})})]})}const Kw={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},qi={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function Bw(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=Kw[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function Ww(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),s.jsx("path",{d:"m21 15-5-5L5 21"})]})}function Jw(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),s.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})}function Yw(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"2",y:"6",width:"8",height:"6",rx:"1"}),s.jsx("rect",{x:"14",y:"12",width:"8",height:"6",rx:"1"}),s.jsx("path",{d:"M10 9h4"}),s.jsx("path",{d:"M14 15V9a2 2 0 0 1 2-2h0"})]})}function Xw(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(-30 12 12)"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(30 12 12)"})]})}function Zd(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Zw(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("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"}),s.jsx("path",{d:"M8 12h8"})]})}function Qw(){return s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{x:"3",y:"3",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M3 12l3.5-3.5a1.4 1.4 0 0 1 2 0L13 13"}),s.jsx("path",{d:"M19 14v6"}),s.jsx("path",{d:"M16 17h6"})]})}const e_=[{id:"home",mode:"home",icon:Jw,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:Ww,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:Yw,labelKey:"nav.node",enabled:tn},{id:"agent",mode:"agent",icon:Xw,labelKey:"nav.agent",enabled:nn},{id:"assets",mode:"assets",icon:Zw,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:Qw,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:Zd,labelKey:"nav.settings",enabled:!0,bottom:!0}];function t_(){const{t:e}=V(),t=f(S=>S.uiMode),n=f(S=>S.setUIMode),r=f(S=>S.settingsOpen),o=f(S=>S.openSettings),a=f(S=>S.closeSettings),i=mt(),l=g.useRef(null),c=g.useCallback(S=>{const b=l.current;if(!b||!S)return;const v=b.getBoundingClientRect(),y=S.getBoundingClientRect();y.left<v.left?b.scrollLeft-=v.left-y.left:y.right>v.right&&(b.scrollLeft+=y.right-v.right)},[]);g.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=g.useCallback(S=>{if(S.settingsAction){r?(a(),history.replaceState(null,"",qi[t]||"#create")):(o(),history.replaceState(null,"","#settings"));return}S.mode&&(r&&a(),n(S.mode),history.replaceState(null,"",qi[S.mode]||"#create"))},[t,r,n,o,a]);g.useEffect(()=>{const S=()=>{const b=Bw();b&&(b.settings?o():(r&&a(),n(b.mode)))};return S(),window.addEventListener("popstate",S),window.addEventListener("hashchange",S),()=>{window.removeEventListener("popstate",S),window.removeEventListener("hashchange",S)}},[]);const m=e_.filter(S=>S.enabled),u=m.filter(S=>!S.bottom),p=m.filter(S=>S.bottom),h=S=>S.settingsAction?r:!r&&S.mode===t,x=S=>s.jsxs("button",{type:"button",className:`nav-rail__btn${h(S)?" is-active":""}`,onClick:()=>d(S),"aria-label":e(S.labelKey),"aria-current":h(S)?"page":void 0,children:[s.jsx(S.icon,{}),s.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(S.labelKey)})]},S.id);return i?s.jsx("nav",{ref:l,className:"nav-rail nav-rail--mobile","aria-label":e("nav.ariaLabel"),onFocusCapture:S=>{S.target instanceof HTMLElement&&c(S.target.closest(".nav-rail__btn"))},children:m.map(x)}):s.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[s.jsx("div",{className:"nav-rail__top",children:u.map(x)}),s.jsx("div",{className:"nav-rail__bottom",children:p.map(x)})]})}const n_=g.lazy(()=>Le(()=>import("./PromptLibraryPanel-v7hIoYy-.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Ye=["prompt","controls","library"],fr="mobile-inflight-panel",hr=e=>`mobile-sheet-tab-${e}`,gr=e=>`mobile-sheet-panel-${e}`;function r_(){const{t:e}=V(),t=f(_=>_.composeSheetOpen),n=f(_=>_.composeSheetTab),r=f(_=>_.setComposeSheetTab),o=f(_=>_.closeComposeSheet),a=f(_=>_.inFlight.length),i=f(_=>_.settingsOpen),l=f(_=>_.uiMode),c=l==="agent"&&nn?"agent":l==="node"&&tn?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=mt(),[m,u]=g.useState(!1),p=g.useRef(a),h=g.useRef(!1),x=g.useRef(null),S=g.useRef({}),b=g.useRef(!1),v=_=>{r(_),requestAnimationFrame(()=>S.current[_]?.focus())},y=(_,N)=>{const j=Ye.indexOf(N),L=_.key==="ArrowRight"?Ye[(j+1)%Ye.length]:_.key==="ArrowLeft"?Ye[(j-1+Ye.length)%Ye.length]:_.key==="Home"?Ye[0]:_.key==="End"?Ye[Ye.length-1]:null;L&&(_.preventDefault(),v(L))},w=Ge(t,o,{autoFocus:!1});g.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&u(!1)},[t,n,o,d,i,c]),g.useLayoutEffect(()=>{const _=p.current>0&&a===0;p.current=a,_&&(u(!1),h.current&&x.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),g.useLayoutEffect(()=>{if(t){b.current=!0;const _=requestAnimationFrame(()=>S.current[n]?.focus());return()=>cancelAnimationFrame(_)}b.current&&(b.current=!1,Hw())},[t,n]);const I=d&&!i&&c==="classic";return g.useEffect(()=>{I||(b.current=!1,f.getState().composeSheetOpen&&o(),$i())},[I]),g.useEffect(()=>()=>$i(),[]),I?s.jsxs(s.Fragment,{children:[t?s.jsx("button",{type:"button",className:"compose-sheet-backdrop","aria-label":e("sheet.close"),onClick:o}):null,s.jsxs("section",{ref:w,id:"mobile-generate-sheet",inert:!t,className:`compose-sheet${t?" compose-sheet--open":""}`,role:"dialog","aria-modal":t?"true":"false","aria-label":e("sheet.generate"),"aria-hidden":!t,children:[s.jsx("button",{type:"button",className:"compose-sheet__handle",onClick:o,"aria-label":e("sheet.close")}),s.jsx("div",{className:"mobile-sheet-tabs",role:"tablist","aria-label":e("sheet.generate"),children:Ye.map(_=>s.jsx("button",{ref:N=>{S.current[_]=N},id:hr(_),type:"button",role:"tab","aria-selected":n===_,"aria-controls":gr(_),tabIndex:n===_?0:-1,className:`mobile-sheet-tabs__button${n===_?" active":""}`,onClick:()=>r(_),onKeyDown:N=>y(N,_),children:e(`sheet.tabs.${_}`)},_))}),s.jsxs("div",{className:"compose-sheet__body",children:[s.jsx("div",{id:gr("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":hr("prompt"),hidden:n!=="prompt",onFocusCapture:_=>{const N=document.getElementById(fr);h.current=N?.contains(_.target)??!1},children:n==="prompt"?s.jsxs(s.Fragment,{children:[s.jsx(aa,{}),a>0?s.jsxs("section",{className:"compose-sheet__inflight",hidden:!m,children:[s.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{x.current?.querySelector(".inflight-badge")?.focus(),u(!1)},"aria-expanded":m,"aria-controls":fr,"aria-label":e("inflight.inlineCollapse",{n:a}),children:[s.jsxs("span",{children:[e("inflight.title")," (",a,")"]}),s.jsx("span",{"aria-hidden":"true",children:"−"})]}),s.jsx(la,{variant:"inline",panelId:fr}),s.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,s.jsxs("div",{ref:x,className:"compose-sheet__actions",children:[s.jsx(ia,{}),s.jsx(Nd,{variant:"inline",panelId:fr,expanded:m,onToggle:u})]})]}):null}),s.jsx("div",{id:gr("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":hr("controls"),hidden:n!=="controls",children:n==="controls"?s.jsx(qd,{}):null}),s.jsx("div",{id:gr("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":hr("library"),hidden:n!=="library",children:n==="library"?s.jsx(g.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:s.jsx(n_,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const o_={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function s_(){const e=f(r=>r.uiMode),t=f(r=>!!r.currentImage||!!r.multimodePreviewFlightId),n=f(r=>r.selectHistoryShortcutTarget);g.useEffect(()=>{if(e!=="classic")return;const r=o=>{const a=o_[o.key];a&&(o.defaultPrevented||_r(o.target)||t&&(o.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const a_={width:1386,height:1506},i_="M1514.188 1193.438c22.435 17.988 39.62 38.926 52.812 64.562l1.926 3.727c22.986 46.788 24.501 100.583 8.633 149.738A218 218 0 0 1 1573 1423l-1.734 4.086c-22.389 50.05-65.407 87.755-116.18 107.168-51.665 17.737-106.248 14.355-155.711-8.441-45.217-22.183-79.302-61.296-96-108.75-15.951-49.467-14.503-104.888 8.313-152.126 10.036-19.045 21.507-36.3 36.312-51.937l2.512-2.672c68.546-70.848 186.432-76.257 263.676-16.89 M2061.598 1162.875c87.152-1.17 172.15 22.723 247.402 66.125l3.93 2.148c9.965 5.455 18.95 12.1 28.07 18.852l5.02 3.633c8.394 6.096 16.446 12.238 23.98 19.367l3.687 3.188c13.799 12.045 27.625 24.667 39.313 38.812l2.852 3.41c16.625 20.137 31.806 41.555 44.148 64.59l2.871 5.305c31.466 59.083 46.667 123.69 46.441 190.57l-.011 15.117c-2.036 94.814-40.73 185.456-96.301 261.008l-3.102 4.23c-6.327 8.544-12.948 16.729-19.898 24.77l-2.793 3.32c-17.524 20.764-36.583 40.996-57.207 58.68a1133 1133 0 0 0-5.813 5.375 286 286 0 0 1-14.348 12.316c-3.115 2.533-6.164 5.136-9.214 7.746-6.378 5.414-12.964 10.505-19.625 15.563l-6.188 4.813c-32.674 25.025-67.623 46.909-102.812 68.187l-4.922 2.992c-14.21 8.597-28.641 16.798-43.078 25.008l-11.125 6.375a1940 1940 0 0 1-23.043 12.945c-7.782 4.316-15.542 8.672-23.305 13.024q-6.54 3.664-13.086 7.312c-10.431 5.82-20.815 11.695-31.086 17.793-5.188 3.039-10.425 5.982-15.668 8.926-10.681 6.02-21.206 12.264-31.687 18.625l-4.613 2.738c-14.547 8.703-28.344 18.43-41.387 29.262l-3.625 2.875c-7.827 7.247-16.52 17.454-17.613 28.543-.223 8.3 1.41 13.514 7.175 19.77 55.603 38.494 237.185 2.592 298.938-4.75 213.071-25.22 213.071-25.22 266.375 15.312a172 172 0 0 1 4.75 4.25l3.176 2.934c31.883 30.632 42.547 76.503 44.008 119.464.657 56.065-7.979 122.487-44.184 167.602l-2.285 2.902c-20.053 25.075-48.226 38.978-79.715 44.098-147.045 14.004-335.555 2.306-480.688 2.313l-257.261.05c-254.265-.455-254.265-.455-286.184-31.398-29.953-30.973-35.267-77.33-35.086-118.512 1.62-55.194 17.418-107.866 41.219-157.453l2.871-6c17.598-35.946 40.3-69.466 66.129-100l3.129-3.719c6.752-7.958 13.743-15.66 20.871-23.281l3.352-3.633c12.97-13.987 26.165-27.933 40.648-40.367q2.412-2.18 4.812-4.375c4.374-3.952 8.898-7.678 13.481-11.383 2.58-2.137 5.054-4.35 7.52-6.617 4.958-4.513 10.183-8.624 15.476-12.734a930 930 0 0 0 11.273-8.953c11.355-9.091 22.942-17.816 34.668-26.422 4.321-3.185 8.613-6.405 12.895-9.641 12.048-9.054 24.446-17.602 36.879-26.117 4.002-2.762 7.97-5.567 11.933-8.383 16.558-11.71 33.392-23.004 50.403-34.043 21.847-14.21 43.604-28.562 65.234-43.102 5.103-3.359 10.258-6.639 15.43-9.89 10.212-6.477 20.237-13.179 30.246-19.965a6225 6225 0 0 1 53.266-35.633c7.978-5.4 15.751-10.999 23.484-16.742q5.128-3.673 10.266-7.336c16.332-11.651 32.276-23.538 47.722-36.344a940 940 0 0 1 9.824-8.008c5.952-4.865 11.56-10.08 17.188-15.312l3.402-3.121c7.576-6.95 14.968-13.876 21.672-21.68a183 183 0 0 1 4.133-4.555c31.578-33.72 54.51-77.773 54.04-124.562-.925-22.846-10.6-44.274-27.247-60.082-20.483-17.818-41.64-25.634-68-31l-3.41-.719c-69.552-12.73-142.57 14.882-204.59 43.032-95.94 43.396-95.94 43.396-130 31.687a50.7 50.7 0 0 1-27-26c-11.409-30.19-1.697-65.624 8-95l2.031-6.176c13.273-39.326 31.523-76.35 52.969-111.824l3.008-4.992c6.951-11.29 14.726-21.655 22.992-32.008q2.57-3.369 5.125-6.75c17.712-23.037 38.228-45.089 60.875-63.25q3.356-2.892 6.687-5.813c19.554-16.8 41.147-30.139 63.313-43.187l4.625-2.762c63.42-36.739 139.53-51.393 211.973-53.363",yr=64,Qd="ima2",Hi=34;let fa=Qd,ms=!1,vt=null,ha="",ps=!1;function eu(){return navigator}function tu(){if(typeof document>"u")return null;if(vt)return vt;const e=document.querySelector('link[rel~="icon"]');if(e)return vt=e,ha=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),vt=t,ps=!0,t}function l_(e){const t=document.createElement("canvas");t.width=yr,t.height=yr;const n=t.getContext("2d");return n?(n.clearRect(0,0,yr,yr),n.fillStyle="#1c1d21",d_(n,6,6,52,52,12),n.fill(),c_(n,30,33),n.beginPath(),n.arc(48,16,e>1?13:10,0,Math.PI*2),n.fillStyle="#ff335f",n.fill(),n.lineWidth=4,n.strokeStyle="#ffffff",n.stroke(),e>1&&(n.fillStyle="#ffffff",n.font="bold 15px sans-serif",n.textAlign="center",n.textBaseline="middle",n.fillText(String(Math.min(e,9)),48,17)),t.toDataURL("image/png")):ha}function c_(e,t,n){const{width:r,height:o}=a_,a=Hi/o;e.save(),e.translate(t-r*a/2,n-Hi/2),e.scale(a,a),e.translate(-1170,-1128),e.fillStyle="#f2f3f5",e.fill(new Path2D(i_)),e.restore()}function d_(e,t,n,r,o,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+o,a),e.arcTo(t+r,n+o,t,n+o,a),e.arcTo(t,n+o,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}async function u_(e){const t=eu();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function m_(){const e=eu();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function p_(e){document.title=`(${e}) ${fa}`;const t=tu();t&&(t.href=l_(e)),u_(e)}function Vi(){document.title=fa,vt&&(ps?(vt.remove(),vt=null,ps=!1):vt.href=ha),m_()}function Ki(){ms||typeof document>"u"||(ms=!0,fa=document.title||Qd,tu())}function f_(e){g.useEffect(()=>(Ki(),()=>{ms&&Vi()}),[]),g.useEffect(()=>{Ki(),e>0?p_(e):Vi()},[e])}const nu="ima2.sidebarCollapsed";function h_(){try{return window.localStorage.getItem(nu)==="1"}catch{return!1}}function g_(e){try{window.localStorage.setItem(nu,e?"1":"0")}catch{}}function ru(e){return e instanceof HTMLElement?e.isContentEditable?!0:e.closest("input, textarea, select, [contenteditable='true']")!==null:!1}function y_(){const[e,t]=g.useState(h_),n=g.useCallback(()=>{t(r=>{const o=!r;return g_(o),o})},[]);return g.useEffect(()=>{if(!Fe())return;const r=o=>{!(o.metaKey||o.ctrlKey)||o.altKey||o.shiftKey||o.key.toLowerCase()==="b"&&(ru(o.target)||(o.preventDefault(),n()))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[n]),{collapsed:e,toggle:n}}function v_(e){g.useEffect(()=>{const t=n=>{!(n.metaKey||n.ctrlKey)||!n.altKey||n.shiftKey||n.key.toLowerCase()==="b"&&(ru(n.target)||(n.preventDefault(),e()))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[e])}function b_(){g.useEffect(()=>{if(typeof window>"u")return;const e=window.visualViewport;if(!e)return;const t=()=>{const n=Math.round(e.height),r=Math.round(e.offsetTop);document.documentElement.style.setProperty("--vv-h",`${n}px`),document.documentElement.style.setProperty("--vv-offset-top",`${r}px`)};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t)}},[])}function x_(){return s.jsxs("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),s.jsx("path",{d:"M9 3v18"})]})}function S_(){return s.jsxs("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),s.jsx("path",{d:"M15 3v18"})]})}function I_({collapsed:e,onToggle:t,controlsId:n,panelCollapsed:r,onPanelToggle:o}){const{t:a}=V(),i=Fe(),l=a(e?"nav.expandSidebar":"nav.collapseSidebar"),c=a(r?"panel.toggleShow":"panel.toggleHide");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"sidebar-top",role:"toolbar","aria-label":a("nav.ariaLabel"),children:[s.jsx("button",{type:"button",className:"sidebar-top__btn",onClick:t,"aria-label":l,"aria-expanded":!e,"aria-controls":n,title:l,children:s.jsx(x_,{})}),s.jsx(Bd,{variant:"strip",trailing:!i?.openSettings}),i?.openSettings?s.jsx("button",{type:"button",className:"sidebar-top__btn sidebar-top__btn--trailing",onClick:()=>i.openSettings?.(),"aria-label":a("nav.desktopSettings"),title:a("nav.desktopSettings"),children:s.jsx(Zd,{})}):null]}),o||Pd()?s.jsx("div",{className:"panel-top",role:o?"toolbar":void 0,"aria-label":o?a("panel.detailSettings"):void 0,"aria-hidden":o?void 0:!0,children:o?s.jsx("button",{type:"button",className:"sidebar-top__btn panel-top__toggle",onClick:o,"aria-label":c,"aria-expanded":!r,"aria-controls":"right-panel-body",title:c,children:s.jsx(S_,{})}):null}):null]})}const w_=g.lazy(()=>Le(()=>import("./NodeCanvas-ybOBBYto.js"),__vite__mapDeps([8,1,2,7,9,10,11])).then(e=>({default:e.NodeCanvas}))),__=g.lazy(()=>Le(()=>import("./SettingsWorkspace-CGZXJLgN.js"),__vite__mapDeps([12,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),E_=g.lazy(()=>Le(()=>import("./CardNewsWorkspace-Bce7Qq0s.js"),__vite__mapDeps([13,1,2])).then(e=>({default:e.CardNewsWorkspace}))),N_=g.lazy(()=>Le(()=>import("./AgentWorkspace-DGEWNErN.js"),__vite__mapDeps([14,1,2,10])).then(e=>({default:e.AgentWorkspace}))),k_=g.lazy(()=>Le(()=>import("./AssetsWorkspace-feT-v8BY.js"),__vite__mapDeps([15,1,2,9,10,16,17])).then(e=>({default:e.AssetsWorkspace}))),j_=g.lazy(()=>Le(()=>import("./AssetGenWorkspace-woj0orEW.js").then(e=>e.A),__vite__mapDeps([18,1,2,9,10,16,19])).then(e=>({default:e.AssetGenWorkspace}))),C_=g.lazy(()=>Le(()=>import("./HomeWorkspace-C7SABT2o.js"),__vite__mapDeps([20,1,2])).then(e=>({default:e.HomeWorkspace}))),A_=g.lazy(()=>Le(()=>import("./PromptLibraryPanel-v7hIoYy-.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function T_(){return s.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function P_(){s_(),b_();const{locale:e}=V(),t=f(C=>C.hydrateHistory),n=f(C=>C.loadSessions),r=f(C=>C.syncCapabilities),o=f(C=>C.startInFlightPolling),a=f(C=>C.reconcileInflight),i=f(C=>C.syncFromStorage),l=f(C=>C.settingsOpen),c=f(C=>C.unseenGeneratedCount),d=f(C=>C.historyStripLayout),m=f(C=>C.workspaceProfile),u=f(C=>C.uiMode),p=u==="agent"&&nn?"agent":u==="node"&&tn?"node":u==="home"?"home":u==="assets"?"assets":u==="asset-gen"?"asset-gen":"classic",h=p==="agent",x=p==="assets",S=p==="asset-gen",b=p==="home",v=mt(),{collapsed:y,toggle:w}=y_(),I=f(C=>C.rightPanelOpen),_=f(C=>C.toggleRightPanel);v_(_);const N=Fe(),j=b||h||x||S,L=!v&&p!=="agent"&&p!=="card-news"&&!x&&!S&&!b,q=$n(m),A=!v&&p==="classic"&&q.composerPlacement==="bottom"&&q.multimodeHistoryGrouping==="sequence",G=!A&&!h&&!x&&!S&&!b;return f_(c),g.useEffect(()=>{document.documentElement.lang=e},[e]),g.useEffect(()=>tx(),[]),g.useEffect(()=>{if(!ue())return r(),t(),n(),a(),o(),Pt(),wa(()=>a()),_a(C=>{C==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{Tn(),wa(()=>{}),_a(()=>{})}},[t,n,a,o,r]),g.useEffect(()=>{const C=T=>{const k=T.detail?.assetId;k&&f.getState().openAssetDetail(k)};return window.addEventListener("ima2:open-assets-detail",C),()=>window.removeEventListener("ima2:open-assets-detail",C)},[]),g.useEffect(()=>{const C=T=>{T.key&&(T.key==="ima2.inFlight"||T.key==="ima2.selectedFilename"||T.key===Ns||T.key===Es||T.key===js)&&i()};return window.addEventListener("storage",C),()=>window.removeEventListener("storage",C)},[i]),g.useEffect(()=>{const C=()=>{Jp(f.getState)};return window.addEventListener("beforeunload",C),()=>{window.removeEventListener("beforeunload",C)}},[]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`app${m==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${G&&d==="horizontal"?" app--history-horizontal":""}${G&&d==="sidebar"?" app--history-sidebar":""}${N?" app--desktop":""}${Qb()?" app--macos":""}${Pd()?" app--windows":""}${y&&!v?" app--nav-collapsed":""}${j?" app--no-sidebar":""}${!I&&L?" app--rp-collapsed":""}`,"data-history-strip-layout":d,"data-mobile":v?"1":void 0,"data-ui-mode":p,children:[v?null:s.jsx(I_,{collapsed:y,onToggle:w,controlsId:j?void 0:"app-sidebar",panelCollapsed:!I,onPanelToggle:L&&!l?_:void 0}),s.jsx(t_,{}),b?null:s.jsx(ax,{}),s.jsx(Vw,{}),G?s.jsx(dI,{}):null,s.jsx(g.Suspense,{fallback:s.jsx(T_,{}),children:l?s.jsx(__,{}):p==="classic"?A?s.jsx(Qx,{}):s.jsx(cs,{}):p==="node"?s.jsx(w_,{}):p==="card-news"?s.jsx(E_,{}):p==="agent"?s.jsx(N_,{}):p==="assets"?s.jsx(k_,{}):p==="asset-gen"?s.jsx(j_,{}):p==="home"?s.jsx(C_,{}):s.jsx(cs,{})}),v||p==="agent"||p==="card-news"||p==="assets"||p==="asset-gen"||p==="home"?null:s.jsx(oI,{})]}),s.jsx(ww,{}),s.jsx(zw,{}),s.jsx(uI,{}),s.jsx(RI,{}),s.jsx(MI,{}),s.jsx(Sw,{}),s.jsx(_w,{}),s.jsx(Cw,{}),s.jsx(Tw,{}),s.jsx(Gw,{}),s.jsx(r_,{}),s.jsx($w,{}),p==="card-news"?s.jsx(g.Suspense,{fallback:null,children:s.jsx(A_,{})}):null]})}const S0=Object.freeze(Object.defineProperty({__proto__:null,default:P_},Symbol.toStringTag,{value:"Module"}));export{Pv as $,vm as A,s0 as B,pm as C,qe as D,md as E,d0 as F,ul as G,u0 as H,Ke as I,m0 as J,p0 as K,y0 as L,da as M,f0 as N,Gr as O,h0 as P,g0 as Q,Xo as R,Xv as S,Ee as T,a0 as U,Im as V,Zv as W,sI as X,Lm as Y,kr as Z,at as _,f as a,l0 as a0,rm as a1,t0 as a2,yf as a3,mw as a4,Sd as a5,v0 as a6,x0 as a7,b0 as a8,o0 as a9,$_ as aA,U_ as aB,_r as aC,q_ as aD,z_ as aE,M_ as aF,H_ as aG,G_ as aH,px as aI,D_ as aJ,Hx as aK,Wi as aL,O as aM,L_ as aN,F_ as aO,O_ as aP,B_ as aQ,V_ as aR,W_ as aS,J_ as aT,K_ as aU,Y_ as aV,X_ as aW,Z_ as aX,Q_ as aY,e0 as aZ,S0 as a_,c0 as aa,$x as ab,ys as ac,Ac as ad,DI as ae,la as af,r0 as ag,Tt as ah,n0 as ai,io as aj,sa as ak,xd as al,lb as am,Te as an,Gd as ao,Ww as ap,Yw as aq,tn as ar,Xw as as,nn as at,Zw as au,qi as av,Tv as aw,Dx as ax,qx as ay,as as az,HI as b,of as c,De as d,jt as e,Pm as f,pl as g,i0 as h,tt as i,Cc as j,Ge as k,vf as l,tm as m,nf as n,$ as o,mt as p,mc as q,mo as r,Se as s,Me as t,V as u,Od as v,zp as w,Fd as x,hS as y,Dd as z};
|