ima2-gen 3.21.0 → 3.22.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/bin/commands/grok.js +8 -1
- package/docs/API.md +4 -1
- package/docs/migration/runtime-test-inventory.md +164 -159
- package/lib/grokSizeMapper.js +2 -0
- package/lib/mcp/adapters/higgsfield.js +17 -10
- package/lib/mcp/adapters/higgsfieldUpload.js +77 -0
- package/lib/mcp/connectionManager.js +32 -0
- package/lib/mcp/modelsCatalog.js +12 -1
- package/lib/xaiAuth.js +35 -3
- package/lib/xaiDeviceLogin.js +30 -4
- package/package.json +2 -2
- package/routes/auth.js +13 -2
- package/routes/mcpMedia.js +21 -7
- package/routes/mcpMultishot.js +11 -7
- package/routes/mcpRecover.js +6 -2
- package/routes/quota.js +50 -14
- package/ui/dist/.vite/manifest.json +64 -64
- package/ui/dist/assets/{AgentWorkspace-CBOIYDSC.js → AgentWorkspace-CRJwrf5D.js} +1 -1
- package/ui/dist/assets/App-B7t5h5M_.js +9 -0
- package/ui/dist/assets/{AssetGenWorkspace-kjhZeUE8.js → AssetGenWorkspace-CR3k3lgk.js} +2 -2
- package/ui/dist/assets/{AssetMediaLightbox-B6YoVErG.js → AssetMediaLightbox-DOP-l7is.js} +1 -1
- package/ui/dist/assets/{AssetsWorkspace-D3yHm95L.js → AssetsWorkspace-i9IE-OMD.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-BVmfGpNh.js → CardNewsWorkspace-B238fPNf.js} +1 -1
- package/ui/dist/assets/{GenerationRequestLogPanel-lNQlY7ax.js → GenerationRequestLogPanel-Bznhoi1c.js} +1 -1
- package/ui/dist/assets/{HomeWorkspace-DoJRK1Oc.js → HomeWorkspace-DmQcpD4W.js} +1 -1
- package/ui/dist/assets/{KeyingPanel-CzXXD18n.js → KeyingPanel-C-9CZfhI.js} +1 -1
- package/ui/dist/assets/{NodeCanvas-Di9xPPrm.js → NodeCanvas-CtSwikbj.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-BRC8Or5u.js → PromptBuilderPanel-CWOtvCbq.js} +1 -1
- package/ui/dist/assets/{PromptImportDialog-DftvHziZ.js → PromptImportDialog-ski4y5rq.js} +2 -2
- package/ui/dist/assets/{PromptImportDiscoverySection-BRVea9Rt.js → PromptImportDiscoverySection-BxPnvWSF.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-y9o9rPoQ.js → PromptImportFolderSection-rt8TMgTU.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-CpseDORF.js → PromptLibraryPanel-evfChzKq.js} +2 -2
- package/ui/dist/assets/SettingsWorkspace-PzprnYiR.js +1 -0
- package/ui/dist/assets/{SpriteRecipeWorkspace-Bt9UmStQ.js → SpriteRecipeWorkspace-BidCI5hK.js} +1 -1
- package/ui/dist/assets/{index-DbV9f53B.js → index-CaFoTJlR.js} +8 -8
- package/ui/dist/assets/{index-C9gJqtx4.js → index-GbV8-z5Y.js} +4 -4
- package/ui/dist/assets/{pptxgen.es-CCODGbBd.js → pptxgen.es-BkpMsCHc.js} +1 -1
- package/ui/dist/assets/{promptBuilderStore-CF1EPSCL.js → promptBuilderStore-B7xCm5Ga.js} +1 -1
- package/ui/dist/assets/useAgentDialogFocus-C80ZVSWi.js +1 -0
- package/ui/dist/index.html +1 -1
- package/ui/dist/assets/App-BLBE-fTl.js +0 -9
- package/ui/dist/assets/SettingsWorkspace-BnvKUZsF.js +0 -1
- package/ui/dist/assets/useAgentDialogFocus-CNcAdwxO.js +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-GbV8-z5Y.js","assets/index-CaFoTJlR.js","assets/index-BPX3wCCR.css","assets/PromptLibraryPanel-evfChzKq.js","assets/PromptBuilderPanel-CWOtvCbq.js","assets/promptBuilderStore-B7xCm5Ga.js","assets/GenerationRequestLogPanel-Bznhoi1c.js","assets/clipboard-DirTPLEi.js","assets/NodeCanvas-CtSwikbj.js","assets/AssetMediaLightbox-DOP-l7is.js","assets/useAgentDialogFocus-C80ZVSWi.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-PzprnYiR.js","assets/CardNewsWorkspace-B238fPNf.js","assets/AgentWorkspace-CRJwrf5D.js","assets/AssetsWorkspace-i9IE-OMD.js","assets/KeyingPanel-C-9CZfhI.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-CR3k3lgk.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-DmQcpD4W.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as fn,i as ue,c as Ze,r as Li,g as fe,a as Dd,b as Gd,L as _t,z as zd,d as qd,e as $d,k as Ud,f as y,s as Hd,l as Vd,j as s,h as Kd,B as $r,_ as Le}from"./index-CaFoTJlR.js";const ca=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},Bd=(e=>e?ca(e):ca),Wd=e=>e;function Jd(e,t=Wd){const n=fn.useSyncExternalStore(e.subscribe,fn.useCallback(()=>t(e.getState()),[e,t]),fn.useCallback(()=>t(e.getInitialState()),[e,t]));return fn.useDebugValue(n),n}const da=e=>{const t=Bd(e),n=r=>Jd(t,r);return Object.assign(n,t),n},Oi=(e=>e?da(e):da);async function Ie(e,t){const n=fe();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 Ze(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"){Li(n);try{await o.body?.cancel()}catch{}throw Ze(n)}}return o}async function $(e,t){const n=await Ie(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 Fi(e,t){t?.throwIfAborted();const n=await Ie(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 ln=null;function Di(){if(!ln){const e=localStorage.getItem("ima2.browserId");e?ln=e:(ln=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",ln))}return ln}function Yt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Di()};return $(e,{...t,headers:n})}function Gi(){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 Yd(){return $("/api/oauth/status")}function Xd(){return $("/api/billing")}const Zd=5400*1e3,Qd=2e3,ua=3e4;let ve=null,Sr="";const zo=new Set;let qo=null,Ye=null,ma=!1,hr=0,wr=0,pa=!1;const eu=3;let as=null;const tu=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function nu(){return Sr?`/api/events?lastEventId=${encodeURIComponent(Sr)}`:"/api/events"}function ru(){wr+=1;const e=ve;ve=null,e?.close(),Ye&&(clearTimeout(Ye),Ye=null)}function ou(){pa||typeof window>"u"||(window.addEventListener(_t,ru),pa=!0)}function fa(e,t){if(e!==wr||t!==fe()||ue()||ve)return;const n=Math.min(Qd*Math.pow(1.5,hr),ua),r=Math.min(n*(.8+Math.random()*.4),ua);hr+=1,Ye=setTimeout(is,r),as?.(hr>=eu?"failed":"reconnecting")}function is(){if(ou(),ue()||ve&&ve.readyState!==EventSource.CLOSED)return;wr+=1;const e=new EventSource(nu());ve=e,Ye&&(clearTimeout(Ye),Ye=null),e.onopen=()=>{if(ve!==e)return;Ye&&(clearTimeout(Ye),Ye=null),hr=0;const t=ma;ma=!0,t&&qo?.(),ve===e&&as?.("connected")};for(const t of tu)e.addEventListener(t,n=>{ve!==e||typeof n.data!="string"||su(t,n)});e.addEventListener("replay-gap",()=>{ve===e&&(Sr="",qo?.())}),e.onerror=t=>{if(ve!==e||typeof t.data=="string")return;ve=null,e.close();const n=++wr,r=fe();if(Dd()?.mode==="lan"){const o=()=>fa(n,r);Gd().then(o,o)}else fa(n,r)}}function su(e,t){t.lastEventId&&(Sr=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 zo)a.jobId===o&&(a.event!==null&&a.event!==e||a.handler(e,r))}function Ct(e,t,n){const r={jobId:e,event:t,handler:n};return zo.add(r),(!ve||ve.readyState===EventSource.CLOSED)&&is(),()=>{zo.delete(r)}}function Xt(e,t=Zd){const n=setTimeout(e,t);return()=>clearTimeout(n)}function ha(e){qo=e}function ga(e){as=e}function At(){(!ve||ve.readyState===EventSource.CLOSED)&&is()}function Ur(e=1e4){const t=fe();return ue()?Promise.reject(Ze(t-1)):(At(),ve&&ve.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const o=Date.now(),a=()=>{if(t!==fe()||ue()){r(Ze(t));return}if(ve&&ve.readyState===EventSource.OPEN){n();return}if(Date.now()-o>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const au=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],iu={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 lu(e){return typeof e=="string"&&au.includes(e)}function ya(e){if(typeof e=="string")return iu[e]}const qi="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Je={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 va(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 cu=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function du(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 ot(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:Je.LAN_TOKEN_REQUIRED,message:Ze().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=o&&o in Je?o:a&&a in Je?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Je.JOB_TRACKING_TIMEOUT,message:qi};const c=lu(i)?ya(i):void 0,d=l?cu.includes(l):!1,m=ya(i);let u,p;c&&!d?(u=l??"UNKNOWN",p=c):d&&l||l?(u=l,p=Je[l]):m?(u=va(r),p=m):(u=va(r),p=Je[u]??Je.UNKNOWN);const h=u==="MODERATION_REFUSED"||u==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||du(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 uu(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function et(e,t="Generation failed"){const n=e.error;let r=t,o,a,i,l;const c=uu(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=ot({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 ba=5e3,xa=3e4;function mu(e){if(!e)return ba;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(xa,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(xa,Math.max(1e3,n-Date.now())):ba}function pu(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function co(){return new DOMException("Aborted","AbortError")}function Hr(...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 Vr({url:e,payload:t,requestId:n,signal:r,parseError:o}){const a=fe();let i=null;const l=c=>new Promise((d,m)=>{if(r?.aborted){m(co());return}const u=()=>{i&&(clearTimeout(i),i=null),m(co())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",u),d()},c),r?.addEventListener("abort",u,{once:!0})});for(;;){if(r?.aborted)throw co();if(a!==fe())throw Ze(a);if(ue())throw Ze(a-1);const c=await Ie(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(pu(c,d)){await l(mu(c.headers.get("Retry-After")));continue}throw o(c,d)}}async function $i(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return At(),new Promise((r,o)=>{let a=!1;const i=new AbortController,l=Hr(t.signal,i.signal),c=u=>{a||(a=!0,m(),d(),u())},d=Ct(n,null,(u,p)=>{a||(u==="done"?c(()=>r(p)):u==="error"&&c(()=>o(et(p,"Generation failed"))))}),m=Xt(()=>{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})}Vr({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(u,p)=>{const h=et(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 fu(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return At(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Hr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Ct(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(et(h,"Multimode generation failed"))))}),u=Xt(()=>{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})}Vr({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 Lw(e){return $("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function hu(e){const t=await e.arrayBuffer(),n=await Ie("/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 Ow(e){return $("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Fw(){return $("/api/prompt-builder/config")}function Dw(e){return $("/api/prompt-builder/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ls(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return At(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Hr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Ct(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(et(h,"Video generation failed"))))}),u=Xt(()=>{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})}Vr({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 Zt(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"),Yt(`/api/history?${t.toString()}`)}function gu(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),Yt(`/api/history?${t.toString()}`)}function yu(e){return Yt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function vu(){return(await $("/api/storage/status")).data}function bu(){return $("/api/storage/open-generated-dir",{method:"POST"})}function Ui(e){return $(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function xu(e){return $(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function Iu(e,t){return $(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function Su(e){return $("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function wu(){return $("/api/sessions")}function _u(e){return $("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function Hi(e){return $(`/api/sessions/${encodeURIComponent(e)}`)}function Eu(e,t){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function Nu(e){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function ku(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 Gw(e){return Yt(`/api/annotations/${encodeURIComponent(e)}`)}async function zw(e,t){await Yt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function qw(e){await Yt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function $w(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 Uw(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 Hw(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 Vw(e){return $(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function Cu(e){const t=new URLSearchParams;return $(`/api/prompts?${t.toString()}`)}function Au(e){return $("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Tu(e){return $(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function Pu(e){return $(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function Ru(e){return $("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Kw(e){return $("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Bw(e){return $("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Ww(){return $("/api/prompts/import/curated-sources")}function Jw(e){return $("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Yw(e){return $("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Xw(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return $(`/api/prompts/import/discovery${n}`)}function Zw(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 Qw(e){return $("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function e_(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 t_(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 cs(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 Mu(e){return $(`/api/assets/${encodeURIComponent(e)}`)}function Kr(e){return $("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function n_(e){return $("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Vi(e,t){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function r_(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 Ie(`/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 Lu(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 Ie(`/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 o_(e){return $("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function Ou(e){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function ds(){return $("/api/assets/folders")}function Fu(e){return $("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Ki(e,t){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function Du(e){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function us(){return $("/api/assets/tags")}function s_(){return $("/api/assets/all",{method:"DELETE"})}async function Gu(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return At(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=Hr(n.signal,l.signal),d=p=>{i||(i=!0,u(),m(),p())},m=Ct(r,null,(p,h)=>{i||(p==="partial"?t.onPartial?.(h):p==="phase"?t.onPhase?.(h):p==="done"?d(()=>o(h)):p==="error"&&d(()=>a(et(h,"Node generation failed"))))}),u=Xt(()=>{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})}Vr({url:"/api/node/generate",payload:e,requestId:r,signal:c,parseError:(p,h)=>{const x=h?.error?.message??`Request failed: ${p.status}`,I=new Error(x);return I.code=h?.error?.code,I.status=h?.status??p.status,I}}).then(()=>{}).catch(p=>{d(()=>a(p instanceof Error?p:new Error(String(p))))})})}const ms=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],zu=new Set(ms);function Tt(e){return typeof e=="string"&&zu.has(e)}const Pt={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:[]}},qu=["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"],Bi={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}},ps={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"}}},Wi=[{value:"gpt-image-2.5-sunburst",label:"GPT Image2.5 Sunburst"},{value:"gpt-image-2.5-flare",label:"GPT Image2.5 Flare"}];function fs(e){return Wi.some(t=>t.value===e)}function Rt(e,t,n){return(n==="xhigh"||n==="max")&&(e!=="api"||!fs(t))?"medium":n}const _r="gpt-6-luna",He=[{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"}],hs=new Set(Pt["gemini-api"].image),Ji=new Set(Pt.atlascloud.image),Yi=new Set(Pt.minimax.image),Xi=new Set(Pt.nai.image),$u=new Set(Pt.oauth.image),Uu=new Set(Pt.api.image),Zi=He.filter(e=>$u.has(e.value)),Hu=["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"],Vu=Hu.map(e=>He.find(t=>t.value===e)).filter(e=>e!==void 0&&Uu.has(e.value)),a_=Zi,Qi=He.filter(e=>e.value.startsWith("grok-")),Ku=He.filter(e=>hs.has(e.value)),Bu=He.filter(e=>Ji.has(e.value)),Wu=He.filter(e=>Yi.has(e.value)),el=He.filter(e=>Xi.has(e.value)),i_=[];function Ju(e){return He.some(t=>t.value===e)}function Yu(e){return typeof e=="string"&&e.startsWith("grok-")}function Xu(e){return typeof e=="string"&&hs.has(e)}function Zu(e){return e==="grok"||e==="grok-api"?Qi:e==="agy"||e==="gemini-api"?Ku.filter(t=>!t.providerHint||t.providerHint===e):e==="atlascloud"?Bu:e==="minimax"?Wu:e==="nai"?el:e==="comfy"?[]:e==="api"?Vu:Zi}function tl(e,t){return e?hs.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:Ji.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:Yi.has(e)?t==="minimax"?`${e} minimax`:e:Xi.has(e)?He.find(n=>n.value===e)?.shortLabel??e:He.find(n=>n.value===e)?.shortLabel??e:null}const gs="grok-imagine-video",tt="grok-imagine-video-1.5",nl="grok-imagine-video-1.5-preview",rl="grok-imagine-video-1.5-2026-05-30",Qu=15,em=10,Ia=15,tm=[{value:gs,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:tt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function nm(e){return e===gs||e===tt||e===nl||e===rl}function Mt(e){return nm(e)?e===nl||e===rl?tt:e:!1}function Sa(e,t){if(t!=="reference-to-video")return Ia;const n=Mt(e);return n?n===tt?Qu:em:Ia}function rm(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function uo(e,t,n){return t!=="1080p"?!0:e===tt&&(n==="text-to-video"||n==="image-to-video")}const Kt="comfy-video:",ol="video:";function om(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Kt}${a}`:o??"":(t==="grok"||t==="grok-api")&&r?`${ol}${r}`:n}const $o=new Set(qu),sm={oauth:_r,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:_r},am={"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 Br(e,t){return typeof t=="string"&&$o.has(t)&&Pt[e].image.includes(t)}function vn(e){return typeof e=="string"&&e.trim().length>0?e:null}function sl(e,t){if(Mt(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Br(n,e))return n;return"oauth"}function lt(e){const t=Tt(e.provider)?e.provider:sl(e.imageModel,e.videoModelSelected);if(t==="comfy"){const r=vn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&$o.has(e.imageModel)?e.imageModel:_r,videoModelSelected:!1,comfyWorkflow:vn(e.comfyWorkflow)??(r&&!$o.has(r)?r:null),comfyVideoWorkflow:vn(e.comfyVideoWorkflow)}}const n=t==="oauth"&&typeof e.imageModel=="string"?am[e.imageModel]??e.imageModel:e.imageModel;return{provider:t,imageModel:Br(t,n)?n:sm[t],videoModelSelected:t==="grok"||t==="grok-api"?Mt(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function im(e,t){return Tt(e)&&Br(e,t)?e:sl(t,!1)}function lm(e,t,n){return e.provider===t?e:lt(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 wa(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 al(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Uo(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of ms){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"?vn(o.image):Br(n,o.image)?o.image:null,i=n==="comfy"?vn(o.video):n==="grok"||n==="grok-api"?Mt(o.video):!1;t[n]={kind:o.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const cm="none",Ho=[{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 il(e){return Ho.some(t=>t.value===e)}const dm={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function um(e){return!il(e)||e==="none"?null:`R:${dm[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"],ll=Ne[0],cl=Ne[1],dl=Ne[2],ul=Ne[3],ys=Ne[4],ml=Ne[5],pl=Ne[6],vs=Ne[7],fl=Ne[8],Vo=Ne[9],Ko=Ne[10],_a=Ne[11],bs=Ne[12],hl=Ne[13],xs=Ne[17],gl=Ne[19],yl=Ne[20],vl=Ne[21],mm=!0,pm=!1,Qt=!0,bl=pm,en=!0,fm=24;function Bo(e){return Math.min(fm,Math.max(1,Math.trunc(e||1)))}const Ea={ko:Ud,en:$d,"zh-Hant":qd,"zh-Hans":zd};function Na(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function hm(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function M(e,t){const n=f.getState().locale;return xl(n,e,t)}function xl(e,t,n){const r=Na(Ea[e],t),o=typeof r=="string"?r:Na(Ea.en,t),a=typeof o=="string"?o:t;return n?hm(a,n):a}function V(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>xl(e,t,n)}}function gm(e){return Math.round(e/16)*16}const St=16,Is=3840,mo=655360,gr=8294400,ym=3,qt=3,ka=Math.floor(Math.sqrt(gr)/St)*St,Il=St,vm=Is,Kn=ym;function ja(e){return Math.floor(e/16)*16}function Er(e){return Math.ceil(e/16)*16}function ze(e){return Math.min(vm,Math.max(Il,e))}function nt(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function Et(e,t){e.includes(t)||e.push(t)}function Ca(e,t){const n=gm(e);return n!==e&&Et(t,"snap"),n}function Aa(e,t){return e<Il&&Et(t,"min"),e>Is&&Et(t,"maxEdge"),ze(e)}function Ta(e,t,n){return e>t*Kn?(Et(n,"ratio"),{w:e,h:ze(Er(e/Kn))}):t>e*Kn?(Et(n,"ratio"),{w:ze(Er(t/Kn)),h:t}):{w:e,h:t}}function bm(e,t,n){if(e*t<mo){Et(n,"minPixels");const i=Math.sqrt(mo/(e*t));let l=ze(Er(e*i)),c=ze(Er(t*i));for(;l*c<mo;)l<=c?l=ze(l+St):c=ze(c+St);return{w:l,h:c}}if(e*t<=gr)return{w:e,h:t};Et(n,"maxPixels");const r=Math.sqrt(gr/(e*t));let o=ze(ja(e*r)),a=ze(ja(t*r));for(;o*a>gr;)o>=a?o=ze(o-St):a=ze(a-St);return{w:o,h:a}}function Ss(e,t,n,r){const o=[],a=nt(e,n),i=nt(t,r);let l=Aa(Ca(a,o),o),c=Aa(Ca(i,o),o);return{w:l,h:c}=Ta(l,c,o),{w:l,h:c}=bm(l,c,o),{w:l,h:c}=Ta(l,c,o),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:o}}function Sl(e,t,n,r){const o=Ss(e,t,n,r);return{w:o.w,h:o.h}}const xm=[{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 Im(e,t){return`${e}x${t}`}function Sm(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 Sl(o,a,o,a)}function Wr(e){const t=Sl(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function $t(e){return e.slice(0,qt).map(Wr)}function wm(e,t){const n=Wr(t),r=e.findIndex(o=>o.id===n.id);return r>=0?$t(e.map((o,a)=>a===r?n:o)):e.length>=qt?$t(e):$t([...e,n])}function _m(e,t,n){const r=Wr({...n,id:t});return $t(e.map(o=>o.id===t?r:o))}const Em=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],Nm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],km=[{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 Cm(){return[{value:"auto",label:M("size.autoLabel"),sub:M("size.autoSub")},{value:"custom",label:M("size.customLabel"),sub:M("size.customSub")}]}const wl=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],_l=["native","karras","exponential","polyexponential"],El=["heavy","light","furryFocus","humanFocus","none"],Nl=["standard","light","none"],Am={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},Nr={min:1,max:50},kr={min:1,max:10},jr={min:0,max:1},kl=2**32-1;function Tm(e,t){return{...Am,...e??{},...t}}function Wo(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Bn(e,t){return typeof e=="string"&&t.includes(e)?e:void 0}function po(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function jl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Bn(t.sampler,wl);r!==void 0&&(n.sampler=r);const o=Bn(t.noiseSchedule,_l);o!==void 0&&(n.noiseSchedule=o);const a=Bn(t.ucPresetId,El);a!==void 0&&(n.ucPresetId=a);const i=Bn(t.qualityPresetId,Nl);i!==void 0&&(n.qualityPresetId=i);const l=po(t.steps,Nr.min,Nr.max);l!==void 0&&(n.steps=l);const c=po(t.scale,kr.min,kr.max);c!==void 0&&(n.scale=c);const d=po(t.cfgRescale,jr.min,jr.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<=kl&&(n.seed=t.seed),n}function Ve(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Jo="vid:",Yo="img:",Pm=/^[\p{L}\p{N}_-]{1,32}$/u;function ws(e){return Pm.test(e)}function Rm(e){return e.references.some(t=>t.tag!==void 0&&!ws(t.tag))}function Cl(e){return e==="video"?"video":"image"}function Jr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function Mm(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function Yr(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)&&Mm(r)))}function Pa(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 Al(e,t,n){const r=Jr(t),o=Yr(n),a={};for(const i of e.parameters){const l=o[i.name];l!==void 0&&Pa(i,l)?a[i.name]=l:i.default!==void 0&&Pa(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function Lm(e){return e?Al(e,null,{}):{ratio:null,parameters:{}}}function Om(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function Tl(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 _s(e){if(!e||typeof e!="object")return Ve();const t=e,n=Array.isArray(t.references)?t.references.map(Tl).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 Es(e,t){const n=_s(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 Pl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Fm(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:Cl(e.mcpMediaKind),ratio:Jr(e.mcpRatio),parameters:Yr(e.mcpParameters)}}function Wn(e,t){return`${e==="video"?Jo:Yo}${t}`}function Dm(e){if(e.startsWith(Jo)){const t=e.slice(Jo.length);return t?{kind:"video",model:t}:null}if(e.startsWith(Yo)){const t=e.slice(Yo.length);return t?{kind:"image",model:t}:null}return null}function Rl(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 Gm(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const o=Cl(e.mcpMediaKind),a=Jr(e.mcpRatio),i=Yr(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=v=>c===void 0||c.includes(v),m=_s(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(Tl).filter(v=>!!v).filter((v,g,_)=>_.findIndex(S=>S.filename===v.filename)===g).slice(0,3);if(x.some(v=>v.dataUrl||v.tag!==void 0&&!ws(v.tag)))return null;const I=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,...I?{endFrameFilename:I}:{},...x.length>0?{references:x.map(({filename:v,tag:g})=>({filename:v,...g?{tag:g}:{}}))}:{},...b?{referenceVideoFilename:b}:{},...e.mcpCharacterElementId?{characterElementId:e.mcpCharacterElementId}:{},...n?{requestId:n}:{}}}function Rn(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 zm(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 Mn(e){if(!Array.isArray(e))return null;const t=e.map(zm);return t.every(n=>n!==null)?t:null}function Ns(e){return e.map(t=>({id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}))}function qm(e){const t=Mn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function $m(){try{const e=localStorage.getItem(ll);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function Um(){try{const e=localStorage.getItem(cl);if(e==="agent")return en?e:"classic";if(e==="card-news")return bl?e:"classic";if(e==="node")return Qt?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function Hm(){try{const e=localStorage.getItem(dl);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function Ra(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function Ma(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(ul);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 Ml(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(ul,JSON.stringify({mode:e,matteColor:t}))}catch{}}function Ll(e){try{localStorage.setItem(ys,e)}catch{}}function Vm(){try{const e=localStorage.getItem(ml);if(il(e))return e}catch{}return cm}function Km(e){try{localStorage.setItem(ml,e)}catch{}}function Bm(){try{const e=localStorage.getItem(gl);return e?jl(JSON.parse(e)):{}}catch{return{}}}function Ol(e){try{localStorage.setItem(gl,JSON.stringify(e))}catch{}}function Wm(){try{const e=localStorage.getItem(pl);if(e==="false")return!1;if(e==="true")return!0}catch{}return mm}function Jm(e){try{localStorage.setItem(pl,String(e))}catch{}}const La={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function Xr(){try{const e=localStorage.getItem(xs);if(!e)return La;const t=JSON.parse(e);return{model:Mt(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 La}}function hn(e){try{const t=Xr();localStorage.setItem(xs,JSON.stringify({...t,...e}))}catch{}}function Fl(){try{const e=localStorage.getItem(Vo);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function st(e){try{e?localStorage.setItem(Vo,e):localStorage.removeItem(Vo)}catch{}}function Ym(){try{const e=localStorage.getItem(Ko);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function ks(e){try{e?localStorage.setItem(Ko,e):localStorage.removeItem(Ko)}catch{}}function Xm(e,t){return`${e}x${t}`}function Sn(e){return Bo(e)}const Dl=new Set(["1024x1024","1536x1024","1024x1536","1360x1024","1024x1360","1824x1024","1024x1824","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840","auto","custom"]);function Zm(e){if(typeof e!="string")return{};if(Dl.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 Gl(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 Qm(e){return Tt(e)}function ep(e){return e==="auto"||e==="direct"}function tp(e){return typeof e=="string"&&Dl.has(e)}function tn(){try{const e=localStorage.getItem(vs);if(!e)return{};const t=JSON.parse(e),n={};Qm(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=Jr(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=Yr(t.mcpParameters)),"imageToolModel"in t&&(n.imageToolModel=t.provider==="api"&&fs(t.imageToolModel)?t.imageToolModel:null),Gl(t.quality)&&(n.quality=Rt(t.provider,n.imageToolModel,t.quality)),tp(t.sizePreset)&&(n.sizePreset=t.sizePreset),typeof t.customW=="number"&&Number.isFinite(t.customW)&&(n.customW=nt(t.customW,1920)),typeof t.customH=="number"&&Number.isFinite(t.customH)&&(n.customH=nt(t.customH,1088)),zl(t.format)&&(n.format=t.format),ql(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=Sn(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=Sn(t.multimodeMaxImages)),ep(t.promptMode)&&(n.promptMode=t.promptMode),typeof t.prompt=="string"&&(n.prompt=t.prompt),typeof t.negativePrompt=="string"&&(n.negativePrompt=t.negativePrompt);const a=Mn(t.insertedPrompts);return a&&(n.insertedPrompts=a),n}catch{return{}}}function np(){return Fm(tn())}function Ln(e,t,n="image"){te({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function te(e){try{const t=tn();localStorage.setItem(vs,JSON.stringify({...t,...e}))}catch{}}function $l(){const e=localStorage.getItem(yl);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ul(){try{const e=$l();return e?.version===1?Uo(e.lanes):{}}catch{return{}}}function rp(e){try{let t=null;try{t=$l()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Uo(t.lanes):{},...Uo(e)};localStorage.setItem(yl,JSON.stringify({version:1,lanes:r}))}catch{}}function Hl(){const e=tn(),t=Xr();let n=null;try{n=localStorage.getItem(ys)}catch{}return lt({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function op(e){Ll(e.imageModel),hn({model:e.videoModelSelected}),te({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function sp(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 Vl(e){return e.filter(t=>t.selected).map(t=>t.id)}function wn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function ap(e,t,n,r){const o=new Set(sp(e,t,n));if(!o.size)return e;if(!r)return wn(e,o);const a=e.find(c=>c.id===n),i=e.some(c=>o.has(c.id)&&c.selected),l=new Set(Vl(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of o)l.add(c);return wn(e,l)}const ip={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Oa=16777216;function Fa(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>Oa){const i=Math.sqrt(Oa/(r*o));r=Math.max(1,Math.floor(r*i)),o=Math.max(1,Math.floor(o*i))}return{w:r,h:o}}function Jn(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 fo(e,t,n){return new Promise((r,o)=>{e.toBlob(a=>a?r(a):o(new Error("canvas.toBlob returned null")),t,n)})}function Yn(e){const t=e.indexOf(",");return t<0?e.length:e.length-t-1}async function js(e,t={}){const n={...ip,...t},r=await Jn(e);if(Yn(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}=Fa(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 fo(l,"image/png"),u=await Jn(m);if(Yn(u)>n.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return u}for(const m of n.qualityLadder){const u=await fo(l,"image/jpeg",m),p=await Jn(u);if(Yn(p)<=n.maxB64Bytes)return p}const d=Fa(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 fo(l,"image/jpeg",m),p=await Jn(u);if(Yn(p)<=n.maxB64Bytes)return p}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{o.close?.()}}function Cr(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 Kl(e){return(e.type||"").toLowerCase()==="image/png"}const Bl=18e4;function lp(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)_n(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function _n(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 Wl(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 Ar(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:Xo(e.kind)??Xo(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:Mn(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 cp(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 nn(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Da(e){return e.filename||e.image}function Ga(e,t){const n=new Map(e.map(r=>[Da(r),r]));for(const r of t)n.set(Da(r),r);return[...n.values()].sort((r,o)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(o.sequenceIndex??Number.MAX_SAFE_INTEGER))}function dp(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 Jl({includeExpired:e=!1}={}){try{const t=localStorage.getItem(fl);if(!t)return[];const n=JSON.parse(t);if(!Array.isArray(n))return[];const r=Date.now();return n.filter(o=>dp(o)&&(e||r-o.startedAt<Bl)).map(o=>({id:o.id,prompt:o.prompt,startedAt:o.startedAt,composerPrompt:typeof o.composerPrompt=="string"?o.composerPrompt:void 0,composerInsertedPrompts:Mn(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:Xo(o.kind)}))}catch{return[]}}function Xo(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 Ue=500,Cs=5;function up(e){return e==="classic"||e==="edit"||e==="generate"||e==="card-news-card"||e==="card-news-set"?e:null}function On(e){const t=Mn(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?Ns(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:up(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 qe(e){return e.filename??e.image}function Yl(e,t){const n=qe(t);return e.filter(r=>qe(r)!==n)}function Xl(e,t){const n=qe(t);return e.find(r=>qe(r)===n)}function Zl(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 Ql(e,t){const n=new Map(e.map(r=>[qe(r),r]));for(const r of t)n.set(qe(r),r);return[...e.map(r=>n.get(qe(r))??r),...t.filter(r=>!e.some(o=>qe(o)===qe(r)))]}function Zr(e,t){return e.slice(0,Math.max(Ue,t))}function As(e){return e.replace(/^data:[^;]+;base64,/,"")}async function Fn(e,t="reference.png"){const n=await Ie(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 js(o,{preserveTransparency:!1})}function mp(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(fl,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function pp(e){return Tm(e.naiServerDefaults,e.naiOptionOverrides)}function Qr(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=Ss(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 fp(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):Cs}async function hp(e){try{const t=await Gi();e({referenceLimit:fp(t.limits?.maxRefCount),naiServerDefaults:jl(t.defaults?.nai??null)})}catch{e({referenceLimit:Cs})}}function Ts(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 gp(e){const t=await Ie(e);if(!t.ok)throw new Error(`reference fetch failed: ${t.status}`);const n=await t.blob();return Ts(new File([n],"reference.png",{type:n.type||"image/png"}))}function yp(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 vp(e){return e?.type==="elementReferenceNode"||e?.data?.nodeType==="element-reference"}function ec(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.filter(r=>!vp(n.get(r.source)))}function tc(e,t,n){return ec(e,t).filter(r=>r.target===n)}function bp(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 l_(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 Fe(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const o=tc(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 nc="ima2.nodeRefs.v1";function Ps(){try{const e=localStorage.getItem(nc);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function rc(e){try{localStorage.setItem(nc,JSON.stringify(e))}catch{}}function xp(e,t){if(!e)return[];const n=Ps()[e]?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function eo(e,t,n){if(!e)return;const r=Ps(),o={...r[e]??{}};n.length===0?delete o[t]:o[t]=n,r[e]=o,rc(r)}function Rs(e,t){eo(e,t,[])}function Ip(e,t){if(!e)return;const n=Ps(),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,rc(n)}const Sp=/\.(mp4|webm|mov)$/i;function Qe(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return Sp.test(t)||e.startsWith("data:video/")}function xe(e){return e?e.mediaType==="video"?!0:Qe(e.filename)||Qe(e.url)||Qe(e.image):!1}const wp=15e3;function Ms(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")))},wp),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 rn(e,t){return Ms(e,n=>n-.1,t)}function oc(e,t){return Ms(e,n=>Math.min(n*.3,.4),t)}function sc(e,t){return Ms(e,n=>n/2,t)}function ac(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:xp(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:Fe(t,n),graphEdges:n,graphVersion:e.graphVersion}}const _p=800;let Xe=null,yr=!1,vr=!1,It=null,ic=0;function lc(){try{const e=sessionStorage.getItem(_a);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(_a,t),t}catch{return"tab_unavailable"}}function cc(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 dc(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 uc(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 Zt({sessionId:n,limit:Ue})).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}),pc(e,t,"recovery"))}async function Ep(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await Hi(n),{graphNodes:o,graphEdges:a,graphVersion:i}=ac(r);t({graphNodes:o,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(M("toast.sessionReloadedElsewhere"),!0),await uc(e,t).catch(()=>{})}async function Np(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:cc(u.data)})),d=dc(i),m=`gs_${Date.now().toString(36)}_${++ic}`;try{const u=await ku(r,o,c,d,{saveId:m,saveReason:n,tabId:lc()});return e().activeSessionId!==r?"skipped":(Ip(r,e().graphNodes.map(p=>p.id)),t({activeSessionGraphVersion:u.graphVersion}),"saved")}catch(u){return u.status===409?(await Ep(e,t),"conflict"):(console.warn("[sessions] save failed:",u),"failed")}}async function mc(e,t,n){return yr?(vr=!0,It||"skipped"):(yr=!0,It=(async()=>{let r=n,o="skipped";do{if(vr=!1,o=await Np(e,t,r),o==="conflict"||o==="failed")break;r="queued"}while(vr);return o})().finally(()=>{yr=!1,It=null}),It)}function pc(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(Xe&&clearTimeout(Xe),Xe=setTimeout(()=>{Xe=null,mc(e,t,n)},_p)))}async function kp(e,t,n="manual"){let r=!1;if(Xe&&(clearTimeout(Xe),Xe=null,r=!0),yr){if(vr=!0,(It?await It:"skipped")==="failed")throw new Error(M("modal.graphSaveFailed"));return}if(r&&await mc(e,t,n)==="failed")throw new Error(M("modal.graphSaveFailed"))}function jp(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;Xe&&(clearTimeout(Xe),Xe=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:cc(i.data)})),r=dc(t.graphEdges),o=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{Ie(o,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++ic}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":lc()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function gt(e,t,n,r={}){const o=xe(e)?void 0:await yp(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=Xl(l.history,i),d=Zl(i,c),m=Yl(l.history,d),u=Zr([d,...m],l.loadedHistoryRetainLimit+1),h=!(r.autoSelectStartedAt!=null&&l.lastHistorySelectedAt>r.autoSelectStartedAt)&&(!l.currentImage||r.autoSelectStartedAt==null||l.lastHistorySelectedAt<=r.autoSelectStartedAt);h&&st(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 Cp(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const Ap=30;function ho(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function Tp(e,t,n=Ap){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function Pp(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 Rp(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 Mp=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function za(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 Mp)l[c]=a.data[c];return{...o,data:l}}),edges:e.edges}}function Lp(e){return e.data.status==="ready"&&!!e.data.imageUrl}function Op(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 Fp(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 Dp(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 Gp(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 zp(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 Ke(e,t){const{code:n,spec:r,message:o}=ot(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return Li(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?M(r.toastKey):o||M("toast.generateFailed");if(t.showToast(a,!0),n==="JOB_TRACKING_TIMEOUT")return{code:n,message:a}}return{code:n,message:o}}const qp=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],$p=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function Up(e){if(qp.includes(e))return"auth";const t=Je[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||$p.includes(e)?"retry":"fix-input"}function fc(e){const{code:t,message:n}=ot(e),r=Up(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const Hp=Bi.grok.video,Vp=3;function Kp(e,t){return Bi[e]?.[t]}function hc(e){if(e.mcpProvider)return Vp;if(e.videoModelSelected)return Math.min(e.serverLimit,Hp);if(Tt(e.provider)&&!ps[e.provider].generate.references)return 0;const t=Kp(e.provider,"image");return t===void 0?e.serverLimit:Math.min(e.serverLimit,t)}function Ls(e,t={}){const n=t.provider??e.provider,r=t.imageModel??e.imageModel;if(n!=="nai")return{};const o={...e.naiOptionOverrides};Wo(r)||(delete o.straightAlpha,delete o.qualityPresetId),o.seed===null&&delete o.seed;const a=e.negativePrompt.trim();return{...o,...a?{negativePrompt:a}:{}}}const Tr=new Map;function on(e,t){Tr.set(e,t)}function sn(e){Tr.delete(e)}function gc(e){Tr.get(e)?.abort(),Tr.delete(e)}const Bp="element-source:",Wp=500;function Jp(e){return`${Bp}${e}`}function c_(e,t){const n=Jp(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function yc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function Yp(e=cs){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:Wp});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 vc(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function d_(e){const t=e.filePath??(e.kind==="element"?yc(e)??"":""),n=vc(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 qa=32,$a="Image_",Xp=/@([\p{L}\p{N}_-]+)/gu,Zp=new Set([" "," ",`
|
|
5
|
+
`,"(","["]);function bc(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${$a}${r}`);)r+=1;return{tag:`${$a}${r}`,nextAttachmentOrdinal:r+1}}function Qp(e,t){const n=new Set(t),r=e.slice(0,qa)||"Element";if(!n.has(r))return r;let o=2;for(;;){const a=`_${o}`,i=`${r.slice(0,qa-a.length)}${a}`;if(!n.has(i))return i;o+=1}}function Dn(e){return e.trayItems.filter(t=>t.kind==="attachment")}function xc(e){return e.trayItems.filter(t=>t.kind==="element")}function ef(e){return Dn(e).map(t=>t.source.dataUrl)}function tf(e){return xc(e).map(t=>t.source.elementId)}function nf(e){const t={trayItems:e};return{referenceImages:ef(t),selectedElementIds:tf(t)}}function Os(e,t){return e.length<t}function to(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 rf(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Fs(e,t){if(!rf(e,t))return e;const n={...e};return delete n[t],n}function of(e){const t=[];for(const n of e.matchAll(Xp)){const r=n.index,o=r>0?e[r-1]:void 0;o!==void 0&&!Zp.has(o)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function sf(e){return e.reduce((t,n)=>t+(n.kind==="attachment"?1:n.source.referenceFilenames.length),0)}function Ds(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:wc(a,l),...nf(a)}}),n}function af(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function Ic(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 lf(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function Sc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function br(e,t,n,r){return r&&(r.id!==e||r.kind!=="element")?null:Ds(t,(o,a)=>{if(!Os(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=lf(i,e,r),c=l?Rl(l.name):null;if(!l||!c)return{result:null};const d=Qp(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:Sc(l)}};return{result:m,patch:{trayItems:[...o.trayItems,m],retiredTags:Fs(o.retiredTags,d),elementCatalog:Ic(i.elementCatalog,l)}}})}function wc(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 Zo(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function cf(e,t,n){Ds(t,r=>{const o=Zo(r.trayItems,e);return o?{result:void 0,patch:{trayItems:r.trayItems.filter(a=>a.tokenId!==o.tokenId),retiredTags:to(r.retiredTags,[o])}}:{result:void 0}})}function _c(e,t,n){const r=af(e);t(o=>({elementCatalog:r,missingElementIds:wc(o.trayItems,r)}))}function Ec(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 bt=new Set;async function df(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 Mu(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=Ic(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 Sc(c))try{const p=await gp(vc(u));r.includes(p)||r.push(p)}catch{}}return{ok:!0,referenceDataUrls:r,notes:o,elementIds:a,revisions:i}}function uf(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 mf(e,t,n,r,o){if(bt.has(e))return null;bt.add(e);const a=r().graphNodes,i=Fe(a,r().graphEdges);i.some((F,T)=>F!==a[T])&&n({graphNodes:i});const l=i.find(F=>F.id===e);if(!l)return bt.delete(e),null;const c=Ec(r().graphNodes,r().graphEdges,[e]),d=await df(c,n,r);if(d.ok===!1)return r().showToast(M("node.elementMissing",{name:d.name}),!0),bt.delete(e),null;const{prompt:m,parentServerNodeId:u}=l.data;if(!m.trim())return r().showToast(M("toast.promptRequired"),!0),bt.delete(e),null;const p=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:p.provider,x=hc({provider:h,serverLimit:p.referenceLimit,videoModelSelected:!!p.videoModelSelected,mcpProvider:p.mcpProvider??null}),I=uf(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()),g=t.parentServerNodeIdOverride!==void 0?t.parentServerNodeIdOverride:u,_=(l.data.extraParentServerNodeIds??[]).filter(F=>F&&F!==g);if(tc(i,r().graphEdges,e).length>0&&!g)return r().showToast(M("node.parentImageRequired"),!0),bt.delete(e),null;const w=p.activeSessionId,N=Date.now(),j=Math.random().toString(36).slice(2,6),L=`fn_${e}_${N}_${j}`,U=new AbortController;on(L,U);const C=[...p.inFlight,{id:L,prompt:m,startedAt:N,kind:"node",sessionId:w,clientNodeId:e}];o(C),n({graphNodes:r().graphNodes.map(F=>F.id===e?{...F,data:{...F.data,status:"pending",pendingRequestId:L,recoveryRequestId:L,pendingPhase:"queued",pendingStartedAt:N,partialImageUrl:null,error:void 0,errorInfo:null,size:v}}:F),activeGenerations:p.activeGenerations+1,inFlight:C}),r().startInFlightPolling();let q=!0;try{const F=await Gu({parentNodeId:g,..._.length?{extraParentNodeIds:_}:{},prompt:m,quality:Rt(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:w,clientNodeId:e,contextMode:"parent-plus-refs",searchMode:p.webSearchEnabled?"on":"off",webSearchEnabled:p.webSearchEnabled,...Ls(p,{provider:h,imageModel:b}),...I.length?{references:I.map(As)}:{},...d.elementIds.length?{elementIds:d.elementIds,elementRevisions:d.revisions,elementNotes:d.notes}:{}},{onPartial:T=>{r().activeSessionId===w&&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===w&&T.phase&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,pendingPhase:T.phase??k.data.pendingPhase}}:k)})}},{signal:U.signal});return r().activeSessionId===w&&(n({graphNodes:r().graphNodes.map(T=>{if(T.id!==e)return T;const k={...T.data};return delete k.partialImageUrl,{...T,data:{...k,serverNodeId:F.nodeId,imageUrl:F.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:F.elapsed,reasoningEffort:F.reasoningEffort,webSearchCalls:F.webSearchCalls,model:F.model??null,imageToolModel:F.imageToolModel??null,size:F.size??null,errorInfo:null}}})}),q=!0,t.suppressToast||r().showToast(M("toast.nodeCreated",{id:F.nodeId.slice(0,8),elapsed:F.elapsed}))),F.nodeId}catch(F){if(nn(F))return r().activeSessionId===w&&(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)}),q=!0),null;const T=F instanceof Error?F.message:M("toast.nodeCreateFailed");return r().activeSessionId===w&&(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:fc(F)}}:k)}),q=!0,Ke(F,r())),null}finally{bt.delete(e);const F=r().inFlight.filter(T=>T.id!==L);o(F),sn(L),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:F}),r().activeSessionId===w&&q&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function pf(e,t,n){if(n().nodeBatchRunning)return;const r=Vl(n().graphNodes).filter(b=>n().graphNodes.find(v=>v.id===b)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(M("nodeBatch.noneSelected"),!0);return}const o=ec(n().graphNodes,n().graphEdges),a=Gp(n().graphNodes,o,r);if(a.length>0){n().showToast(M("nodeBatch.parentRequired",{count:a.length}),!0);return}const i=zp(n().graphNodes,n().graphEdges,r);if(i.length>0){n().showToast(M("nodeBatch.cycleBlocked",{count:i.length}),!0);return}const l=Op(n().graphNodes,o,r),c=new Set(r),d=l.filter(b=>{if(e==="regenerate-all")return!0;const v=n().graphNodes.find(g=>g.id===b);return v?!Lp(v):!1});if(d.length===0){n().showToast(M("nodeBatch.nothingToRun"));return}const u=Ec(n().graphNodes,n().graphEdges,d).find(b=>b.missing);if(u){n().showToast(M("node.elementMissing",{name:u.name}),!0);return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});let p=0,h=0,x=0;const I=new Set;try{for(const b of d){if(n().nodeBatchStopping)break;if(I.has(b)){x+=1;continue}const v=Fe(n().graphNodes,n().graphEdges);v.some((N,j)=>N!==n().graphNodes[j])&&t({graphNodes:v});const g=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:g,suppressToast:!0}))){h+=1;for(const N of Dp(o,b))I.add(N);continue}p+=1;const S=new Set(Fp(o,c)),w=n().graphNodes.map(N=>S.has(N.id)?{...N,data:{...N.data,status:"stale",error:M("nodeBatch.staleBecauseParentChanged")}}:N);t({graphNodes:Fe(w,n().graphEdges)})}h>0?n().showToast(M("nodeBatch.partialFinished",{done:p,failed:h,skipped:x,total:d.length}),!0):n().showToast(M("nodeBatch.finished",{done:p,total:d.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function Qo(e){return Array.isArray(e.images)}function ff(e,t){return e.modes.includes("both")||e.modes.includes(t)}function no(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||!ff(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 hf=[{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"]}],gf=[{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"]}],yf=[{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"]}],Nc=[...hf,...gf,...yf];function kc(e){return Nc.find(t=>t.id===e)}function ro(){return[...Nc]}function jc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Cc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function vf(e,t,n){const r=n();if(r.uiMode!=="classic")return;const o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=no({catalog:ro(),presetIds:r.selectedPresetIds,provider:Cc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Ns(r.insertedPrompts),d=e??r.getResolvedSize(),m=`mm_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=new AbortController;on(m,u);const p=Date.now(),h=p,x=Sn(r.multimodeMaxImages),I=[...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(I),t({activeGenerations:r.activeGenerations+1,inFlight:I,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:al(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:jc(r),...Ls(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(As)}:{}},g=await fu(v,{onPartial:w=>{t(N=>{const j=N.multimodeSequences[m];return j?{multimodeSequences:{...N.multimodeSequences,[m]:{...j,partials:[...j.partials,{image:w.image,index:w.index??null}].slice(-x)}}}:{}})},onImage:w=>{t(N=>{const j=N.multimodeSequences[m];if(!j)return{};const L=Ga(j.images,[w]);return L.length===j.images.length?{}:{multimodeSequences:{...N.multimodeSequences,[m]:{...j,sequenceId:w.sequenceId??j.sequenceId,returned:L.length,images:L,status:"partial"}}}})}},{signal:u.signal}),_=g.images.map(w=>({...w,prompt:i,elapsed:Number.parseFloat(g.elapsed),provider:g.provider,usage:g.usage,requestId:w.requestId??g.requestId??m,composerPrompt:l,composerInsertedPrompts:c,quality:g.quality,size:g.size,model:g.model??null,imageToolModel:g.imageToolModel??null}));for(const w of _)await gt(w,t,n,{autoSelectStartedAt:h});t(w=>({multimodeSequences:{...w.multimodeSequences,[m]:(()=>{const N=w.multimodeSequences[m],j=Ga(N?.images??[],_);return{sequenceId:g.sequenceId,requestId:m,requested:g.requested,returned:j.length,images:j,partials:[],status:g.status,elapsed:g.elapsed}})()}}));const S=g.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(M(S,{returned:g.returned,requested:g.requested,elapsed:g.elapsed}))}catch(v){v.name==="AbortError"||nn(v)?t(g=>{const _=g.multimodeSequences[m];return _?{multimodeSequences:{...g.multimodeSequences,[m]:{..._,status:"canceled"}}}:{}}):(t(g=>{const _=g.multimodeSequences[m];return _?{multimodeSequences:{...g.multimodeSequences,[m]:{..._,status:"error",error:v.message}}}:{}}),Ke(v,n()))}finally{const v=n().inFlight.filter(g=>g.id!==m);Pe(v),sn(m),t(g=>{const _=new Set(g.activeFlightIds);_.delete(m);let S=g.multimodePreviewFlightId;const w=g.multimodeSequences[m]?.status,N=w==="complete"||w==="partial";if(S===m&&!N){const L=[..._];S=L.length>0?L[L.length-1]:null}const j={...g.multimodeSequences};return N&&S!==m&&delete j[m],{activeGenerations:Math.max(0,g.activeGenerations-1),inFlight:v,activeFlightIds:_,multimodePreviewFlightId:S,multimodeSequences:j}})}}async function bf(e,t,n){const r=n(),o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=no({catalog:ro(),presetIds:r.selectedPresetIds,provider:Cc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Ns(r.insertedPrompts),d=e??r.getResolvedSize(),m=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,u=new AbortController;on(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 I={prompt:i,quality:r.quality,size:d,format:r.format,moderation:r.moderation,provider:r.provider,n:r.provider==="nai"?1:r.count,model:al(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:jc(r),...Ls(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(As)}:{}},b=await $i(I,{signal:u.signal});if(Qo(b)&&b.images.length>1){for(const v of b.images){const g={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 gt(g,t,n,{autoSelectStartedAt:h})}n().showToast(M("toast.generatedBatch",{count:b.images.length,elapsed:b.elapsed}))}else{let v;if(Qo(b)){const g=b.images[0];v={image:g.image,filename:g.filename,reasoningEffort:b.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:b.elapsed,provider:b.provider,providerUrl:g.providerUrl??null,usage:b.usage,requestId:b.requestId??m,quality:b.quality,size:b.size,model:b.model??null,imageToolModel:b.imageToolModel??null,createdAt:g.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 gt(v,t,n,{autoSelectStartedAt:h}),n().showToast(M("toast.generatedSingle",{elapsed:b.elapsed}))}}catch(I){!(I instanceof Error&&I.name==="AbortError")&&!nn(I)&&Ke(I,n())}finally{const I=n().inFlight.filter(b=>b.id!==m);Pe(I),sn(m),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:I})}}function xf(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 If(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,o=await Ie(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 Sf(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(!xf(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 wf=Sf({fetchGeneratedFrame:If,extractFromElement:(e,t,n)=>t==="last"?rn(e,n):t==="first"?oc(e,n):sc(e,n)}),Pr="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 _f(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 Xn(e){return typeof e=="string"&&e.trim()?e.trim():null}function Ac(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:_f(e.videoContinuity.entries)};const t=Xn(e.revisedPrompt)??Xn(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:Xn(e.userPrompt)??Xn(e.prompt),revisedPrompt:t,createdAt:e.createdAt??Date.now()}]}}function En(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 Ef(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 Tc(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 Pc(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"&&Tt(e.provider)&&ps[e.provider].multimode.supported?"multimode":"image"}function Nf(e){return e.mcpProvider?e.multimode:Pc(e)==="multimode"}async function kf(e,t){const n=t();if(!Rn(n.prompt,n.insertedPrompts)||Gs(t))return;const o=Pc(n);if(o==="video")return t().runVideoGenerate();const a=o==="multimode",i=Qr(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&&(gc(n),t().cancelInFlightJob(n),e(r=>{const o=r.multimodeSequences[n];return o?{multimodeSequences:{...r.multimodeSequences,[n]:{...o,status:"canceled"}}}:{}}))}function Gs(e){return(e().missingElementIds??[]).length>0?(e().showToast(M("toast.missingElements"),!0),!0):!1}async function Cf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Gs(t))return;const r=Xm(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 Af(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(M("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const a=Qr(n(),{kind:"node",clientId:e});if(a){t({customSizeConfirm:a});return}await n().runGenerateNode(e)}async function Tf(e,t,n){const r=n().graphNodes.find(a=>a.id===e);if(!r)return;if(!r.data.prompt.trim()){n().showToast(M("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const o=Qr(n(),{kind:"node-in-place",clientId:e});if(o){t({customSizeConfirm:o});return}await n().runGenerateNodeInPlace(e)}async function Pf(e,t,n,r){const o=r().graphNodes.find(i=>i.id===e);if(!o)return;if(!o.data.prompt.trim()){r().showToast(M("toast.promptRequired"),!0);return}if(r().videoModelSelected){const i=r().addSiblingNode(e);return r().runVideoGenerate(i)}if(!t){const i=Qr(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 Rf(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 Rc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Mc(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 Lc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function Mf(e,t,n){const r=e?n().graphNodes.find(S=>S.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():Rn(n().prompt,n().insertedPrompts);if(!i.trim()){n().showToast(Pr,!0);return}const l=n(),c=no({catalog:ro(),presetIds:l.selectedPresetIds,provider:Lc(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 S=n().graphNodes.find(w=>w.data.serverNodeId===r.data.parentServerNodeId);if(S?.data.imageUrl)if(Qe(S.data.imageUrl))try{const w=S.data.imageUrl.replace(/^\/generated\//,"");u=(await wf.extractFrame({kind:"generated",filename:w},"last")).dataUrl,p=S.data.videoContinuity??Ac({filename:w,prompt:S.data.prompt,userPrompt:S.data.prompt,revisedPrompt:S.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=w}catch{n().showToast(M("video.continuationFallbackT2V"),!0)}else m=S.data.imageUrl.replace(/^\/generated\//,"")}const x=Date.now(),I=x,b=`vid_${x}_${Math.random().toString(36).slice(2,6)}`,v=new AbortController;on(b,v);const g=n().activeSessionId,_=[...n().inFlight,{id:b,prompt:d,startedAt:x,kind:"video",sessionId:g,clientNodeId:e??null}];Pe(_),r&&t({graphNodes:n().graphNodes.map(S=>S.id===e?{...S,data:{...S.data,status:"pending",pendingRequestId:b,pendingPhase:"queued",pendingStartedAt:x,partialImageUrl:null,error:void 0,errorInfo:null}}:S)}),t({inFlight:_,activeGenerations:_.length,videoProgress:0}),n().startInFlightPolling();try{const S=n().providerUrlReference,w={prompt:d,requestId:b,...Mc(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:Rc(n()),sessionId:g,clientNodeId:e??null,...S?{providerUrl:S}:{}},N=await ls(w,{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===g&&(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:g};await gt(j,t,n,{autoSelectStartedAt:I})}}catch(S){if(nn(S))r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(w=>w.id===e?{...w,data:{...w.data,status:w.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0,errorInfo:null}}:w)});else{const w=ot(S).code==="JOB_TRACKING_TIMEOUT",N=w?Ke(S,n()).message:S instanceof Error?S.message:"Video generation failed",j=w?{...fc(S),message:N}:null;r&&n().activeSessionId===g&&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)}),w||n().showToast(N,!0)}}finally{const S=n().inFlight.filter(w=>w.id!==b);Pe(S),sn(b),t({inFlight:S,activeGenerations:S.length,videoProgress:null}),n().startInFlightPolling()}}async function Lf(e,t,n,r){const o=t?.trim();if(!o)throw r().showToast(Pr,!0),new Error(Pr);if(Gs(r))return!1;const a=r(),i=no({catalog:ro(),presetIds:a.selectedPresetIds,provider:Lc(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;on(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:Rc(r()),requestId:m,...Mc(r()),mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},x=await ls(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}),I={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 gt(I,n,r,{autoSelectStartedAt:d})}catch(h){return nn(h)||(ot(h).code==="JOB_TRACKING_TIMEOUT"?Ke(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),sn(m),n({inFlight:h,activeGenerations:h.length,videoProgress:null}),r().startInFlightPolling()}return!0}function es(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 Nn(e){const t=new Map([...Jl({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,es(r)])),memory:new Map(e.inFlight.map(n=>[n.id,n])),scopes:lp({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function zs(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function Oc(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&&_n(r,e.scopes)}).map(([n])=>n))}function Of(e,t,n){const r=Ar(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 es(o)===es(e)?e:o}function Ff(e,t,n,r,o){if(t&&(o.mode==="reconcile"||!n))return[_n(Ar(t),r.scopes)?Of(e,t,o.mode):e];if(n)return _n(Ar(n),r.scopes)?(n.status==="error"&&o.terminalErrors.push(cp(n)),[]):[e];const a=o.now-e.startedAt;return(o.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function Fc(e,t,n,r){if(!zs(e,t))return null;const o=Nn(t),a=Oc(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)?Ff(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=Ar(p);_n(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 kn=0;function jn(){if(kn+=1,typeof window>"u")return;const e=window;e.__ima2InflightTimer!==void 0&&clearInterval(e.__ima2InflightTimer),e.__ima2InflightTimer=void 0,e.__ima2StopTicks=0,window.removeEventListener(_t,jn)}function Df(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)Ke(o,n())}function Gf(e,t){e.length&&t(n=>{const r=new Set(n.history.map(qe)),o=e.filter(a=>{const i=qe(a);return r.has(i)?!1:(r.add(i),!0)});return o.length?(!n.currentImage&&o[0]?.filename&&st(o[0].filename),{history:Zr([...o,...n.history],Math.max(Ue,n.history.length+o.length)),currentImage:n.currentImage??o[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+o.length)}):{}})}function zf(e,t,n){const r=Nn(n()),o=Oc(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<Bl);i.length!==r.local.size&&(Pe(i),t({inFlight:i,activeGenerations:i.length}))}async function qf(e,t,n,r,o){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await Zt({limit:Ue,since:a});if(!o()||!zs(e,r()))return;Gf(i.map(On),n),t&&zf(t,n,r)}catch{}}function $f(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function Uf(e,t,n){if(ue()){jn();return}const r=fe(),o=kn,a=()=>!ue()&&r===fe()&&o===kn,i=Nn(t());let l=null;if(!$f(t(),n))try{const c=await Wl(i.scopes);if(!a())return;const d=Fc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;Df(d,e,t),l={snapshot:Nn(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&zs(i,t())&&await qf(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&jn()}function Hf(e,t){if(typeof window>"u"||ue())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(_t,jn),n.__ima2InflightTimer=window.setInterval(()=>Uf(e,t,n),1500))}async function Vf(e,t){if(ue())return;const n=fe(),r=kn;try{const o=Nn(t()),a=await Wl(o.scopes);if(ue()||n!==fe()||r!==kn)return;const i=Fc(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)Ke(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const Nt=()=>"nc_"+Math.random().toString(36).slice(2,10);function Ua(e,t){return{x:e*360,y:t*320}}const Kf=360,Dc=320;function Bf(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 qs(e){const t=e.filter(r=>!r.data.parentServerNodeId);if(t.length===0)return Ua(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:Ua(0,0).x,y:n+Dc}}function Gc(e,t,n){const r=Bf(e.id,t,n),o=e.position.x+Kf;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+Dc}}const Cn="source-right",An="target-left";function oo(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function Wf(e,t){return e&&e.startsWith(`${t}-`)?e:null}function Jf(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 Yf(e,t){const n=Nt();t().recordGraphHistory("add-root");const r={id:n,type:"imageNode",position:qs(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 Xf(e,t,n){const r=Nt();n().recordGraphHistory("add-root-from-history");const o={id:r,type:"imageNode",position:qs(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 Zf(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return e;n().recordGraphHistory("add-child");const o=Nt(),a={id:o,type:"imageNode",position:Gc(r,n().graphNodes,n().graphEdges),data:{clientId:o,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:Qe(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:oo(e,o,Cn,An),source:e,target:o,sourceHandle:Cn,targetHandle:An};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&Qe(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 rn(l);t({graphNodes:n().graphNodes.map(d=>d.id===o?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return o}function Qf(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=Nt(),u={id:m,type:"imageNode",position:qs(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=Nt(),c={id:l,type:"imageNode",position:Gc(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:oo(a,l,Cn,An),source:a,target:l,sourceHandle:Cn,targetHandle:An};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function eh(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=Nt(),l=Wf(n,"source")??Cn,c=Jf(l)??An,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:oo(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 th(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return e;n().recordGraphHistory("duplicate-branch");const o=Nt(),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 Fn(i,"node-reference.png");t({graphNodes:n().graphNodes.map(c=>c.id===o?{...c,data:{...c.data,referenceImages:[l]}}:c)})}catch{}})()}return o}function nh(e,t,n,r){n({graphNodes:r().graphNodes.map(o=>o.id===e?{...o,data:{...o.data,prompt:t}}:o)}),r().scheduleGraphSave()}function rh(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),Rs(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:Fe(a,i),graphEdges:i}),n().scheduleGraphSave()}function oh(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)Rs(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:Fe(o,a),graphEdges:a}),n().scheduleGraphSave()}function sh(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:Fe(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(M("edge.disconnected"))}function ah(e,t,n,r,o,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(bp(a().graphEdges,e,t)){a().showToast(M("edge.cycleBlocked"),!0);return}if(!a().graphNodes.find(d=>d.id===e))return;a().recordGraphHistory("connect-nodes");const c=[...a().graphEdges,{id:oo(e,t,n,r),source:e,target:t,sourceHandle:n,targetHandle:r}];o({graphNodes:Fe(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function ih(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(M("toast.refLimitExceeded"),!0);return}const c=t.slice(0,Math.max(0,l)),d=c.filter(Cr),m=c.filter(h=>!Cr(h)),p=(await Promise.all(m.map(async h=>{try{return await js(h,{preserveTransparency:Kl(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 I=[...x.data.referenceImages??[],...p].slice(0,r().referenceLimit);return eo(h,e,I),{...x,data:{...x.data,referenceImages:I}}})}),r().scheduleGraphSave()}d.length>0&&r().showToast(M("toast.refHeicUnsupported"),!0),m.length-p.length>0&&r().showToast(M("toast.refTooLarge"),!0),t.length>l&&r().showToast(M("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 eo(r().activeSessionId,e,l),{...a,data:{...a.data,referenceImages:l}}})}),r().scheduleGraphSave())}async function lh(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(M("toast.refLimitExceeded"),!0);return}let i;try{i=Qe(t)||Qe(n)?await rn(t):await Fn(t,n||"node-reference.png")}catch{o().showToast(M("toast.currentImageLoadFailed"),!0);return}zc(e,i,r,o)}function ch(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 eo(r().activeSessionId,e,a),{...o,data:{...o.data,referenceImages:a}}})}),r().scheduleGraphSave()}function dh(e,t,n){Rs(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const Ha=10;function qc(e,t){return t?t.filename&&e.filename===t.filename?!0:e.image===t.image:!1}function uh(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(t=>!!t)}function Lt(e){return e.filter(t=>!t.canvasVersion)}function rt(e,t){if(!t)return null;const n=Lt(e);if(!t.canvasVersion)return n.find(a=>qc(a,t))??null;const r=uh(t);return n.find(a=>a.filename?r.includes(a.filename):!1)??null}function mh(e,t){const n=Lt(e),r=rt(e,t);return n.findIndex(o=>qc(o,r))}function ph(e,t,n){const r=Lt(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=mh(e,t);if(o<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-Ha:Ha,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 $c(e,t){const n=Lt(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 bn(e){return!e.canvasVersion}function xr(e){const t=new Set;return e.filter(n=>{const r=Te(n);return t.has(r)?!1:(t.add(r),!0)})}const Uc=72,Va=10;function Hc(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 fh(e){return e<=1?1:e===2?2:4}function Vc(e){const t=new Set,n=new Map,r=[];for(const o of e){if(!bn(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(Hc);return r}function Kc(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Te(e):null}function go(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function hh(e,t,n,r,o=Uc){const a=Vc(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 go(i);if(n==="last")return go(l);const c=Kc(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const m=n==="pagePrevious"?-Va:n==="pageNext"?Va: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?go(p):null}const Bc={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},gh={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},yh={default:Bc,"prompt-studio":gh};function Gn(e,t){return yh[e]??Bc}function vh(e,t){return Gn(e).promptBuilderSurface!=="off"}const bh="history:";function Wc(e,t,n){if(!t||n||!t.startsWith(bh)||!(t in e))return e;const r={...e};return delete r[t],r}function xh(e){const t=e.multimodePreviewFlightId;return t?t.startsWith("history:")?t.slice(8):e.multimodeSequences[t]?.sequenceId??null:null}async function Ih(e,t){const n=t().historyNextCursor;if(!(!n||t().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const r=await Zt({limit:Ue,cursor:n}),o=r.items.map(On);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(M("gallery.loadOlderFailed"),!0)}}}async function Sh(e,t){try{const n=await Zt({limit:Ue,favoritesOnly:!0}),r=n.items.map(On);e(o=>{const a=Ql(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(M("gallery.loadOlderFailed"),!0)}}async function wh(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await Zt({limit:Ue,cursor:n,favoritesOnly:!0}),o=r.items.map(On);e(a=>{const i=Ql(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(M("gallery.loadOlderFailed"),!0)}}}function _h(e,t,n){const r=Date.now(),o=n().history,a=e.canvasVersion?rt(o,e)??Lt(o)[0]??null:rt(o,e)??e;st(a?.filename??null);const i=Gn(n().workspaceProfile).restoreComposerFromHistory,l=n().prompt,c=n().insertedPrompts,d=l.trim()!==""||c.length>0,m=i&&a&&!d?qm(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:Wc(x.multimodeSequences,u,!!h),...m}))}function Eh(e,t,n){const r=Date.now(),o=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(Hc);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";st(null),t(d=>({currentImage:null,lastHistorySelectedAt:r,unseenGeneratedCount:0,canvasOpen:!1,multimodePreviewFlightId:a,multimodeSequences:{...Wc(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:o,partials:[],status:c}}}))}function Nh(e,t,n){const r=n(),o=Gn(r.workspaceProfile);if(r.uiMode==="classic"&&o.multimodeHistoryGrouping==="sequence"){const i=hh(r.history,r.currentImage,e,xh(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=ph(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function kh(e,t,n){const r=e.canvasVersion?rt(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(M("gallery.deleteFailed"),!0);return}const o=r.filename,a=n().currentImage,l=(a?rt(n().history,a)??a:null)?.filename===o,c=l?$c(n().history,o):a;try{await Ui(o),t(d=>{const m=mp(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&&st(c?.filename??null),n().showToast(M("gallery.movedToSystemTrash",{filename:o}))}catch(d){console.error("[history] trash failed",d),n().showToast(M("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(M("gallery.deleteFailed"),!0);return}if(!window.confirm(M("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 Ui(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&&st(null),n().showToast(M("history.sequenceDeleted",{count:a.size}))}catch(d){console.error("[history] sequence trash failed",d),n().showToast(M("gallery.deleteFailed"),!0)}}async function Ch(e,t){const n=t().trashPending;if(n)try{await Iu(n.filename,n.trashId),t().addHistoryItem(n.item),e({trashPending:null})}catch(r){console.error("[history] restore failed",r),t().showToast(M("gallery.restoreFailed"),!0)}}async function Ah(e,t,n){const r=e.canvasVersion?rt(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(M("gallery.deleteFailed"),!0);return}const o=r.filename;if(!window.confirm(M("result.permanentDeleteConfirm",{filename:o})))return;const i=n().currentImage,c=(i?rt(n().history,i)??i:null)?.filename===o,d=c?$c(n().history,o):i;try{await xu(o),t(m=>({history:m.history.filter(u=>u.filename!==o),currentImage:d,trashPending:m.trashPending?.filename===o?null:m.trashPending})),c&&st(d?.filename??null),n().showToast(M("gallery.permanentDeleted",{filename:o}))}catch(m){console.error("[history] permanent delete failed",m),n().showToast(M("gallery.deleteFailed"),!0)}}function Th(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&&st(null)}function Ph(e,t,n){const r=n(),o={...e,createdAt:e.createdAt||Date.now()},a=Xl(r.history,o),i=Zl(o,a),l=Yl(r.history,i);t({history:Zr([i,...l],r.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(r.loadedHistoryRetainLimit,Math.min(r.history.length+1,r.loadedHistoryRetainLimit+1))})}async function Rh(e,t,n){if(!e.type||!/^image\/(png|jpeg|webp)$/.test(e.type))return n().showToast(M("toast.localImportInvalid"),!0),null;try{const r=await hu(e);return n().addHistoryItem(r),t({currentImage:r,unseenGeneratedCount:0}),r.filename&&st(r.filename),n().showToast(M("toast.localImportSuccess")),r}catch{return n().showToast(M("toast.localImportFailed"),!0),null}}function Mh(e,t){(async()=>{try{const n=await Zt({limit:Ue}),r=n.items.map(On);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Ue}),r.length>0){const o=Fl(),a=o?r.find(c=>c.filename===o):null,i=Lt(r),l=(a?rt(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(Ue,r.length)}),l?.filename!==o&&st(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function Jc(e,t){try{const{sessions:n}=await wu();if(e({sessions:n}),!t().activeSessionId){const o=Ym(),a=o?n.some(i=>i.id===o):!1;o&&a?await t().switchSession(o):await t().createAndSwitchSession(M("session.firstGraph"))}}catch(n){console.warn("[sessions] load failed:",n),t().showToast(M("modal.sessionInitialLoadFailed"),!0),window.confirm(M("modal.sessionInitialLoadRetry"))&&await Jc(e,t)}}async function Lh(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(M("modal.sessionSwitchSaveFailed"),!0);return}t({sessionLoading:!0});try{const{session:r}=await Hi(e),{graphNodes:o,graphEdges:a,graphVersion:i}=ac(r);t({activeSessionId:e,activeSessionGraphVersion:i,graphNodes:o,graphEdges:a,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),ks(e),await n().reconcileGraphPending().catch(()=>{})}catch(r){console.warn("[sessions] switch failed:",r),t({sessionLoading:!1}),n().showToast(M("toast.sessionLoadFailed"),!0)}}}async function Oh(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:M("session.assetAbortedError")}}});e({graphNodes:c})}await uc(t,e).catch(()=>{})}async function Fh(e,t,n){e==null&&(e=M("session.untitled"));try{const{session:r}=await _u(e);t({sessions:[r,...n().sessions],activeSessionId:r.id,activeSessionGraphVersion:r.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),ks(r.id)}catch(r){console.warn("[sessions] create failed:",r),n().showToast(M("toast.sessionCreateFailed"),!0)}}async function Dh(e,t,n){const r=n().activeSessionId;if(r)try{await Eu(r,e),t({sessions:n().sessions.map(o=>o.id===r?{...o,title:e,updatedAt:Date.now()}:o)})}catch{n().showToast(M("toast.sessionRenameFailed"),!0)}}async function Gh(e,t,n){try{await Nu(e);const r=n().sessions.filter(o=>o.id!==e);t({sessions:r}),n().activeSessionId===e&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),ks(null),r.length>0?await n().switchSession(r[0].id):await n().createAndSwitchSession(M("session.firstGraph")))}catch{n().showToast(M("toast.sessionDeleteFailed"),!0)}}function zh(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),n.imageToolModel=e.provider==="api"&&fs(t.imageToolModel)?t.imageToolModel:null,n.quality=Rt(e.provider,n.imageToolModel,Gl(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&&Ju(t.model)&&(n.imageModel=t.model);const o=Zm(t.size);return o.preset&&(n.sizePreset=o.preset),o.preset==="custom"&&o.w&&o.h&&(n.customW=nt(o.w,e.customW),n.customH=nt(o.h,e.customH)),n}function zn(e,t){return Ds(e,t)}function $s(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 Yc(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function Us(e,t){return zn(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(!Os(o,r))break;const m=bc(c,i),u=Yc(d,m.tag);o.push(u),l.push(u),i.add(u.tag),a=Fs(a,u.tag),c=m.nextAttachmentOrdinal}return l.length===0?{result:l}:{result:l,patch:{trayItems:o,nextAttachmentOrdinal:c,retiredTags:a,providerUrlReference:null}}})}function qh(e,t,n){return Us(e,t)}function so(e,t,n,r){const o=$s(e);return o?Us([{dataUrl:e,mimeType:o,origin:t}],n)[0]??null:null}function $h(e,t,n){so(e,"gallery",t)}async function Uh(e,t,n){const r=n().activeReferenceLimit(),o=Math.max(0,r-n().trayItems.length),a=e.slice(0,o),i=a.filter(Cr),l=a.filter(u=>!Cr(u)),d=(await Promise.all(l.map(async u=>{try{const p=await js(u,{preserveTransparency:Kl(u)}),h=$s(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=Us(d,t);i.length>0&&n().showToast(M("toast.refHeicUnsupported"),!0),l.length-d.length>0&&n().showToast(M("toast.refTooLarge"),!0),(e.length>o||d.length>m.length)&&n().showToast(M("toast.refLimitExceeded"),!0)}async function Hh(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let o="";try{o=await Ts(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(M("metadata.readFailed"),!0),!1}}function Vh(e,t){const n=t().metadataRestore;if(!n)return;const r=zh(t(),n.metadata);if(te({imageToolModel:r.imageToolModel,quality:r.quality}),r.imageModel&&Ll(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(M("metadata.applied"))}function Hs(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function Vs(e,t){t.length!==e.length&&te({insertedPrompts:t})}function Xc(e,t,n){const r=n().insertedPrompts;zn(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:to(o.retiredTags,[a])};if(a.kind==="attachment"){const c=Dn({trayItems:i}).length===0;l.canvasReferenceImage=a.source.dataUrl===o.canvasReferenceImage?null:o.canvasReferenceImage,c&&(l.insertedPrompts=Hs(o),l.videoContinuityLineage=null)}return{result:void 0,patch:l}}),Vs(r,n().insertedPrompts)}function Kh(e,t,n){const r=Dn(n())[e];r&&Xc(r.tokenId,t,n)}function Bh(e,t){const n=t().insertedPrompts;zn(e,r=>{const o=Dn(r);return{result:void 0,patch:{trayItems:r.trayItems.filter(i=>i.kind!=="attachment"),retiredTags:to(r.retiredTags,o),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Hs(r),providerUrlReference:null}}}),Vs(n,t().insertedPrompts)}function Wh(e,t){const n=t().insertedPrompts;zn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Hs(r),providerUrlReference:null}})),Vs(n,t().insertedPrompts)}function Jh(e,t,n){const r=Dn(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(!Os(a,t))return{result:!1};const i=bc(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=Yc(n,i.tag),c=Fs(to(e.retiredTags,r),l.tag);return{result:!0,patch:{trayItems:[l,...a],nextAttachmentOrdinal:i.nextAttachmentOrdinal,retiredTags:c,canvasReferenceImage:n.dataUrl,providerUrlReference:null}}}async function Yh(e,t,n,r){let o;try{o=await Fn(r??e.image,e.filename||"canvas-version-reference.png")}catch{throw n().showToast(M("toast.currentImageLoadFailed"),!0),new Error("canvas_reference_attach_failed")}const a=$s(o);if(!a){n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!zn(t,(l,c)=>Jh(l,c,{dataUrl:o,mimeType:a,originalName:e.filename||"canvas-version-reference.png",origin:"canvas"}))){n().showToast(M("toast.refSlotFull"),!0);return}n().showToast(M("canvas.version.usingAsReference"))}function Zc(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Xh(e,t){const n=t().currentImage;if(!n){t().showToast(M("toast.noCurrentImageForRef"),!0);return}if(t().trayItems.length>=t().activeReferenceLimit()){t().showToast(M("toast.refSlotFull"),!0);return}let r;try{r=await Fn(Zc(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!so(r,"gallery",e)){t().showToast(M("toast.refSlotFull"),!0);return}t().showToast(M("toast.addedCurrentAsRef"))}async function Zh(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(M("toast.refSlotFull"),!0);return}let r;try{r=await Fn(Zc(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!so(r,"gallery",t)){n().showToast(M("toast.refSlotFull"),!0);return}n().showToast(M("toast.addedCurrentAsRef"))}function qn(e){const{provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e();return lt({provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:o,comfyVideoWorkflow:a})}function $n(e,t,n,r){const o=Ul();o[e.provider]={...o[e.provider],...wa(e)};const a={...o[t.provider],...wa(t)};r&&delete a[r],o[t.provider]=a,rp(o),op(t),n(i=>{const l=t.provider==="api"?i.imageToolModel:null,c=Rt(t.provider,l,i.quality);return te({imageToolModel:l,quality:c}),{...t,imageToolModel:l,quality:c}})}function Qh(e,t,n){const r=qn(n);if(e===r.provider)return;const o=Tt(e)?Ul()[e]:void 0,a=lm(r,e,o);$n(r,a,t)}function eg(e,t,n){const r=qn(n),o=lt({provider:im(r.provider,e),imageModel:e,videoModelSelected:!1});$n(r,o,t)}function tg(e,t,n){const r=qn(n),o=lt({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:Mt(e)||tt});$n(r,o,t)}function ng(e,t,n){const r=qn(n),o=lt({...r,provider:"comfy",comfyWorkflow:e,comfyVideoWorkflow:null});$n(r,o,t,e===null?"image":void 0)}function rg(e,t,n){const r=qn(n),o=lt({...r,provider:"comfy",comfyVideoWorkflow:e,videoModelSelected:!1});$n(r,o,t,e===null?"video":void 0)}function og(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 sg(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&&og(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const ag=1e4;let Tn=[];async function Ks(e){const t=await $("/api/mcp/providers",{signal:e});return Tn=Array.isArray(t.providers)?t.providers:[],Tn}function ig(e){return Fi("/api/mcp/providers",e)}function lg(e,t){return Fi(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function cg(){return Tn}async function u_(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 m_(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function p_(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function Qc(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 dg(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 ug(e,t){let n=!1;const r=()=>n?!1:(n=!0,o(),a(),!0),o=Ct(e,null,(i,l)=>{if(i==="done"){const c=dg(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?.(et(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Xt(()=>{if(!r())return;const i=new Error("MCP generation timed out");i.code="MCP_STREAM_TIMEOUT",t.onError?.(i)});return r}async function mg(e,t){const n=e.requestId??`mcp_ui_${crypto.randomUUID()}`,r=ug(n,t);try{const a=(await Ks()).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 Ur(),await $("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(o){throw r(),o}}function ed(){const[e,t]=y.useState(()=>[...Tn]),[n,r]=y.useState(Tn.length===0),[o,a]=y.useState(null),i=y.useCallback(async()=>{try{const l=await Ks();t([...l]),a(null)}catch(l){a(l instanceof Error?l:new Error(String(l)))}finally{r(!1)}},[]);return y.useEffect(()=>{i();const l=window.setInterval(()=>{i()},ag);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:o,refresh:i}}let Rr=null;function td(e){if(ot(e).code==="JOB_TRACKING_TIMEOUT")return M("toast.jobTrackingTimeout");const t=e,n=t.code??t.message??"";return n.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")||t.message?.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")?M("mcp.errorUnsupportedInput"):n==="MCP_END_FRAME_REQUIRES_START"?M("mcp.errorEndRequiresStart"):n==="INVALID_MCP_REFERENCES"?M("mcp.errorInvalidReferences"):n==="INVALID_START_FRAME"?M("mcp.errorInvalidFrame"):n.startsWith("INVALID_MCP_TEMP_REFERENCE")||n==="MCP_TEMP_REFERENCES_FAILED"?M("mcp.errorTempReferences"):M(n==="MCP_NOT_CONNECTED"||n==="MCP_PROVIDER_UNKNOWN"?"mcp.selectionUnavailable":"mcp.generateFailed")}async function pg(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 fg(e){try{await $(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function hg(e,t,n){let r=()=>{};const o=new Promise(i=>{r=i});if(await mg(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(td(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 gg(e){const t=e();if((t.mcpProvider?cg().find(c=>c.id===t.mcpProvider):void 0)?.executable===!1){e().showToast(M("mcp.higgsfieldLocked"),!0);return}const r=Rn(t.prompt,t.insertedPrompts);if(!r)return;const o=t.mcpReferenceSelection??Ve();if(Rm(o)){e().showToast(M("mcp.referenceTagInvalid"),!0);return}const a=t.selectedElementIds??[];if(t.mcpCharacterElementId&&a.length>0){e().showToast(M("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?Rl(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 pg(o);l=c.batchId;const d=Gm({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 hg(d,e,!!l)}catch(c){e().showToast(td(c),!0)}finally{l&&await fg(l)}}function an(e){Ln(null,null,"image"),te({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ve(),mcpCharacterElementId:null,...Rr?{generate:Rr}:{}})}function ao(e,t,n,r=null,o){if(!e){an(t);return}Rr||(Rr=n().generate);const a=n().mcpProvider===e?n().mcpModel??r:r,i=o??n().mcpMediaKind??"image",l=n().mcpProvider!==e;Ln(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:Ve()}:{},count:1,multimode:!1,generate:()=>gg(n)})}function yg(e,t,n){Ln(n().mcpProvider??null,e,n().mcpMediaKind??"image"),te({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ve()})}function vg(e,t,n,r,o){const a=Lm(o);let i=o?Es(o.inputRoles,r().mcpReferenceSelection):Ve();const l=r().currentImage;o?.inputRoles.includes("start_image")&&!i.startFrameFilename&&l?.filename&&!xe(l)&&(i={...i,startFrameFilename:l.filename}),Ln(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 bg(e,t,n){(n().mcpMediaKind??"image")!==e&&(Ln(n().mcpProvider??null,null,e),te({mcpRatio:null,mcpParameters:{}}),t({mcpMediaKind:e,mcpModel:null,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ve()}))}function xg(e,t){te({mcpRatio:e}),t({mcpRatio:e})}function Ig(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 Sg(e,t,n){const r=Es(n().mcpInputRoles??[],_s(e)),o=n().mcpReferenceSelection??Ve();Pl(o,r)||t({mcpReferenceSelection:r})}function wg(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},o=Al(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??Ve(),i=Es(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!Om(r,o),d=!Pl(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 _g(e,t){const n=np();n.provider&&(ao(n.provider,e,t,n.model,n.kind),te({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function Eg(e,t,n){an(t),Qh(e,t,n)}function Ng(e,t,n){n().provider!=="api"&&(e=null);const r=Rt(n().provider,e,n().quality);te({imageToolModel:e,quality:r}),t({imageToolModel:e,quality:r})}function kg(e,t,n){e=Rt(n().provider,n().imageToolModel,e),te({quality:e}),t({quality:e})}function jg(e,t){te({sizePreset:e}),t({sizePreset:e})}function Cg(e,t,n,r){const o=nt(e,r().customW),a=nt(t,r().customH);te({customW:o,customH:a}),n({customW:o,customH:a})}function Ag(e,t){te({grokAspectRatio:e}),t({grokAspectRatio:e})}function Tg(e,t){te({grokResolution:e}),t({grokResolution:e})}function Pg(e,t){te({format:e}),t({format:e})}function Rg(e,t){te({moderation:e}),t({moderation:e})}function Mg(e,t,n){an(t),eg(e,t,n)}function Lg(e,t,n){an(t),tg(e,t,n)}function Og(e,t,n){an(t),ng(e,t,n)}function Fg(e,t,n){an(t),rg(e,t,n)}function Dg(e){return sg(e())}function Gg(e,t){Km(e),t({reasoningEffort:e})}function zg(e,t){Jm(e),t({webSearchEnabled:e})}function qg(e,t){const n=Sn(e);te({count:n}),t({count:n})}function $g(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 Ug(e,t){const n=Sn(e);te({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function Hg(e,t){te({promptMode:e}),t({promptMode:e})}function Vg(e,t){te({prompt:e}),t({prompt:e})}function Kg(e,t){te({negativePrompt:e}),t({negativePrompt:e})}function Bg(e,t,n,r){const o={...r().naiOptionOverrides,[e]:t};Ol(o),n({naiOptionOverrides:o})}function Wg(e){Ol({}),e({naiOptionOverrides:{}})}function Jg(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 yo="starred";async function Yg(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(yo))return"noop";if(r)return await t.updateAsset(r.id,{tags:[...new Set([...r.tags,yo])]}),"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:[yo],metadata:{origin:"star",mediaType:o}}),"created"}function Xg(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 Zg(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 Qg(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 ey(e){te({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function ty(e){e({promptLibraryLoading:!0});try{const t=await Cu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function ny(e,t,n){try{await Au(e),await n().loadPromptLibrary(),n().showToast(M("promptLibrary.saved"))}catch(r){console.error("[PromptLibrary] save failed",r),n().showToast(M("promptLibrary.saveFailed"),!0)}}async function ry(e,t,n){try{await Tu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function oy(e,t,n){try{await Pu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function sy(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()||M("promptLibrary.untitled"),text:i.trim(),tags:[]})}if(r.length===0){n().showToast(M("promptLibrary.importNoValidFiles"),!0);return}const o=await Ru({prompts:r});await n().loadPromptLibrary(),n().showToast(M("promptLibrary.imported",{count:o.promptsImported}))}catch(r){console.error("[PromptLibrary] import failed",r),n().showToast(M("promptLibrary.importFailed"),!0)}}async function ay(e,t,n){const r=e.filename;if(!r)return null;let o;try{o=(await yu(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(M("gallery.favoriteFailed"),!0),null}if(!o)return o;try{await Yg({...e,filename:r},{getAssets:cs,createAsset:Kr,updateAsset:Vi})!=="noop"&&n().showToast(M("assets.starSaved"))}catch(a){console.error("[GalleryFavorite] asset sync failed",a),n().showToast(M("assets.starSaveFailed"),!0)}return o}async function iy(e,t,n){if(e){gc(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(M("toast.cancelFailed"),!0)}}}function ly(e,t){const n=Jl(),r=Fl(),o=Hl(),a=Xr(),i=tn();e(l=>{const c=r?l.history.find(p=>p.filename===r)??null:null,d=c?rt(l.history,c):null,m=Lt(l.history)[0]??null,u=l.currentImage?.canvasVersion?rt(l.history,l.currentImage)??m:l.currentImage;return{inFlight:n,activeGenerations:n.length,...o,imageToolModel:o.provider==="api"?i.imageToolModel??null:null,quality:Rt(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 cy(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):Zr([e,...n.history],n.loadedHistoryRetainLimit+1):n.history,loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,Math.min(n.history.length+1,n.loadedHistoryRetainLimit+1))}))}function dy(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function uy(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(ll,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function my(e,t){try{localStorage.setItem(bs,e)}catch{}t({galleryScope:e})}function py(e,t){try{localStorage.setItem(hl,e),localStorage.setItem(bs,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function fy(e,t){const n=e==="card-news"&&!bl?"classic":e;try{localStorage.setItem(cl,n)}catch{}t({uiMode:n})}function hy(e,t){try{localStorage.setItem(dl,e)}catch{}t({historyStripLayout:e})}function gy(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 yy(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 vy(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 by(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 xy(e,t,n){t({graphNodes:Fe(e,n().graphEdges)}),n().scheduleGraphSave()}function Iy(e,t,n){t({graphEdges:e,graphNodes:Fe(n().graphNodes,e)}),n().scheduleGraphSave()}function Sy(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:wn(t().graphNodes,[])}})}function wy(e,t,n,r){n({graphNodes:ap(r().graphNodes,r().graphEdges,e,t)})}function _y(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(M("nodeBatch.stopQueued")))}function Ey(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function Ny(e,t,n){t({canvasExportBackground:e}),Ml(e,n().canvasExportMatteColor)}function ky(e,t,n){t({canvasExportMatteColor:e}),Ml(n().canvasExportBackground,e)}const ct=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let vo=0;async function nd(e){const{folders:t}=await ds();e({assetsFolders:t})}const Bs=nd;async function Ws(e,t,n){const r=e!==!1;if(!r&&n().assetsLoading)return;const o=++vo;t({assetsLoading:!0,...r?{assetsLoadError:!1}:{}});try{const a=n().assetsFilters,i=await cs({...a,cursor:r?null:n().assetsCursor}),l=r?await Promise.all([ds(),us()]):null;if(o!==vo)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){ct(a),o===vo&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function jy(e,t){!t().assetsCursor||t().assetsLoading||await Ws(!1,e,t)}function Ka(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),Ws(!0,t,n)}async function Cy(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 Kr({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 ct(o),!1}}async function Ay(e,t,n){try{const{asset:r}=await Vi(e,t);let o=null;try{o=(await us()).tags}catch(a){ct(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 ct(r),!1}}async function Ty(e,t){try{return await Ou(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return ct(n),!1}}async function Py(e,t,n){try{return await Fu({name:e,parentId:t}),await Bs(n),!0}catch(r){return ct(r),!1}}async function Ry(e,t,n){try{return await Ki(e,{name:t}),await Bs(n),!0}catch(r){return ct(r),!1}}async function My(e,t,n){try{return await Ki(e,{parentId:t}),await Bs(n),!0}catch(r){return ct(r),!1}}async function Ly(e,t){try{await Du(e);const[{folders:n},{tags:r}]=await Promise.all([ds(),us()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return ct(n),!1}}function Oy(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(Yu(e.imageModel)||Xu(e.imageModel)))return e.imageModel}async function rd(e,t,n){if(!e.filename)return;const r=n();try{await Kr({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 Fy(e,t,n){const r=n().assetGenItems.find(o=>o.requestId===e);r&&(r.mediaType==="video"?await od(r,t,n):await rd(r,t,n))}async function Dy(e,t,n,r){const o=n(),a=o.assetGenPrompt.trim(),i=await ls({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 gt(l,t,n,{autoSelectStartedAt:Date.now()}),t(c=>({assetGenItems:[l,...c.assetGenItems]})),await od(l,t,n),n().showToast(M("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function od(e,t,n){if(!e.filename)return;const r=n();try{await Kr({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 Gy(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;on(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 Dy(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:Oy(n),requestId:o,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await $i(c,{signal:a.signal}),m=Qo(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 gt(u,e,t,{autoSelectStartedAt:i}),e(p=>({assetGenItems:[u,...p.assetGenItems]})),await rd(u,e,t),t().showToast(M("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!nn(c)){const d=Ke(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),sn(o),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function zy(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function cn(e){te({presetIds:e})}const qy=e=>({selectedPresetIds:tn().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return cn(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(o=>o!==t);return cn(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(o=>o!==t):[...n.selectedPresetIds,t];return cn(r),{selectedPresetIds:r}}),clearPresets:()=>{cn([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=zy(t);cn(n),e({selectedPresetIds:n})}});function $y(){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 Un=(e,t="POST",n)=>({method:t,signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),Uy=e=>$("/api/sprite-recipes",{signal:e}),Hy=(e,t)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),Vy=(e,t)=>$("/api/sprite-recipes",Un(e,"POST",t)),Ky=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,Un(t,"PATCH",n)),By=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),Wy=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Un({assetId:t},"POST",n)),Jy=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),Bt=new Map,Hn=e=>e instanceof Error?e.message:String(e),sd=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function Yy(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await Uy();e({spriteRecipes:n.map(sd)}),t().activeSpriteRecipeId&&await Js(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:Hn(n)})}finally{e({spriteRecipeLoading:!1})}}async function Js(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await Hy(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:Hn(r)})}finally{t({spriteRecipeLoading:!1})}}async function Xy(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await Ky(n.activeSpriteRecipeId,n.spriteRecipeDraft):await Vy(n.spriteRecipeDraft);return e(o=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[sd(r.recipe),...o.spriteRecipes.filter(a=>a.id!==r.recipe.id)]})),r.recipe.id}catch(n){return e({spriteRecipeError:Hn(n)}),null}finally{e({spriteRecipeSaving:!1})}}function ad(e,t,n){Bt.get(e)?.(),Bt.set(e,Ct(e,null,(r,o)=>nv({event:r,data:{...o,requestId:e}},t,n)))}function Ys(e){Bt.get(e)?.(),Bt.delete(e)}function id(e,t){return ot(e).code==="JOB_TRACKING_TIMEOUT"?Ke(e,t()).message:Hn(e)}async function Zy(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{ad(r,e,t),await Ur(),await By(n,{requestId:r,async:!0})}catch(o){Ys(r),e({spriteRecipeError:id(o,t),spriteRecipeGenerating:!1})}}async function Qy(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:o}=await Wy(r,e);t({activeSpriteRecipe:o,spriteRecipeDraft:o,spriteRecipeDirty:!1})}catch(o){t({spriteRecipeError:Hn(o)})}finally{t({spriteRecipeGenerating:!1})}}}async function ev(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const o=crypto.randomUUID();try{ad(o,t,n),await Ur(),await Jy(r,{requestId:o,stateKeys:e,async:!0})}catch(a){Ys(o),t({spriteRecipeError:id(a,n),spriteRecipeGenerating:!1})}}async function tv(e,t,n){Bt.get(e)?.(),Bt.delete(e),t({spriteRecipeGenerating:!1})}function nv(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")&&Ys(String(e.data.requestId??"")),e.event==="error"){const a=String(e.data.message??"Generation failed"),i=et(e.data,a),l=ot(i).code==="JOB_TRACKING_TIMEOUT"?Ke(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&Js(a,t)}}function rv(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const Ce=tn(),Zn=Xr(),Qn=Hl(),f=Oi((e,t,n)=>({...qy(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:$y(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>Yy(e,t),selectSpriteRecipe:r=>Js(r,e),updateSpriteRecipeDraft:r=>rv(r,e),saveSpriteRecipe:()=>Xy(e,t),generateSpriteAnchor:()=>Zy(e,t),approveSpriteAnchor:r=>Qy(r,e,t),generateSpriteRows:r=>ev(r,e,t),cancelSpriteJob:r=>tv(r,e),assetsFolders:[],assetsTags:[],assetsLoading:!1,assetsLoadError:!1,assetsCursor:null,assetsFilters:{kind:null,folderId:null,tag:null,q:""},assetGenPrompt:"",assetGenBackground:"chroma-green",assetGenProvider:Qn.provider==="grok"||Qn.provider==="grok-api"?Qn.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}),Ka({folderId:r},e,t)},loadAssetFolders:()=>nd(e),retryAssetGenSave:r=>Fy(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:()=>Gy(e,t),loadAssets:r=>Ws(r,e,t),loadMoreAssets:()=>jy(e,t),setAssetsFilters:r=>Ka(r,e,t),saveToAssets:r=>Cy(r,e,t),updateAssetItem:(r,o)=>Ay(r,o,e),deleteAssetItem:r=>Ty(r,e),createAssetFolder:(r,o)=>Py(r,o,e),renameAssetFolder:(r,o)=>Ry(r,o,e),moveAssetFolder:(r,o)=>My(r,o,e),deleteAssetFolder:r=>Ly(r,e),...Qn,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:Bm(),naiServerDefaults:null,insertedPrompts:Ce.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:Ve(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:Cs,activeReferenceLimit:()=>hc({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>sf(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:Di(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:Ma().mode,canvasExportMatteColor:Ma().matteColor,syncCapabilities:()=>hp(e),addTrayAttachments:async r=>qh(r,e),addTrayAttachmentDataUrl:(r,o)=>so(r,o,e),addTrayElement:r=>br(r,e),addElementFromMention:r=>br(r.id,e,t,r),syncElementCatalog:r=>_c(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>Xc(r,e,t),clearTray:()=>Wh(e,t),addElementId:r=>{br(r,e)},removeElementId:r=>cf(r,e),addReferences:r=>Uh(r,e,t),addReferenceDataUrl:r=>$h(r,e),metadataRestore:null,readDroppedImageMetadata:(r,o=null)=>Hh(r,o,e,t),applyMetadataRestore:()=>Vh(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>dy(e,t),removeReference:r=>Kh(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>Bh(e,t),attachCanvasVersionReference:(r,o)=>Yh(r,e,t,o),useCurrentAsReference:()=>Xh(e,t),useImageAsReference:r=>Zh(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>iy(r,e,t),startInFlightPolling:()=>{Hf(e,t)},reconcileInflight:async()=>{await Vf(e,t)},syncFromStorage:()=>ly(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>cy(r,e),addGeneratedHistoryItem:async r=>{await gt(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:Ue,loadOlderHistory:async()=>Ih(e,t),loadFavoriteHistory:async()=>Sh(e,t),loadOlderFavoriteHistory:async()=>wh(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:$m(),toggleRightPanel:()=>uy(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:Ra(bs),galleryDefaultScope:Ra(hl),setGalleryScope:r=>my(r,e),setGalleryDefaultScope:r=>py(r,e),reasoningEffort:Vm(),webSearchEnabled:Wm(),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:Um(),setUIMode:r=>fy(r,e),historyStripLayout:Hm(),setHistoryStripLayout:r=>hy(r,e),locale:Vd(),setLocale:r=>{Hd(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const o=t();e({graphHistoryPast:Tp(o.graphHistoryPast,ho(o.graphNodes,o.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),o=Pp(r.graphHistoryPast,ho(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=za(o.restored,r.graphNodes);return e({graphNodes:Fe(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),o=Rp(r.graphHistoryPast,ho(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=za(o.restored,r.graphNodes);return e({graphNodes:Fe(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>xy(r,e,t),setGraphEdges:r=>Iy(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>sh(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>Sy(e,t),selectAllGraphNodes:()=>{e({graphNodes:wn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,o)=>wy(r,o,e,t),clearNodeSelection:()=>{e({graphNodes:wn(t().graphNodes,[])})},cancelNodeBatch:()=>_y(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await Jc(e,t)},async switchSession(r){await Lh(r,e,t)},async reconcileGraphPending(){await Oh(e,t)},async createAndSwitchSession(r){await Fh(r,e,t)},async renameCurrentSession(r){await Dh(r,e,t)},async deleteSessionById(r){await Gh(r,e,t)},scheduleGraphSave(){pc(t,e)},async flushGraphSave(r="manual"){await kp(t,e,r)},addRootNode:()=>Yf(e,t),createRootNodeFromHistoryItem:r=>Xf(r,e,t),addChildNode:r=>Zf(r,e,t),addSiblingNode:r=>Qf(r,e,t),updateNodePrompt:(r,o)=>nh(r,o,e,t),addNodeReferences:async(r,o)=>ih(r,o,e,t),addNodeReferenceDataUrl:(r,o)=>zc(r,o,e,t),addNodeReferenceFromUrl:async(r,o,a)=>lh(r,o,a,e,t),removeNodeReference:(r,o)=>ch(r,o,e,t),clearNodeReferences:r=>dh(r,e,t),duplicateBranchRoot:r=>th(r,e,t),generateNode:r=>Af(r,e,t),generateNodeInPlace:r=>Tf(r,e,t),generateNodeVariation:(r,o)=>Pf(r,o,e,t),runGenerateNode:(r,o)=>Rf(r,o,e,t),async runGenerateNodeInPlace(r,o={}){return mf(r,o,e,t,Pe)},async runNodeBatch(r){await pf(r,e,t)},deleteNode:r=>rh(r,e,t),deleteNodes:r=>oh(r,e,t),addChildNodeAt:(r,o,a)=>eh(r,o,a,e,t),connectNodes:(r,o,a,i)=>ah(r,o,a,i,e,t),setProvider:r=>Eg(r,e,t),setImageToolModel:r=>Ng(r,e,t),setQuality:r=>kg(r,e,t),setSizePreset:r=>jg(r,e),setCustomSize:(r,o)=>Cg(r,o,e,t),setGrokAspectRatio:r=>Ag(r,e),setGrokResolution:r=>Tg(r,e),setFormat:r=>Pg(r,e),setModeration:r=>Rg(r,e),setImageModel:r=>Mg(r,e,t),videoDuration:Zn.duration,videoResolution:Zn.resolution,videoSingleRefMode:Zn.singleRefMode,videoAspectRatio:Zn.aspectRatio,videoReferenceVoices:[],videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>Lg(r,e,t),setComfyWorkflow:r=>Og(r,e,t),setComfyVideoWorkflow:r=>Fg(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),hn({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),hn({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),hn({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}),hn({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>Dg(t),runVideoGenerate:async r=>{await Mf(r,e,t)},animateImage:async(r,o)=>Lf(r,o,e,t),setReasoningEffort:r=>Gg(r,e),setWebSearchEnabled:r=>zg(r,e),setCount:r=>qg(r,e),setMultimode:r=>$g(r,e,t),setMultimodeMaxImages:r=>Ug(r,e),setPromptMode:r=>Hg(r,e),setPrompt:r=>Vg(r,e),setNegativePrompt:r=>Kg(r,e),setNaiOption:(r,o)=>Bg(r,o,e,t),resetNaiOptions:()=>Wg(e),insertPromptToComposer:r=>Xg(r,e),removeInsertedPromptFromComposer:r=>Zg(r,e),moveInsertedPromptInComposer:(r,o)=>Qg(r,o,e),clearInsertedPrompts:()=>ey(e),selectHistory:r=>_h(r,e,t),showHistorySequence:r=>Eh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>Nh(r,e,t),trashHistoryItem:async r=>kh(r,e,t),trashHistorySequence:async r=>jh(r,e,t),restorePendingTrash:async()=>Ch(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>Ah(r,e,t),removeFromHistory:r=>Th(r,e,t),addHistoryItem:r=>Ph(r,e,t),importLocalImageToHistory:async r=>Rh(r,e,t),getResolvedSize:()=>Jg(t),generate:()=>kf(e,t),async generateMultimode(r){await vf(r,e,t)},cancelMultimode:()=>jf(e,t),async runGenerate(r){await bf(r,e,t)},confirmCustomSizeAdjustment:()=>Cf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){Mh(e)},showToast:(r,o=!1)=>gy(r,o,e),dismissToast:r=>yy(r,e),showErrorCard:(r,o)=>vy(r,o,e),dismissErrorCard:r=>by(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:()=>ty(e),savePromptToLibrary:r=>ny(r,e,t),deletePromptFromLibrary:r=>ry(r,e,t),togglePromptFavorite:r=>oy(r,e,t),importPromptsToLibrary:r=>sy(r,e,t),toggleGalleryFavorite:r=>ay(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)=>Ey(r,o,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>Ny(r,e,t),setCanvasExportMatteColor:r=>ky(r,e,t)})),ov=/^[\p{L}\p{N}_-]$/u,sv=new Set([" "," ","(","["]);function av(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(!ov.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&&!sv.has(a)&&a!==`
|
|
8
|
+
`?null:{start:o,end:n,query:e.slice(r,n)}}function $e({title:e,help:t,items:n,value:r,onChange:o,className:a}){const i=y.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 io=Kd();function iv(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const lv=(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}]}},Ba=(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=y.useId(),I=y.useRef(null),b=y.useRef(null),v=y.useRef(null),[g,_]=y.useState(!1),[S,w]=y.useState({top:0,left:0,width:200,maxHeight:260}),{flat:N,rendered:j}=lv(t,e),L=N.length===0,[U,C]=y.useState(()=>Math.max(0,N.findIndex(O=>O.value===n))),q=y.useRef({buffer:"",at:0}),F=N.find(O=>O.value===n),T=O=>`${x}-opt-${O}`,k=O=>O.searchText?O.searchText:typeof O.label=="string"?O.label:O.value,P=O=>{const ee=Date.now(),J=q.current;J.buffer=ee-J.at>1e3?O:J.buffer+O,J.at=ee;const me=J.buffer.toLowerCase(),ge=J.buffer.length===1?U+1:U;for(let ie=0;ie<N.length;ie+=1){const ke=(ge+ie+N.length)%N.length,le=N[ke];if(!(!le||le.disabled)&&k(le).toLowerCase().startsWith(me)){C(ke);return}}};y.useEffect(()=>{if(!g)return;const O=ee=>{const J=ee.target;J instanceof Node&&(I.current?.contains(J)||v.current?.contains(J)||_(!1))};return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[g]),y.useLayoutEffect(()=>{if(!d||!g)return;const O=b.current?.getBoundingClientRect();if(O){const ge=Math.max(0,window.innerWidth-24),ie=Math.min(300,ge,Math.max(190,O.width)),ke=Math.max(12,window.innerWidth-ie-12),le=Math.min(Math.max(12,O.left),ke),Se=window.innerHeight-O.bottom-12,je=O.top-12,Re=Se>=160||Se>=je?"down":"up",ce=Math.max(0,Re==="down"?Se:je),be=Math.min(420,ce),G=8+N.length*44,ye=v.current?.scrollHeight??G,A=Math.min(ye,be);w({top:Re==="down"?O.bottom+4:Math.max(12,O.top-A-4),left:le,width:ie,maxHeight:be})}const ee=()=>_(!1),J=me=>{iv(me,v.current)&&_(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,g]),y.useEffect(()=>{g&&v.current?.querySelector(`[data-index="${U}"]`)?.scrollIntoView({block:"nearest"})},[g,U]);const B=()=>{L||(C(Math.max(0,N.findIndex(O=>O.value===n))),_(!0))};y.useEffect(()=>{L&&(_(!1),C(0))},[L]);const se=O=>{let ee=U;for(let J=0;J<N.length&&(ee=(ee+O+N.length)%N.length,!!N[ee]?.disabled);J+=1);C(ee)},oe=O=>{const ee=N[O];!ee||ee.disabled||(r(ee.value),_(!1),b.current?.focus())},ae=O=>{if(!g){["Enter"," ","ArrowDown","ArrowUp"].includes(O.key)&&(O.preventDefault(),B());return}if(O.key==="Escape")O.preventDefault(),_(!1);else if(O.key==="ArrowDown")O.preventDefault(),se(1);else if(O.key==="ArrowUp")O.preventDefault(),se(-1);else if(O.key==="Home")O.preventDefault(),C(Ba(N,"first",U));else if(O.key==="End")O.preventDefault(),C(Ba(N,"last",U));else if(O.key==="Enter"||O.key===" "){if(O.key===" "&&Date.now()-q.current.at<=1e3&&q.current.buffer){O.preventDefault(),P(" ");return}O.preventDefault(),oe(U)}else O.key==="Tab"?_(!1):O.key.length===1&&!O.metaKey&&!O.ctrlKey&&!O.altKey&&(O.preventDefault(),P(O.key))};let he=-1;const D=g&&!L?s.jsx("ul",{className:`ctl-select__list${d?" ctl-select__list--portal":""}`,role:"listbox",id:x,ref:v,style:d?{position:"fixed",top:S.top,left:S.left,width:S.width,maxHeight:S.maxHeight}:void 0,children:j.map((O,ee)=>s.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[O.label?s.jsx("div",{className:"ctl-select__group-label",children:O.label}):null,s.jsx("ul",{role:"group","aria-label":typeof O.label=="string"?O.label:void 0,className:"ctl-select__group-items",children:O.items.map(J=>{he+=1;const me=he;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===U?" is-active":""}${J.disabled?" is-disabled":""}${J.stacked?" is-stacked":""}`,onPointerEnter:()=>C(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:I,children:[s.jsxs("button",{type:"button",id:l,ref:b,className:`ctl-select__trigger${g?" is-open":""}`,role:"combobox","aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?x:void 0,"aria-activedescendant":g&&N[U]?T(U):void 0,"aria-label":o,"aria-describedby":a,disabled:c||L,title:h,onClick:()=>g?_(!1):B(),onKeyDown:ae,children:[s.jsx("span",{className:"ctl-select__value",children:m??F?.label??p??""}),u??F?.sub?s.jsx("span",{className:"ctl-select__value-sub",children:u??F?.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?io.createPortal(D,document.body):D:null]})}function cv({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 ld({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 Xs({className:e,children:t,ariaLabel:n}){return s.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":n,children:t})}function dv(){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 cd({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(dv,{})})}function uv(){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 Wa=12,mv=240;function pv(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 fv(e,t){const n=pv(e,t),r=window.innerHeight-n.bottom,o=r<mv?"top":"bottom",a=o==="bottom"?r:n.top;return{left:Math.max(Wa,Math.min(n.left,window.innerWidth-332)),top:o==="bottom"?n.bottom+6:Math.max(Wa,n.top-Math.min(320,a-8)),placement:o,maxHeight:Math.max(120,Math.min(320,a-12))}}function hv(){return window.matchMedia("(max-width: 640px)").matches}function gv({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=y.useId(),[h,x]=y.useState(0),[I,b]=y.useState(null),[v,g]=y.useState(!1),_=y.useRef(null),S=y.useMemo(()=>{const L=o.trim().toLocaleLowerCase();return L?a.filter(U=>[U.name,...U.tags??[]].some(C=>C.toLocaleLowerCase().includes(L))):a},[a,o]),w=L=>{x(L),u?.(L)},N=()=>{const L=S[h];L&&d(L)};if(y.useLayoutEffect(()=>{if(!e||!t.current)return;const L=()=>{if(!t.current){m();return}g(hv()),b(fv(t.current,r))},U=()=>requestAnimationFrame(L);return L(),window.addEventListener("resize",U),t.current.addEventListener("scroll",U),()=>{window.removeEventListener("resize",U),t.current?.removeEventListener("scroll",U)}},[e,t,r,m]),y.useEffect(()=>{w(0)},[o,S.length]),y.useEffect(()=>{if(!e)return;const L=t.current;if(!L)return;L.setAttribute("aria-controls",p),L.setAttribute("aria-expanded","true");const U=C=>{if(document.activeElement===L&&!(n?.current||C.isComposing||C.keyCode===229)&&!(C.key==="Enter"&&(C.ctrlKey||C.metaKey))){if(C.key==="Escape"){C.preventDefault(),m("escape");return}C.key==="ArrowDown"||C.key==="ArrowUp"?(C.preventDefault(),w((h+(C.key==="ArrowDown"?1:-1)+S.length)%Math.max(1,S.length))):C.key==="Home"?(C.preventDefault(),w(0)):C.key==="End"?(C.preventDefault(),w(Math.max(0,S.length-1))):C.key==="Enter"?S.length&&(C.preventDefault(),N()):C.key==="Tab"&&S.length&&N()}};return L.addEventListener("keydown",U),()=>{L.removeAttribute("aria-controls"),L.removeAttribute("aria-expanded"),L.removeAttribute("aria-activedescendant"),L.removeEventListener("keydown",U)}},[e,t,n,p,h,S,m]),y.useEffect(()=>{const L=t.current,U=S[h];L&&U&&L.setAttribute("aria-activedescendant",`${p}-${U.id}`)},[h,S,p,t]),y.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const j=s.jsx("section",{className:`element-mention-menu${v?" is-mobile":""}`,style:v?void 0:{left:I.left,top:I.top,maxHeight:I.maxHeight},"aria-label":i,children:s.jsx("ul",{id:p,className:"element-mention-menu__list",role:"listbox",ref:_,children:S.length?S.map((L,U)=>s.jsxs("li",{id:`${p}-${L.id}`,role:"option","aria-selected":U===h,className:`element-mention-menu__option${U===h?" is-active":""}`,onPointerEnter:()=>w(U),onMouseDown:C=>{C.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 io.createPortal(j,document.body)}function yv(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function vv(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??yv(e.source.referenceFilenames[0])}function bv({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=vv(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 xv({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 Iv({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(xv,{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 Sv=new Set(["character","product","style","scene"]);function wv(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&Sv.has(t)?t:"character"}function _v(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 Ev(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),o=new Set(n);return xc({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:wv(i),thumbnail:_v(i)??a.source.thumbnailUrl,missing:o.has(a.source.elementId)||t!==null&&!i}})}function Nv(e){const t=Ev(e.items,e.assets,e.missingElementIds);return t.length===0?null:s.jsx(Xs,{ariaLabel:e.selectedLabel,children:t.map(n=>{const r=e.kindLabel(n.kind);return s.jsx(Iv,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const kv=["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=y.useRef(null),a=y.useRef(null),[i,l]=y.useState([]),c=y.useMemo(()=>of(e).filter(m=>Object.prototype.hasOwnProperty.call(t,m.tag)),[e,t]),d=y.useMemo(()=>[...new Set(c.map(m=>`@${m.tag}`))],[c]);return y.useLayoutEffect(()=>{const m=n.current,u=o.current,p=a.current?.firstChild;if(!m||!u||!(p instanceof Text)){l([]);return}const h=()=>{const I=getComputedStyle(m);kv.forEach(g=>{u.style[g]=I[g]}),u.scrollTop=m.scrollTop,u.scrollLeft=m.scrollLeft;const b=u.getBoundingClientRect(),v=[];for(const g of c){const _=document.createRange();_.setStart(p,g.start),_.setEnd(p,g.end),Array.from(_.getClientRects()).forEach((S,w)=>{v.push({key:`${g.start}-${g.end}-${w}`,left:S.left-b.left+u.scrollLeft,top:S.top-b.top+u.scrollTop,width:S.width,height:S.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 lo(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 rn(o);t.addReferenceDataUrl(a);const i=Ac(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(Ef(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 dd(e){const t=await lo(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const Cv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:lo,continueFromItemAsUrl:dd},Symbol.toStringTag,{value:"Module"}));function Av({text:e,mode:t,onClose:n}){const{t:r}=V(),o=f(x=>x.savePromptToLibrary),[a,i]=y.useState(e.slice(0,30)),[l,c]=y.useState(e),[d,m]=y.useState(""),[u,p]=y.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 Tv({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(cv,{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 Pv({canAddMore:e,onAttach:t}){const{t:n}=V(),r=f(I=>I.prompt),o=f(I=>I.currentImage),a=f(I=>I.videoModelSelected),i=f(I=>I.selectVideoModel),l=f(I=>I.setImageModel),c=f(I=>I.promptMode),d=f(I=>I.setPromptMode),m=f(I=>I.storyboardActive),u=f(I=>I.toggleStoryboard),[p,h]=y.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 lo(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(_r):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(Tv,{variant:"compact"}),s.jsxs("div",{className:"composer__tool-wrap",children:[s.jsx("button",{type:"button",className:"composer__tool composer__tool--full",onClick:()=>h(I=>!I),disabled:!r.trim(),title:n("promptLibrary.saveTitle"),"aria-label":n("promptLibrary.saveTitle"),children:n("prompt.savePrompt")}),p&&s.jsx(Av,{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 Ja(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 Rv(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=Ja(c.clipboardData?.items??null);d.length!==0&&(c.preventDefault(),i(d,r()))};return y.useEffect(()=>{const c=d=>{const m=d.target;if(["INPUT","TEXTAREA"].includes(m?.tagName??"")||m?.isContentEditable)return;const u=Ja(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 ud="grok-imagine-video",Mv="grok-imagine-video-1.5",md=new Set([Mv,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function Lv(e){return e.type.startsWith("audio/")}function Ov(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function Fv(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,o=typeof r=="string"&&md.has(r),a=r===ud;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(Lv(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(Ov(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 Dv(e){const t=e.videoModelSelected;return typeof t=="string"&&md.has(t)?"image/*,audio/*":t===ud?"image/*,video/mp4":"image/*"}function Gv(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 zv({onImages:e}){const{t}=V(),n=f(o=>o.videoModelSelected),r=f(o=>o.showToast);return o=>{if(o.length===0)return;const a=Fv(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(Gv(i,t),!0)}}function qv({variant:e,onSubmit:t}){const n=f(d=>d.provider),r=f(d=>d.negativePrompt),o=f(d=>d.setNegativePrompt),a=y.useRef(!1),{t:i}=V();if(y.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 bo="tray:";function xo(e){return`${e.start}:${e.end}:${e.query}`}function $v(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):br(e.id,f.setState,f.getState,e)}function Uv(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):_c(e,f.setState,f.getState)}function Hv(e){const t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function Zs({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,I]=y.useState([]),b=E=>{const W=x.find(Q=>Q.id===E);return W?$v(W):(u?.(E),null)};y.useEffect(()=>{let E=!1;return Yp().then(W=>{E||(I(W),Uv(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{E=!0}},[]);const{t:v}=V(),g=f(E=>E.trayItems),_=f(E=>E.retiredTags),S=f(E=>E.removeTrayItem),w=f(E=>E.activeReferenceLimit()),N=f(E=>E.providerUrlReference),j=f(E=>E.setProviderUrlReference),L=f(E=>E.addReferences),U=f(E=>E.addReferenceDataUrl),C=f(E=>E.useImageAsReference),q=f(E=>E.readDroppedImageMetadata),F=f(E=>E.videoModelSelected),T=y.useRef(null),k=y.useRef(null),P=y.useRef(null),[B,se]=y.useState(!1),[oe,ae]=y.useState(null),he=y.useRef(!1),D=y.useRef(null),O=y.useRef(null),ee=f(E=>E.promptMode),J=f(Nf),me=f(E=>E.multimodeMaxImages),ge=ee==="direct",ie=r==="nai",ke=o.filter(E=>E.placement!=="after"),le=o.filter(E=>E.placement==="after"),Se=[...ke.map(E=>E.id),"__main_prompt__",...le.map(E=>E.id)],je=g.length<w,Re=J?g.length>0?v("multimode.promptPlaceholderWithRefs"):v("multimode.promptPlaceholder"):g.length>0?v("prompt.placeholderWithRefs"):v("prompt.placeholder"),ce=()=>{h.length>0||l()},be=()=>k.current?.selectionStart??f.getState().prompt.length,G=(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,R=Math.max(0,Math.min(W,we.length)),Y=Q.map(H=>`@${H.tag} `).join("");n(`${we.slice(0,R)}${Y}${we.slice(R)}`);const _e=R+Y.length;return requestAnimationFrame(()=>k.current?.setSelectionRange(_e,_e)),Q.length},ye=(E,W)=>{const Q=`@${E} `,we=f.getState().prompt,R=`${we.slice(0,W.start)}${Q}${we.slice(W.end)}`,Y=W.start+Q.length;n(R),requestAnimationFrame(()=>k.current?.setSelectionRange(Y,Y))},A=(E,W)=>{if(he.current)return;const Q=av(E,W);ae(Q&&xo(Q)!==O.current?Q:null)},ne=async(E,W,Q)=>{if(E.length===0)return 0;const we=new Set(f.getState().trayItems.map(R=>R.tokenId));try{return Q&&E.length===1&&await q(E[0])?0:(await L(E),G(we,W))}catch{return 0}},de=async E=>{const W=P.current??be();P.current=null,await ne(E,W,!0)},K=zv({onImages:E=>{de(E)}}),z=()=>{je&&(P.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 R={image:we,url:E.url,filename:E.filename};if(xe(R)){const Y=await rn(we);Y&&U(Y)}else await C(R);G(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)},Ge=E=>{E.currentTarget.contains(E.relatedTarget)||se(!1)},Ft=Rv({maxRefs:w,trayItemCount:g.length,captureAttachmentCaret:be,addFilesAtCaret:ne}),Be=y.useRef(null),dt=y.useRef(e);y.useLayoutEffect(()=>{const E=k.current;if(!E)return;(Be.current===null||dt.current!==e)&&(Be.current=Hv(window.getComputedStyle(E).maxHeight)??0,dt.current=e),E.style.height="auto";const W=Be.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ut=(E,W)=>{const Q=Se.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<Se.length-1},vt=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:!ut(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:!ut(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":""}${ge?" composer--direct":""}${J?" composer--multimode":""}${ge&&J?" composer--combined-modes":""}`,role:"group","aria-label":J?v("multimode.composerAriaLabel",{count:me}):v("prompt.label"),onDrop:re,onDragOver:Oe,onDragLeave:Ge,onPaste:Ft,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})}),ge&&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")]}),g.length>0&&s.jsx("span",{className:"composer__count",children:v("prompt.refCount",{count:g.length,max:w})})]})]}),s.jsx(bv,{items:g,limit:w,onRemove:S,onAdd:z}),ke.length>0&&s.jsx("div",{className:"composer__prompt-chips",children:ke.map(vt)}),c.length>0&&s.jsx(Xs,{ariaLabel:v("home.selectedPresets"),children:c.map(E=>{const W=kc(E);return W?s.jsx(ld,{onRemove:()=>d(E),removeLabel:v("common.removeNamed",{name:W.name}),children:W.name},E):null})}),s.jsx(Nv,{items:g,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:_,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:()=>{he.current=!0,ae(null)},onCompositionEnd:E=>{he.current=!1,D.current=E.currentTarget.value,queueMicrotask(()=>{D.current=null}),A(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{O.current=null,n(E.target.value),D.current!==E.target.value&&A(E.target.value,E.target.selectionStart)},onClick:E=>A(E.currentTarget.value,E.currentTarget.selectionStart),onKeyDown:E=>{if(!(he.current||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229)){if(E.key==="Escape"&&oe){E.preventDefault(),O.current=xo(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(qv,{variant:"classic",onSubmit:ce})]}),s.jsx(gv,{open:oe!==null,textareaRef:k,composingRef:he,caret:oe?.end??0,query:oe?.query??"",elements:[...g.filter(E=>E.kind==="attachment").map(E=>({id:`${bo}${E.tokenId}`,name:E.tag,kind:"reference",thumbnail:E.source.dataUrl})),...x.map(E=>{const W=yc(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=Zo(f.getState().trayItems,E.id);if(E.id.startsWith(bo)){const we=E.id.slice(bo.length),R=f.getState().trayItems.find(Y=>Y.tokenId===we);R&&oe&&ye(R.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=Zo(f.getState().trayItems,E.id);!Q||!oe||(ye(Q.tag,oe),ae(null))},onClose:E=>{E==="escape"&&oe&&(O.current=xo(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(vt)]}),s.jsx(Pv,{canAddMore:je,onAttach:z}),B&&s.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:v("prompt.dropHere",{max:w})}),s.jsx("input",{ref:T,type:"file",accept:Dv({videoModelSelected:F}),multiple:!0,hidden:!0,onChange:E=>{const W=Array.from(E.target.files??[]);W.length>0?K(W):P.current=null,E.target.value=""}})]})}function Qs(){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 pd(e,t=28){const n=e.trim().replace(/\s+/g," ");return n.length>t?`${n.slice(0,t)}...`:n}function ea(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(Bv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o,variant:e.variant,panelId:e.panelId}):s.jsx(Vv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o})}function Vv(e){return s.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>s.jsx(Kv,{f:t,...e},t.id))})}function Kv({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:pd(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 Bv(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(Wv,{f:o,determinateVideoId:n,validVideoProgress:r,...e},o.id))})}function Wv({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=Yv(e)??Xv(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(Zv,{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:pd(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(Jv,{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 Jv({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 Yv(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function Xv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function Zv({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 Ya="(max-width: 800px)";function yt(){const[e,t]=y.useState(()=>typeof window<"u"?window.matchMedia(Ya).matches:!1);return y.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Ya),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const Qv=10,mt=12;function eb({anchorRef:e,panelId:t,focusOnOpen:n,onRequestClose:r,onPointerEnter:o,onPointerLeave:a}){const{t:i}=V(),l=y.useRef(null),c=y.useRef(null),d=y.useRef(null),[m,u]=y.useState({left:mt,top:mt,caretTop:24}),[p,h]=y.useState(!1);y.useLayoutEffect(()=>{const b=()=>{const _=e.current,S=l.current;if(!_||!S)return;const w=_.getBoundingClientRect(),N=_.closest(".sidebar")?.getBoundingClientRect(),j=S.getBoundingClientRect(),L=N?N.right:w.right,U=Math.max(mt,window.innerWidth-j.width-mt),C=Math.max(mt,window.innerHeight-j.height-mt),q=Math.min(Math.max(L+Qv,mt),U),F=Math.min(Math.max(w.bottom-j.height,mt),C),T=Math.min(Math.max(w.top+w.height/2-F,16),j.height-16);u({left:q,top:F,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 g=new ResizeObserver(v);return e.current&&g.observe(e.current),l.current&&g.observe(l.current),()=>{window.removeEventListener("resize",v),window.removeEventListener("scroll",v,!0),g.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),y.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),y.useEffect(()=>{const b=g=>{const _=g.target;_&&(e.current?.contains(_)||l.current?.contains(_))||r(!1)},v=g=>{g.key==="Escape"&&(g.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`,I={left:m.left,top:m.top,"--inflight-caret-top":`${m.caretTop}px`};return io.createPortal(s.jsxs("div",{ref:l,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":x,"data-positioned":p,style:I,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(ea,{variant:"popup",panelId:t}),s.jsx("footer",{className:"inflight-popup__footer",children:i("inflight.footerHint")})]}),document.body)}const tb=180,nb=180;function fd({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const o=f(C=>C.inFlight.length),a=yt(),{t:i}=V(),[l,c]=y.useState("closed"),[d,m]=y.useState(!1),u=y.useRef(null),p=y.useRef(null),h=y.useRef(null),x=e==="inline"?n:l!=="closed",I=()=>{p.current!=null&&window.clearTimeout(p.current),h.current!=null&&window.clearTimeout(h.current),p.current=null,h.current=null};if(y.useEffect(()=>I,[]),y.useLayoutEffect(()=>{if(o!==0)return;const C=document.activeElement;x&&C instanceof HTMLElement&&C.closest(".inflight-popup")&&u.current?.focus(),I(),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,g=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=null},_=()=>{e!=="popup"||l==="pinned"||!v()||(g(),p.current!=null&&window.clearTimeout(p.current),p.current=window.setTimeout(()=>c("hover"),tb))},S=()=>{p.current!=null&&window.clearTimeout(p.current),p.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),nb))},w=C=>{I(),c("closed"),m(!1),C&&u.current?.focus()},N=C=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){w(!1);return}m(C.detail===0),c("pinned")},j=C=>{C.pointerType==="mouse"&&_()},L=o>99?"99+":String(o),U=x?"inflight.badgeClose":"inflight.badgeOpen";return s.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:j,onPointerLeave:S,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(U,{n:o}),title:i(U,{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(eb,{anchorRef:u,panelId:t,focusOnOpen:d,onRequestClose:w,onPointerEnter:g,onPointerLeave:S}):null]})}function rb(){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]=y.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(uv,{})})]}),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 f_(){return $("/api/comfy/workflows")}function h_(e){return $("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function g_(e){return $("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function y_(e){return $("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function v_(e){return $(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function ob(e){return ab(await $("/api/models",e?{signal:e}:{}))}function sb(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function xn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function gn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xa(e){if(!gn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return xn();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 xn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return xn();t.executable=e.executable}return t}function ab(e){return!gn(e)||e.ok!==!0||!gn(e.lanes)?xn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!gn(n)||!sb(n.status)||!gn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return xn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Xa),video:n.models.video.map(Xa)}};return[t,r]}))}const hd={phase:"idle",catalog:null,observedAt:null,error:null},ft=new Set;let Pn=hd,Mr=0,pt=null,er=null;const Za=()=>{na()};function ta(){return Pn}function yn(e){Pn=e;for(const t of[...ft])ft.has(t)&&t()}function Io(e,t){return e===Mr&&pt===t&&!t.signal.aborted&&ft.size>0}function ib(e){const t=e;return t?.status===401||t?.status===403?"app-auth":t?.code==="MODEL_CATALOG_INVALID"?"invalid":"request"}async function na(){const e=++Mr;if(pt?.abort(),pt=null,ft.size===0){yn(hd);return}const t=new AbortController;if(pt=t,yn({...Pn,phase:"loading",error:null}),!!Io(e,t))try{const n=await ob(t.signal);Io(e,t)&&yn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){Io(e,t)&&yn({...Pn,phase:"error",error:ib(n)})}finally{e===Mr&&pt===t&&(pt=null)}}function lb(e){const t=ft.size===0;return ft.add(e),t&&(typeof window<"u"&&(er=window,er.addEventListener("focus",Za)),na()),()=>{!ft.delete(e)||ft.size>0||(++Mr,pt?.abort(),pt=null,er?.removeEventListener("focus",Za),er=null,yn({...Pn,phase:"idle",error:null}))}}function Vn(){return{...y.useSyncExternalStore(lb,ta),refresh:na}}function Ut(e){return e.executable!==!1&&!e.description?.endsWith("(offline)")}function kt(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=ps.comfy,c=r.image.some(Ut)||r.video.some(Ut),d=e.phase==="ready"&&n?.status==="ready"&&c,m=!!(d&&i&&Ut(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 cb={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 Wt(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":cb[e.code]}const gd=[{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"}],Qa=new Map(gd.map(e=>[e.value,e.label])),db=new Set(["runway","higgsfield"]),tr="mcp:",nr="core:",So="effort:",wo=ol,dn=Kt;function ub(e){ao(e,f.setState,f.getState)}function mb(e){yg(e,f.setState,f.getState)}function pb(e,t,n){vg(e,t,f.setState,f.getState,n)}const _o={image:[],video:[]};function Eo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function fb(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function yd({compact:e=!1}={}){const{t}=V(),n=f(A=>A.provider),r=f(A=>A.imageModel),o=f(A=>A.videoModelSelected),a=f(A=>A.mcpProvider??null),i=f(A=>A.mcpModel??null),l=f(A=>A.mcpMediaKind??"image"),c=f(A=>A.setProvider),d=f(A=>A.setImageModel),m=f(A=>A.selectVideoModel),u=f(A=>A.setComfyWorkflow),p=f(A=>A.comfyWorkflow),h=f(A=>A.setComfyVideoWorkflow),x=f(A=>A.comfyVideoWorkflow),I=f(A=>A.setReasoningEffort),b=f(A=>A.reasoningEffort),{providers:v,loading:g,error:_}=ed(),[S,w]=y.useState(_o),[N,j]=y.useState(!1),[L,U]=y.useState(0),[C,q]=y.useState(!1),F=Vn(),T=F.catalog??{},k=T.comfy?.models??{image:[],video:[]};y.useEffect(()=>{_g(f.setState,f.getState)},[]);const P=a?v.find(A=>A.id===a)??null:null,B=!!(P?.enabled&&P.status.state==="connected");y.useEffect(()=>{if(!a||!B){w(_o),j(!1);return}const A=new AbortController;return q(!0),j(!1),Qc(a,A.signal).then(ne=>{if(A.signal.aborted)return;w(ne);const de=f.getState(),z=(de.mcpMediaKind==="video"?ne.video:ne.image).find(X=>X.id===de.mcpModel);z&&wg(z.capabilities,f.setState,f.getState)}).catch(ne=>{ne.name!=="AbortError"&&(A.signal.aborted||(w(_o),j(!0)))}).finally(()=>{A.signal.aborted||q(!1)}),()=>A.abort()},[a,B,L]);const se=y.useMemo(()=>v.filter(A=>A.enabled&&A.status.state==="connected"),[v]),oe=a?`${tr}${a}`:`${nr}${n}`,ae=Zu(n).filter(A=>A.providerHint===void 0||A.providerHint===n),he=n==="comfy"?k.image.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,disabled:F.phase!=="ready"||T.comfy?.status!=="ready"||!Ut(A),reason:A.lockReason})):[],D=n==="comfy"?k.video.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,reason:A.lockReason,disabled:F.phase!=="ready"||T.comfy?.status!=="ready"||!Ut(A)})):[],O=om({provider:n,imageModel:r,videoModel:o,comfyWorkflow:p,comfyVideoWorkflow:x}),ee=a?i?Wn(l,i):"":O,J=!a&&(n==="oauth"||n==="api")&&!o,me=!!(i&&(S.image.some(A=>A.id===i)||S.video.some(A=>A.id===i))),ge=P?.executable===!1?P.lockReason??t("mcp.higgsfieldLocked"):null,ie=a?P?P.status.state!=="connected"?t("mcp.disconnectedSelection"):P.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,ke=A=>{if(A.startsWith(nr)){const K=A.slice(nr.length);if(!Qa.has(K))return;c(K);return}const ne=A.slice(tr.length),de=v.find(K=>K.id===ne);!de||de.status.state!=="connected"||ub(ne)},le=A=>{const ne=f.getState();if(ne.provider!==n||(ne.mcpProvider??null)!==a)return;const de=ta();if(ne.mcpProvider){if(A.startsWith(dn))return;const K=Dm(A);if(K){const X=(K.kind==="video"?S.video:S.image).find(re=>re.id===K.model);pb(K.model,K.kind,X?.capabilities)}else mb(A||null);return}if(ne.provider==="comfy"){const K=A.startsWith(dn),z=K?A.slice(dn.length):A;if(!kt(de,K?{comfyVideoWorkflow:z}:{comfyWorkflow:z}).selectedAvailable)return;K?h(z):u(z||null);return}if(!A.startsWith(dn)){if(A.startsWith(So)){I(A.slice(So.length));return}if(A.startsWith(wo)){m(A.slice(wo.length));return}d(A)}},Se=Object.keys(T).filter(A=>!db.has(A)),je=Se.length>0?Se:gd.map(A=>A.value);je.includes("comfy")||je.push("comfy");const Re=[{label:t("mcp.coreProviders"),items:je.map(A=>{const ne=T[A],de=Qa.get(A),K=ne?fb(ne.status,t):null;return{value:`${nr}${A}`,label:de??Eo(A),...K?{sub:K}:{},...ne?.reason?{title:ne.reason}:{},...de?{}:{disabled:!0}}})}];se.length>0&&Re.push({label:t("mcp.connectedProviders"),items:se.map(A=>({value:`${tr}${A.id}`,label:Eo(A.id),sub:A.executable===!1?t("mcp.locked"):void 0}))}),a&&!se.some(A=>A.id===a)&&Re.push({items:[{value:`${tr}${a}`,label:Eo(a),sub:t("mcp.unavailable"),disabled:!0}]});const ce=[];if(a)i&&!me&&ce.push({items:[{value:Wn(l,i),label:i}]}),ce.push({label:t("mcp.imageModels"),items:S.image.map(A=>({value:Wn("image",A.id),label:A.label}))}),ce.push({label:t("mcp.videoModels"),items:S.video.map(A=>({value:Wn("video",A.id),label:A.label}))});else{const A=T[n]?.models.video.length??0,ne=(n==="grok"||n==="grok-api")&&A>0;ce.push({label:t("mcp.imageModels"),items:n==="comfy"?he.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:`${dn}${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:tm.map(K=>({value:`${wo}${K.value}`,label:K.shortLabel}))}),J&&ce.push({label:t("sidebar.reasoningLabel"),items:Ho.map(K=>({value:`${So}${K.value}`,label:K.shortLabel,sub:K.value===b?"●":void 0}))});const de=new Set(ce.flatMap(K=>K.items.map(z=>z.value)));O&&!de.has(O)&&ce.unshift({items:[{value:O,label:O.includes(":")?O.split(":").slice(1).join(":"):O,title:t("mcp.unavailable"),...n==="comfy"?{disabled:!0}:{}}]})}const be=Ho.find(A=>A.value===b),G=n==="comfy"&&!a?kt(F,{comfyWorkflow:p,comfyVideoWorkflow:x}):null,ye=G?t(Wt(G,F)):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(C?"mcp.loadingModels":"mcp.chooseModel"):n==="comfy"?t("mcp.chooseModel"):void 0,triggerSub:J&&be?be.shortLabel:void 0,portal:!0}),ie||ge||_||N||ye?s.jsx("span",{className:G?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:G&&ye?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:ye}),F.phase==="error"?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{F.refresh()},children:t("comfy.display.refresh")}):null]}):ie??ge??(N?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>U(A=>A+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function vd(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function In(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(vd):[]}}async function Ot(e,t){const n=await Ie(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 hb(){return Ot("/api/cardnews/image-templates")}function gb(){return Ot("/api/cardnews/role-templates")}async function yb(e){const t=await Ot("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:In(t.plan)}}function vb(e){return Ot("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function bb(e){return Ot(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function xb(e){const n=(await Ot(`/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 ei(e){return Ot(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:In(t.plan)}))}function Ib(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function Sb(e){return e[0]?.id||"academy-lesson-square"}function wb(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function _b(e){return Math.round(e/16)*16}function Lr(e){return Math.min(Is,Math.max(1024,_b(e)))}function ti(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Lr(e.customW)}x${Lr(e.customH)}`}function bd(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 Eb(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?bd(t.error)||M("cardNews.error"):void 0}}function Nb(e){return new Promise(t=>setTimeout(t,e))}function No(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:bd(o.error)}:r})}}const Ee=Oi((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([hb(),gb()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:Sb(n.templates),roleTemplateId:wb(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:Lr(n),customH:Lr(r)})},async draft(){const n=t();e({loading:!0,error:null,draftError:null});try{const{plan:r,planner:o}=await yb({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:ti(n)});e({activePlan:In(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 vb({...o,size:ti(n),quality:r.quality,moderation:r.moderation,model:r.imageModel,sessionId:r.activeSessionId});for(e(c=>({activePlan:c.activePlan?No(c.activePlan,i):c.activePlan}));["queued","running"].includes(i.status);)await Nb(900),i=await bb(i.jobId),e(c=>({activePlan:c.activePlan?No(c.activePlan,i):c.activePlan}));const l=await ei(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?In(l.plan):c.activePlan?No(c.activePlan,i):c.activePlan,selectedTextFieldId:null})),r.showToast(M("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 xb({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?Eb(d,vd(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 ei(n);e({activePlan:In(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 kb(){const{t:e}=V(),t=Ee(S=>S.hydrate),n=Ee(S=>S.topic),r=Ee(S=>S.audience),o=Ee(S=>S.goal),a=Ee(S=>S.contentBrief),i=Ee(S=>S.outputSizePreset),l=Ee(S=>S.customW),c=Ee(S=>S.customH),d=Ee(S=>S.setBriefField),m=Ee(S=>S.setOutputSizePreset),u=Ee(S=>S.setCustomSize),p=Ee(S=>S.draft),h=Ee(S=>S.loading),x=Ee(S=>S.generating),I=Ee(S=>S.draftError),b=Ee(S=>S.generateSet),v=Ee(S=>S.activePlan),g=v?.cards||[],_={total:g.length,done:g.filter(S=>S.status==="generated").length};return y.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:S=>d("topic",S.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:S=>d("audience",S.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:S=>d("goal",S.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:S=>d("contentBrief",S.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(S=>s.jsx("button",{type:"button",className:`option-btn${i===S?" active":""}`,onClick:()=>m(S),children:S==="custom"?e("cardNews.customSize"):S==="1024x1024"?"1024²":"2048²"},S))}),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:S=>u(Number.parseInt(S.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:S=>u(l,Number.parseInt(S.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")]}),I?s.jsx("div",{className:"card-news-error",role:"alert",children:I}):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(S=>S.locked),children:[x?s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,x?e("cardNews.progress.generating",{done:_.done,total:_.total}):e("cardNews.batchGenerate")]})]})}function Jt({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?En(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(Jt,{}),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 Cb({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=fh(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(Jt,{},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 ni="ima2.sidebarHistoryCollapsed";function ri(){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 Ab({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 Tb(){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 g=v.multimodePreviewFlightId;return g?g.startsWith("history:")?g.slice(8):v.multimodeSequences[g]?.sequenceId??null:null}),d=f(v=>v.openGallery),m=y.useRef({}),[u,p]=y.useState(()=>{try{return localStorage.getItem(ni)==="1"}catch{return!1}}),{t:h}=V(),x=Kc(t,c),I=y.useMemo(()=>Vc(e).slice(0,Uc),[e]);y.useEffect(()=>{!x||u||m.current[x]?.scrollIntoView({block:"nearest",inline:"nearest"})},[x,u,I]),y.useEffect(()=>{try{localStorage.setItem(ni,u?"1":"0")}catch{}},[u]);const b=(v,g)=>{m.current[v]=g};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 g=l[v.id];if(v.kind==="multimode"&&g){const _=[s.jsx(Ab,{count:g.requested},`coll-sk-${v.id}`)];for(let S=0;S<g.requested;S++)g.images[S]||_.push(s.jsx(ri,{},`sk-${v.id}-${S}`));return _}return s.jsx(ri,{},`sk-${v.id}`)}),I.length===0&&i.length===0?s.jsx("button",{type:"button",className:"sidebar-history__empty",onClick:d,children:h("history.emptyRecent")}):null,I.map(v=>v.type==="sequence"?s.jsx(Cb,{entry:v,active:x===v.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteSequenceAria",{count:v.items.length}),setRef:b,onSelect:r,onDelete:g=>{a(g)}},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:g=>{o(g)}},v.key))]})]})}const Pb="sidebar-inflight-panel";function Rb(){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=yt(),i=t==="agent"&&en?"agent":t==="node"&&Qt?"node":t==="assets"?"assets":t==="asset-gen"?"asset-gen":"classic",l=Gn(n),c=!a&&i==="classic"&&l.composerPlacement==="bottom"&&l.multimodeHistoryGrouping==="sequence";return s.jsxs(s.Fragment,{children:[s.jsx(Mb,{}),i==="classic"?c?s.jsx(s.Fragment,{children:s.jsx(Tb,{})}):s.jsxs(s.Fragment,{children:[s.jsx(Zs,{}),s.jsxs("div",{className:"sidebar-generate-with-inflight",children:[s.jsx(Qs,{}),s.jsx(fd,{variant:"popup",panelId:Pb})]})]}):i==="card-news"?s.jsx(s.Fragment,{children:s.jsx(kb,{})}):i==="node"?s.jsxs(s.Fragment,{children:[s.jsx(rb,{}),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(ea,{})]}):null]})}function Mb(){const e=yt();return s.jsx(s.Fragment,{children:s.jsxs("div",{className:"logo",children:[s.jsx($r,{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"})]}),s.jsxs("div",{className:"logo-actions",children:[s.jsx(Ob,{}),s.jsx(yd,{compact:e})]})]})})}function Lb(){return s.jsx("aside",{className:"sidebar",children:s.jsx("div",{className:"sidebar__scroll",children:s.jsx(Rb,{})})})}function Ob(){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 Fb=1024,Db=1024,Gb="blank-canvas.png";function oi(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function zb(e){const t=oi(e?.width,Fb),n=oi(e?.height,Db),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],Gb,{type:"image/png"})}const rr=1024;function qb(e){const t=/^(\d+)x(\d+)$/.exec(e);if(!t)return{width:rr,height:rr};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:rr,height:rr}:{width:n,height:r}}function $b(){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]=y.useState(!1),l=y.useCallback(async()=>{if(!a){i(!0);try{const c=qb(r()),d=await zb(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 Ub(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 Hb(e,t){try{const n=await Ie("/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 et(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 Vb(e,t){const n=fe();return ue()?Promise.reject(Ze(n-1)):(At(),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=Ct(e.requestId,null,(p,h)=>{p==="done"?c(()=>r(h)):p==="error"&&c(()=>o(et(h,"Video extension failed")))}),i=Xt(()=>c(()=>{d(),o(new Error("Video extension stream timed out"))})),t.aborted)return m();t.addEventListener("abort",m,{once:!0}),Ur().then(()=>{if(n!==fe())throw Ze(n);if(ue())throw Ze(n-1);return Hb(e,t)}).catch(p=>c(()=>o(p)))}))}let xt={source:null,status:"idle"},un=null,si=0;const ts=new Set;function or(e,t){xt={source:e,status:t};for(const n of ts)n()}const Gt={getSnapshot:()=>xt,subscribe(e){return ts.add(e),()=>{ts.delete(e)}},select(e){xt.status!=="pending"&&xt.source!==e&&or(e,"idle")},start(e){if(xt.status==="pending"||xt.source===e.sourceVideoId&&xt.status==="tracking-expired")return null;const t=new AbortController;return un=t,si=fe(),or(e.sourceVideoId,"pending"),Vb(e,t.signal).then(n=>(un=null,or(e.sourceVideoId,"idle"),n),n=>{un=null;const r=ot(n).code,o=n instanceof DOMException&&n.name==="AbortError";throw or(e.sourceVideoId,o||r==="LAN_TOKEN_REQUIRED"?"idle":r==="JOB_TRACKING_TIMEOUT"?"tracking-expired":"error"),n})},cancel(){un?.abort()},releaseView(){!ue()&&si===fe()&&un?.abort()}};async function Kb(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 et(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 Bb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),Ht=[];function Wb(e){return Ht.length>0&&Ht[Ht.length-1]===e}function De(e,t,n={}){const r=y.useRef(null),o=y.useRef(t);o.current=t;const a=y.useId(),{trap:i=!0,autoFocus:l=!0,restoreFocus:c=!0}=n;return y.useEffect(()=>{if(!e)return;Ht.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,m=r.current,u=()=>Array.from(m?.querySelectorAll(Bb)??[]).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(!Wb(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 g=v[0],_=v[v.length-1];b.shiftKey&&document.activeElement===g?(b.preventDefault(),_.focus()):!b.shiftKey&&document.activeElement===_&&(b.preventDefault(),g.focus())};document.addEventListener("keydown",h);let x="programmatic";const I=o.current;return o.current=b=>{x=b??"programmatic",I(b)},()=>{const b=Ht.indexOf(a);b!==-1&&Ht.splice(b,1),document.removeEventListener("keydown",h),p(x)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const Jb={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 Yb(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function ra(e){return Yb(e)?String(e):null}function Xb(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function ai(e){return e?e.replace("x","×"):null}function Zb(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=ra(n);o&&e.push({label:t,value:o,...r})}function ko(e,t,n,r={}){typeof n!="number"||n<=0||Z(e,t,n,r)}function Qb(e,t,n){const r=Zb(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 tx(e){return e?Jb[e]??e:null}function nx(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const o=ra(r);if(!o)return;const a=nx(o);!a||t.has(a)||(t.add(a),e.push({label:n,value:o,copyValue:o,pre:!0}))}function ii(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function li(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 rx(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 ox({item:e,onClose:t,onCopy:n}){const{t:r,locale:o}=V(),a=De(!0,t),i=y.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=tx(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),ai(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(_=>!!_),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"),ai(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"),ii(e.usage,"input_tokens"),{compact:!0}),ko(h,r("metadata.fields.cachedTokens"),li(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),ii(e.usage,"output_tokens"),{compact:!0}),ko(h,r("metadata.fields.reasoningTokens"),li(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),ko(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"),Xb(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 I=[];Z(I,r("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),Z(I,r("metadata.fields.videoResolution"),e.video?.resolution),Z(I,r("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),Z(I,r("metadata.fields.videoRequestedModel"),e.video?.requestedModel),Z(I,r("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),Z(I,r("metadata.fields.videoModelFallback"),e.video?.modelFallback),Z(I,r("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:ra(e.video?.xaiVideoRequestId)??void 0}),Z(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&m.push({title:r("metadata.sections.video"),fields:I});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=[],g=new Set;return sr(v,g,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),sr(v,g,r("metadata.fields.revisedPrompt"),e.revisedPrompt),sr(v,g,r("metadata.fields.prompt"),e.prompt),sr(v,g,r("metadata.fields.composerPrompt"),e.composerPrompt),Qb(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:_=>_.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(_=>s.jsx("span",{children:_},_))}):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(_=>s.jsxs("section",{className:_.compact?"metadata-modal__section metadata-modal__section--compact":"metadata-modal__section",children:[s.jsx("h4",{children:_.title}),s.jsx("dl",{children:_.fields.map(S=>s.jsxs("div",{className:rx(S),children:[s.jsx("dt",{children:S.label}),s.jsxs("dd",{children:[S.pre?s.jsx("pre",{children:S.value}):s.jsx("span",{children:S.value}),S.copyValue?s.jsx("button",{type:"button",onClick:()=>n(S.copyValue),"aria-label":r("metadata.copyField",{label:S.label}),children:r("metadata.copy")}):null]})]},`${_.title}:${S.label}`))})]},_.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 sx(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function xd(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 ax(e,t){const n=sx(e);if(!n||xd(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 ix=[2,4,8,16],lx=["sublime","photo","photo_denoiser"];function cx({pending:e,onSubmit:t,onClose:n}){const{t:r}=V(),o=De(!0,n,{trap:!1,restoreFocus:v=>v!=="outsidePointer"}),[a,i]=y.useState(2),[l,c]=y.useState(""),[d,m]=y.useState(10),[u,p]=y.useState(10),[h,x]=y.useState(30),I={scaleFactor:a,...l?{flavor:l}:{},sharpen:d,smartGrain:u,ultraDetail:h},b=xd("image",I);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:ix.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")}),lx.map(v=>s.jsx("option",{value:v,children:v},v))]})]}),[["sharpen",d,m],["smartGrain",u,p],["ultraDetail",h,x]].map(([v,g,_])=>s.jsxs("label",{className:"upscale-popover__field",children:[s.jsxs("span",{children:[v," ",s.jsx("output",{children:g})]}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:g,onChange:S=>_(Number(S.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(I),children:r(e?"inflight.streaming":"result.upscaleStart")}),s.jsx("button",{type:"button",className:"action-btn",onClick:n,children:r("common.cancel")})]})]})}const dx="canvas-mode-context",ux="Canvas Mode",ci=36e5,mx=["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 px({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=V(),r=f(z=>z.currentImage),o=f(z=>z.showToast),a=f(z=>z.insertPromptToComposer),i=f(z=>z.createRootNodeFromHistoryItem),l=f(z=>z.trashHistoryItem),c=f(z=>z.saveToAssets),d=f(z=>z.permanentlyDeleteHistoryItemByClick),m=f(z=>z.canvasOpen),u=f(z=>z.openCanvas),[p,h]=y.useState(!1),[x,I]=y.useState(!1),b=y.useSyncExternalStore(Gt.subscribe,Gt.getSnapshot),[v,g]=y.useState("idle"),[_,S]=y.useState(!1),[w,N]=y.useState(!1),[j,L]=y.useState(!1),[U,C]=y.useState(!1),q=y.useRef(null);y.useEffect(()=>{let z=!0;return Ks().then(X=>{z&&C(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{z=!1}},[]);const F=async z=>{if(!T?.filename||j)return;const X=ax(T.filename,z);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)}};y.useEffect(()=>Gt.releaseView,[]);const T=e??r,k=T?.filename??null;y.useEffect(()=>{Gt.select(k)},[k]);const P=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,he=B&&!!T.filename,O=!!((T.provider==="grok"||T.provider==="grok-api")&&!B&&T.providerUrl&&T.createdAt&&Date.now()-T.createdAt<ci),ee=async()=>{if(!(!T.filename||x)){I(!0);try{await f.getState().animateImage(T.filename,T.prompt??void 0)&&o(n("toast.animateDone"))}catch(z){const X=z instanceof Error?z.message:n("toast.animateFailed");o(X,!0)}finally{I(!1)}}},J=async()=>{if(!T.filename||P==="pending"||P==="tracking-expired")return;const z=`vext_${crypto.randomUUID()}`;try{const X=Gt.start({requestId:z,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(Ub(re,T)),o(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Oe=ot(X).code;Oe==="JOB_TRACKING_TIMEOUT"||Oe==="LAN_TOKEN_REQUIRED"?Ke(X,f.getState()):re||o(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},me=()=>Gt.cancel(),ge=async()=>{if(!T.filename||v==="pending")return;const z=window.prompt(n("result.editVideoPrompt"))?.trim();if(!z)return;const X=new AbortController;q.current=X,g("pending");try{const re=await Kb({videoUrl:T.filename,prompt:z,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...T,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:z,userPrompt:z,model:re.model||"grok-imagine-video",format:"mp4"}),g("idle"),o(n("toast.animateDone"))}catch(re){const Oe=re instanceof DOMException&&re.name==="AbortError";g(Oe?"idle":"error"),Oe||o(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{q.current===X&&(q.current=null)}},ie=()=>q.current?.abort(),ke=()=>{const z=document.createElement("a");z.href=T.image,z.download=T.filename||"generated.png",z.click()},le=async z=>{const re=await(await fetch(z)).blob();let Oe;if(re.type==="image/png")Oe=re;else{const Ge=new Image;Ge.crossOrigin="anonymous";const Ft=URL.createObjectURL(re);await new Promise((dt,ut)=>{Ge.onload=()=>dt(),Ge.onerror=ut,Ge.src=Ft});const Be=document.createElement("canvas");Be.width=Ge.naturalWidth,Be.height=Ge.naturalHeight,Be.getContext("2d").drawImage(Ge,0,0),URL.revokeObjectURL(Ft),Oe=await new Promise((dt,ut)=>Be.toBlob(vt=>vt?dt(vt):ut(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Oe})])},Se=async()=>{try{if(B){const z=await rn(se);await le(z)}else await le(T.image);o(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{o(n("toast.copyFailed"),!0)}},je=async()=>{try{const z=await oc(se);await le(z),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},Re=async()=>{try{const z=await sc(se);await le(z),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 z=>{try{await navigator.clipboard.writeText(z),o(n("toast.metadataCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},G=async()=>{let z={ok:!1,isVideo:!1,hasPrompt:!1};try{z=await lo(T)}catch{}m&&e&&a({id:dx,name:ux,text:mx});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),o(n(z.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ye=async()=>{if(B||!T.providerUrl||!T.createdAt||Date.now()-T.createdAt>=ci){o(n("toast.continueAsUrlExpired"),!0);return}try{await dd(T)}catch{}const z=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');z&&(z.focus(),z.setSelectionRange(z.value.length,z.value.length)),o(n("toast.continueAsUrlStarted"))},A=async()=>{if(!(!T.filename||p)){h(!0);try{const z=await Su({filename:T.filename});o(n("toast.comfyExported",{filename:z.uploadedFilename}))}catch(z){const X=z instanceof Error?z.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:Se,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 z=await c(T);o(n(z?"chain.savedToAssets":"chain.saveToAssetsFailed"),!z)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),s.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:G,title:n("result.continueHereTitle"),children:n("result.continueHere")}),O&&s.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ye()},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")}),U&&T.filename&&(B?s.jsx("button",{type:"button",className:"action-btn",disabled:j,onClick:()=>{F({})},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(z=>!z),title:n("result.upscaleTitle"),children:n("result.upscale")}),w?s.jsx(cx,{pending:j,onSubmit:z=>{F(z)},onClose:()=>N(!1)}):null]})),he&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",onClick:J,disabled:P==="pending"||P==="tracking-expired","aria-busy":P==="pending",title:n(P==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:P==="pending"?n("inflight.streaming"):P==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),P==="pending"&&s.jsx("button",{type:"button",className:"action-btn",onClick:me,children:n("common.cancel")}),s.jsx("button",{type:"button",className:"action-btn",onClick:ge,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:()=>S(!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:()=>{A()},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")})]})]})]}),_&&s.jsx(ox,{item:T,onClose:()=>S(!1),onCopy:z=>{be(z)}})]})}const fx=["auto","flat","detailed","mono"],it={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function hx(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 gx(e){return`${Math.round(e/1024)}KB`}function yx(){const{t:e}=V(),t=f(q=>q.vectorizeTarget),n=f(q=>q.setVectorizeTarget),r=f(q=>q.addAssetGenDerivedItem),o=f(q=>q.selectedProjectId),a=f(q=>q.showToast),i=y.useRef(null),l=y.useRef(t?.filename??null);l.current=t?.filename??null;const c=y.useCallback(()=>{i.current?.abort(),i.current=null,n(null)},[n]),d=De(!!t,c),[m,u]=y.useState("auto"),[p,h]=y.useState(it.colorPrecision),[x,I]=y.useState(it.filterSpeckle),[b,v]=y.useState(it.cornerThreshold),[g,_]=y.useState(!1),[S,w]=y.useState(null),[N,j]=y.useState(null);y.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),w(null),j(null)},[t?.filename]),y.useEffect(()=>()=>i.current?.abort(),[]);const L=y.useCallback(()=>{if(!t?.filename||g)return;const q=t.filename,F=new AbortController;i.current=F,_(!0),w(null),Lu({source:q,preset:m,...p!==it.colorPrecision?{colorPrecision:p}:{},...x!==it.filterSpeckle?{filterSpeckle:x}:{},...b!==it.cornerThreshold?{cornerThreshold:b}:{},projectId:o,signal:F.signal}).then(T=>{if(!(i.current!==F||l.current!==q)){if(!T.filePath)throw new Error(e("vectorize.saveError"));j({filePath:T.filePath,pathCount:T.pathCount,bytes:T.bytes}),r(hx(t,T.filePath)),a(e("vectorize.saved"))}}).catch(T=>{if(T instanceof DOMException&&T.name==="AbortError"||i.current!==F||l.current!==q)return;const k=T instanceof Error?T.message:e("vectorize.saveError");w(k),a(k,!0)}).finally(()=>{i.current!==F||l.current!==q||(i.current=null,_(!1))})},[t,g,m,p,x,b,o,r,a,e]);if(!t)return null;const U=t.url||t.image,C=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:q=>q.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":g,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:U??"",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:C?s.jsx("img",{src:C,alt:e("vectorize.resultAlt")}):s.jsx("span",{className:"keying-panel__loading",role:"status",children:e(g?"vectorize.running":"vectorize.idle")})})]})]}),s.jsx("div",{className:"keying-panel__modes",role:"group","aria-label":e("vectorize.preset"),children:fx.map(q=>s.jsx("button",{type:"button",className:m===q?"is-active":"","aria-pressed":m===q,onClick:()=>u(q),children:e(`vectorize.preset_${q}`)},q))}),N?s.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(N.pathCount),size:gx(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:q=>h(Number(q.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:q=>I(Number(q.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:q=>v(Number(q.target.value))})]}),s.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(it.colorPrecision),I(it.filterSpeckle),v(it.cornerThreshold)},children:e("vectorize.reset")})]})]}),s.jsxs("footer",{className:"keying-panel__actions",children:[S?s.jsx("span",{className:"keying-panel__save-error",role:"alert",children:S}):null,s.jsx("button",{type:"button",className:"assetgen-generate",disabled:g||!t.filename,onClick:L,children:e(g?"vectorize.running":"vectorize.run")}),C?s.jsx("a",{className:"assetgen-popup__close",href:C,download:N?.filePath,children:e("vectorize.download")}):null,s.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function vx({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 bx(){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],I=d.get(h)??(x?void 0:m.shift());return{index:h,image:x,partial:I}});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 I=h&&o?.filename&&h.filename===o.filename;return s.jsxs("article",{className:`multimode-sequence__slot${h?" done":""}${I?" 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 xx({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 Ir(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function Ix(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 b_(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const wt=1,Id=5,ar=.22;function Sx(e){return Math.min(Id,Math.max(wt,e))}function wx(e){const[t,n]=y.useState(1),[r,o]=y.useState({x:0,y:0}),[a,i]=y.useState(null),l=y.useRef(0),c=y.useRef(null),d=y.useCallback(()=>{cancelAnimationFrame(l.current),l.current=0,c.current=null,n(1),o({x:0,y:0}),i(null)},[]);y.useEffect(()=>{d()},[d,e]),y.useEffect(()=>()=>{cancelAnimationFrame(l.current)},[]);const m=y.useCallback(b=>{n(v=>{const g=Sx(v+b);return g<=wt?(o({x:0,y:0}),wt):Number(g.toFixed(2))})},[]),u=y.useCallback(b=>{b.preventDefault(),m(b.deltaY<0?ar:-ar)},[m]),p=y.useCallback(()=>{if(t>wt){d();return}n(2)},[d,t]),h=y.useCallback(b=>{t<=wt||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=y.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]),I=y.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(ar),zoomOut:()=>m(-ar),handleWheel:u,handleDoubleClick:p,handlePointerDown:h,handlePointerMove:x,handlePointerUp:I}}const _x=y.lazy(()=>Le(()=>import("./index-GbV8-z5Y.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function Ex(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Nx(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function kx(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 ns(){const e=f(D=>D.currentImage),t=f(D=>D.importLocalImageToHistory),n=f(D=>{const O=D.multimodePreviewFlightId;return O?D.multimodeSequences[O]??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(),[I,b]=y.useState(!1),[v,g]=y.useState(null),{creatingBlankCanvas:_,createBlankCanvas:S}=$b(),w=y.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")))},U=D=>{if(D.key==="Delete"||D.key==="Backspace"){if(!e||D.target!==D.currentTarget||Ir(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&&(Ir(D.target)||(D.preventDefault(),D.key==="ArrowLeft"?r("previous"):D.key==="ArrowRight"?r("next"):D.key==="Home"?r("first"):D.key==="End"&&r("last")))},C=D=>{Ir(D.target)||(i(),D.currentTarget.focus())},q=y.useCallback(()=>{window.requestAnimationFrame(()=>w.current?.focus())},[]),F=async()=>{const D=e?.filename;if(!(!e||!D||v===D)){g(D);try{await h(e)}finally{g(O=>O===D?null:O)}}},T=y.useCallback(D=>{Array.from(D.dataTransfer.types).includes("Files")&&(D.preventDefault(),b(O=>O||!0))},[]),k=y.useCallback(D=>{D.currentTarget.contains(D.relatedTarget)||b(!1)},[]),P=y.useCallback(async D=>{if(!Array.from(D.dataTransfer.types).includes("Files"))return;D.preventDefault(),b(!1);const O=Array.from(D.dataTransfer.files).filter(ee=>/^image\/(png|jpeg|webp)$/.test(ee.type));O.length!==0&&await t(O[0])},[t]);if(c&&e)return s.jsxs(s.Fragment,{children:[s.jsx(y.Suspense,{fallback:s.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:s.jsx(_x,{currentImage:e})}),s.jsx(yx,{})]});const B=Ex(e?.quality),se=Nx(e?.size),oe=tl(e?.model,e?.provider),ae=e?kx(e):null,he=Ix(e?.filename,u,p,e?.isFavorite);return s.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:T,onDragLeave:k,onDrop:P,children:[I?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(bx,{}):e&&ae?s.jsxs("div",{ref:w,className:"result-container visible",tabIndex:0,onMouseDown:C,onKeyDown:U,"aria-label":x("canvas.imageViewerAria"),children:[s.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${j.zoom>wt?" 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(cd,{variant:"result",active:he,busy:v===e.filename,label:x(he?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:F}):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(En(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(xx,{zoom:j.zoom,minZoom:wt,maxZoom:Id,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,Tc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?x("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,um(e.reasoningEffort),B,se,oe]).filter(D=>!!D).join(" · ")}),s.jsx(px,{onAfterDeleteFocus:q}),e.prompt?s.jsx(vx,{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:()=>{S()},disabled:_,children:x(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function jx(){return s.jsxs("div",{className:"classic-workspace",children:[s.jsx("div",{className:"classic-workspace__stage",children:s.jsx(ns,{})}),s.jsxs("div",{className:"classic-workspace__dock",children:[s.jsx(Zs,{variant:"bottom"}),s.jsx(Qs,{})]})]})}const Sd="ima2.customSizeSlots";function Cx(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 Ax(){try{const e=localStorage.getItem(Sd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?$t(t.filter(Cx)):[]}catch{return[]}}function Tx(e){try{localStorage.setItem(Sd,JSON.stringify($t(e)))}catch{}}function Px(e,t,n){return Wr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function mn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function Rx(){const e=f(P=>P.sizePreset),t=f(P=>P.setSizePreset),n=f(P=>P.customW),r=f(P=>P.customH),o=f(P=>P.setCustomSize),{t:a}=V(),[i,l]=y.useState(String(n)),[c,d]=y.useState(String(r)),[m,u]=y.useState(e==="custom"),[p,h]=y.useState(()=>Ax()),[x,I]=y.useState(null),[b,v]=y.useState("free"),g=e==="custom",_=Ss(i,c,n,r),S=Cm().filter(P=>P.value==="auto");y.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),y.useEffect(()=>{g||(u(!1),I(null))},[g]);function w(P){h(P),Tx(P)}function N(){const P=nt(i,n),B=nt(c,r);o(P,B),l(String(P)),d(String(B))}function j(P){P.key==="Enter"&&(P.preventDefault(),N())}function L(){t("custom"),u(!0),I(p.length>=qt?p[0]?.id??null:null)}function U(P){t(P),P!=="custom"&&(u(!1),I(null))}function C(P){t("custom"),o(P.w,P.h),l(String(P.w)),d(String(P.h)),u(!1),I(P.id)}function q(P){v(P.id);const B=Sm(P);B&&(l(String(B.w)),d(String(B.h)))}function F(){const P=Px(_.w,_.h,b),B=p.length>=qt&&x?_m(p,x,P):wm(p,P);w(B),t("custom"),o(_.w,_.h),l(String(_.w)),d(String(_.h)),I(P.id),u(!1)}const T=_.reasons.length>0?_.reasons.map(P=>a(`size.adjustedReasons.${P}`)).join(", "):a("size.noAdjustment"),k=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${ka}×${ka}`}):null;return s.jsxs("div",{className:"option-group size-picker",children:[s.jsx("div",{className:"section-title",children:a("size.title")}),s.jsx($e,{title:"",items:mn(Em),value:e,onChange:U}),s.jsx($e,{title:"",items:mn(Nm),value:e,onChange:U}),s.jsx($e,{title:"",items:mn(km),value:e,onChange:U}),s.jsx($e,{title:"",items:mn(jm),value:e,onChange:U}),s.jsxs("div",{className:"option-row size-picker__quick-row",children:[mn(S).map(P=>s.jsxs("button",{type:"button",className:`option-btn${e===P.value?" active":""}`,onClick:()=>U(P.value),children:[P.label,P.sub?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:P.sub})]}):null]},P.value)),s.jsxs("button",{type:"button",className:`option-btn${g?" 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(P=>s.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===P.w&&r===P.h?" active":""}`,onClick:()=>C(P),children:[P.w,"×",P.h,s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:P.ratio||a("size.customSlot")})]},P.id))}):null,m?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"size-picker__ratio-row",children:xm.map(P=>s.jsx("button",{type:"button",className:`size-picker__ratio${b===P.id?" active":""}`,onClick:()=>q(P),children:P.id==="free"?a("size.ratioFree"):P.label},P.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:P=>l(P.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:P=>d(P.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:Im(_.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(P=>s.jsxs("button",{type:"button",className:`size-picker__replace${x===P.id?" active":""}`,onClick:()=>I(P.id),children:[P.w,"×",P.h]},P.id))]}):null,s.jsx("button",{type:"button",className:"size-picker__save",onClick:F,children:p.length>=qt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),s.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const jo=[1,2,4];function Mx(){const e=f(g=>g.count),t=f(g=>g.setCount),n=f(g=>g.uiMode),r=f(g=>g.multimode),o=f(g=>g.multimodeMaxImages),a=f(g=>g.setMultimodeMaxImages),{t:i}=V(),l=n==="classic"&&r,c=l?o:e,d=l?a:t,[m,u]=y.useState(!jo.includes(c)),[p,h]=y.useState(String(c));y.useEffect(()=>{u(!jo.includes(c)),h(String(c))},[l,c]);function x(g=p){const _=Bo(Number.parseInt(g,10));d(_),h(String(_))}function I(g){u(!1),h(String(g)),d(g)}function b(g){const _=Bo(c+g);u(!0),h(String(_)),d(_)}function v(g){g.key==="Enter"&&(g.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:[jo.map(g=>s.jsx("button",{type:"button",className:`option-btn${c===g&&!m?" active":""}`,onClick:()=>I(g),children:g},g)),s.jsx("button",{type:"button",className:`option-btn${m?" active":""}`,onClick:()=>{u(g=>!g),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:g=>h(g.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 Lx={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}},Ox={512:.045,"1K":.067,"2K":.101,"4K":.151},Fx={512:.134,"1K":.134,"2K":.134,"4K":.24};function Dx(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function Gx(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),o=Dx(r),i=t==="nano-banana-pro"?Fx:Ox;return i[o]??i["1K"]??.003}function zx(e,t,n,r){return n==="gemini-api"?Gx(t,r):Lx[e]?.[t]??0}function qx(){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=zx(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 Or="ima2:oauth-changed",$x=3e3,Ux=15e3;function wd(){const[e,t]=y.useState(null);return y.useEffect(()=>{let n=!1,r=null;const o=async()=>{r&&clearTimeout(r),r=null;try{const i=await Yd();if(n)return;t(i),i.status==="starting"?r=setTimeout(o,$x):i.status!=="ready"&&(r=setTimeout(o,Ux))}catch{n||t(null)}},a=()=>{o()};return window.addEventListener(Or,a),o(),()=>{n=!0,window.removeEventListener(Or,a),r&&clearTimeout(r)}},[]),e}function Hx(){const[e,t]=y.useState(null),[n,r]=y.useState(!1);return y.useEffect(()=>{let o=!1;return Xd().then(a=>{o||t(a)}).catch(()=>{o||r(!0)}),()=>{o=!0}},[]),{data:e,error:n}}function _d(){const[e,t]=y.useState(null);return y.useEffect(()=>{if(ue())return;const n=fe();let r=!1,o=null,a=0;const i=async()=>{o&&(clearTimeout(o),o=null);const d=++a;if(!(r||ue()||n!==fe()))try{const m=await Ie("/api/grok/status");if(r||d!==a)return;const u=await m.json();if(r||d!==a||ue()||n!==fe())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(_t,c),window.removeEventListener(Or,l)};return window.addEventListener(_t,c),window.addEventListener(Or,l),i(),c},[]),e}function Ed(){const[e,t]=y.useState(null),[n,r]=y.useState(null),o=y.useRef(!1),a=y.useCallback(async()=>{if(!o.current||ue())return;const i=fe();try{const c=await(await Ie("/api/keys/status")).json();if(!o.current||ue()||i!==fe())return;t(c),r(null)}catch(l){if(!o.current||ue()||i!==fe())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return y.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(_t,d)};return window.addEventListener(_t,d),c(),d},[a]),{data:e,error:n,mutate:a}}function Nd(){const{t:e}=V(),t=wd(),{data:n}=Hx(),r=_d(),{data:o}=Ed(),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,I=o?.nai?.valid===!0,b=Vn(),v=kt(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:I,reason:I?"":e("provider.naiApiKeyRequired")},comfy:{ok:v.laneAvailable,reason:e(v.laneAvailable?"comfy.display.available":Wt(v,b)),hint:e("comfy.display.chooseWorkflow")}}}function Vx({open:e,providerLabel:t,reason:n,hint:r,onClose:o}){const{t:a}=V(),i=De(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 ir="core:",Co="mcp:",Kx={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"}},Ao=ms.map(e=>Kx[e]);function To(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Po({tone:e}){return s.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function di(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 Ro({mcpProviders:e}){const{t}=V(),n=f(C=>C.provider),r=f(C=>C.mcpProvider??null),o=f(C=>C.setProvider),a=Nd(),i=Vn(),l=f(C=>C.comfyWorkflow),c=f(C=>C.comfyVideoWorkflow),d=kt(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),m=n==="comfy"&&!r,u=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[p,h]=y.useState(null),x=C=>{const q=a[C.value];return C.value==="comfy"?m?t(Wt(d,i)):q.reason:q.ok?t("provider.statusReady"):q.reason},I=C=>C.enabled?C.status.state==="connected"?C.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):C.status.state==="connecting"?t("mcp.connecting"):C.status.state==="auth_required"?t("provider.statusAuthRequired"):C.status.state==="offline"||C.status.state==="error"?t(`mcp.status.${C.status.state}`):t("provider.statusDisconnected"):t("mcp.disabledProvider"),b=[{label:t("mcp.coreProviders"),items:Ao.map(C=>{const q=a[C.value];return{value:`${ir}${C.value}`,searchText:`${C.provider} ${C.value==="comfy"?t("comfy.display.localMethod"):C.method}`,label:s.jsxs("span",{className:"provider-option",children:[s.jsx(Po,{tone:C.value==="comfy"&&m?u:q.ok?"ok":"bad"}),s.jsxs("span",{children:[C.provider," ",C.value==="comfy"?t("comfy.display.localMethod"):C.method]})]}),sub:x(C)}})}],v=e.filter(C=>C.enabled).map(C=>({value:`${Co}${C.id}`,searchText:To(C.id),label:s.jsxs("span",{className:"provider-option",children:[s.jsx(Po,{tone:di(C)}),s.jsx("span",{children:To(C.id)})]}),sub:I(C)}));v.length>0&&b.push({label:"MCP",items:v});const g=r?`${Co}${r}`:`${ir}${n}`,_=r?null:Ao.find(C=>C.value===n)??null,S=r?e.find(C=>C.id===r)??null:null,w=_?.value==="comfy",N=w?t(Wt(d,i)):_?x(_):S?I(S):t("provider.statusDisconnected"),j=w?u:_?a[_.value].ok?"ok":"bad":S?di(S):"bad",L=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",U=C=>{if(C.startsWith(ir)){const T=C.slice(ir.length);if(!Tt(T))return;const k=Ao.find(B=>B.value===T),P=a[T];if(T==="comfy"){o(T);return}if(!P.ok){h({label:k?`${k.provider} ${k.method}`:T,reason:P.reason,hint:P.hint});return}o(T);return}const q=C.slice(Co.length),F=e.find(T=>T.id===q);if(!F||!F.enabled||F.status.state!=="connected"){h({label:To(q),reason:!F||!F.enabled?t("mcp.disabledProvider"):F.status.state==="disconnected"?t("mcp.disconnectedSelection"):I(F)});return}ao(q,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:g,onChange:U,triggerSub:w?"":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(Po,{tone:j}),s.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),s.jsx("span",{className:"provider-status-line__value",children:N})]}),w&&i.observedAt!==null?s.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,w&&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(w?"comfy.display.localMethod":"provider.authMethodTitle"),children:[s.jsx("span",{children:L}),j!=="bad"&&!w?s.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),s.jsx(Vx,{open:!!p,providerLabel:p?.label??"",reason:p?.reason??"",hint:p?.hint,onClose:()=>h(null)})]})}const Bx=[{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"}],Wx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function Jx(){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:Bx.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:Wx.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 Yx(){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:Qi.map(r=>({value:r.value,label:e(r.fullLabelKey)})),value:t,onChange:n,portal:!0})]})}function kd({values:e,value:t,defaultValue:n,onChange:r,allowAuto:o=!1,disabled:a,ariaLabel:i}){const{t:l}=V(),c=y.useId();if(e.length===0)return null;const d=t??n??e[0],m=e.reduce((x,I,b)=>Math.abs(I-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 ui=3;function Xx(){const{t:e}=V(),t=f(u=>u.videoModelSelected),n=f(u=>u.videoReferenceVoices),r=f(u=>u.toggleVideoReferenceVoice),[o,a]=y.useState([]),[i,l]=y.useState("");y.useEffect(()=>{let u=!0;return Gi().then(p=>{u&&a(p.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{u=!1}},[]);const c=Mt(t)===tt,d=n.length>=ui,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:ui}):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 Zx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],Qx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),mi=[3,5,8,10,12,15],eI=[{value:gs,label:"Grok V",sub:"Fast"},{value:tt,label:"Grok V1.5",sub:"HD"}];function tI(){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),I=f(k=>k.videoContinuityLineage),b=f(k=>k.selectedPresetIds),v=f(k=>k.removePreset),g=b.map(k=>kc(k)).filter(k=>k?.category==="camera-motion"),_=rm(r,o),S=Sa(t,_),w=Tc(I),N=uo(t,"1080p",_),j=uo(tt,"1080p",_),L=Zx.map(k=>k.value==="1080p"?{...k,disabled:!j}:k);y.useEffect(()=>{uo(t,c,_)||d("720p")},[_,c,d,t]),y.useEffect(()=>{i!==null&&i>S&&l(S)},[i,S,l]);const U=k=>{const P=Sa(k,_);i!==null&&i>P&&x(e("video.durationClampedToModel",{seconds:P})),n(k)},C=k=>{if(k==="1080p"){if(!j)return;N||n(tt)}d(k)},[q,F]=y.useState(null);y.useEffect(()=>{Ie("/api/config/grok-planner").then(k=>k.json()).then(F).catch(()=>{})},[]);const T=async k=>{const P=q?.model;F(B=>B?{...B,model:k}:null);try{const B=await Ie("/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(F(se=>se&&P?{...se,model:P}: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:eI.map(k=>s.jsxs("button",{type:"button",className:`option-btn${t===k.value?" active":""}`,onClick:()=>U(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.${_}`,{n:r})})]}),w?s.jsxs("div",{className:"provider-compat-note",role:"note",children:[s.jsx("strong",{children:e("common.continuity")}),s.jsx("span",{children:w})]}):null,s.jsx(Xx,{}),g.length>0&&s.jsx(Xs,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(k=>s.jsx(ld,{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(kd,{values:mi.filter(k=>k<=S),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??mi[0])})]}),r===1&&s.jsx($e,{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($e,{title:e("video.resolutionTitle"),help:j?void 0:e("video.resolution1080Help"),items:L,value:c,onChange:C}),s.jsx($e,{title:e("video.aspectTitle"),items:Qx,value:m,onChange:u}),q&&s.jsx("div",{className:"video-controls__pills",children:s.jsx(Me,{className:"video-controls__pill",items:q.options.map(k=>({value:k,label:k})),value:q.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:Pr})]})]})}const pi=e=>Symbol.iterator in e,fi=e=>"entries"in e,hi=(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},nI=(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 rI(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:pi(e)&&pi(t)?fi(e)&&fi(t)?hi(e,t):nI(e,t):hi({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function oI(e){const t=fn.useRef(void 0);return n=>{const r=e(n);return rI(t.current,r)?t.current:t.current=r}}const sI=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function aI(){const{t:e}=V(),t=f(oI(pp)),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=Wo(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:el.map(m=>({value:m.value,label:m.shortLabel})),value:o,onChange:m=>{Wo(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:sI.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:wl.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:_l.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:Nr.min,max:Nr.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:kr.min,max:kr.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:jr.min,max:jr.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:El.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:Nl.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),kl))}})]}),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 iI="",jd=3;function gi(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 lI(e,t){return e[t]??null}function Cd(e,t,n){const r=!t||e.some(o=>o.filename===t);return[{value:iI,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 Mo({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:Cd(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 cI({index:e,images:t,selection:n,disabled:r,onChange:o,t:a}){const i=lI(n.references,e),l=new Set(n.references.filter((x,I)=>I!==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 I=[...n.references];x?I[e]={filename:x,...i?.tag?{tag:i.tag}:{}}:I.splice(e,1),o({...n,references:I})},u=x=>{if(!i)return;const I=[...n.references],{tag:b,...v}=i;I[e]={...v,...x?{tag:x}:{}},o({...n,references:I})},p=!!(i?.tag&&!ws(i.tag)),h=`mcp-reference-tag-error-${e}`;return s.jsxs("div",{className:"mcp-reference-slot__reference",children:[s.jsx(Me,{items:Cd(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 dI({selection:e,disabled:t,onChange:n,t:r}){const o=y.useRef(null),[a,i]=y.useState(null),l=e.references.length>=jd,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 Ts(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 uI({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:jd},(a,i)=>s.jsx(cI,{index:i,images:e,selection:t,disabled:n,onChange:r,t:o},i)),s.jsx(dI,{selection:t,disabled:n,onChange:r,t:o})]})}function mI({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)??Ve(),l=y.useMemo(()=>gi(r,o,a,!1),[r,o,a]),c=y.useMemo(()=>gi(r,o,a,!0),[r,o,a]),d=u=>Sg(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(Mo,{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(Mo,{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(uI,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?s.jsx(Mo,{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 pI(e){return Array.isArray(e)&&e.includes("image_references")}function fI(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function x_(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 I_(e){return e.length>3}function hI({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(!pI(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=fI({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 yi=new Set(["duration","resolution","quality","mode"]);function vi(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function oa(e){return e.options&&e.options.length>0?vi(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):vi([e.min,...e.default!==void 0?[e.default]:[],e.max])}function bi(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 gI(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function yI(e){return[...oa(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function vI({parameter:e,value:t,disabled:n,onChange:r}){const{t:o}=V();if(e.name==="duration"&&e.type==="number"){const l=yI(e);if(l.length>1){const c=bi(e.name,o);return s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:c}),s.jsx(kd,{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=oa(e);if(a.length===0)return null;const i=bi(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:gI(l,o)},`${typeof l}:${String(l)}`))]})]})}function xi({entries:e,parameters:t,disabled:n,onParameter:r}){return s.jsx(s.Fragment,{children:e.map(o=>s.jsx(vI,{parameter:o,value:t[o.name],disabled:n,onChange:a=>r(o.name,a)},o.name))})}function bI({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=>oa(p).length>0),d=c.filter(p=>yi.has(p.name)),m=c.filter(p=>!yi.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(xi,{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(mI,{inputRoles:e.capabilities.inputRoles,disabled:r}),s.jsx(hI,{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(xi,{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 lr={image:[],video:[]},xI={};function II(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function SI({record:e}){const{t}=V(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),o=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??xI,[c,d]=y.useState(lr),[m,u]=y.useState("idle"),[p,h]=y.useState(0),x=e?.executable===!1,I=e?.status.state==="connected";if(y.useEffect(()=>{if(!n||!I){d(lr),u("idle");return}const _=new AbortController;return d(lr),u("loading"),Qc(n,_.signal).then(S=>{_.signal.aborted||(d(S),u("ready"))}).catch(S=>{S.name!=="AbortError"&&(_.signal.aborted||(d(lr),u("error")))}),()=>_.abort()},[n,I,p]),!n)return null;const b=o==="video"?c.video:c.image,v=b.find(_=>_.id===r)??null,g=_=>bg(_,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:[II(n)," · MCP"]}),s.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>ao(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),I?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:()=>g("image"),children:t("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${o==="video"?" active":""}`,"aria-pressed":o==="video",onClick:()=>g("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(_=>_+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(bI,{entry:v,ratio:a,parameters:l,disabled:x,onRatio:_=>xg(_,f.setState),onParameter:(_,S)=>Ig(_,S,f.setState,f.getState)})]}):s.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function wI(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"?`${Kt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!Ut(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 _I(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(Kt),o=r?e.slice(Kt.length):e;kt(ta(),r?{comfyVideoWorkflow:o}:{comfyWorkflow:o}).selectedAvailable&&(r?n.setComfyVideoWorkflow(o):n.setComfyWorkflow(o))}function EI(){const{t:e}=V(),t=y.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=Vn(),m=kt(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),u=l?`${Kt}${l}`:i??"",p=wI(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(Wt(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=>_I(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 NI=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],cr=[{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"}],kI=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Fr={"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 jI(e){for(const[t,n]of Object.entries(Fr))for(const[r,o]of Object.entries(n))if(o===e)return{ratio:t,res:r};return null}function CI(e,t){const n=e/t;let r="1:1",o=1/0;const a=[...Object.keys(Fr),"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 Ad(){const{t:e}=V(),t=f(G=>G.provider),n=f(G=>G.imageToolModel),r=f(G=>G.setImageToolModel),o=f(G=>G.quality),a=f(G=>G.setQuality),i=f(G=>G.format),l=f(G=>G.setFormat),c=f(G=>G.moderation),d=f(G=>G.setModeration),m=f(G=>G.multimode),u=f(G=>G.setMultimode),p=f(G=>G.imageModel),h=f(G=>G.setImageModel),x=f(G=>G.selectVideoModel),I=f(G=>G.sizePreset),b=f(G=>G.customW),v=f(G=>G.customH),g=f(G=>G.setSizePreset),_=f(G=>G.setCustomSize),S=f(G=>G.uiMode),w=f(G=>G.videoModelSelected),N=f(G=>G.mcpProvider??null),{providers:j}=ed(),L=S==="classic",U=t==="grok"||t==="grok-api",C=t==="agy",q=t==="gemini-api",F=C||q,T=t==="nai",k=t==="comfy",P=U||F||T,B=I==="custom"?`${b}x${v}`:"1024x1024",se=q&&I==="auto",oe=q&&!se?jI(B):null,ae=oe??{ratio:"",res:""},he=q&&!se&&I==="custom"&&!oe,D=p==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[O,ee]=y.useState(!1),[J,me]=y.useState(String(b)),[ge,ie]=y.useState(String(v)),ke=(G,ye)=>{const A=Fr[G||"1:1"]?.[ye||"1K"]||"1024x1024",[ne,de]=A.split("x").map(Number);ee(!1),g("custom"),_(ne,de)},le=()=>{const G=Number(J),ye=Number(ge);!Number.isFinite(G)||!Number.isFinite(ye)||G<=0||ye<=0||(g("custom"),_(G,ye),ee(!1))},Se=[{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=U?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:C?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:q?{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=G=>{G==="video"?x("grok-imagine-video"):h(p)};return N?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ro,{mcpProviders:j}),s.jsx(SI,{record:j.find(G=>G.id===N)??null})]}):k?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ro,{mcpProviders:j}),s.jsx(EI,{})]}):s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ro,{mcpProviders:j}),s.jsxs("details",{className:"provider-compat-details",children:[s.jsx("summary",{children:ce.title}),s.jsx("p",{children:ce.body})]}),U&&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${w?"":" active"}`,onClick:()=>be("image"),children:e("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${w?" active":""}`,onClick:()=>be("video"),children:e("grokMode.video")})]})}),w?s.jsx(tI,{}):s.jsxs(s.Fragment,{children:[C?null:U?s.jsxs(s.Fragment,{children:[s.jsx(Yx,{}),s.jsx(Jx,{})]}):T?s.jsx(aI,{}):q?s.jsxs(s.Fragment,{children:[s.jsx($e,{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"}),[cr.slice(0,3),cr.slice(3,6),cr.slice(6,8),cr.slice(8)].map((G,ye)=>s.jsx("div",{className:"option-row",children:G.map(A=>s.jsx("button",{type:"button",className:`option-btn${ae.ratio===A.value?" active":""}`,onClick:()=>ke(A.value,ae.res),children:A.label},A.value))},ye))]}),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:kI.map(G=>s.jsxs("button",{type:"button",className:`option-btn${ae.res===G.value?" active":""}`,onClick:()=>ke(ae.ratio,G.value),children:[s.jsx("span",{children:G.label}),s.jsx("br",{}),s.jsx("small",{children:Fr[ae.ratio]?.[G.value]?.replace("x","×")||""})]},G.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),g("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${he||O?" active":""}`,onClick:()=>ee(G=>!G),children:[e("size.customPlus"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),O?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:G=>me(G.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:ge,onChange:G=>ie(G.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(J)>0&&Number(ge)>0?s.jsxs("div",{className:"size-picker__preview",children:[s.jsx("span",{children:e("size.normalizedPreview")}),s.jsx("strong",{children:(()=>{const G=CI(Number(J),Number(ge));return`${G.ratio} · ${G.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")},...Wi],value:n??"",onChange:G=>r(G||null),portal:!0})]}),s.jsx($e,{className:Se.length>3?"quality-options-expanded":"",title:e("quality.title"),items:Se,value:o,onChange:a}),s.jsx(Rx,{})]}),P?null:s.jsxs(s.Fragment,{children:[s.jsx($e,{title:e("format.title"),items:NI,value:i,onChange:l}),s.jsx($e,{title:e("moderation.title"),items:je,value:c,onChange:d}),s.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),L&&!F&&!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")})]})}),F||T?null:s.jsx(Mx,{}),T?null:s.jsx(qx,{})]})]})}const AI=y.lazy(()=>Le(()=>import("./PromptLibraryPanel-evfChzKq.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),TI=y.lazy(()=>Le(()=>import("./PromptBuilderPanel-CWOtvCbq.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),PI=y.lazy(()=>Le(()=>import("./GenerationRequestLogPanel-Bznhoi1c.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.GenerationRequestLogPanel})));function RI(){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]=y.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);y.useEffect(()=>{if(typeof window>"u")return;const v=window.matchMedia("(max-width: 800px)"),g=()=>d(v.matches);return v.addEventListener("change",g),()=>v.removeEventListener("change",g)},[]);const[m,u]=y.useState(!1),p=vh(i)&&!c,h=c?e:!0,x=De(c&&e,t),I=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.jsxs("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:[!c&&s.jsx("button",{type:"button",className:"right-panel-toggle","aria-expanded":e,"aria-controls":"right-panel-body",onClick:t,title:l(e?"panel.toggleHide":"panel.toggleShow"),children:e?">":"<"}),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":I==="builder","aria-controls":"right-panel-tab-builder",title:l("promptBuilder.title"),className:`right-panel-tabs__button${I==="builder"?" active":""}`,onClick:()=>b("builder"),children:l("promptBuilder.title")}):null,s.jsx("button",{type:"button",role:"tab","aria-selected":I==="log","aria-controls":"right-panel-tab-log",title:l("generationLog.title"),className:`right-panel-tabs__button${p?"":" right-panel-tabs__button--full"}${I==="log"?" active":""}`,onClick:()=>b("log"),children:l("generationLog.title")}),s.jsx("button",{type:"button",role:"tab","aria-selected":I==="library","aria-controls":"right-panel-tab-library",title:l("promptLibrary.title"),className:`right-panel-tabs__button right-panel-tabs__button--full${I==="library"?" active":""}`,onClick:()=>b("library"),children:l("promptLibrary.title")}),s.jsx("button",{type:"button",role:"tab","aria-selected":I==="settings","aria-controls":"right-panel-tab-settings",title:l("panel.detailSettings"),className:`right-panel-tabs__button right-panel-tabs__button--full${I==="settings"?" active":""}`,onClick:()=>b("settings"),children:l("panel.detailSettings")})]}),I==="builder"&&p?s.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:s.jsx(y.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(TI,{variant:"sidebar"})})}):I==="library"?s.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:s.jsx(y.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(AI,{variant:"embedded"})})}):I==="log"?s.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:s.jsx(y.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(PI,{})})}):s.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:s.jsx(Ad,{})})]})]})]})}function MI(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 LI({id:e}){const{t}=V();return s.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function OI({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 FI({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&&(Qe(l.url)||Qe(l.image))?s.jsx(Jt,{className:"collection-mini"},c):s.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function DI(e){const t=y.useRef(null),n=y.useRef(new Map),[r,o]=y.useState(()=>new Set);y.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=y.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 GI(){const e=f(g=>g.history),t=f(g=>g.currentImage),n=f(g=>g.historyStripLayout),r=f(g=>g.selectHistory),o=f(g=>g.openGallery),a=f(g=>g.inFlight),i=f(g=>g.multimodeSequences),l=y.useRef({}),[c,d]=y.useState(null),m=DI(c),{t:u}=V(),p=t?Te(t):null,h=y.useMemo(()=>xr(e.filter(bn)),[e]),x=y.useMemo(()=>{const g=[];for(const _ of a){const S=i[_.id];if(_.kind==="multimode"&&S){g.push({type:"collection-skeleton",id:_.id,count:S.requested});for(let w=0;w<S.requested;w++)S.images[w]||g.push({type:"skeleton",id:`${_.id}_${w}`,count:1})}else g.push({type:"skeleton",id:_.id,count:1})}return g},[a,i]),{completedSequences:I,sequenceFirstKeys:b}=y.useMemo(()=>{const g=new Map,_=new Set;for(const S of h)if(S.sequenceId&&(S.sequenceTotalRequested??0)>1){g.has(S.sequenceId)||_.add(Te(S));const w=g.get(S.sequenceId)||[];w.push(S),g.set(S.sequenceId,w)}return{completedSequences:g,sequenceFirstKeys:_}},[h]);y.useEffect(()=>{p&&l.current[p]?.scrollIntoView({block:"nearest",inline:"nearest"})},[p,h]);const v=(g,_)=>{const S=m.supported?m.visibleKeys.has(g):!0;return s.jsx("div",{ref:w=>{l.current[g]=w,m.register(g,w)},className:"history-thumb","data-history-lazy-key":g,"aria-hidden":S?void 0:!0,style:{padding:0,overflow:"hidden"},children:S?_:null},g)};return s.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:MI,"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(g=>g.type==="collection-skeleton"?s.jsx(OI,{id:g.id,count:g.count},`coll-${g.id}`):s.jsx(LI,{id:g.id},g.id)),h.map(g=>{const _=Te(g),S=p===_;if(g.sequenceId&&I.has(g.sequenceId)&&b.has(_)){const w=I.get(g.sequenceId);return[v(`coll-${g.sequenceId}`,s.jsx(FI,{sequenceId:g.sequenceId,images:w})),...w.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:U=>{U.dataTransfer.setData("application/ima2-ref",JSON.stringify(En(N))),U.dataTransfer.effectAllowed="copy"},children:[N.thumb?s.jsx("img",{src:N.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Jt,{}),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:U=>{U.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:N.url||N.image,filename:N.filename})),U.dataTransfer.effectAllowed="copy"}}))})]}return g.sequenceId&&I.has(g.sequenceId)&&!b.has(_)?null:xe(g)?v(_,s.jsxs("div",{className:`history-thumb history-thumb--video${S?" active":""}`,onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify(En(g))),w.dataTransfer.effectAllowed="copy"},children:[g.thumb?s.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Jt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):v(_,s.jsx("img",{src:g.thumb||g.url||g.image,alt:"",className:`history-thumb${S?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:g.url||g.image,filename:g.filename})),w.dataTransfer.effectAllowed="copy"}}))})]})}const Ii=3e3;function zI(){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]=y.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),l=y.useRef(new Map);y.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)}},[]),y.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)},Ii);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)},Ii);d.set(p,h)}}},[o,r,n,a,t]),y.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=Je[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)})})}function qI(){return null}function $I(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 UI(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(Ib(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:o,handleDownloadCardNewsManifest:a}}const HI=["ArrowLeft","ArrowRight","Home","End"];function VI(){return y.useCallback(e=>{if(!HI.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 Lo({className:e,ariaLabel:t,tabs:n,value:r,onChange:o}){const a=VI(),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 KI({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 BI=[{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 WI(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 Ie(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(()=>Cv);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 JI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function YI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function XI(e){return{modelLabel:tl(e.model,e.provider),derivation:JI(e),sourceLabel:YI(e)}}function ZI(e){return!e.modelLabel&&!e.derivation}function QI({view:e,size:t="sm"}){const{t:n}=V();return ZI(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 eS({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 tS({item:e,active:t,itemRef:n,onSelect:r,onDelete:o,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=y.useMemo(()=>BI.filter(u=>u.available(e)),[e]),d=y.useCallback(async(u,p)=>{p.stopPropagation(),await WI(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)?En(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(Jt,{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(eS,{id:u.id})},u.id))}):null,e.filename&&a&&s.jsx(cd,{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(QI,{view:XI(e)})]})}function nS(e){return typeof e=="object"?e.key:e}function rS(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 zt(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 Si(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const wi=(e,t)=>Math.abs(e-t)<1.01,oS=(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 pn;const Oo=()=>{if(pn!==void 0)return pn;if(typeof navigator>"u")return pn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return pn=!0;const e=navigator.maxTouchPoints;return pn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},_i=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},sS=e=>e,aS=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},iS=(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(_i(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(_i(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Dr={passive:!0},lS=typeof window>"u"?!0:"onscrollend"in window,cS=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const o=e.targetWindow;if(!o)return;const a=e.options.useScrollendEvent&&lS;let i=0;const l=a?null:oS(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,Dr),a&&r.addEventListener("scrollend",m,Dr),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",m),l?.cancel()}},dS=(e,t)=>cS(e,t,n=>{const{horizontal:r,isRtl:o}=e.options;return r?n.scrollLeft*(o&&-1||1):n.scrollTop}),uS=(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"]},mS=(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})},pS=mS;function fS(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 hS{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:sS,rangeExtractor:aS,onChange:()=>{},measureElement:uS,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,I=S=>nS(x[S]),b=u>0?I(0):null,v=u>0?I(u-1):null;if(p!==u||u>0&&p>0&&(o.getItemKey(0)!==b||o.getItemKey(p-1)!==v)){c=!0;const S=u>0?this.getVirtualItemForOffset(this.getScrollOffset())??h[0]:null;S&&(i=[S.key,this.getScrollOffset()-S.start]);const w=o.followOnAppend===!0?"auto":o.followOnAppend||null;w&&p>0&&this.isAtEnd(a.scrollEndThreshold)&&(u===0||o.getItemKey(p-1)!==v)&&(p>u||fS(u,p,I,o.getItemKey))&&(l=w)}}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:I}=this.options;let b=0;for(;b<x&&I(b)!==u;)b++;if(b<x){const v=h[b];if(v){const g=Math.max(0,v.start+p);!l&&g!==this.scrollOffset&&(m=g-this.scrollOffset,this.scrollOffset=g,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=zt(()=>(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,!(!Oo()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};i.addEventListener("touchstart",l,Dr),i.addEventListener("touchend",c,Dr),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&&(Oo()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?d!==0&&(this._iosDeferredAdjustment+=d):((r=this.scrollState)==null?void 0:r.behavior)==="smooth"&&!wi(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=zt(()=>[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=zt(()=>[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 g of this.laneAssignments.keys())g>=n&&this.laneAssignments.delete(g);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(g=>{this.itemSizeCache.set(g.key,g.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 g=n*2;let _=(u=this._singleLaneMeasurements)==null?void 0:u.flat;if(!_||_.length<g){const j=new Float64Array(g);_&&h>0&&j.set(_.subarray(0,h*2)),_=j}const S=h===0?new Array(n):this._singleLaneMeasurements.items.slice();let w;if(h===0)w=r+o;else{const j=h-1;w=_[j*2]+_[j*2+1]+d}for(let j=h;j<n;j++){const L=a(j);S[j]=L;const U=p.get(L),C=typeof U=="number"?U:this.options.estimateSize(j);_[j*2]=w,_[j*2+1]=C,w+=C+d}this._singleLaneMeasurements={flat:_,items:S};const N=rS(S,_);return this.measurementsCache=N,N}const x=this.measurementsCache.slice(0,h),I=new Array(l).fill(void 0),b=new Float64Array(l);let v=0;for(let g=0;g<h;g++){const _=x[g];_&&(I[_.lane]===void 0&&v++,I[_.lane]=g,b[_.lane]=_.end)}for(let g=h;g<n;g++){const _=a(g),S=this.laneAssignments.get(g);let w,N;const j=c==="estimate"||p.has(_);if(S!==void 0&&this.options.lanes>1){w=S;const q=I[w],F=q!==void 0?x[q]:void 0;N=F?F.end+d:r+o}else if(v===l){let q=0,F=b[0],T=I[0];for(let k=1;k<l;k++){const P=b[k];(P<F||P===F&&I[k]<T)&&(q=k,F=P,T=I[k])}w=q,N=F+d,j&&this.laneAssignments.set(g,w)}else w=g%this.options.lanes,N=r+o,j&&this.laneAssignments.set(g,w);const L=p.get(_),U=typeof L=="number"?L:this.options.estimateSize(g),C=N+U;x[g]={index:g,start:N,size:U,end:C,key:_,lane:w},I[w]===void 0&&v++,I[w]=g,b[w]=C}return this.measurementsCache=x,x},{key:!1,debug:()=>this.options.debug}),this.calculateRange=zt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,o,a)=>n.length===0||r===0?(this.range=null,null):(this.range=yS(n,r,o,a,a===1&&this._singleLaneMeasurements!==null?this._singleLaneMeasurements.flat:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=zt(()=>{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,I=this.getScrollOffset()+this.scrollAdjustments,v=!this.itemSizeCache.has(d)?c<I:c+u<=I&&this.scrollDirection!=="backward",g=((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 _=!1;h?_=this.applyScrollAdjustment(this.getTotalSize()-x):g&&(_=this.applyScrollAdjustment(p)),this.notify(_),this._retryClampedAdjustment()}},this.getVirtualItems=zt(()=>[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=Td(0,o.length-1,i?c=>a[c*2]:c=>Si(o[c]).start,n);return Si(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(Oo()&&(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&&wi(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 Td=(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 gS(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 yS(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=gS(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=Td(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 Fo=typeof document<"u"?y.useLayoutEffect:y.useEffect;function vS({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const o=y.useReducer(u=>u+1,0)[1],a=y.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=y.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",I=h?"left":"top",b=u.options.scrollMargin,v=u.getVirtualItems();for(const g of v){const _=g.start-b,S=u.elementsCache.get(g.key);S&&p.lastPositions.get(S)!==_&&(p.lastPositions.set(S,_),x?S.style.transform=h?`translate3d(${_}px, 0, 0)`:`translate3d(0, ${_}px, 0)`:S.style[I]=`${_}px`)}},d={...r,onChange:(u,p)=>{var h;const x=a.current;let I=!0;if(x.enabled){c(u);const b=u.range,v=x.prevRange;I=!v||v.isScrolling!==u.isScrolling||v.startIndex!==b?.startIndex||v.endIndex!==b?.endIndex,I&&(x.prevRange=b?{startIndex:b.startIndex,endIndex:b.endIndex,isScrolling:u.isScrolling}:null)}I&&(e&&p&&!i.current?io.flushSync(o):o()),(h=r.onChange)==null||h.call(r,u,p)}},[m]=y.useState(()=>{const u=new hS(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 I=u.getTotalSize();x.lastSize=I;const b=u.options.horizontal?"width":"height";h.style[b]=`${I}px`}}})});return m.setOptions(d),Fo(()=>m._didMount(),[]),Fo(()=>(l(m),m._willUpdate())),Fo(()=>{c(m)}),m}function bS(e){return vS({observeElementRect:iS,observeElementOffset:dS,scrollToFn:pS,...e})}const Gr=170,zr=10,Pd=36,xS=44;function IS(e){const t=Math.max(Gr,e-Pd);return Math.max(1,Math.floor((t+zr)/(Gr+zr)))}function SS(e,t){const n=Math.max(Gr,e-Pd);return Math.max(Gr,Math.floor((n-zr*Math.max(0,t-1))/t))+zr}function wS(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 _S({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:o}){const a=y.useRef(null),[i,l]=y.useState(0),c=y.useMemo(()=>IS(i||960),[i]),d=y.useMemo(()=>SS(i||960,c),[i,c]),m=y.useMemo(()=>wS(e,c),[e,c]);y.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=bS({count:m.length,getScrollElement:()=>n,estimateSize:p=>m[p]?.type==="header"?xS:d,overscan:6});return y.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,I)=>o(x,h.id,I))})},h.id):null})})}function Ei({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 ES({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 NS({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 Ni="ima2.storageNoticeDismissed.0.09.23";function kS(e){const t=y.useRef(null),n=y.useRef(new Map),[r,o]=y.useState(()=>new Set);y.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=y.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 jS(){const{t:e,locale:t}=V(),n=f(R=>R.galleryOpen),r=f(R=>R.closeGallery),o=f(R=>R.history),a=f(R=>R.selectHistory),i=f(R=>R.currentImage),l=f(R=>R.trashHistoryItem),c=f(R=>R.showToast),d=f(R=>R.toggleGalleryFavorite),m=f(R=>R.galleryScope),u=f(R=>R.setGalleryScope),p=f(R=>R.historyNextCursor),h=f(R=>R.historyLoadingOlder),x=f(R=>R.favoriteHistoryNextCursor),I=f(R=>R.favoriteHistoryLoadingOlder),b=f(R=>R.loadOlderHistory),v=f(R=>R.loadFavoriteHistory),g=f(R=>R.loadOlderFavoriteHistory),_=f(Cp),[S,w]=y.useState(""),[N,j]=y.useState("date"),[L,U]=y.useState(!1),[C,q]=y.useState(()=>new Set),F=y.useRef(new Set),[T,k]=y.useState([]),[P,B]=y.useState([]),[se,oe]=y.useState(!1),[ae,he]=y.useState(!1),[D,O]=y.useState(!1),[ee,J]=y.useState(0),[me,ge]=y.useState(null),[ie,ke]=y.useState(()=>{try{return localStorage.getItem(Ni)==="1"}catch{return!1}}),le=y.useRef(null),Se=y.useRef({}),[je,Re]=y.useState(null),ce=y.useRef(0),be=y.useRef({open:!1,selectedKey:null}),G=y.useMemo(()=>xr(o.filter(bn)),[o]),ye=y.useCallback(R=>{le.current=R,Re(R)},[]),A=kS(je),ne=De(n,r);y.useEffect(()=>{n||w("")},[n]),y.useEffect(()=>{if(!n)return;let R=!1;return(async()=>{try{const Y=await vu();R||ge(Y)}catch{R||ge({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}})}})(),()=>{R=!0}},[n]),y.useEffect(()=>{if(!n||N!=="session")return;let R=!1;return k([]),B([]),oe(!0),he(!1),O(!1),(async()=>{try{const Y=await gu({limit:500,sessionId:m==="current-session"?_:void 0});if(R)return;O(Y.nextCursor!==null||Y.total>=500);const _e=H=>{const pe=H.kind,at=pe==="classic"||pe==="edit"||pe==="generate"||pe==="card-news-card"||pe==="card-news-set"?pe:null,la=H.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(H.filename??"");return{image:H.url,url:H.url,filename:H.filename,thumb:H.thumb??(la?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:at,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:xr(H.items.filter(bn).map(_e))})).filter(H=>H.items.length>0)),B(xr(Y.loose.filter(bn).map(_e)))}catch{R||he(!0)}finally{R||oe(!1)}})(),()=>{R=!0}},[n,N,m,_,ee]),y.useEffect(()=>{!n||N==="session"||!L||v()},[n,N,L,v]);const de=y.useMemo(()=>{const R=S.trim().toLowerCase().normalize("NFC");return G.filter(Y=>L&&!Y.isFavorite?!1:R?(Y.prompt??"").toLowerCase().normalize("NFC").includes(R)||(Y.filename??"").toLowerCase().normalize("NFC").includes(R):!0)},[G,S,L]),K=y.useMemo(()=>L?T.map(R=>({...R,items:R.items.filter(Y=>Y.isFavorite)})).filter(R=>R.items.length>0):T,[T,L]),z=y.useMemo(()=>L?P.filter(R=>R.isFavorite):P,[P,L]),X=y.useMemo(()=>{const R=new Map;for(const Y of de){const _e=$I(Y.createdAt,t);R.has(_e)||R.set(_e,[]),R.get(_e).push(Y)}return Array.from(R.entries())},[de,t]),re=N==="session"?K.reduce((R,Y)=>R+Y.items.length,0)+z.length:de.length;y.useLayoutEffect(()=>{const R=i?Te(i):null;if(!n){be.current={open:!1,selectedKey:R};return}const Y=be.current,_e=!Y.open||Y.selectedKey!==R;be.current={open:!0,selectedKey:R};const H=R?Se.current[R]: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,z.length]);async function Oe(R,Y){Y.stopPropagation();const _e=Te(R);await l(R),delete Se.current[_e],window.requestAnimationFrame(()=>le.current?.focus())}async function Ge(R){const Y=R.filename;if(!(!Y||F.current.has(Y))){F.current.add(Y),q(new Set(F.current));try{const _e=await d(R);if(_e===null)return;k(H=>H.map(pe=>({...pe,items:pe.items.map(at=>at.filename===Y?{...at,isFavorite:_e}:at)}))),B(H=>H.map(pe=>pe.filename===Y?{...pe,isFavorite:_e}:pe))}finally{F.current.delete(Y),q(new Set(F.current))}}}async function Ft(){try{await bu(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Be,handleCopyCardNewsSetPath:dt,handleDownloadCardNewsManifest:ut}=UI(r,c,e);function vt(){ke(!0);try{localStorage.setItem(Ni,"1")}catch{}}if(!n)return null;const E=R=>R==="earlier"||R==="today"||R==="yesterday"||R==="thisWeek"?e(`gallery.${R}`):R,W=(R,Y,_e)=>{const H=i?.image===R.image,pe=Te(R),at=Dt=>{Se.current[pe]=Dt,A.register(pe,Dt)};return(A.supported?A.visibleKeys.has(pe):!0)?R.kind==="card-news-set"?s.jsx("div",{ref:at,className:"gallery__tile-wrap gallery-card-news-set",children:s.jsx(KI,{item:R,onOpen:Dt=>{Be(Dt)},onCopyPath:dt,onDownloadManifest:ut})},`${Y}-${pe}`):s.jsx(tS,{item:R,active:H,itemRef:at,onSelect:Dt=>{a(Dt),r()},onDelete:Oe,onToggleFavorite:Ge,favoriteBusy:!!(R.filename&&C.has(R.filename)),t:e},`${Y}-${pe}`):s.jsx("div",{ref:at,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:R=>R.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}),S||L?e("gallery.totalFiltered",{n:G.length}):""]}),s.jsx(Lo,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:L?"favorites":"all",onChange:R=>U(R==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),s.jsx(Lo,{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(Lo,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:m,onChange:u,tabs:[{value:"current-session",label:e("gallery.scope.current"),disabled:!_},{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:S,onChange:R=>w(R.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(NS,{status:me,dismissed:ie,onOpenFolder:Ft,onDismiss:vt,t:e}),s.jsx("div",{className:"gallery__scroll",ref:ye,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(R=>R+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(ES,{groups:K,loose:z,favoritesOnly:L,galleryScope:m,setGalleryScope:u,renderTile:W,t:e}),s.jsx(Ei,{showSessions:Q,favoritesOnly:L,query:S,historyNextCursor:p,favoriteHistoryNextCursor:x,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{b()},onLoadOlderFavorites:()=>{g()},t:e})]}):de.length===0?s.jsx("div",{className:"gallery__empty",children:G.length===0?e("gallery.emptyAll"):e(L?"gallery.emptyFavorites":"gallery.noResults")}):s.jsxs(s.Fragment,{children:[s.jsx(_S,{dateGroups:X,selectedKey:we,scrollElement:je,localizeBucket:E,renderTile:W}),s.jsx(Ei,{showSessions:Q,favoritesOnly:L,query:S,historyNextCursor:p,favoriteHistoryNextCursor:x,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{b()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function CS(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 AS(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=V(),o=De(!!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(CS(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 dr(e){return e==null||e===""?"-":String(e)}function TS(){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=De(!!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:dr(l)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.size")}),s.jsx("strong",{children:dr(i.size)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.quality")}),s.jsx("strong",{children:dr(i.quality)})]}),s.jsxs("div",{children:[s.jsx("span",{children:e("metadata.model")}),s.jsx("strong",{children:dr(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 PS=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function jt(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Vt(e){return!e||typeof e!="object"||Array.isArray(e)?jt():e}function rs(e){return typeof e!="string"||!e.trim()?jt():e}function Rd(e){return e===void 0?{}:typeof e!="boolean"?jt():{executable:e}}function RS(e){const t=Vt(e),n=Vt(t.status);return typeof t.enabled!="boolean"||!PS.has(n.state)?jt():{id:rs(t.id),enabled:t.enabled,...Rd(t.executable),status:{state:n.state}}}function ki(e){return Array.isArray(e)?e.map(t=>{const n=Vt(t);return{id:rs(n.id),label:rs(n.label),...Rd(n.executable)}}):jt()}function ji(e,t){const n=Vt(e);if(n.ok!==!0||!Array.isArray(n.providers))return jt();const r=n.providers.map(RS);if(t===null)return{providers:r,catalog:null};const o=Vt(t),a=Vt(o.models);return o.ok!==!0?jt():{providers:r,catalog:{image:ki(a.image),video:ki(a.video)}}}function MS(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 LS(){const{t:e}=V(),t=f(m=>m.mcpProvider??""),n=f(m=>m.mcpModel??null),r=f(m=>m.mcpMediaKind??"image"),[o,a]=y.useState(0),[i,l]=y.useState({selection:{provider:t,model:n,kind:r},phase:"loading",observedAt:null,providers:[],catalog:null});if(y.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 ig(m.signal),I=ji(h,null).providers.find(g=>g.id===t),b=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await lg(t,m.signal):null,v=ji(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=MS(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 Ci={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 OS(){const{t:e}=V(),t=f(w=>w.readinessPopupOpen),n=f(w=>w.closeReadinessPopup),r=f(w=>w.openSettings),o=f(w=>w.provider),a=f(w=>w.mcpProvider??null),i=f(w=>w.imageModel),l=f(w=>w.reasoningEffort),c=f(w=>w.webSearchEnabled),d=f(w=>w.comfyWorkflow),m=f(w=>w.comfyVideoWorkflow),u=Nd(),p=Vn(),h=o==="grok",x=He.find(w=>w.value===i),I=De(t,n);if(!t)return null;const b=u[o],v=kt(p,{comfyWorkflow:d,comfyVideoWorkflow:m}),g=o==="comfy"&&!a,_=g?v.selectedAvailable:b.ok,S=()=>{n(),r("providers")};return s.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:n,role:"presentation",children:s.jsxs("div",{ref:I,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:w=>w.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(LS,{}):null,!a&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`provider-readiness__status${_?" is-ok":" is-blocked"}`,children:[s.jsx("span",{"aria-hidden":"true"}),s.jsx("strong",{children:e(g?Wt(v,p):_?"readiness.ready":"readiness.blocked")}),s.jsx("small",{children:g?e("comfy.display.controlsHelp"):_?e("readiness.readyBody"):b.reason})]}),!g&&b.hint?s.jsx("p",{className:"modal__hint",children:b.hint}):null,g?s.jsxs("dl",{className:"provider-readiness__facts",children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.provider")}),s.jsx("dd",{children:Ci.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:Ci[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:S,children:e(g?"comfy.display.manage":"readiness.openAccount")})]})]})})}function FS(){try{return localStorage.getItem(vl)==="1"}catch{return!1}}function Do({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 Go({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 DS(){const{t:e}=V(),t=f(S=>S.openSettings),n=f(S=>S.settingsOpen),r=wd(),o=_d(),{data:a}=Ed(),[i,l]=y.useState(FS),[c,d]=y.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,I=!i&&!c&&!n&&(m&&u&&p&&h),b=()=>{try{localStorage.setItem(vl,"1")}catch{}l(!0)},v=()=>d(!0),g=()=>{b(),t("providers")},_=De(I,v);return I?s.jsx("div",{className:"modal-backdrop onboarding-backdrop",role:"presentation",onClick:S=>{S.target===S.currentTarget&&v()},children:s.jsxs("div",{ref:_,className:"modal onboarding",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[s.jsxs("section",{className:"onboarding__intro",children:[s.jsx($r,{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(Do,{num:1,current:!0,title:e("onboarding.steps.signIn.title"),hint:e("onboarding.steps.signIn.hint")}),s.jsx(Do,{num:2,title:e("onboarding.steps.firstImage.title"),hint:e("onboarding.steps.firstImage.hint")}),s.jsx(Do,{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(Go,{primary:!0,title:e("onboarding.choices.chatgpt.title"),body:e("onboarding.choices.chatgpt.body"),badge:e("onboarding.recommended"),onChoose:g}),s.jsx(Go,{title:e("onboarding.choices.grok.title"),body:e("onboarding.choices.grok.body"),onChoose:g}),s.jsx(Go,{title:e("onboarding.choices.apiKey.title"),body:e("onboarding.choices.apiKey.body"),onChoose:g})]}),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 sa="/api/github/star",GS="https://api.github.com/repos/lidge-ai/ima2-gen";function zS(){return $(sa)}async function qS(){return(await Ie(sa,{method:"POST"})).ok}async function $S(){await Ie(`${sa}/dismiss`,{method:"POST"})}async function US(){try{const e=await fetch(GS,{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 Md(e,t){return!e||e.mediaType==="video"?!1:typeof e.createdAt=="number"&&e.createdAt>=t}function HS(e){const{status:t}=e;return!t||t.prompted||t.state==="starred"||e.settingsOpen||e.readinessOpen?!1:Md(e.head,e.mountedAt)}const VS=1800;function KS(){const{t:e}=V(),t=f(N=>N.history[0]??null),n=f(N=>N.settingsOpen),r=f(N=>N.readinessPopupOpen),o=y.useRef(Date.now()),a=y.useRef(!1),[i,l]=y.useState(null),[c,d]=y.useState(!1),[m,u]=y.useState("ask"),[p,h]=y.useState(null),x=t?{createdAt:t.createdAt,mediaType:t.mediaType}:null,I=Md(x,o.current);y.useEffect(()=>{a.current||!I||(a.current=!0,zS().then(l).catch(()=>{}))},[I]),y.useEffect(()=>{c||!HS({status:i,head:x,mountedAt:o.current,settingsOpen:n,readinessOpen:r})||(d(!0),US().then(h))},[i,t,n,r,c]),y.useEffect(()=>{if(m!=="thanks")return;const N=setTimeout(()=>d(!1),VS);return()=>clearTimeout(N)},[m]);const b=()=>{d(!1),l(N=>N&&{...N,prompted:!0})},v=()=>{b(),m!=="thanks"&&$S().catch(()=>{})},g=De(c,v);if(!c||!i)return null;const _=i.state!=="unauthenticated",S=async()=>{u("starring");const N=await qS().catch(()=>!1);u(N?"thanks":"failed"),N&&l({...i,state:"starred",prompted:!0})},w=()=>{window.open(i.url,"_blank","noopener"),v()};return s.jsx("div",{className:"modal-backdrop star-prompt-backdrop",role:"presentation",children:s.jsxs("div",{ref:g,className:"modal star-prompt",role:"dialog","aria-modal":"true","aria-labelledby":"star-prompt-title",tabIndex:-1,children:[s.jsx($r,{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:[_&&m!=="failed"?s.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{S()},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:w,"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(_?"starPrompt.noteGh":"starPrompt.noteSignIn")})]})})}function BS(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=V(),[o,a]=y.useState(Date.now());return y.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 WS(){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 JS(){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(!yt()||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(WS,{})})}let qr=null;function YS(e){qr=e}function XS(){const e=qr;qr=null,e?.isConnected&&e.focus()}function Ai(){qr=null}function ZS(){const{t:e}=V(),t=f(m=>m.openComposeSheet),n=f(m=>m.settingsOpen),r=f(m=>m.uiMode),o=r==="agent"&&en?"agent":r==="node"&&Qt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=yt(),i=y.useRef(null),l=y.useRef(null),c=y.useRef(null),d=(m,u)=>{u.current&&YS(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($r,{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(yd,{compact:!0})})]})}const QS={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},Ti={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function ew(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=QS[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function tw(){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 nw(){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 rw(){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 ow(){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 sw(){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 aw(){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 iw(){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 lw=[{id:"home",mode:"home",icon:nw,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:tw,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:rw,labelKey:"nav.node",enabled:Qt},{id:"agent",mode:"agent",icon:ow,labelKey:"nav.agent",enabled:en},{id:"assets",mode:"assets",icon:aw,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:iw,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:sw,labelKey:"nav.settings",enabled:!0,bottom:!0}];function cw(){const{t:e}=V(),t=f(I=>I.uiMode),n=f(I=>I.setUIMode),r=f(I=>I.settingsOpen),o=f(I=>I.openSettings),a=f(I=>I.closeSettings),i=yt(),l=y.useRef(null),c=y.useCallback(I=>{const b=l.current;if(!b||!I)return;const v=b.getBoundingClientRect(),g=I.getBoundingClientRect();g.left<v.left?b.scrollLeft-=v.left-g.left:g.right>v.right&&(b.scrollLeft+=g.right-v.right)},[]);y.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=y.useCallback(I=>{if(I.settingsAction){r?(a(),history.replaceState(null,"",Ti[t]||"#create")):(o(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",Ti[I.mode]||"#create"))},[t,r,n,o,a]);y.useEffect(()=>{const I=()=>{const b=ew();b&&(b.settings?o():(r&&a(),n(b.mode)))};return I(),window.addEventListener("popstate",I),window.addEventListener("hashchange",I),()=>{window.removeEventListener("popstate",I),window.removeEventListener("hashchange",I)}},[]);const m=lw.filter(I=>I.enabled),u=m.filter(I=>!I.bottom),p=m.filter(I=>I.bottom),h=I=>I.settingsAction?r:!r&&I.mode===t,x=I=>s.jsxs("button",{type:"button",className:`nav-rail__btn${h(I)?" is-active":""}`,onClick:()=>d(I),"aria-label":e(I.labelKey),"aria-current":h(I)?"page":void 0,children:[s.jsx(I.icon,{}),s.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(I.labelKey)})]},I.id);return i?s.jsx("nav",{ref:l,className:"nav-rail nav-rail--mobile","aria-label":e("nav.ariaLabel"),onFocusCapture:I=>{I.target instanceof HTMLElement&&c(I.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 dw=y.lazy(()=>Le(()=>import("./PromptLibraryPanel-evfChzKq.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),We=["prompt","controls","library"],ur="mobile-inflight-panel",mr=e=>`mobile-sheet-tab-${e}`,pr=e=>`mobile-sheet-panel-${e}`;function uw(){const{t:e}=V(),t=f(w=>w.composeSheetOpen),n=f(w=>w.composeSheetTab),r=f(w=>w.setComposeSheetTab),o=f(w=>w.closeComposeSheet),a=f(w=>w.inFlight.length),i=f(w=>w.settingsOpen),l=f(w=>w.uiMode),c=l==="agent"&&en?"agent":l==="node"&&Qt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=yt(),[m,u]=y.useState(!1),p=y.useRef(a),h=y.useRef(!1),x=y.useRef(null),I=y.useRef({}),b=y.useRef(!1),v=w=>{r(w),requestAnimationFrame(()=>I.current[w]?.focus())},g=(w,N)=>{const j=We.indexOf(N),L=w.key==="ArrowRight"?We[(j+1)%We.length]:w.key==="ArrowLeft"?We[(j-1+We.length)%We.length]:w.key==="Home"?We[0]:w.key==="End"?We[We.length-1]:null;L&&(w.preventDefault(),v(L))},_=De(t,o,{autoFocus:!1});y.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&u(!1)},[t,n,o,d,i,c]),y.useLayoutEffect(()=>{const w=p.current>0&&a===0;p.current=a,w&&(u(!1),h.current&&x.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),y.useLayoutEffect(()=>{if(t){b.current=!0;const w=requestAnimationFrame(()=>I.current[n]?.focus());return()=>cancelAnimationFrame(w)}b.current&&(b.current=!1,XS())},[t,n]);const S=d&&!i&&c==="classic";return y.useEffect(()=>{S||(b.current=!1,f.getState().composeSheetOpen&&o(),Ai())},[S]),y.useEffect(()=>()=>Ai(),[]),S?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:_,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:We.map(w=>s.jsx("button",{ref:N=>{I.current[w]=N},id:mr(w),type:"button",role:"tab","aria-selected":n===w,"aria-controls":pr(w),tabIndex:n===w?0:-1,className:`mobile-sheet-tabs__button${n===w?" active":""}`,onClick:()=>r(w),onKeyDown:N=>g(N,w),children:e(`sheet.tabs.${w}`)},w))}),s.jsxs("div",{className:"compose-sheet__body",children:[s.jsx("div",{id:pr("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":mr("prompt"),hidden:n!=="prompt",onFocusCapture:w=>{const N=document.getElementById(ur);h.current=N?.contains(w.target)??!1},children:n==="prompt"?s.jsxs(s.Fragment,{children:[s.jsx(Zs,{}),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":ur,"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(ea,{variant:"inline",panelId:ur}),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(Qs,{}),s.jsx(fd,{variant:"inline",panelId:ur,expanded:m,onToggle:u})]})]}):null}),s.jsx("div",{id:pr("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":mr("controls"),hidden:n!=="controls",children:n==="controls"?s.jsx(Ad,{}):null}),s.jsx("div",{id:pr("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":mr("library"),hidden:n!=="library",children:n==="library"?s.jsx(y.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:s.jsx(dw,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const mw={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function pw(){const e=f(r=>r.uiMode),t=f(r=>!!r.currentImage||!!r.multimodePreviewFlightId),n=f(r=>r.selectHistoryShortcutTarget);y.useEffect(()=>{if(e!=="classic")return;const r=o=>{const a=mw[o.key];a&&(o.defaultPrevented||Ir(o.target)||t&&(o.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const fw={width:1386,height:1506},hw="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",fr=64,Ld="ima2",Pi=34;let aa=Ld,os=!1,ht=null,ia="",ss=!1;function Od(){return navigator}function Fd(){if(typeof document>"u")return null;if(ht)return ht;const e=document.querySelector('link[rel~="icon"]');if(e)return ht=e,ia=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),ht=t,ss=!0,t}function gw(e){const t=document.createElement("canvas");t.width=fr,t.height=fr;const n=t.getContext("2d");return n?(n.clearRect(0,0,fr,fr),n.fillStyle="#1c1d21",vw(n,6,6,52,52,12),n.fill(),yw(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")):ia}function yw(e,t,n){const{width:r,height:o}=fw,a=Pi/o;e.save(),e.translate(t-r*a/2,n-Pi/2),e.scale(a,a),e.translate(-1170,-1128),e.fillStyle="#f2f3f5",e.fill(new Path2D(hw)),e.restore()}function vw(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 bw(e){const t=Od();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function xw(){const e=Od();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function Iw(e){document.title=`(${e}) ${aa}`;const t=Fd();t&&(t.href=gw(e)),bw(e)}function Ri(){document.title=aa,ht&&(ss?(ht.remove(),ht=null,ss=!1):ht.href=ia),xw()}function Mi(){os||typeof document>"u"||(os=!0,aa=document.title||Ld,Fd())}function Sw(e){y.useEffect(()=>(Mi(),()=>{os&&Ri()}),[]),y.useEffect(()=>{Mi(),e>0?Iw(e):Ri()},[e])}function ww(){y.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)}},[])}const _w=y.lazy(()=>Le(()=>import("./NodeCanvas-CtSwikbj.js"),__vite__mapDeps([8,1,2,7,9,10,11])).then(e=>({default:e.NodeCanvas}))),Ew=y.lazy(()=>Le(()=>import("./SettingsWorkspace-PzprnYiR.js"),__vite__mapDeps([12,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),Nw=y.lazy(()=>Le(()=>import("./CardNewsWorkspace-B238fPNf.js"),__vite__mapDeps([13,1,2])).then(e=>({default:e.CardNewsWorkspace}))),kw=y.lazy(()=>Le(()=>import("./AgentWorkspace-CRJwrf5D.js"),__vite__mapDeps([14,1,2,10])).then(e=>({default:e.AgentWorkspace}))),jw=y.lazy(()=>Le(()=>import("./AssetsWorkspace-i9IE-OMD.js"),__vite__mapDeps([15,1,2,9,10,16,17])).then(e=>({default:e.AssetsWorkspace}))),Cw=y.lazy(()=>Le(()=>import("./AssetGenWorkspace-CR3k3lgk.js").then(e=>e.A),__vite__mapDeps([18,1,2,9,10,16,19])).then(e=>({default:e.AssetGenWorkspace}))),Aw=y.lazy(()=>Le(()=>import("./HomeWorkspace-DmQcpD4W.js"),__vite__mapDeps([20,1,2])).then(e=>({default:e.HomeWorkspace}))),Tw=y.lazy(()=>Le(()=>import("./PromptLibraryPanel-evfChzKq.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function Pw(){return s.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function Rw(){pw(),ww();const{locale:e}=V(),t=f(w=>w.hydrateHistory),n=f(w=>w.loadSessions),r=f(w=>w.syncCapabilities),o=f(w=>w.startInFlightPolling),a=f(w=>w.reconcileInflight),i=f(w=>w.syncFromStorage),l=f(w=>w.settingsOpen),c=f(w=>w.unseenGeneratedCount),d=f(w=>w.historyStripLayout),m=f(w=>w.workspaceProfile),u=f(w=>w.uiMode),p=u==="agent"&&en?"agent":u==="node"&&Qt?"node":u==="home"?"home":u==="assets"?"assets":u==="asset-gen"?"asset-gen":"classic",h=p==="agent",x=p==="assets",I=p==="asset-gen",b=p==="home",v=yt(),g=Gn(m),_=!v&&p==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",S=!_&&!h&&!x&&!I&&!b;return Sw(c),y.useEffect(()=>{document.documentElement.lang=e},[e]),y.useEffect(()=>{if(!ue())return r(),t(),n(),a(),o(),At(),ha(()=>a()),ga(w=>{w==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{jn(),ha(()=>{}),ga(()=>{})}},[t,n,a,o,r]),y.useEffect(()=>{const w=N=>{const j=N.detail?.assetId;j&&f.getState().openAssetDetail(j)};return window.addEventListener("ima2:open-assets-detail",w),()=>window.removeEventListener("ima2:open-assets-detail",w)},[]),y.useEffect(()=>{const w=N=>{N.key&&(N.key==="ima2.inFlight"||N.key==="ima2.selectedFilename"||N.key===vs||N.key===ys||N.key===xs)&&i()};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[i]),y.useEffect(()=>{const w=()=>{jp(f.getState)};return window.addEventListener("beforeunload",w),()=>{window.removeEventListener("beforeunload",w)}},[]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`app${m==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${S&&d==="horizontal"?" app--history-horizontal":""}${S&&d==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":d,"data-mobile":v?"1":void 0,"data-ui-mode":p,children:[s.jsx(cw,{}),b?null:s.jsx(Lb,{}),s.jsx(ZS,{}),S?s.jsx(GI,{}):null,s.jsx(y.Suspense,{fallback:s.jsx(Pw,{}),children:l?s.jsx(Ew,{}):p==="classic"?_?s.jsx(jx,{}):s.jsx(ns,{}):p==="node"?s.jsx(_w,{}):p==="card-news"?s.jsx(Nw,{}):p==="agent"?s.jsx(kw,{}):p==="assets"?s.jsx(jw,{}):p==="asset-gen"?s.jsx(Cw,{}):p==="home"?s.jsx(Aw,{}):s.jsx(ns,{})}),v||p==="agent"||p==="card-news"||p==="assets"||p==="asset-gen"||p==="home"?null:s.jsx(RI,{})]}),s.jsx(AS,{}),s.jsx(BS,{}),s.jsx(zI,{}),s.jsx(qI,{}),s.jsx(jS,{}),s.jsx(TS,{}),s.jsx(OS,{}),s.jsx(DS,{}),s.jsx(KS,{}),s.jsx(uw,{}),s.jsx(JS,{}),p==="card-news"?s.jsx(y.Suspense,{fallback:null,children:s.jsx(Tw,{})}):null]})}const S_=Object.freeze(Object.defineProperty({__proto__:null,default:Rw},Symbol.toStringTag,{value:"Module"}));export{uv as $,Xu as A,a_ as B,Ku as C,$e as D,ed as E,u_ as F,Qi as G,m_ as H,He as I,p_ as J,f_ as K,v_ as L,na as M,h_ as N,Or as O,g_ as P,y_ as Q,Ho as R,Av as S,Ee as T,i_ as U,tm as V,Tv as W,MI as X,fm as Y,_r as Z,ot as _,f as a,c_ as a0,Ou as a1,n_ as a2,Jp as a3,bS as a4,cd as a5,b_ as a6,I_ as a7,x_ as a8,s_ as a9,Uw as aA,$w as aB,Ir as aC,Hw as aD,qw as aE,Lw as aF,Vw as aG,zw as aH,$b as aI,Gw as aJ,bx as aK,Oi as aL,M as aM,Ow as aN,Dw as aO,Fw as aP,Ww as aQ,Kw as aR,Jw as aS,Yw as aT,Bw as aU,Xw as aV,Zw as aW,Qw as aX,e_ as aY,t_ as aZ,S_ as a_,d_ as aa,yx as ab,cs as ac,vc as ad,VI as ae,ea as af,o_ as ag,Ct as ah,r_ as ai,ro as aj,Xs as ak,ld as al,qv as am,Te as an,Nd as ao,tw as ap,rw as aq,Qt as ar,ow as as,en as at,aw as au,Ti as av,dv as aw,px as ax,vx as ay,Qo as az,XI as b,Fp as c,Fe as d,Nt as e,um as f,tl as g,l_ as h,Qe as i,yc as j,De as k,Yp as l,Mu as m,Lp as n,$ as o,yt as p,ec as q,io as r,Ie as s,Me as t,V as u,wd as v,bp as w,_d as x,Hx as y,Ed as z};
|