ima2-gen 3.18.0 → 3.19.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.
Files changed (49) hide show
  1. package/bin/commands/doctor.js +13 -8
  2. package/bin/commands/gpt.js +216 -0
  3. package/bin/ima2.js +89 -53
  4. package/bin/lib/doctor-providers.js +19 -4
  5. package/docs/API.md +6 -3
  6. package/docs/migration/runtime-test-inventory.md +4 -1
  7. package/lib/authStatus.js +93 -0
  8. package/lib/chatgptAuth.js +236 -0
  9. package/lib/chatgptLogin.js +257 -0
  10. package/lib/codexDetect.js +16 -10
  11. package/lib/oauthLauncher.js +32 -0
  12. package/lib/oauthProxy/runtime.js +3 -0
  13. package/node_modules/openai-oauth/dist/chunk-2AENSHRT.js +84 -14
  14. package/node_modules/openai-oauth/package.json +2 -2
  15. package/package.json +3 -3
  16. package/routes/auth.js +111 -204
  17. package/routes/health.js +23 -9
  18. package/routes/quota.js +4 -9
  19. package/server.js +56 -11
  20. package/ui/dist/.vite/manifest.json +64 -64
  21. package/ui/dist/assets/{AgentWorkspace-CxbtxZYs.js → AgentWorkspace-C6ke6Eo4.js} +1 -1
  22. package/ui/dist/assets/{App-x_fzCXKb.js → App-pMN1OjNW.js} +8 -8
  23. package/ui/dist/assets/{AssetGenWorkspace-BIYh26wL.js → AssetGenWorkspace-DzEfpUy_.js} +2 -2
  24. package/ui/dist/assets/{AssetMediaLightbox-ordAqhjX.js → AssetMediaLightbox-Bx0azN0S.js} +1 -1
  25. package/ui/dist/assets/AssetsWorkspace-CHw1u9VC.js +1 -0
  26. package/ui/dist/assets/{CardNewsWorkspace-BfR-FMwo.js → CardNewsWorkspace-DsjqhaYO.js} +2 -2
  27. package/ui/dist/assets/{GenerationRequestLogPanel-CaVBCWhI.js → GenerationRequestLogPanel-EYEiHIr9.js} +1 -1
  28. package/ui/dist/assets/{HomeWorkspace-x-oJypd7.js → HomeWorkspace-DbnY1YF2.js} +1 -1
  29. package/ui/dist/assets/{KeyingPanel-SsAIeDy3.js → KeyingPanel-8J_RMrxg.js} +1 -1
  30. package/ui/dist/assets/{NodeCanvas-B1R-fOYq.js → NodeCanvas-DmjbNcTa.js} +1 -1
  31. package/ui/dist/assets/{PromptBuilderPanel-gGHOSb6l.js → PromptBuilderPanel-CL34Jpso.js} +1 -1
  32. package/ui/dist/assets/{PromptImportDialog-B5Wv2cie.js → PromptImportDialog-B24cvEkK.js} +2 -2
  33. package/ui/dist/assets/{PromptImportDiscoverySection-B5AdpMnV.js → PromptImportDiscoverySection-Bbw1_J_3.js} +1 -1
  34. package/ui/dist/assets/{PromptImportFolderSection-DgIWI0j2.js → PromptImportFolderSection-CMpxuE8e.js} +1 -1
  35. package/ui/dist/assets/PromptLibraryPanel-Ct98TJ61.js +2 -0
  36. package/ui/dist/assets/SettingsWorkspace-DL9Tm90P.js +1 -0
  37. package/ui/dist/assets/{SpriteRecipeWorkspace-ghZGUlM8.js → SpriteRecipeWorkspace-BJUH1ddP.js} +1 -1
  38. package/ui/dist/assets/{index-B-iNVdeL.js → index-CHeVGnoy.js} +6 -6
  39. package/ui/dist/assets/{index-Co3ZHk9P.js → index-D_LpLGWV.js} +3 -3
  40. package/ui/dist/assets/{pptxgen.es-D6s2Ip8Q.js → pptxgen.es-s4xfPXLT.js} +1 -1
  41. package/ui/dist/assets/{promptBuilderStore-CQxHJQz4.js → promptBuilderStore-DQR29LwN.js} +1 -1
  42. package/ui/dist/assets/useAgentDialogFocus-DAeS9IWG.js +1 -0
  43. package/ui/dist/index.html +1 -1
  44. package/vendor/openai-oauth-1.0.2-ima2.2.tgz +0 -0
  45. package/ui/dist/assets/AssetsWorkspace-BuiwpbQQ.js +0 -1
  46. package/ui/dist/assets/PromptLibraryPanel-CGcqRRsJ.js +0 -2
  47. package/ui/dist/assets/SettingsWorkspace-BhbAnrYw.js +0 -1
  48. package/ui/dist/assets/useAgentDialogFocus-ALfcs_Em.js +0 -1
  49. package/vendor/openai-oauth-1.0.2-ima2.1.tgz +0 -0
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Co3ZHk9P.js","assets/index-B-iNVdeL.js","assets/index-CxX85A3B.css","assets/PromptLibraryPanel-CGcqRRsJ.js","assets/PromptBuilderPanel-gGHOSb6l.js","assets/promptBuilderStore-CQxHJQz4.js","assets/GenerationRequestLogPanel-CaVBCWhI.js","assets/clipboard-DirTPLEi.js","assets/NodeCanvas-B1R-fOYq.js","assets/AssetMediaLightbox-ordAqhjX.js","assets/useAgentDialogFocus-ALfcs_Em.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-BhbAnrYw.js","assets/CardNewsWorkspace-BfR-FMwo.js","assets/AgentWorkspace-CxbtxZYs.js","assets/AssetsWorkspace-BuiwpbQQ.js","assets/KeyingPanel-SsAIeDy3.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-BIYh26wL.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-x-oJypd7.js"])))=>i.map(i=>d[i]);
2
- import{R as pn,i as ue,c as Xe,r as Ai,g as fe,a as Cd,b as jd,L as _t,z as Td,d as Pd,e as Ad,k as Rd,f as v,s as Md,l as Ld,j as s,h as Od,_ as Me}from"./index-B-iNVdeL.js";const ia=e=>{let t;const n=new Set,r=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const m=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,m))}},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},Fd=(e=>e?ia(e):ia),Dd=e=>e;function Gd(e,t=Dd){const n=pn.useSyncExternalStore(e.subscribe,pn.useCallback(()=>t(e.getState()),[e,t]),pn.useCallback(()=>t(e.getInitialState()),[e,t]));return pn.useDebugValue(n),n}const la=e=>{const t=Fd(e),n=r=>Gd(t,r);return Object.assign(n,t),n},Ri=(e=>e?la(e):la);async function Ne(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 Xe(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"){Ai(n);try{await o.body?.cancel()}catch{}throw Xe(n)}}return o}async function $(e,t){const n=await Ne(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 u=c?.rawCode??l.rawCode,p=c?.errorClass??l.errorClass;throw typeof u=="string"&&(d.rawCode=u),typeof p=="string"&&(d.errorClass=p),typeof r.currentVersion=="number"&&(d.currentVersion=r.currentVersion),d}return r}async function Mi(e,t){t?.throwIfAborted();const n=await Ne(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 an=null;function Li(){if(!an){const e=localStorage.getItem("ima2.browserId");e?an=e:(an=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",an))}return an}function Jt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Li()};return $(e,{...t,headers:n})}function Oi(){return $("/api/capabilities")}function Fi(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 Te(e){return $(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function zd(){return $("/api/oauth/status")}function qd(){return $("/api/billing")}const $d=5400*1e3,Ud=2e3,ca=3e4;let ve=null,wr="";const Oo=new Set;let Fo=null,Je=null,da=!1,hr=0,_r=0,ua=!1;const Hd=3;let ns=null;const Vd=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function Kd(){return wr?`/api/events?lastEventId=${encodeURIComponent(wr)}`:"/api/events"}function Bd(){_r+=1;const e=ve;ve=null,e?.close(),Je&&(clearTimeout(Je),Je=null)}function Wd(){ua||typeof window>"u"||(window.addEventListener(_t,Bd),ua=!0)}function ma(e,t){if(e!==_r||t!==fe()||ue()||ve)return;const n=Math.min(Ud*Math.pow(1.5,hr),ca),r=Math.min(n*(.8+Math.random()*.4),ca);hr+=1,Je=setTimeout(rs,r),ns?.(hr>=Hd?"failed":"reconnecting")}function rs(){if(Wd(),ue()||ve&&ve.readyState!==EventSource.CLOSED)return;_r+=1;const e=new EventSource(Kd());ve=e,Je&&(clearTimeout(Je),Je=null),e.onopen=()=>{if(ve!==e)return;Je&&(clearTimeout(Je),Je=null),hr=0;const t=da;da=!0,t&&Fo?.(),ve===e&&ns?.("connected")};for(const t of Vd)e.addEventListener(t,n=>{ve!==e||typeof n.data!="string"||Jd(t,n)});e.addEventListener("replay-gap",()=>{ve===e&&(wr="",Fo?.())}),e.onerror=t=>{if(ve!==e||typeof t.data=="string")return;ve=null,e.close();const n=++_r,r=fe();if(Cd()?.mode==="lan"){const o=()=>ma(n,r);jd().then(o,o)}else ma(n,r)}}function Jd(e,t){t.lastEventId&&(wr=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 Oo)a.jobId===o&&(a.event!==null&&a.event!==e||a.handler(e,r))}function jt(e,t,n){const r={jobId:e,event:t,handler:n};return Oo.add(r),(!ve||ve.readyState===EventSource.CLOSED)&&rs(),()=>{Oo.delete(r)}}function Yt(e,t=$d){const n=setTimeout(e,t);return()=>clearTimeout(n)}function pa(e){Fo=e}function fa(e){ns=e}function Tt(){(!ve||ve.readyState===EventSource.CLOSED)&&rs()}function os(e=1e4){const t=fe();return ue()?Promise.reject(Xe(t-1)):(Tt(),ve&&ve.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const o=Date.now(),a=()=>{if(t!==fe()||ue()){r(Xe(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 Yd=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],Xd={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 Zd(e){return typeof e=="string"&&Yd.includes(e)}function ha(e){if(typeof e=="string")return Xd[e]}const Di="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",We={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 ga(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 Qd=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function eu(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:We.LAN_TOKEN_REQUIRED,message:Xe().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=o&&o in We?o:a&&a in We?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:We.JOB_TRACKING_TIMEOUT,message:Di};const c=Zd(i)?ha(i):void 0,d=l?Qd.includes(l):!1,u=ha(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=We[l]):u?(p=ga(r),m=u):(p=ga(r),m=We[p]??We.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||eu(r):void 0;return{code:p,spec:m,message:r,...a?{rawCode:a}:o&&!l?{rawCode:o}:{},...i&&(c||u)?{errorClass:i}:{},...h?{moderationStage:h}:{}}}function tu(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function Qe(e,t="Generation failed"){const n=e.error;let r=t,o,a,i,l;const c=tu(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 m=n;typeof m.message=="string"&&m.message&&r===t&&(r=m.message),typeof m.code=="string"&&(o=o??m.code),typeof m.rawCode=="string"&&(a=m.rawCode),typeof m.errorClass=="string"&&(i=m.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 u=ot({code:o,rawCode:a,message:r,errorClass:i});u.code==="JOB_TRACKING_TIMEOUT"&&(o=u.code,r=u.message,d=504,l="timed_out",a=void 0,i=void 0);const p=new Error(r);return p.code=o,p.status=d,a&&(p.rawCode=a),i&&(p.errorClass=i),l&&(p.phase=l),p}const ya=5e3,va=3e4;function nu(e){if(!e)return ya;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(va,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(va,Math.max(1e3,n-Date.now())):ya}function ru(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function io(){return new DOMException("Aborted","AbortError")}function qr(...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 $r({url:e,payload:t,requestId:n,signal:r,parseError:o}){const a=fe();let i=null;const l=c=>new Promise((d,u)=>{if(r?.aborted){u(io());return}const p=()=>{i&&(clearTimeout(i),i=null),u(io())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",p),d()},c),r?.addEventListener("abort",p,{once:!0})});for(;;){if(r?.aborted)throw io();if(a!==fe())throw Xe(a);if(ue())throw Xe(a-1);const c=await Ne(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(ru(c,d)){await l(nu(c.headers.get("Retry-After")));continue}throw o(c,d)}}async function Gi(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return Tt(),new Promise((r,o)=>{let a=!1;const i=new AbortController,l=qr(t.signal,i.signal),c=p=>{a||(a=!0,u(),d(),p())},d=jt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>o(Qe(m,"Generation failed"))))}),u=Yt(()=>{c(()=>{i.abort(),Te(n),o(new Error("Generation stream timed out"))})});if(t.signal){if(t.signal.aborted){c(()=>{i.abort(),Te(n),o(new DOMException("Aborted","AbortError"))});return}t.signal.addEventListener("abort",()=>{c(()=>{i.abort(),Te(n),o(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(p,m)=>{const h=Qe(m,`Request failed: ${p.status}`);return h.status=h.status??p.status,h}}).then(()=>{}).catch(p=>{c(()=>o(p instanceof Error?p:new Error(String(p))))})})}async function ou(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="image"?t.onImage?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Multimode generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Multimode generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/generate/multimode",payload:e,requestId:r,signal:c,parseError:(m,h)=>{const b=new Error(h.error??`Request failed: ${m.status}`);return b.code=h.code,b.status=h.status??m.status,b}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}function iw(e){return $("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function su(e){const t=await e.arrayBuffer(),n=await Ne("/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 lw(e){return $("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function cw(){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 ss(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="planning"?t.onPlanning?.():m==="submitted"?t.onSubmitted?.(h):m==="progress"?t.onProgress?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Video generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Video generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/video/generate",payload:{provider:"grok",...e},requestId:r,signal:c,parseError:(m,h)=>{const b=new Error(h.error??`Request failed: ${m.status}`);return b.code=h.code,b.status=h.status??m.status,b}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}function Xt(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"),Jt(`/api/history?${t.toString()}`)}function au(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),Jt(`/api/history?${t.toString()}`)}function iu(e){return Jt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function lu(){return(await $("/api/storage/status")).data}function cu(){return $("/api/storage/open-generated-dir",{method:"POST"})}function zi(e){return $(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function du(e){return $(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function uu(e,t){return $(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function mu(e){return $("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function pu(){return $("/api/sessions")}function fu(e){return $("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function qi(e){return $(`/api/sessions/${encodeURIComponent(e)}`)}function hu(e,t){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function gu(e){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function yu(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 vu(e){return $("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function uw(e){return Jt(`/api/annotations/${encodeURIComponent(e)}`)}async function mw(e,t){await Jt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function pw(e){await Jt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function fw(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 hw(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 gw(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 yw(e){return $(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function bu(e){const t=new URLSearchParams;return $(`/api/prompts?${t.toString()}`)}function xu(e){return $("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Iu(e){return $(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function Su(e){return $(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function wu(e){return $("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function vw(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 xw(){return $("/api/prompts/import/curated-sources")}function Iw(e){return $("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Sw(e){return $("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ww(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return $(`/api/prompts/import/discovery${n}`)}function _w(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 Ew(e){return $("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Nw(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 kw(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 as(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 _u(e){return $(`/api/assets/${encodeURIComponent(e)}`)}function Ur(e){return $("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Cw(e){return $("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function $i(e,t){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function jw(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 Ne(`/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 Eu(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 Ne(`/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 Tw(e){return $("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function Nu(e){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function is(){return $("/api/assets/folders")}function ku(e){return $("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Ui(e,t){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function Cu(e){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ls(){return $("/api/assets/tags")}function Pw(){return $("/api/assets/all",{method:"DELETE"})}async function ju(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Node generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Node generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/node/generate",payload:e,requestId:r,signal:c,parseError:(m,h)=>{const b=h?.error?.message??`Request failed: ${m.status}`,I=new Error(b);return I.code=h?.error?.code,I.status=h?.status??m.status,I}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}const cs=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],Tu=new Set(cs);function Pt(e){return typeof e=="string"&&Tu.has(e)}const An={oauth:{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","gpt-5.3-codex-spark"],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:[]}},Pu=["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","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"],Hi={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}},ds={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:!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"}},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"}}},Vi=[{value:"gpt-image-2.5-sunburst",label:"GPT Image2.5 Sunburst"},{value:"gpt-image-2.5-flare",label:"GPT Image2.5 Flare"}];function us(e){return Vi.some(t=>t.value===e)}function At(e,t,n){return(n==="xhigh"||n==="max")&&(e!=="api"||!us(t))?"medium":n}const gr="gpt-5.6-luna",et=[{value:"gpt-5.6-luna",shortLabel:"5.6l",fullLabelKey:"settings.imageModel.gpt56Luna"},{value:"gpt-6-astra",shortLabel:"6a",fullLabelKey:"settings.imageModel.gpt6Astra"},{value:"gpt-5.6-terra",shortLabel:"5.6t",fullLabelKey:"settings.imageModel.gpt56Terra"},{value:"gpt-5.6-sol",shortLabel:"5.6s",fullLabelKey:"settings.imageModel.gpt56Sol"},{value:"gpt-5.5",shortLabel:"5.5",fullLabelKey:"settings.imageModel.gpt55"},{value:"gpt-5.4",shortLabel:"5.4",fullLabelKey:"settings.imageModel.gpt54"},{value:"gpt-5.4-mini",shortLabel:"5.4m",fullLabelKey:"settings.imageModel.gpt54Mini"},{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 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"}],Hr=new Set(An["gemini-api"].image),ms=new Set(An.atlascloud.image),ps=new Set(An.minimax.image),fs=new Set(An.nai.image),Au=et.filter(e=>!e.value.startsWith("grok-")&&!Hr.has(e.value)&&!ms.has(e.value)&&!ps.has(e.value)&&!fs.has(e.value)),Ru=et.filter(e=>e.value.startsWith("grok-")),Mu=et.filter(e=>Hr.has(e.value)),Lu=et.filter(e=>ms.has(e.value)),Ou=et.filter(e=>ps.has(e.value)),Ki=et.filter(e=>fs.has(e.value)),Aw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Fu(e){return et.some(t=>t.value===e)}function Du(e){return typeof e=="string"&&e.startsWith("grok-")}function Gu(e){return typeof e=="string"&&Hr.has(e)}function zu(e){return e==="grok"||e==="grok-api"?Ru:e==="agy"||e==="gemini-api"?Mu:e==="atlascloud"?Lu:e==="minimax"?Ou:e==="nai"?Ki:e==="comfy"?[]:Au}function Bi(e,t){return e?Hr.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:ms.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:ps.has(e)?t==="minimax"?`${e} minimax`:e:fs.has(e)?et.find(n=>n.value===e)?.shortLabel??e:et.find(n=>n.value===e)?.shortLabel??e:null}const hs="grok-imagine-video",tt="grok-imagine-video-1.5",Wi="grok-imagine-video-1.5-preview",Ji="grok-imagine-video-1.5-2026-05-30",qu=15,$u=10,ba=15,Uu=[{value:hs,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:tt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Hu(e){return e===hs||e===tt||e===Wi||e===Ji}function Rt(e){return Hu(e)?e===Wi||e===Ji?tt:e:!1}function xa(e,t){if(t!=="reference-to-video")return ba;const n=Rt(e);return n?n===tt?qu:$u:ba}function Vu(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function lo(e,t,n){return t!=="1080p"?!0:e===tt&&(n==="text-to-video"||n==="image-to-video")}const Vt="comfy-video:",Yi="video:";function Ku(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Vt}${a}`:o??"":(t==="grok"||t==="grok-api")&&r?`${Yi}${r}`:n}const Do=new Set(Pu),Bu={oauth:gr,api:gr,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:gr};function Vr(e,t){return typeof t=="string"&&Do.has(t)&&An[e].image.includes(t)}function yn(e){return typeof e=="string"&&e.trim().length>0?e:null}function Xi(e,t){if(Rt(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Vr(n,e))return n;return"oauth"}function lt(e){const t=Pt(e.provider)?e.provider:Xi(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=yn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Do.has(e.imageModel)?e.imageModel:gr,videoModelSelected:!1,comfyWorkflow:yn(e.comfyWorkflow)??(n&&!Do.has(n)?n:null),comfyVideoWorkflow:yn(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Vr(t,e.imageModel)?e.imageModel:Bu[t],videoModelSelected:t==="grok"||t==="grok-api"?Rt(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Wu(e,t){return Pt(e)&&Vr(e,t)?e:Xi(t,!1)}function Ju(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 Ia(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 Zi(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Go(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of cs){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"?yn(o.image):Vr(n,o.image)?o.image:null,i=n==="comfy"?yn(o.video):n==="grok"||n==="grok-api"?Rt(o.video):!1;t[n]={kind:o.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Yu="none",zo=[{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 Qi(e){return zo.some(t=>t.value===e)}const Xu={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Zu(e){return!Qi(e)||e==="none"?null:`R:${Xu[e]}`}const ke=["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"],el=ke[0],tl=ke[1],nl=ke[2],rl=ke[3],gs=ke[4],ol=ke[5],sl=ke[6],ys=ke[7],al=ke[8],qo=ke[9],$o=ke[10],Sa=ke[11],vs=ke[12],il=ke[13],bs=ke[17],ll=ke[19],cl=ke[20],Qu=!0,em=!1,Zt=!0,dl=em,Qt=!0,tm=24;function Uo(e){return Math.min(tm,Math.max(1,Math.trunc(e||1)))}const wa={ko:Rd,en:Ad,"zh-Hant":Pd,"zh-Hans":Td};function _a(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function nm(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 ul(n,e,t)}function ul(e,t,n){const r=_a(wa[e],t),o=typeof r=="string"?r:_a(wa.en,t),a=typeof o=="string"?o:t;return n?nm(a,n):a}function V(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>ul(e,t,n)}}function rm(e){return Math.round(e/16)*16}const St=16,xs=3840,co=655360,yr=8294400,om=3,zt=3,Ea=Math.floor(Math.sqrt(yr)/St)*St,ml=St,sm=xs,Kn=om;function Na(e){return Math.floor(e/16)*16}function Er(e){return Math.ceil(e/16)*16}function ze(e){return Math.min(sm,Math.max(ml,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 ka(e,t){const n=rm(e);return n!==e&&Et(t,"snap"),n}function Ca(e,t){return e<ml&&Et(t,"min"),e>xs&&Et(t,"maxEdge"),ze(e)}function ja(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 am(e,t,n){if(e*t<co){Et(n,"minPixels");const i=Math.sqrt(co/(e*t));let l=ze(Er(e*i)),c=ze(Er(t*i));for(;l*c<co;)l<=c?l=ze(l+St):c=ze(c+St);return{w:l,h:c}}if(e*t<=yr)return{w:e,h:t};Et(n,"maxPixels");const r=Math.sqrt(yr/(e*t));let o=ze(Na(e*r)),a=ze(Na(t*r));for(;o*a>yr;)o>=a?o=ze(o-St):a=ze(a-St);return{w:o,h:a}}function Is(e,t,n,r){const o=[],a=nt(e,n),i=nt(t,r);let l=Ca(ka(a,o),o),c=Ca(ka(i,o),o);return{w:l,h:c}=ja(l,c,o),{w:l,h:c}=am(l,c,o),{w:l,h:c}=ja(l,c,o),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:o}}function pl(e,t,n,r){const o=Is(e,t,n,r);return{w:o.w,h:o.h}}const im=[{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 lm(e,t){return`${e}x${t}`}function cm(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 pl(o,a,o,a)}function Kr(e){const t=pl(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function qt(e){return e.slice(0,zt).map(Kr)}function dm(e,t){const n=Kr(t),r=e.findIndex(o=>o.id===n.id);return r>=0?qt(e.map((o,a)=>a===r?n:o)):e.length>=zt?qt(e):qt([...e,n])}function um(e,t,n){const r=Kr({...n,id:t});return qt(e.map(o=>o.id===t?r:o))}const mm=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],pm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],fm=[{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"}],hm=[{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 gm(){return[{value:"auto",label:M("size.autoLabel"),sub:M("size.autoSub")},{value:"custom",label:M("size.customLabel"),sub:M("size.customSub")}]}const fl=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],hl=["native","karras","exponential","polyexponential"],gl=["heavy","light","furryFocus","humanFocus","none"],yl=["standard","light","none"],ym={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},Cr={min:0,max:1},vl=2**32-1;function vm(e,t){return{...ym,...e??{},...t}}function Ho(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 uo(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function bl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Bn(t.sampler,fl);r!==void 0&&(n.sampler=r);const o=Bn(t.noiseSchedule,hl);o!==void 0&&(n.noiseSchedule=o);const a=Bn(t.ucPresetId,gl);a!==void 0&&(n.ucPresetId=a);const i=Bn(t.qualityPresetId,yl);i!==void 0&&(n.qualityPresetId=i);const l=uo(t.steps,Nr.min,Nr.max);l!==void 0&&(n.steps=l);const c=uo(t.scale,kr.min,kr.max);c!==void 0&&(n.scale=c);const d=uo(t.cfgRescale,Cr.min,Cr.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<=vl&&(n.seed=t.seed),n}function Ue(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Vo="vid:",Ko="img:",bm=/^[\p{L}\p{N}_-]{1,32}$/u;function Ss(e){return bm.test(e)}function xm(e){return e.references.some(t=>t.tag!==void 0&&!Ss(t.tag))}function xl(e){return e==="video"?"video":"image"}function Br(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function Im(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function Wr(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)&&Im(r)))}function Ta(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 Il(e,t,n){const r=Br(t),o=Wr(n),a={};for(const i of e.parameters){const l=o[i.name];l!==void 0&&Ta(i,l)?a[i.name]=l:i.default!==void 0&&Ta(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function Sm(e){return e?Il(e,null,{}):{ratio:null,parameters:{}}}function wm(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function Sl(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 ws(e){if(!e||typeof e!="object")return Ue();const t=e,n=Array.isArray(t.references)?t.references.map(Sl).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 _s(e,t){const n=ws(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 wl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function _m(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:xl(e.mcpMediaKind),ratio:Br(e.mcpRatio),parameters:Wr(e.mcpParameters)}}function Wn(e,t){return`${e==="video"?Vo:Ko}${t}`}function Em(e){if(e.startsWith(Vo)){const t=e.slice(Vo.length);return t?{kind:"video",model:t}:null}if(e.startsWith(Ko)){const t=e.slice(Ko.length);return t?{kind:"image",model:t}:null}return null}function _l(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 Nm(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const o=xl(e.mcpMediaKind),a=Br(e.mcpRatio),i=Wr(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=y=>c===void 0||c.includes(y),u=ws(e.mcpReferenceSelection),p=l?d("start_image")?u.startFrameFilename:null:o==="video"?e.currentImageFilename??null:null,m=l&&d("image_references")?u.references:[],h=d("image_references")?e.elementReferences??[]:[],b=[...m,...h].map(Sl).filter(y=>!!y).filter((y,g,_)=>_.findIndex(w=>w.filename===y.filename)===g).slice(0,3);if(b.some(y=>y.dataUrl||y.tag!==void 0&&!Ss(y.tag)))return null;const I=l&&d("end_image")&&p?u.endFrameFilename:null,x=l&&d("video_references")?u.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:p??void 0,...I?{endFrameFilename:I}:{},...b.length>0?{references:b.map(({filename:y,tag:g})=>({filename:y,...g?{tag:g}:{}}))}:{},...x?{referenceVideoFilename:x}:{},...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(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-D_LpLGWV.js","assets/index-CHeVGnoy.js","assets/index-CxX85A3B.css","assets/PromptLibraryPanel-Ct98TJ61.js","assets/PromptBuilderPanel-CL34Jpso.js","assets/promptBuilderStore-DQR29LwN.js","assets/GenerationRequestLogPanel-EYEiHIr9.js","assets/clipboard-DirTPLEi.js","assets/NodeCanvas-DmjbNcTa.js","assets/AssetMediaLightbox-Bx0azN0S.js","assets/useAgentDialogFocus-DAeS9IWG.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-DL9Tm90P.js","assets/CardNewsWorkspace-DsjqhaYO.js","assets/AgentWorkspace-C6ke6Eo4.js","assets/AssetsWorkspace-CHw1u9VC.js","assets/KeyingPanel-8J_RMrxg.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-DzEfpUy_.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-DbnY1YF2.js"])))=>i.map(i=>d[i]);
2
+ import{R as pn,i as ue,c as Xe,r as Ri,g as fe,a as jd,b as Td,L as _t,z as Ad,d as Pd,e as Rd,k as Md,f as v,s as Ld,l as Od,j as s,h as Fd,_ as Me}from"./index-CHeVGnoy.js";const ia=e=>{let t;const n=new Set,r=(d,u)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const m=t;t=u??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(h=>h(t,m))}},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},Dd=(e=>e?ia(e):ia),Gd=e=>e;function zd(e,t=Gd){const n=pn.useSyncExternalStore(e.subscribe,pn.useCallback(()=>t(e.getState()),[e,t]),pn.useCallback(()=>t(e.getInitialState()),[e,t]));return pn.useDebugValue(n),n}const la=e=>{const t=Dd(e),n=r=>zd(t,r);return Object.assign(n,t),n},Mi=(e=>e?la(e):la);async function Ne(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 Xe(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"){Ri(n);try{await o.body?.cancel()}catch{}throw Xe(n)}}return o}async function $(e,t){const n=await Ne(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 u=c?.rawCode??l.rawCode,p=c?.errorClass??l.errorClass;throw typeof u=="string"&&(d.rawCode=u),typeof p=="string"&&(d.errorClass=p),typeof r.currentVersion=="number"&&(d.currentVersion=r.currentVersion),d}return r}async function Li(e,t){t?.throwIfAborted();const n=await Ne(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 an=null;function Oi(){if(!an){const e=localStorage.getItem("ima2.browserId");e?an=e:(an=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",an))}return an}function Jt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Oi()};return $(e,{...t,headers:n})}function Fi(){return $("/api/capabilities")}function Di(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 Te(e){return $(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function qd(){return $("/api/oauth/status")}function $d(){return $("/api/billing")}const Ud=5400*1e3,Hd=2e3,ca=3e4;let ve=null,wr="";const Oo=new Set;let Fo=null,Je=null,da=!1,hr=0,_r=0,ua=!1;const Vd=3;let ns=null;const Kd=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function Bd(){return wr?`/api/events?lastEventId=${encodeURIComponent(wr)}`:"/api/events"}function Wd(){_r+=1;const e=ve;ve=null,e?.close(),Je&&(clearTimeout(Je),Je=null)}function Jd(){ua||typeof window>"u"||(window.addEventListener(_t,Wd),ua=!0)}function ma(e,t){if(e!==_r||t!==fe()||ue()||ve)return;const n=Math.min(Hd*Math.pow(1.5,hr),ca),r=Math.min(n*(.8+Math.random()*.4),ca);hr+=1,Je=setTimeout(rs,r),ns?.(hr>=Vd?"failed":"reconnecting")}function rs(){if(Jd(),ue()||ve&&ve.readyState!==EventSource.CLOSED)return;_r+=1;const e=new EventSource(Bd());ve=e,Je&&(clearTimeout(Je),Je=null),e.onopen=()=>{if(ve!==e)return;Je&&(clearTimeout(Je),Je=null),hr=0;const t=da;da=!0,t&&Fo?.(),ve===e&&ns?.("connected")};for(const t of Kd)e.addEventListener(t,n=>{ve!==e||typeof n.data!="string"||Yd(t,n)});e.addEventListener("replay-gap",()=>{ve===e&&(wr="",Fo?.())}),e.onerror=t=>{if(ve!==e||typeof t.data=="string")return;ve=null,e.close();const n=++_r,r=fe();if(jd()?.mode==="lan"){const o=()=>ma(n,r);Td().then(o,o)}else ma(n,r)}}function Yd(e,t){t.lastEventId&&(wr=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 Oo)a.jobId===o&&(a.event!==null&&a.event!==e||a.handler(e,r))}function jt(e,t,n){const r={jobId:e,event:t,handler:n};return Oo.add(r),(!ve||ve.readyState===EventSource.CLOSED)&&rs(),()=>{Oo.delete(r)}}function Yt(e,t=Ud){const n=setTimeout(e,t);return()=>clearTimeout(n)}function pa(e){Fo=e}function fa(e){ns=e}function Tt(){(!ve||ve.readyState===EventSource.CLOSED)&&rs()}function os(e=1e4){const t=fe();return ue()?Promise.reject(Xe(t-1)):(Tt(),ve&&ve.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const o=Date.now(),a=()=>{if(t!==fe()||ue()){r(Xe(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 Xd=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],Zd={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 Qd(e){return typeof e=="string"&&Xd.includes(e)}function ha(e){if(typeof e=="string")return Zd[e]}const Gi="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",We={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 ga(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 eu=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function tu(e){const t=(e||"").toLowerCase();return t.includes("request was rejected")||t.includes("prompt was rejected")?"input":t.includes("image was filtered")||t.includes("generated image")?"output":"unknown"}function 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:We.LAN_TOKEN_REQUIRED,message:Xe().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=o&&o in We?o:a&&a in We?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:We.JOB_TRACKING_TIMEOUT,message:Gi};const c=Qd(i)?ha(i):void 0,d=l?eu.includes(l):!1,u=ha(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=We[l]):u?(p=ga(r),m=u):(p=ga(r),m=We[p]??We.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||tu(r):void 0;return{code:p,spec:m,message:r,...a?{rawCode:a}:o&&!l?{rawCode:o}:{},...i&&(c||u)?{errorClass:i}:{},...h?{moderationStage:h}:{}}}function nu(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function Qe(e,t="Generation failed"){const n=e.error;let r=t,o,a,i,l;const c=nu(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 m=n;typeof m.message=="string"&&m.message&&r===t&&(r=m.message),typeof m.code=="string"&&(o=o??m.code),typeof m.rawCode=="string"&&(a=m.rawCode),typeof m.errorClass=="string"&&(i=m.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 u=ot({code:o,rawCode:a,message:r,errorClass:i});u.code==="JOB_TRACKING_TIMEOUT"&&(o=u.code,r=u.message,d=504,l="timed_out",a=void 0,i=void 0);const p=new Error(r);return p.code=o,p.status=d,a&&(p.rawCode=a),i&&(p.errorClass=i),l&&(p.phase=l),p}const ya=5e3,va=3e4;function ru(e){if(!e)return ya;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(va,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(va,Math.max(1e3,n-Date.now())):ya}function ou(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function io(){return new DOMException("Aborted","AbortError")}function qr(...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 $r({url:e,payload:t,requestId:n,signal:r,parseError:o}){const a=fe();let i=null;const l=c=>new Promise((d,u)=>{if(r?.aborted){u(io());return}const p=()=>{i&&(clearTimeout(i),i=null),u(io())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",p),d()},c),r?.addEventListener("abort",p,{once:!0})});for(;;){if(r?.aborted)throw io();if(a!==fe())throw Xe(a);if(ue())throw Xe(a-1);const c=await Ne(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(ou(c,d)){await l(ru(c.headers.get("Retry-After")));continue}throw o(c,d)}}async function zi(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return Tt(),new Promise((r,o)=>{let a=!1;const i=new AbortController,l=qr(t.signal,i.signal),c=p=>{a||(a=!0,u(),d(),p())},d=jt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>o(Qe(m,"Generation failed"))))}),u=Yt(()=>{c(()=>{i.abort(),Te(n),o(new Error("Generation stream timed out"))})});if(t.signal){if(t.signal.aborted){c(()=>{i.abort(),Te(n),o(new DOMException("Aborted","AbortError"))});return}t.signal.addEventListener("abort",()=>{c(()=>{i.abort(),Te(n),o(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(p,m)=>{const h=Qe(m,`Request failed: ${p.status}`);return h.status=h.status??p.status,h}}).then(()=>{}).catch(p=>{c(()=>o(p instanceof Error?p:new Error(String(p))))})})}async function su(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="image"?t.onImage?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Multimode generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Multimode generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/generate/multimode",payload:e,requestId:r,signal:c,parseError:(m,h)=>{const b=new Error(h.error??`Request failed: ${m.status}`);return b.code=h.code,b.status=h.status??m.status,b}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}function dw(e){return $("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function au(e){const t=await e.arrayBuffer(),n=await Ne("/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 uw(e){return $("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function mw(){return $("/api/prompt-builder/config")}function pw(e){return $("/api/prompt-builder/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ss(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="planning"?t.onPlanning?.():m==="submitted"?t.onSubmitted?.(h):m==="progress"?t.onProgress?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Video generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Video generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/video/generate",payload:{provider:"grok",...e},requestId:r,signal:c,parseError:(m,h)=>{const b=new Error(h.error??`Request failed: ${m.status}`);return b.code=h.code,b.status=h.status??m.status,b}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}function Xt(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"),Jt(`/api/history?${t.toString()}`)}function iu(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),Jt(`/api/history?${t.toString()}`)}function lu(e){return Jt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function cu(){return(await $("/api/storage/status")).data}function du(){return $("/api/storage/open-generated-dir",{method:"POST"})}function qi(e){return $(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function uu(e){return $(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function mu(e,t){return $(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function pu(e){return $("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function fu(){return $("/api/sessions")}function hu(e){return $("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function $i(e){return $(`/api/sessions/${encodeURIComponent(e)}`)}function gu(e,t){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function yu(e){return $(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function vu(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 bu(e){return $("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function fw(e){return Jt(`/api/annotations/${encodeURIComponent(e)}`)}async function hw(e,t){await Jt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function gw(e){await Jt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function yw(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 vw(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 bw(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 xw(e){return $(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function xu(e){const t=new URLSearchParams;return $(`/api/prompts?${t.toString()}`)}function Iu(e){return $("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Su(e){return $(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function wu(e){return $(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function _u(e){return $("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Iw(e){return $("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Sw(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 _w(e){return $("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Ew(e){return $("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Nw(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return $(`/api/prompts/import/discovery${n}`)}function kw(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 Cw(e){return $("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function jw(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 Tw(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 as(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 Eu(e){return $(`/api/assets/${encodeURIComponent(e)}`)}function Ur(e){return $("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Aw(e){return $("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Ui(e,t){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Pw(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 Ne(`/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 Nu(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 Ne(`/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 Rw(e){return $("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function ku(e){return $(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function is(){return $("/api/assets/folders")}function Cu(e){return $("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Hi(e,t){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function ju(e){return $(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ls(){return $("/api/assets/tags")}function Mw(){return $("/api/assets/all",{method:"DELETE"})}async function Tu(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return Tt(),new Promise((o,a)=>{let i=!1;const l=new AbortController,c=qr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>o(h)):m==="error"&&d(()=>a(Qe(h,"Node generation failed"))))}),p=Yt(()=>{d(()=>{l.abort(),Te(r),a(new Error("Node generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Te(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}$r({url:"/api/node/generate",payload:e,requestId:r,signal:c,parseError:(m,h)=>{const b=h?.error?.message??`Request failed: ${m.status}`,I=new Error(b);return I.code=h?.error?.code,I.status=h?.status??m.status,I}}).then(()=>{}).catch(m=>{d(()=>a(m instanceof Error?m:new Error(String(m))))})})}const cs=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],Au=new Set(cs);function At(e){return typeof e=="string"&&Au.has(e)}const Pn={oauth:{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","gpt-5.3-codex-spark"],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:[]}},Pu=["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","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"],Vi={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}},ds={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:!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"}},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"}}},Ki=[{value:"gpt-image-2.5-sunburst",label:"GPT Image2.5 Sunburst"},{value:"gpt-image-2.5-flare",label:"GPT Image2.5 Flare"}];function us(e){return Ki.some(t=>t.value===e)}function Pt(e,t,n){return(n==="xhigh"||n==="max")&&(e!=="api"||!us(t))?"medium":n}const gr="gpt-5.6-luna",et=[{value:"gpt-5.6-luna",shortLabel:"5.6l",fullLabelKey:"settings.imageModel.gpt56Luna"},{value:"gpt-6-astra",shortLabel:"6a",fullLabelKey:"settings.imageModel.gpt6Astra"},{value:"gpt-5.6-terra",shortLabel:"5.6t",fullLabelKey:"settings.imageModel.gpt56Terra"},{value:"gpt-5.6-sol",shortLabel:"5.6s",fullLabelKey:"settings.imageModel.gpt56Sol"},{value:"gpt-5.5",shortLabel:"5.5",fullLabelKey:"settings.imageModel.gpt55"},{value:"gpt-5.4",shortLabel:"5.4",fullLabelKey:"settings.imageModel.gpt54"},{value:"gpt-5.4-mini",shortLabel:"5.4m",fullLabelKey:"settings.imageModel.gpt54Mini"},{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 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"}],Hr=new Set(Pn["gemini-api"].image),ms=new Set(Pn.atlascloud.image),ps=new Set(Pn.minimax.image),fs=new Set(Pn.nai.image),Ru=et.filter(e=>!e.value.startsWith("grok-")&&!Hr.has(e.value)&&!ms.has(e.value)&&!ps.has(e.value)&&!fs.has(e.value)),Mu=et.filter(e=>e.value.startsWith("grok-")),Lu=et.filter(e=>Hr.has(e.value)),Ou=et.filter(e=>ms.has(e.value)),Fu=et.filter(e=>ps.has(e.value)),Bi=et.filter(e=>fs.has(e.value)),Lw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Du(e){return et.some(t=>t.value===e)}function Gu(e){return typeof e=="string"&&e.startsWith("grok-")}function zu(e){return typeof e=="string"&&Hr.has(e)}function qu(e){return e==="grok"||e==="grok-api"?Mu:e==="agy"||e==="gemini-api"?Lu:e==="atlascloud"?Ou:e==="minimax"?Fu:e==="nai"?Bi:e==="comfy"?[]:Ru}function Wi(e,t){return e?Hr.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:ms.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:ps.has(e)?t==="minimax"?`${e} minimax`:e:fs.has(e)?et.find(n=>n.value===e)?.shortLabel??e:et.find(n=>n.value===e)?.shortLabel??e:null}const hs="grok-imagine-video",tt="grok-imagine-video-1.5",Ji="grok-imagine-video-1.5-preview",Yi="grok-imagine-video-1.5-2026-05-30",$u=15,Uu=10,ba=15,Hu=[{value:hs,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:tt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Vu(e){return e===hs||e===tt||e===Ji||e===Yi}function Rt(e){return Vu(e)?e===Ji||e===Yi?tt:e:!1}function xa(e,t){if(t!=="reference-to-video")return ba;const n=Rt(e);return n?n===tt?$u:Uu:ba}function Ku(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function lo(e,t,n){return t!=="1080p"?!0:e===tt&&(n==="text-to-video"||n==="image-to-video")}const Vt="comfy-video:",Xi="video:";function Bu(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:o,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Vt}${a}`:o??"":(t==="grok"||t==="grok-api")&&r?`${Xi}${r}`:n}const Do=new Set(Pu),Wu={oauth:gr,api:gr,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:gr};function Vr(e,t){return typeof t=="string"&&Do.has(t)&&Pn[e].image.includes(t)}function yn(e){return typeof e=="string"&&e.trim().length>0?e:null}function Zi(e,t){if(Rt(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Vr(n,e))return n;return"oauth"}function lt(e){const t=At(e.provider)?e.provider:Zi(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=yn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Do.has(e.imageModel)?e.imageModel:gr,videoModelSelected:!1,comfyWorkflow:yn(e.comfyWorkflow)??(n&&!Do.has(n)?n:null),comfyVideoWorkflow:yn(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Vr(t,e.imageModel)?e.imageModel:Wu[t],videoModelSelected:t==="grok"||t==="grok-api"?Rt(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Ju(e,t){return At(e)&&Vr(e,t)?e:Zi(t,!1)}function Yu(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 Ia(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 Qi(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Go(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of cs){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"?yn(o.image):Vr(n,o.image)?o.image:null,i=n==="comfy"?yn(o.video):n==="grok"||n==="grok-api"?Rt(o.video):!1;t[n]={kind:o.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Xu="none",zo=[{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 el(e){return zo.some(t=>t.value===e)}const Zu={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Qu(e){return!el(e)||e==="none"?null:`R:${Zu[e]}`}const ke=["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"],tl=ke[0],nl=ke[1],rl=ke[2],ol=ke[3],gs=ke[4],sl=ke[5],al=ke[6],ys=ke[7],il=ke[8],qo=ke[9],$o=ke[10],Sa=ke[11],vs=ke[12],ll=ke[13],bs=ke[17],cl=ke[19],dl=ke[20],em=!0,tm=!1,Zt=!0,ul=tm,Qt=!0,nm=24;function Uo(e){return Math.min(nm,Math.max(1,Math.trunc(e||1)))}const wa={ko:Md,en:Rd,"zh-Hant":Pd,"zh-Hans":Ad};function _a(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function rm(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 ml(n,e,t)}function ml(e,t,n){const r=_a(wa[e],t),o=typeof r=="string"?r:_a(wa.en,t),a=typeof o=="string"?o:t;return n?rm(a,n):a}function V(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>ml(e,t,n)}}function om(e){return Math.round(e/16)*16}const St=16,xs=3840,co=655360,yr=8294400,sm=3,zt=3,Ea=Math.floor(Math.sqrt(yr)/St)*St,pl=St,am=xs,Kn=sm;function Na(e){return Math.floor(e/16)*16}function Er(e){return Math.ceil(e/16)*16}function ze(e){return Math.min(am,Math.max(pl,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 ka(e,t){const n=om(e);return n!==e&&Et(t,"snap"),n}function Ca(e,t){return e<pl&&Et(t,"min"),e>xs&&Et(t,"maxEdge"),ze(e)}function ja(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 im(e,t,n){if(e*t<co){Et(n,"minPixels");const i=Math.sqrt(co/(e*t));let l=ze(Er(e*i)),c=ze(Er(t*i));for(;l*c<co;)l<=c?l=ze(l+St):c=ze(c+St);return{w:l,h:c}}if(e*t<=yr)return{w:e,h:t};Et(n,"maxPixels");const r=Math.sqrt(yr/(e*t));let o=ze(Na(e*r)),a=ze(Na(t*r));for(;o*a>yr;)o>=a?o=ze(o-St):a=ze(a-St);return{w:o,h:a}}function Is(e,t,n,r){const o=[],a=nt(e,n),i=nt(t,r);let l=Ca(ka(a,o),o),c=Ca(ka(i,o),o);return{w:l,h:c}=ja(l,c,o),{w:l,h:c}=im(l,c,o),{w:l,h:c}=ja(l,c,o),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:o}}function fl(e,t,n,r){const o=Is(e,t,n,r);return{w:o.w,h:o.h}}const lm=[{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 cm(e,t){return`${e}x${t}`}function dm(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 fl(o,a,o,a)}function Kr(e){const t=fl(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function qt(e){return e.slice(0,zt).map(Kr)}function um(e,t){const n=Kr(t),r=e.findIndex(o=>o.id===n.id);return r>=0?qt(e.map((o,a)=>a===r?n:o)):e.length>=zt?qt(e):qt([...e,n])}function mm(e,t,n){const r=Kr({...n,id:t});return qt(e.map(o=>o.id===t?r:o))}const pm=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],fm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],hm=[{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"}],gm=[{value:"1152x2048",label:"1152×2048",sub:"2K 9:16"},{value:"3840x2160",label:"3840×2160",sub:"4K 16:9"},{value:"2160x3840",label:"2160×3840",sub:"4K 9:16"}];function ym(){return[{value:"auto",label:M("size.autoLabel"),sub:M("size.autoSub")},{value:"custom",label:M("size.customLabel"),sub:M("size.customSub")}]}const hl=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],gl=["native","karras","exponential","polyexponential"],yl=["heavy","light","furryFocus","humanFocus","none"],vl=["standard","light","none"],vm={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},Cr={min:0,max:1},bl=2**32-1;function bm(e,t){return{...vm,...e??{},...t}}function Ho(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 uo(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function xl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Bn(t.sampler,hl);r!==void 0&&(n.sampler=r);const o=Bn(t.noiseSchedule,gl);o!==void 0&&(n.noiseSchedule=o);const a=Bn(t.ucPresetId,yl);a!==void 0&&(n.ucPresetId=a);const i=Bn(t.qualityPresetId,vl);i!==void 0&&(n.qualityPresetId=i);const l=uo(t.steps,Nr.min,Nr.max);l!==void 0&&(n.steps=l);const c=uo(t.scale,kr.min,kr.max);c!==void 0&&(n.scale=c);const d=uo(t.cfgRescale,Cr.min,Cr.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<=bl&&(n.seed=t.seed),n}function Ue(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Vo="vid:",Ko="img:",xm=/^[\p{L}\p{N}_-]{1,32}$/u;function Ss(e){return xm.test(e)}function Im(e){return e.references.some(t=>t.tag!==void 0&&!Ss(t.tag))}function Il(e){return e==="video"?"video":"image"}function Br(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function Sm(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function Wr(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)&&Sm(r)))}function Ta(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 Sl(e,t,n){const r=Br(t),o=Wr(n),a={};for(const i of e.parameters){const l=o[i.name];l!==void 0&&Ta(i,l)?a[i.name]=l:i.default!==void 0&&Ta(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function wm(e){return e?Sl(e,null,{}):{ratio:null,parameters:{}}}function _m(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function wl(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 ws(e){if(!e||typeof e!="object")return Ue();const t=e,n=Array.isArray(t.references)?t.references.map(wl).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 _s(e,t){const n=ws(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 _l(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Em(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:Il(e.mcpMediaKind),ratio:Br(e.mcpRatio),parameters:Wr(e.mcpParameters)}}function Wn(e,t){return`${e==="video"?Vo:Ko}${t}`}function Nm(e){if(e.startsWith(Vo)){const t=e.slice(Vo.length);return t?{kind:"video",model:t}:null}if(e.startsWith(Ko)){const t=e.slice(Ko.length);return t?{kind:"image",model:t}:null}return null}function El(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 km(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const o=Il(e.mcpMediaKind),a=Br(e.mcpRatio),i=Wr(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=y=>c===void 0||c.includes(y),u=ws(e.mcpReferenceSelection),p=l?d("start_image")?u.startFrameFilename:null:o==="video"?e.currentImageFilename??null:null,m=l&&d("image_references")?u.references:[],h=d("image_references")?e.elementReferences??[]:[],b=[...m,...h].map(wl).filter(y=>!!y).filter((y,g,_)=>_.findIndex(w=>w.filename===y.filename)===g).slice(0,3);if(b.some(y=>y.dataUrl||y.tag!==void 0&&!Ss(y.tag)))return null;const I=l&&d("end_image")&&p?u.endFrameFilename:null,x=l&&d("video_references")?u.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:p??void 0,...I?{endFrameFilename:I}:{},...b.length>0?{references:b.map(({filename:y,tag:g})=>({filename:y,...g?{tag:g}:{}}))}:{},...x?{referenceVideoFilename:x}:{},...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
3
 
4
- `)}function km(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(km);return t.every(n=>n!==null)?t:null}function Es(e){return e.map(t=>({id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}))}function Cm(e){const t=Mn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function jm(){try{const e=localStorage.getItem(el);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function Tm(){try{const e=localStorage.getItem(tl);if(e==="agent")return Qt?e:"classic";if(e==="card-news")return dl?e:"classic";if(e==="node")return Zt?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function Pm(){try{const e=localStorage.getItem(nl);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function Pa(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function Aa(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(rl);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 El(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(rl,JSON.stringify({mode:e,matteColor:t}))}catch{}}function Nl(e){try{localStorage.setItem(gs,e)}catch{}}function Am(){try{const e=localStorage.getItem(ol);if(Qi(e))return e}catch{}return Yu}function Rm(e){try{localStorage.setItem(ol,e)}catch{}}function Mm(){try{const e=localStorage.getItem(ll);return e?bl(JSON.parse(e)):{}}catch{return{}}}function kl(e){try{localStorage.setItem(ll,JSON.stringify(e))}catch{}}function Lm(){try{const e=localStorage.getItem(sl);if(e==="false")return!1;if(e==="true")return!0}catch{}return Qu}function Om(e){try{localStorage.setItem(sl,String(e))}catch{}}const Ra={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function Jr(){try{const e=localStorage.getItem(bs);if(!e)return Ra;const t=JSON.parse(e);return{model:Rt(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 Ra}}function fn(e){try{const t=Jr();localStorage.setItem(bs,JSON.stringify({...t,...e}))}catch{}}function Cl(){try{const e=localStorage.getItem(qo);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function st(e){try{e?localStorage.setItem(qo,e):localStorage.removeItem(qo)}catch{}}function Fm(){try{const e=localStorage.getItem($o);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function Ns(e){try{e?localStorage.setItem($o,e):localStorage.removeItem($o)}catch{}}function Dm(e,t){return`${e}x${t}`}function In(e){return Uo(e)}const jl=new Set(["1024x1024","1536x1024","1024x1536","1360x1024","1024x1360","1824x1024","1024x1824","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840","auto","custom"]);function Gm(e){if(typeof e!="string")return{};if(jl.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 Tl(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"}function Pl(e){return e==="png"||e==="jpeg"||e==="webp"}function Al(e){return e==="low"||e==="auto"}function zm(e){return Pt(e)}function qm(e){return e==="auto"||e==="direct"}function $m(e){return typeof e=="string"&&jl.has(e)}function en(){try{const e=localStorage.getItem(ys);if(!e)return{};const t=JSON.parse(e),n={};zm(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=Br(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=Wr(t.mcpParameters)),"imageToolModel"in t&&(n.imageToolModel=t.provider==="api"&&us(t.imageToolModel)?t.imageToolModel:null),Tl(t.quality)&&(n.quality=At(t.provider,n.imageToolModel,t.quality)),$m(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)),Pl(t.format)&&(n.format=t.format),Al(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=In(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=In(t.multimodeMaxImages)),qm(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 Um(){return _m(en())}function Ln(e,t,n="image"){te({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function te(e){try{const t=en();localStorage.setItem(ys,JSON.stringify({...t,...e}))}catch{}}function Rl(){const e=localStorage.getItem(cl);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ml(){try{const e=Rl();return e?.version===1?Go(e.lanes):{}}catch{return{}}}function Hm(e){try{let t=null;try{t=Rl()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Go(t.lanes):{},...Go(e)};localStorage.setItem(cl,JSON.stringify({version:1,lanes:r}))}catch{}}function Ll(){const e=en(),t=Jr();let n=null;try{n=localStorage.getItem(gs)}catch{}return lt({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Vm(e){Nl(e.imageModel),fn({model:e.videoModelSelected}),te({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Km(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 Ol(e){return e.filter(t=>t.selected).map(t=>t.id)}function Sn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function Bm(e,t,n,r){const o=new Set(Km(e,t,n));if(!o.size)return e;if(!r)return Sn(e,o);const a=e.find(c=>c.id===n),i=e.some(c=>o.has(c.id)&&c.selected),l=new Set(Ol(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of o)l.add(c);return Sn(e,l)}const Wm={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Ma=16777216;function La(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>Ma){const i=Math.sqrt(Ma/(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 mo(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 ks(e,t={}){const n={...Wm,...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}=La(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 u=await mo(l,"image/png"),p=await Jn(u);if(Yn(p)>n.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return p}for(const u of n.qualityLadder){const p=await mo(l,"image/jpeg",u),m=await Jn(p);if(Yn(m)<=n.maxB64Bytes)return m}const d=La(a,i,2048);l.width=d.w,l.height=d.h,c.drawImage(o,0,0,d.w,d.h);for(const u of[.7,.5,.35]){const p=await mo(l,"image/jpeg",u),m=await Jn(p);if(Yn(m)<=n.maxB64Bytes)return m}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{o.close?.()}}function jr(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 Fl(e){return(e.type||"").toLowerCase()==="image/png"}const Dl=18e4;function Jm(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)wn(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function wn(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 Gl(e){const t=await Promise.all(e.map(n=>Fi({kind:n.kind,sessionId:n.sessionId,includeTerminal:!0})));return{jobs:t.flatMap(n=>n.jobs),terminalJobs:t.flatMap(n=>n.terminalJobs??[])}}function Tr(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:Bo(e.kind)??Bo(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 Ym(e){const t=typeof e.errorCode=="string"&&e.errorCode?e.errorCode:"UNKNOWN",n=new Error(t==="JOB_TRACKING_TIMEOUT"?Di: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 tn(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Oa(e){return e.filename||e.image}function Fa(e,t){const n=new Map(e.map(r=>[Oa(r),r]));for(const r of t)n.set(Oa(r),r);return[...n.values()].sort((r,o)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(o.sequenceIndex??Number.MAX_SAFE_INTEGER))}function zl({includeExpired:e=!1}={}){try{const t=localStorage.getItem(al);if(!t)return[];const n=JSON.parse(t);if(!Array.isArray(n))return[];const r=Date.now();return n.filter(o=>o&&typeof o.id=="string"&&typeof o.prompt=="string"&&typeof o.startedAt=="number"&&(e||r-o.startedAt<Dl)).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:Bo(o.kind)}))}catch{return[]}}function Bo(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 $e=500,Cs=5;function Xm(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?Es(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:Xm(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 ql(e,t){const n=qe(t);return e.filter(r=>qe(r)!==n)}function $l(e,t){const n=qe(t);return e.find(r=>qe(r)===n)}function Ul(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 Hl(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 Yr(e,t){return e.slice(0,Math.max($e,t))}function js(e){return e.replace(/^data:[^;]+;base64,/,"")}async function Fn(e,t="reference.png"){const n=await Ne(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 ks(o,{preserveTransparency:!1})}function Zm(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 Ae(e){try{localStorage.setItem(al,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function Qm(e){return vm(e.naiServerDefaults,e.naiOptionOverrides)}function Xr(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=Is(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 ep(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):Cs}async function tp(e){try{const t=await Oi();e({referenceLimit:ep(t.limits?.maxRefCount),naiServerDefaults:bl(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 np(e){const t=await Ne(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 rp(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 op(e){return e?.type==="elementReferenceNode"||e?.data?.nodeType==="element-reference"}function Vl(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.filter(r=>!op(n.get(r.source)))}function Kl(e,t,n){return Vl(e,t).filter(r=>r.target===n)}function sp(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 Rw(e,t){const n=new Map,r=new Map;for(const i of e)n.set(i.id,0);for(const i of t){n.set(i.target,(n.get(i.target)??0)+1);const l=r.get(i.source)??[];l.push(i.target),r.set(i.source,l)}const o=e.filter(i=>(n.get(i.id)??0)===0).map(i=>i.id);let a=0;for(let i=0;i<o.length;i++){a+=1;for(const l of r.get(o[i])??[]){const c=(n.get(l)??0)-1;n.set(l,c),c===0&&o.push(l)}}return a<e.length}function De(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const o=Kl(e,t,r.id),i=(o[0]?n.get(o[0].source):null)?.data.serverNodeId??null,l=new Set(i?[i]:[]),c=[];for(const p of o.slice(1)){const m=n.get(p.source)?.data.serverNodeId;!m||l.has(m)||(l.add(m),c.push(m))}const d=r.data.extraParentServerNodeIds??[];return r.data.parentServerNodeId===i&&d.length===c.length&&d.every((p,m)=>p===c[m])?r:{...r,data:{...r.data,parentServerNodeId:i,extraParentServerNodeIds:c}}})}const Bl="ima2.nodeRefs.v1";function Ps(){try{const e=localStorage.getItem(Bl);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Wl(e){try{localStorage.setItem(Bl,JSON.stringify(e))}catch{}}function ap(e,t){if(!e)return[];const n=Ps()[e]?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function Zr(e,t,n){if(!e)return;const r=Ps(),o={...r[e]??{}};n.length===0?delete o[t]:o[t]=n,r[e]=o,Wl(r)}function As(e,t){Zr(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,Wl(n)}const lp=/\.(mp4|webm|mov)$/i;function Ze(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return lp.test(t)||e.startsWith("data:video/")}function xe(e){return e?e.mediaType==="video"?!0:Ze(e.filename)||Ze(e.url)||Ze(e.image):!1}const cp=15e3;function Rs(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",u),a.onloadedmetadata=null,a.onseeked=null,a.onerror=null,a.src="",a.load()},d=p=>{i||(i=!0,c(),p())};function u(){d(()=>o(Object.assign(new Error("frame extraction aborted"),{code:"VIDEO_FRAME_EXTRACT_ABORTED"})))}if(n.signal?.aborted){u();return}n.signal?.addEventListener("abort",u),l=setTimeout(()=>{d(()=>o(new Error("frame extraction timed out")))},cp),a.onloadedmetadata=()=>{const p=a.duration;if(!Number.isFinite(p)||p<=0){d(()=>o(new Error("video duration is unavailable")));return}a.currentTime=Math.max(0,t(p))},a.onseeked=()=>{try{const p=document.createElement("canvas");p.width=a.videoWidth,p.height=a.videoHeight;const m=p.getContext("2d");if(!m){d(()=>o(new Error("canvas 2d context unavailable")));return}m.drawImage(a,0,0);const h=p.toDataURL("image/jpeg",.85);d(()=>r(h))}catch(p){d(()=>o(p))}},a.onerror=()=>{d(()=>o(new Error("Failed to load video for frame extraction")))},a.src=e})}function nn(e,t){return Rs(e,n=>n-.1,t)}function Jl(e,t){return Rs(e,n=>Math.min(n*.3,.4),t)}function Yl(e,t){return Rs(e,n=>n/2,t)}function Xl(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:ap(e.id,r.id),video:o.video??null};return{id:r.id,type:o.nodeType==="element-reference"?"elementReferenceNode":"imageNode",position:{x:r.x,y:r.y},data:c}}),n=e.edges.map(r=>{const o=r.data??{};return{id:r.id,source:r.source,target:r.target,sourceHandle:typeof o.sourceHandle=="string"?o.sourceHandle:null,targetHandle:typeof o.targetHandle=="string"?o.targetHandle:null}});return{graphNodes:De(t,n),graphEdges:n,graphVersion:e.graphVersion}}const dp=800;let Ye=null,vr=!1,br=!1,It=null,Zl=0;function Ql(){try{const e=sessionStorage.getItem(Sa);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(Sa,t),t}catch{return"tab_unavailable"}}function ec(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 tc(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 nc(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 Xt({sessionId:n,limit:$e})).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,p=(d?o.find(m=>(m.sessionId??null)===n&&(m.requestId??null)===d):null)??o.find(m=>(m.sessionId??null)===n&&(m.clientNodeId??null)===l.id&&(!c||(m.createdAt??0)>=c));return p?(a=!0,{...l,data:{...l.data,status:"ready",imageUrl:p.url,serverNodeId:p.nodeId??l.data.serverNodeId,size:p.size??l.data.size??null,elapsed:p.elapsed??l.data.elapsed,reasoningEffort:p.reasoningEffort??l.data.reasoningEffort,video:p.video??l.data.video??null,pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0}}):l});a&&(t({graphNodes:i}),oc(e,t,"recovery"))}async function up(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await qi(n),{graphNodes:o,graphEdges:a,graphVersion:i}=Xl(r);t({graphNodes:o,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(M("toast.sessionReloadedElsewhere"),!0),await nc(e,t).catch(()=>{})}async function mp(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(p=>({id:p.id,x:p.position.x,y:p.position.y,data:ec(p.data)})),d=tc(i),u=`gs_${Date.now().toString(36)}_${++Zl}`;try{const p=await yu(r,o,c,d,{saveId:u,saveReason:n,tabId:Ql()});return e().activeSessionId!==r?"skipped":(ip(r,e().graphNodes.map(m=>m.id)),t({activeSessionGraphVersion:p.graphVersion}),"saved")}catch(p){return p.status===409?(await up(e,t),"conflict"):(console.warn("[sessions] save failed:",p),"failed")}}async function rc(e,t,n){return vr?(br=!0,It||"skipped"):(vr=!0,It=(async()=>{let r=n,o="skipped";do{if(br=!1,o=await mp(e,t,r),o==="conflict"||o==="failed")break;r="queued"}while(br);return o})().finally(()=>{vr=!1,It=null}),It)}function oc(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=null,rc(e,t,n)},dp)))}async function pp(e,t,n="manual"){let r=!1;if(Ye&&(clearTimeout(Ye),Ye=null,r=!0),vr){if(br=!0,(It?await It:"skipped")==="failed")throw new Error(M("modal.graphSaveFailed"));return}if(r&&await rc(e,t,n)==="failed")throw new Error(M("modal.graphSaveFailed"))}function fp(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;Ye&&(clearTimeout(Ye),Ye=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:ec(i.data)})),r=tc(t.graphEdges),o=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{Ne(o,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++Zl}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":Ql()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function gt(e,t,n,r={}){const o=xe(e)?void 0:await rp(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=$l(l.history,i),d=Ul(i,c),u=ql(l.history,d),p=Yr([d,...u],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:p,...h?{currentImage:d}:{},loadedHistoryRetainLimit:Math.max(l.loadedHistoryRetainLimit,Math.min(l.history.length+1,l.loadedHistoryRetainLimit+1)),unseenGeneratedCount:l.unseenGeneratedCount+1})}function hp(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const gp=30;function po(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function yp(e,t,n=gp){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function vp(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 bp(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 xp=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function Da(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 xp)l[c]=a.data[c];return{...o,data:l}}),edges:e.edges}}function Ip(e){return e.data.status==="ready"&&!!e.data.imageUrl}function Sp(e,t,n){const r=new Set(n),o=new Set(e.map(p=>p.id)),a=new Map,i=new Map;for(const p of r)o.has(p)&&(a.set(p,0),i.set(p,[]));for(const p of t)!r.has(p.source)||!r.has(p.target)||(i.get(p.source)?.push(p.target),a.set(p.target,(a.get(p.target)??0)+1));const l=e.map(p=>p.id),c=l.filter(p=>r.has(p)&&(a.get(p)??0)===0),d=[];for(let p=0;p<c.length;p++){const m=c[p];d.push(m);for(const h of i.get(m)??[])a.set(h,(a.get(h)??0)-1),(a.get(h)??0)===0&&c.push(h)}const u=new Set(d);return d.concat(l.filter(p=>r.has(p)&&!u.has(p)))}function wp(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 _p(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 Ep(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 Np(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 u of i.get(l[d])??[]){const p=(a.get(u)??0)-1;a.set(u,p),p===0&&l.push(u)}}return[...a.keys()].filter(d=>!c.has(d))}function He(e,t){const{code:n,spec:r,message:o}=ot(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return Ai(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 kp=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],Cp=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function jp(e){if(kp.includes(e))return"auth";const t=We[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||Cp.includes(e)?"retry":"fix-input"}function sc(e){const{code:t,message:n}=ot(e),r=jp(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const Tp=Hi.grok.video,Pp=3;function Ap(e,t){return Hi[e]?.[t]}function ac(e){if(e.mcpProvider)return Pp;if(e.videoModelSelected)return Math.min(e.serverLimit,Tp);if(Pt(e.provider)&&!ds[e.provider].generate.references)return 0;const t=Ap(e.provider,"image");return t===void 0?e.serverLimit:Math.min(e.serverLimit,t)}function Ms(e,t={}){const n=t.provider??e.provider,r=t.imageModel??e.imageModel;if(n!=="nai")return{};const o={...e.naiOptionOverrides};Ho(r)||(delete o.straightAlpha,delete o.qualityPresetId),o.seed===null&&delete o.seed;const a=e.negativePrompt.trim();return{...o,...a?{negativePrompt:a}:{}}}const Pr=new Map;function rn(e,t){Pr.set(e,t)}function on(e){Pr.delete(e)}function ic(e){Pr.get(e)?.abort(),Pr.delete(e)}const Rp="element-source:",Mp=500;function Lp(e){return`${Rp}${e}`}function Mw(e,t){const n=Lp(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function lc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function Op(e=as){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:Mp});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 cc(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function Lw(e){const t=e.filePath??(e.kind==="element"?lc(e)??"":""),n=cc(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 Ga=32,za="Image_",Fp=/@([\p{L}\p{N}_-]+)/gu,Dp=new Set([" "," ",`
5
- `,"(","["]);function dc(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${za}${r}`);)r+=1;return{tag:`${za}${r}`,nextAttachmentOrdinal:r+1}}function Gp(e,t){const n=new Set(t),r=e.slice(0,Ga)||"Element";if(!n.has(r))return r;let o=2;for(;;){const a=`_${o}`,i=`${r.slice(0,Ga-a.length)}${a}`;if(!n.has(i))return i;o+=1}}function Dn(e){return e.trayItems.filter(t=>t.kind==="attachment")}function uc(e){return e.trayItems.filter(t=>t.kind==="element")}function zp(e){return Dn(e).map(t=>t.source.dataUrl)}function qp(e){return uc(e).map(t=>t.source.elementId)}function $p(e){const t={trayItems:e};return{referenceImages:zp(t),selectedElementIds:qp(t)}}function Ls(e,t){return e.length<t}function Qr(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 Up(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Os(e,t){if(!Up(e,t))return e;const n={...e};return delete n[t],n}function Hp(e){const t=[];for(const n of e.matchAll(Fp)){const r=n.index,o=r>0?e[r-1]:void 0;o!==void 0&&!Dp.has(o)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function Vp(e){return e.reduce((t,n)=>t+(n.kind==="attachment"?1:n.source.referenceFilenames.length),0)}function Fs(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:fc(a,l),...$p(a)}}),n}function Kp(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function mc(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 Bp(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function pc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function xr(e,t,n,r){return r&&(r.id!==e||r.kind!=="element")?null:Fs(t,(o,a)=>{if(!Ls(o.trayItems,a))return{result:null};if(o.trayItems.some(p=>p.kind==="element"&&p.source.elementId===e))return{result:null};const i=o,l=Bp(i,e,r),c=l?_l(l.name):null;if(!l||!c)return{result:null};const d=Gp(c,o.trayItems.map(p=>p.tag)),u={kind:"element",tokenId:crypto.randomUUID(),tag:d,insertedAt:Date.now(),source:{elementId:e,nameAtInsertion:l.name,referenceFilenames:pc(l)}};return{result:u,patch:{trayItems:[...o.trayItems,u],retiredTags:Os(o.retiredTags,d),elementCatalog:mc(i.elementCatalog,l)}}})}function fc(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 Wo(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function Wp(e,t,n){Fs(t,r=>{const o=Wo(r.trayItems,e);return o?{result:void 0,patch:{trayItems:r.trayItems.filter(a=>a.tokenId!==o.tokenId),retiredTags:Qr(r.retiredTags,[o])}}:{result:void 0}})}function hc(e,t,n){const r=Kp(e);t(o=>({elementCatalog:r,missingElementIds:fc(o.trayItems,r)}))}function gc(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 u=d.data;a.set(d.id,{nodeId:d.id,elementId:typeof u.elementId=="string"&&u.elementId?u.elementId:null,name:typeof u.elementName=="string"&&u.elementName||typeof u.elementId=="string"&&u.elementId||"element",missing:u.missing===!0})}}else i.push(d.id)}}}return[...a.values()]}const bt=new Set;async function Jp(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 _u(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=mc(n().elementCatalog,c),u=c.updatedAt??c.createdAt;a.push(c.id),i[c.id]=u,typeof c.notes=="string"&&c.notes.trim()&&o.push(`${c.name}: ${c.notes.trim()}`),t({elementCatalog:d,graphNodes:n().graphNodes.map(p=>p.id===l.nodeId?{...p,data:{...p.data,resolvedRevision:u,missing:!1}}:p)});for(const p of pc(c))try{const m=await np(cc(p));r.includes(m)||r.push(m)}catch{}}return{ok:!0,referenceDataUrls:r,notes:o,elementIds:a,revisions:i}}function Yp(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 Xp(e,t,n,r,o){if(bt.has(e))return null;bt.add(e);const a=r().graphNodes,i=De(a,r().graphEdges);i.some((q,C)=>q!==a[C])&&n({graphNodes:i});const l=i.find(q=>q.id===e);if(!l)return bt.delete(e),null;const c=gc(r().graphNodes,r().graphEdges,[e]),d=await Jp(c,n,r);if(d.ok===!1)return r().showToast(M("node.elementMissing",{name:d.name}),!0),bt.delete(e),null;const{prompt:u,parentServerNodeId:p}=l.data;if(!u.trim())return r().showToast(M("toast.promptRequired"),!0),bt.delete(e),null;const m=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:m.provider,b=ac({provider:h,serverLimit:m.referenceLimit,videoModelSelected:!!m.videoModelSelected,mcpProvider:m.mcpProvider??null}),I=Yp(l.data.referenceImages??[],d.referenceDataUrls,b),x=typeof l.data.model=="string"&&l.data.model?l.data.model:m.imageModel,y=t.sizeOverride??(typeof l.data.size=="string"&&l.data.size?l.data.size:m.getResolvedSize()),g=t.parentServerNodeIdOverride!==void 0?t.parentServerNodeIdOverride:p,_=(l.data.extraParentServerNodeIds??[]).filter(q=>q&&q!==g);if(Kl(i,r().graphEdges,e).length>0&&!g)return r().showToast(M("node.parentImageRequired"),!0),bt.delete(e),null;const S=m.activeSessionId,N=Date.now(),P=Math.random().toString(36).slice(2,6),L=`fn_${e}_${N}_${P}`,U=new AbortController;rn(L,U);const j=[...m.inFlight,{id:L,prompt:u,startedAt:N,kind:"node",sessionId:S,clientNodeId:e}];o(j),n({graphNodes:r().graphNodes.map(q=>q.id===e?{...q,data:{...q.data,status:"pending",pendingRequestId:L,recoveryRequestId:L,pendingPhase:"queued",pendingStartedAt:N,partialImageUrl:null,error:void 0,errorInfo:null,size:y}}:q),activeGenerations:m.activeGenerations+1,inFlight:j}),r().startInFlightPolling();let z=!0;try{const q=await ju({parentNodeId:g,..._.length?{extraParentNodeIds:_}:{},prompt:u,quality:At(h,m.imageToolModel,m.quality),size:y,format:m.format,moderation:m.moderation,provider:h,model:x,...h==="api"&&m.imageToolModel?{imageToolModel:m.imageToolModel}:{},reasoningEffort:m.reasoningEffort,storyboard:m.storyboardActive||void 0,requestId:L,sessionId:S,clientNodeId:e,contextMode:"parent-plus-refs",searchMode:m.webSearchEnabled?"on":"off",webSearchEnabled:m.webSearchEnabled,...Ms(m,{provider:h,imageModel:x}),...I.length?{references:I.map(js)}:{},...d.elementIds.length?{elementIds:d.elementIds,elementRevisions:d.revisions,elementNotes:d.notes}:{}},{onPartial:C=>{r().activeSessionId===S&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"pending",partialImageUrl:C.image,pendingPhase:"partial"}}:k)})},onPhase:C=>{r().activeSessionId===S&&C.phase&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,pendingPhase:C.phase??k.data.pendingPhase}}:k)})}},{signal:U.signal});return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(C=>{if(C.id!==e)return C;const k={...C.data};return delete k.partialImageUrl,{...C,data:{...k,serverNodeId:q.nodeId,imageUrl:q.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:q.elapsed,reasoningEffort:q.reasoningEffort,webSearchCalls:q.webSearchCalls,model:q.model??null,imageToolModel:q.imageToolModel??null,size:q.size??null,errorInfo:null}}})}),z=!0,t.suppressToast||r().showToast(M("toast.nodeCreated",{id:q.nodeId.slice(0,8),elapsed:q.elapsed}))),q.nodeId}catch(q){if(tn(q))return r().activeSessionId===S&&(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)}),z=!0),null;const C=q instanceof Error?q.message:M("toast.nodeCreateFailed");return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:C,errorInfo:sc(q)}}:k)}),z=!0,He(q,r())),null}finally{bt.delete(e);const q=r().inFlight.filter(C=>C.id!==L);o(q),on(L),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:q}),r().activeSessionId===S&&z&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function Zp(e,t,n){if(n().nodeBatchRunning)return;const r=Ol(n().graphNodes).filter(x=>n().graphNodes.find(y=>y.id===x)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(M("nodeBatch.noneSelected"),!0);return}const o=Vl(n().graphNodes,n().graphEdges),a=Ep(n().graphNodes,o,r);if(a.length>0){n().showToast(M("nodeBatch.parentRequired",{count:a.length}),!0);return}const i=Np(n().graphNodes,n().graphEdges,r);if(i.length>0){n().showToast(M("nodeBatch.cycleBlocked",{count:i.length}),!0);return}const l=Sp(n().graphNodes,o,r),c=new Set(r),d=l.filter(x=>{if(e==="regenerate-all")return!0;const y=n().graphNodes.find(g=>g.id===x);return y?!Ip(y):!1});if(d.length===0){n().showToast(M("nodeBatch.nothingToRun"));return}const p=gc(n().graphNodes,n().graphEdges,d).find(x=>x.missing);if(p){n().showToast(M("node.elementMissing",{name:p.name}),!0);return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});let m=0,h=0,b=0;const I=new Set;try{for(const x of d){if(n().nodeBatchStopping)break;if(I.has(x)){b+=1;continue}const y=De(n().graphNodes,n().graphEdges);y.some((N,P)=>N!==n().graphNodes[P])&&t({graphNodes:y});const g=y.find(N=>N.id===x)?.data.parentServerNodeId??null;if(!(n().videoModelSelected?await n().runVideoGenerate(x).then(()=>n().graphNodes.find(P=>P.id===x)?.data.serverNodeId??null):await n().runGenerateNodeInPlace(x,{parentServerNodeIdOverride:g,suppressToast:!0}))){h+=1;for(const N of _p(o,x))I.add(N);continue}m+=1;const w=new Set(wp(o,c)),S=n().graphNodes.map(N=>w.has(N.id)?{...N,data:{...N.data,status:"stale",error:M("nodeBatch.staleBecauseParentChanged")}}:N);t({graphNodes:De(S,n().graphEdges)})}h>0?n().showToast(M("nodeBatch.partialFinished",{done:m,failed:h,skipped:b,total:d.length}),!0):n().showToast(M("nodeBatch.finished",{done:m,total:d.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function Jo(e){return Array.isArray(e.images)}function Qp(e,t){return e.modes.includes("both")||e.modes.includes(t)}function eo(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||!Qp(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 ef=[{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"]}],tf=[{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"]}],nf=[{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"]}],yc=[...ef,...tf,...nf];function vc(e){return yc.find(t=>t.id===e)}function to(){return[...yc]}function bc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function xc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function rf(e,t,n){const r=n();if(r.uiMode!=="classic")return;const o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=eo({catalog:to(),presetIds:r.selectedPresetIds,provider:xc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Es(r.insertedPrompts),d=e??r.getResolvedSize(),u=`mm_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;rn(u,p);const m=Date.now(),h=m,b=In(r.multimodeMaxImages),I=[...r.inFlight,{id:u,prompt:i,startedAt:m,kind:"multimode",composerPrompt:l,composerInsertedPrompts:c}],x={sequenceId:u,requestId:u,requested:b,returned:0,images:[],partials:[],status:"pending"};Ae(I),t({activeGenerations:r.activeGenerations+1,inFlight:I,activeFlightIds:new Set([...r.activeFlightIds,u]),multimodeSequences:{...r.multimodeSequences,[u]:x},multimodePreviewFlightId:u}),n().startInFlightPolling();try{const y={prompt:i,quality:r.quality,size:d,format:r.format,moderation:r.moderation,provider:r.provider,maxImages:b,model:Zi(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:bc(r),...Ms(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(js)}:{}},g=await ou(y,{onPartial:S=>{t(N=>{const P=N.multimodeSequences[u];return P?{multimodeSequences:{...N.multimodeSequences,[u]:{...P,partials:[...P.partials,{image:S.image,index:S.index??null}].slice(-b)}}}:{}})},onImage:S=>{t(N=>{const P=N.multimodeSequences[u];if(!P)return{};const L=Fa(P.images,[S]);return L.length===P.images.length?{}:{multimodeSequences:{...N.multimodeSequences,[u]:{...P,sequenceId:S.sequenceId??P.sequenceId,returned:L.length,images:L,status:"partial"}}}})}},{signal:p.signal}),_=g.images.map(S=>({...S,prompt:i,elapsed:Number.parseFloat(g.elapsed),provider:g.provider,usage:g.usage,requestId:S.requestId??g.requestId??u,composerPrompt:l,composerInsertedPrompts:c,quality:g.quality,size:g.size,model:g.model??null,imageToolModel:g.imageToolModel??null}));for(const S of _)await gt(S,t,n,{autoSelectStartedAt:h});t(S=>({multimodeSequences:{...S.multimodeSequences,[u]:(()=>{const N=S.multimodeSequences[u],P=Fa(N?.images??[],_);return{sequenceId:g.sequenceId,requestId:u,requested:g.requested,returned:P.length,images:P,partials:[],status:g.status,elapsed:g.elapsed}})()}}));const w=g.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(M(w,{returned:g.returned,requested:g.requested,elapsed:g.elapsed}))}catch(y){y.name==="AbortError"||tn(y)?t(g=>{const _=g.multimodeSequences[u];return _?{multimodeSequences:{...g.multimodeSequences,[u]:{..._,status:"canceled"}}}:{}}):(t(g=>{const _=g.multimodeSequences[u];return _?{multimodeSequences:{...g.multimodeSequences,[u]:{..._,status:"error",error:y.message}}}:{}}),He(y,n()))}finally{const y=n().inFlight.filter(g=>g.id!==u);Ae(y),on(u),t(g=>{const _=new Set(g.activeFlightIds);_.delete(u);let w=g.multimodePreviewFlightId;const S=g.multimodeSequences[u]?.status,N=S==="complete"||S==="partial";if(w===u&&!N){const L=[..._];w=L.length>0?L[L.length-1]:null}const P={...g.multimodeSequences};return N&&w!==u&&delete P[u],{activeGenerations:Math.max(0,g.activeGenerations-1),inFlight:y,activeFlightIds:_,multimodePreviewFlightId:w,multimodeSequences:P}})}}async function of(e,t,n){const r=n(),o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=eo({catalog:to(),presetIds:r.selectedPresetIds,provider:xc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Es(r.insertedPrompts),d=e??r.getResolvedSize(),u=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;rn(u,p);const m=Date.now(),h=m,b=[...r.inFlight,{id:u,prompt:i,startedAt:m,composerPrompt:l,composerInsertedPrompts:c}];Ae(b),t({activeGenerations:r.activeGenerations+1,inFlight:b}),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:Zi(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,storyboard:r.storyboardActive||void 0,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:bc(r),...Ms(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(js)}:{}},x=await Gi(I,{signal:p.signal});if(Jo(x)&&x.images.length>1){for(const y of x.images){const g={image:y.image,filename:y.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:y.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:y.createdAt??Date.now()};await gt(g,t,n,{autoSelectStartedAt:h})}n().showToast(M("toast.generatedBatch",{count:x.images.length,elapsed:x.elapsed}))}else{let y;if(Jo(x)){const g=x.images[0];y={image:g.image,filename:g.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:g.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:g.createdAt??Date.now()}}else y={image:x.image,filename:x.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:x.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:x.createdAt??Date.now()};await gt(y,t,n,{autoSelectStartedAt:h}),n().showToast(M("toast.generatedSingle",{elapsed:x.elapsed}))}}catch(I){!(I instanceof Error&&I.name==="AbortError")&&!tn(I)&&He(I,n())}finally{const I=n().inFlight.filter(x=>x.id!==u);Ae(I),on(u),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:I})}}function sf(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 af(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,o=await Ne(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 lf(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(!sf(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 cf=lf({fetchGeneratedFrame:af,extractFromElement:(e,t,n)=>t==="last"?nn(e,n):t==="first"?Jl(e,n):Yl(e,n)}),Ar="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 df(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 Ic(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:df(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 _n(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 uf(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 Sc(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 wc(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"&&Pt(e.provider)&&ds[e.provider].multimode.supported?"multimode":"image"}function mf(e){return e.mcpProvider?e.multimode:wc(e)==="multimode"}async function pf(e,t){const n=t();if(!Rn(n.prompt,n.insertedPrompts)||Ds(t))return;const o=wc(n);if(o==="video")return t().runVideoGenerate();const a=o==="multimode",i=Xr(n,{kind:a?"multimode":"classic"});if(i){e({customSizeConfirm:i});return}if(a){await t().generateMultimode();return}await t().runGenerate()}function ff(e,t){const n=t().multimodePreviewFlightId;n&&(ic(n),t().cancelInFlightJob(n),e(r=>{const o=r.multimodeSequences[n];return o?{multimodeSequences:{...r.multimodeSequences,[n]:{...o,status:"canceled"}}}:{}}))}function Ds(e){return(e().missingElementIds??[]).length>0?(e().showToast(M("toast.missingElements"),!0),!0):!1}async function hf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Ds(t))return;const r=Dm(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 gf(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=Xr(n(),{kind:"node",clientId:e});if(a){t({customSizeConfirm:a});return}await n().runGenerateNode(e)}async function yf(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=Xr(n(),{kind:"node-in-place",clientId:e});if(o){t({customSizeConfirm:o});return}await n().runGenerateNodeInPlace(e)}async function vf(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=Xr(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 bf(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 _c(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ec(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 Nc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function xf(e,t,n){const r=e?n().graphNodes.find(w=>w.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(Ar,!0);return}const l=n(),c=eo({catalog:to(),presetIds:l.selectedPresetIds,provider:Nc(l.provider),mode:"video"}),d=c.promptFragment?`${c.promptFragment} ${i}`:i;let u,p,m=r?r.data.videoContinuity??null:n().videoContinuityLineage,h;if(r&&o.length===0&&r.data.parentServerNodeId){const w=n().graphNodes.find(S=>S.data.serverNodeId===r.data.parentServerNodeId);if(w?.data.imageUrl)if(Ze(w.data.imageUrl))try{const S=w.data.imageUrl.replace(/^\/generated\//,"");p=(await cf.extractFrame({kind:"generated",filename:S},"last")).dataUrl,m=w.data.videoContinuity??Ic({filename:S,prompt:w.data.prompt,userPrompt:w.data.prompt,revisedPrompt:w.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=S}catch{n().showToast(M("video.continuationFallbackT2V"),!0)}else u=w.data.imageUrl.replace(/^\/generated\//,"")}const b=Date.now(),I=b,x=`vid_${b}_${Math.random().toString(36).slice(2,6)}`,y=new AbortController;rn(x,y);const g=n().activeSessionId,_=[...n().inFlight,{id:x,prompt:d,startedAt:b,kind:"video",sessionId:g,clientNodeId:e??null}];Ae(_),r&&t({graphNodes:n().graphNodes.map(w=>w.id===e?{...w,data:{...w.data,status:"pending",pendingRequestId:x,pendingPhase:"queued",pendingStartedAt:b,partialImageUrl:null,error:void 0,errorInfo:null}}:w)}),t({inFlight:_,activeGenerations:_.length,videoProgress:0}),n().startInFlightPolling();try{const w=n().providerUrlReference,S={prompt:d,requestId:x,...Ec(n()),referenceImages:o.length>0&&!a?o:void 0,sourceImage:a?o[0]:o.length>0?void 0:p,sourceFilename:o.length===0&&!p?u:void 0,continueFromVideo:h,continuityLineage:m,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:_c(n()),sessionId:g,clientNodeId:e??null,...w?{providerUrl:w}:{}},N=await ss(S,{onPlanning:()=>t({inFlight:n().inFlight.map(P=>P.id===x?{...P,phase:"planning"}:P)}),onSubmitted:()=>t({inFlight:n().inFlight.map(P=>P.id===x?{...P,phase:"streaming"}:P)}),onProgress:({progress:P})=>t({videoProgress:P??null})},{signal:y.signal});if(r&&N&&n().activeSessionId===g&&(t({graphNodes:n().graphNodes.map(P=>P.id===e?{...P,data:{...P.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??m,video:{...N.video??{},...N.videoSeries?.topic?{topic:N.videoSeries.topic}:{}}}}:P)}),n().scheduleGraphSave(),n().flushGraphSave("video-node-complete")),N){const P={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??x,createdAt:Date.now(),sessionId:g};await gt(P,t,n,{autoSelectStartedAt:I})}}catch(w){if(tn(w))r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(S=>S.id===e?{...S,data:{...S.data,status:S.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0,errorInfo:null}}:S)});else{const S=ot(w).code==="JOB_TRACKING_TIMEOUT",N=S?He(w,n()).message:w instanceof Error?w.message:"Video generation failed",P=S?{...sc(w),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:P}}:L)}),S||n().showToast(N,!0)}}finally{const w=n().inFlight.filter(S=>S.id!==x);Ae(w),on(x),t({inFlight:w,activeGenerations:w.length,videoProgress:null}),n().startInFlightPolling()}}async function If(e,t,n,r){const o=t?.trim();if(!o)throw r().showToast(Ar,!0),new Error(Ar);if(Ds(r))return!1;const a=r(),i=eo({catalog:to(),presetIds:a.selectedPresetIds,provider:Nc(a.provider),mode:"video"}),l=i.promptFragment?`${i.promptFragment} ${o}`:o,c=Date.now(),d=c,u=`vid_${c}_${Math.random().toString(36).slice(2,6)}`,p=new AbortController;rn(u,p);const m=[...r().inFlight,{id:u,prompt:l,startedAt:c,kind:"video",sessionId:r().activeSessionId,clientNodeId:null}];Ae(m),n({inFlight:m,activeGenerations:m.length,videoProgress:0}),r().startInFlightPolling();try{const h={prompt:l,presetIds:i.appliedPresetIds,elementIds:_c(r()),requestId:u,...Ec(r()),mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},b=await ss(h,{onPlanning:()=>n({inFlight:r().inFlight.map(x=>x.id===u?{...x,phase:"planning"}:x)}),onSubmitted:()=>n({inFlight:r().inFlight.map(x=>x.id===u?{...x,phase:"streaming"}:x)}),onProgress:({progress:x})=>n({videoProgress:x??null})},{signal:p.signal}),I={image:b.url,filename:b.filename,url:b.url,mediaType:"video",prompt:l,elapsed:b.elapsed,video:b.video??{},videoSeries:b.videoSeries??null,videoContinuity:b.videoContinuity??null,revisedPrompt:b.revisedPrompt??null,requestId:b.requestId??u,createdAt:Date.now(),sessionId:r().activeSessionId};await gt(I,n,r,{autoSelectStartedAt:d})}catch(h){return tn(h)||(ot(h).code==="JOB_TRACKING_TIMEOUT"?He(h,r()):r().showToast(h instanceof Error?h.message:"Video generation failed",!0)),!1}finally{const h=r().inFlight.filter(b=>b.id!==u);Ae(h),on(u),n({inFlight:h,activeGenerations:h.length,videoProgress:null}),r().startInFlightPolling()}return!0}function Yo(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 En(e){const t=new Map([...zl({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,Yo(r)])),memory:new Map(e.inFlight.map(n=>[n.id,n])),scopes:Jm({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function Gs(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function kc(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&&wn(r,e.scopes)}).map(([n])=>n))}function Sf(e,t,n){const r=Tr(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 Yo(o)===Yo(e)?e:o}function wf(e,t,n,r,o){if(t&&(o.mode==="reconcile"||!n))return[wn(Tr(t),r.scopes)?Sf(e,t,o.mode):e];if(n)return wn(Tr(n),r.scopes)?(n.status==="error"&&o.terminalErrors.push(Ym(n)),[]):[e];const a=o.now-e.startedAt;return(o.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function Cc(e,t,n,r){if(!Gs(e,t))return null;const o=En(t),a=kc(e,o),i=new Map(n.jobs.map(p=>[p.requestId,p])),l=new Map(n.terminalJobs.map(p=>[p.requestId,p])),c=[],d=[...o.local.values()].flatMap(p=>a.has(p.id)?wf(p,i.get(p.id),l.get(p.id),e,{...r,terminalErrors:c}):[p]),u=new Set;for(const[p,m]of i){const h=Tr(m);wn(h,e.scopes)&&(u.add(p),!((h.kind??"classic")==="classic"&&e.uiMode==="node")&&(h.kind==="node"&&(e.uiMode!=="node"||(h.sessionId??null)!==e.activeSessionId)||!e.local.has(p)&&!o.local.has(p)&&d.push(h)))}return{inFlight:d,terminalErrors:c,eligibleIds:a,serverActiveIds:u}}let Nn=0;function kn(){if(Nn+=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,kn)}function _f(e,t,n){const r=n();Ae(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)He(o,n())}function Ef(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:Yr([...o,...n.history],Math.max($e,n.history.length+o.length)),currentImage:n.currentImage??o[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+o.length)}):{}})}function Nf(e,t,n){const r=En(n()),o=kc(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<Dl);i.length!==r.local.size&&(Ae(i),t({inFlight:i,activeGenerations:i.length}))}async function kf(e,t,n,r,o){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await Xt({limit:$e,since:a});if(!o()||!Gs(e,r()))return;Ef(i.map(On),n),t&&Nf(t,n,r)}catch{}}function Cf(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function jf(e,t,n){if(ue()){kn();return}const r=fe(),o=Nn,a=()=>!ue()&&r===fe()&&o===Nn,i=En(t());let l=null;if(!Cf(t(),n))try{const c=await Gl(i.scopes);if(!a())return;const d=Cc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;_f(d,e,t),l={snapshot:En(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&Gs(i,t())&&await kf(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&kn()}function Tf(e,t){if(typeof window>"u"||ue())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(_t,kn),n.__ima2InflightTimer=window.setInterval(()=>jf(e,t,n),1500))}async function Pf(e,t){if(ue())return;const n=fe(),r=Nn;try{const o=En(t()),a=await Gl(o.scopes);if(ue()||n!==fe()||r!==Nn)return;const i=Cc(o,t(),a,{mode:"reconcile",now:Date.now()});if(!i)return;Ae(i.inFlight),e({inFlight:i.inFlight,activeGenerations:i.inFlight.length});for(const l of i.terminalErrors)He(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const Nt=()=>"nc_"+Math.random().toString(36).slice(2,10);function qa(e,t){return{x:e*360,y:t*320}}const Af=360,jc=320;function Rf(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 zs(e){const t=e.filter(r=>!r.data.parentServerNodeId);if(t.length===0)return qa(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:qa(0,0).x,y:n+jc}}function Tc(e,t,n){const r=Rf(e.id,t,n),o=e.position.x+Af;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+jc}}const Cn="source-right",jn="target-left";function no(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function Mf(e,t){return e&&e.startsWith(`${t}-`)?e:null}function Lf(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 Of(e,t){const n=Nt();t().recordGraphHistory("add-root");const r={id:n,type:"imageNode",position:zs(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 Ff(e,t,n){const r=Nt();n().recordGraphHistory("add-root-from-history");const o={id:r,type:"imageNode",position:zs(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 Df(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:Tc(r,n().graphNodes,n().graphEdges),data:{clientId:o,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:Ze(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:no(e,o,Cn,jn),source:e,target:o,sourceHandle:Cn,targetHandle:jn};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&Ze(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 nn(l);t({graphNodes:n().graphNodes.map(d=>d.id===o?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return o}function Gf(e,t,n){const r=n().graphNodes.find(u=>u.id===e);if(!r)return e;n().recordGraphHistory("add-sibling");const o=n().graphEdges.find(u=>u.target===e);if(!o){const u=Nt(),p={id:u,type:"imageNode",position:zs(n().graphNodes),data:{clientId:u,serverNodeId:null,parentServerNodeId:null,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...n().graphNodes,p]}),n().scheduleGraphSave(),u}const a=o.source,i=n().graphNodes.find(u=>u.id===a);if(!i)return e;const l=Nt(),c={id:l,type:"imageNode",position:Tc(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:no(a,l,Cn,jn),source:a,target:l,sourceHandle:Cn,targetHandle:jn};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function zf(e,t,n,r,o){const a=o().graphNodes.find(p=>p.id===e);if(!a)return e;o().recordGraphHistory("add-child-at");const i=Nt(),l=Mf(n,"source")??Cn,c=Lf(l)??jn,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}},u={id:no(e,i,l,c),source:e,target:i,sourceHandle:l,targetHandle:c};return r({graphNodes:[...o().graphNodes,d],graphEdges:[...o().graphEdges,u]}),o().scheduleGraphSave(),i}function qf(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 $f(e,t,n,r){n({graphNodes:r().graphNodes.map(o=>o.id===e?{...o,data:{...o.data,prompt:t}}:o)}),r().scheduleGraphSave()}function Uf(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&&Te(o),As(n().activeSessionId,e);const a=n().graphNodes.filter(l=>l.id!==e),i=n().graphEdges.filter(l=>l.source!==e&&l.target!==e);t({graphNodes:De(a,i),graphEdges:i}),n().scheduleGraphSave()}function Hf(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)As(n().activeSessionId,i);for(const i of n().graphNodes)r.has(i.id)&&i.data?.pendingRequestId&&Te(i.data.pendingRequestId);const o=n().graphNodes.filter(i=>!r.has(i.id)),a=n().graphEdges.filter(i=>!r.has(i.source)&&!r.has(i.target));t({graphNodes:De(o,a),graphEdges:a}),n().scheduleGraphSave()}function Vf(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(p=>p.target===c.id),u=d?n().graphNodes.find(p=>p.id===d.source):null;return{...c,data:{...c.data,parentServerNodeId:u?.data.serverNodeId??null}}});t({graphNodes:De(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(M("edge.disconnected"))}function Kf(e,t,n,r,o,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(sp(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:no(e,t,n,r),source:e,target:t,sourceHandle:n,targetHandle:r}];o({graphNodes:De(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function Bf(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(jr),u=c.filter(h=>!jr(h)),m=(await Promise.all(u.map(async h=>{try{return await ks(h,{preserveTransparency:Fl(h)})}catch(b){return console.warn("[addNodeReferences] compress failed",b),null}}))).filter(h=>!!h);if(m.length>0){const h=r().activeSessionId;n({graphNodes:r().graphNodes.map(b=>{if(b.id!==e)return b;const I=[...b.data.referenceImages??[],...m].slice(0,r().referenceLimit);return Zr(h,e,I),{...b,data:{...b.data,referenceImages:I}}})}),r().scheduleGraphSave()}d.length>0&&r().showToast(M("toast.refHeicUnsupported"),!0),u.length-m.length>0&&r().showToast(M("toast.refTooLarge"),!0),t.length>l&&r().showToast(M("toast.refLimitExceeded"),!0)}function Pc(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 Zr(r().activeSessionId,e,l),{...a,data:{...a.data,referenceImages:l}}})}),r().scheduleGraphSave())}async function Wf(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=Ze(t)||Ze(n)?await nn(t):await Fn(t,n||"node-reference.png")}catch{o().showToast(M("toast.currentImageLoadFailed"),!0);return}Pc(e,i,r,o)}function Jf(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 Zr(r().activeSessionId,e,a),{...o,data:{...o.data,referenceImages:a}}})}),r().scheduleGraphSave()}function Yf(e,t,n){As(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const $a=10;function Ac(e,t){return t?t.filename&&e.filename===t.filename?!0:e.image===t.image:!1}function Xf(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(t=>!!t)}function Mt(e){return e.filter(t=>!t.canvasVersion)}function rt(e,t){if(!t)return null;const n=Mt(e);if(!t.canvasVersion)return n.find(a=>Ac(a,t))??null;const r=Xf(t);return n.find(a=>a.filename?r.includes(a.filename):!1)??null}function Zf(e,t){const n=Mt(e),r=rt(e,t);return n.findIndex(o=>Ac(o,r))}function Qf(e,t,n){const r=Mt(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=Zf(e,t);if(o<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-$a:$a,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 Rc(e,t){const n=Mt(e),r=n.findIndex(o=>o.filename===t);return r<0?null:n[r+1]??n[r-1]??null}function Pe(e){return e.filename||e.image}function vn(e){return!e.canvasVersion}function Ir(e){const t=new Set;return e.filter(n=>{const r=Pe(n);return t.has(r)?!1:(t.add(r),!0)})}const Mc=72,Ua=10;function Lc(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 eh(e){return e<=1?1:e===2?2:4}function Oc(e){const t=new Set,n=new Map,r=[];for(const o of e){if(!vn(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=Pe(o);t.has(a)||(t.add(a),r.push({type:"image",key:a,item:o}))}for(const o of n.values())o.items.sort(Lc);return r}function Fc(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Pe(e):null}function fo(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function th(e,t,n,r,o=Mc){const a=Oc(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 fo(i);if(n==="last")return fo(l);const c=Fc(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const u=n==="pagePrevious"?-Ua:n==="pageNext"?Ua:n==="previous"?-1:1,p=Math.max(0,Math.min(a.length-1,d+u));if(p===d)return null;const m=a[p];return m?fo(m):null}const Dc={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},nh={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},rh={default:Dc,"prompt-studio":nh};function Gn(e,t){return rh[e]??Dc}function oh(e,t){return Gn(e).promptBuilderSurface!=="off"}const sh="history:";function Gc(e,t,n){if(!t||n||!t.startsWith(sh)||!(t in e))return e;const r={...e};return delete r[t],r}function ah(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 Xt({limit:$e,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 lh(e,t){try{const n=await Xt({limit:$e,favoritesOnly:!0}),r=n.items.map(On);e(o=>{const a=Hl(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 ch(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await Xt({limit:$e,cursor:n,favoritesOnly:!0}),o=r.items.map(On);e(a=>{const i=Hl(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 dh(e,t,n){const r=Date.now(),o=n().history,a=e.canvasVersion?rt(o,e)??Mt(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,u=i&&a&&!d?Cm(a):{},p=n().multimodePreviewFlightId,m=p?n().multimodeSequences[p]:null,h=m&&a&&m.images.some(b=>b.filename===a.filename);t(b=>({currentImage:a,lastHistorySelectedAt:r,unseenGeneratedCount:0,multimodePreviewFlightId:h?p:null,multimodeSequences:Gc(b.multimodeSequences,p,!!h),...u}))}function uh(e,t,n){const r=Date.now(),o=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(Lc);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:{...Gc(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:o,partials:[],status:c}}}))}function mh(e,t,n){const r=n(),o=Gn(r.workspaceProfile);if(r.uiMode==="classic"&&o.multimodeHistoryGrouping==="sequence"){const i=th(r.history,r.currentImage,e,ah(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=Qf(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function ph(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?Rc(n().history,o):a;try{await zi(o),t(d=>{const u=Zm(d.multimodeSequences,o),p=d.multimodePreviewFlightId&&!u[d.multimodePreviewFlightId]?null:d.multimodePreviewFlightId;return{history:d.history.filter(m=>m.filename!==o),currentImage:c,multimodePreviewFlightId:p,multimodeSequences:u,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 fh(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 zi(d);t(d=>{const u={...d.multimodeSequences};return delete u[`history:${e}`],delete u[e],{history:d.history.filter(p=>!p.filename||!a.has(p.filename)),currentImage:l?null:d.currentImage,multimodePreviewFlightId:c?null:d.multimodePreviewFlightId,multimodeSequences:u,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 hh(e,t){const n=t().trashPending;if(n)try{await uu(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 gh(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?Rc(n().history,o):i;try{await du(o),t(u=>({history:u.history.filter(p=>p.filename!==o),currentImage:d,trashPending:u.trashPending?.filename===o?null:u.trashPending})),c&&st(d?.filename??null),n().showToast(M("gallery.permanentDeleted",{filename:o}))}catch(u){console.error("[history] permanent delete failed",u),n().showToast(M("gallery.deleteFailed"),!0)}}function yh(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 vh(e,t,n){const r=n(),o={...e,createdAt:e.createdAt||Date.now()},a=$l(r.history,o),i=Ul(o,a),l=ql(r.history,i);t({history:Yr([i,...l],r.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(r.loadedHistoryRetainLimit,Math.min(r.history.length+1,r.loadedHistoryRetainLimit+1))})}async function bh(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 su(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 xh(e,t){(async()=>{try{const n=await Xt({limit:$e}),r=n.items.map(On);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:$e}),r.length>0){const o=Cl(),a=o?r.find(c=>c.filename===o):null,i=Mt(r),l=(a?rt(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max($e,r.length)}),l?.filename!==o&&st(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function zc(e,t){try{const{sessions:n}=await pu();if(e({sessions:n}),!t().activeSessionId){const o=Fm(),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 zc(e,t)}}async function Ih(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 qi(e),{graphNodes:o,graphEdges:a,graphVersion:i}=Xl(r);t({activeSessionId:e,activeSessionGraphVersion:i,graphNodes:o,graphEdges:a,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),Ns(e),await n().reconcileGraphPending().catch(()=>{})}catch(r){console.warn("[sessions] switch failed:",r),t({sessionLoading:!1}),n().showToast(M("toast.sessionLoadFailed"),!0)}}}async function Sh(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 Fi({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 u=d.data?.pendingRequestId;if(!u||d.data.status!=="pending"&&d.data.status!=="reconciling")return d;if(a.has(u)){const h=a.get(u)??null;return{...d,data:{...d.data,status:"reconciling",pendingPhase:h}}}const p=d.data.pendingStartedAt??0;if(p&&i-p<l)return{...d,data:{...d.data,status:"reconciling"}};const m=!!d.data.imageUrl||!!d.data.serverNodeId;return{...d,data:{...d.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:m?"ready":"stale",error:m?void 0:M("session.assetAbortedError")}}});e({graphNodes:c})}await nc(t,e).catch(()=>{})}async function wh(e,t,n){e==null&&(e=M("session.untitled"));try{const{session:r}=await fu(e);t({sessions:[r,...n().sessions],activeSessionId:r.id,activeSessionGraphVersion:r.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),Ns(r.id)}catch(r){console.warn("[sessions] create failed:",r),n().showToast(M("toast.sessionCreateFailed"),!0)}}async function _h(e,t,n){const r=n().activeSessionId;if(r)try{await hu(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 Eh(e,t,n){try{await gu(e);const r=n().sessions.filter(o=>o.id!==e);t({sessions:r}),n().activeSessionId===e&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),Ns(null),r.length>0?await n().switchSession(r[0].id):await n().createAndSwitchSession(M("session.firstGraph")))}catch{n().showToast(M("toast.sessionDeleteFailed"),!0)}}function Nh(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),n.imageToolModel=e.provider==="api"&&us(t.imageToolModel)?t.imageToolModel:null,n.quality=At(e.provider,n.imageToolModel,Tl(t.quality)?t.quality:e.quality),Pl(t.format)&&(n.format=t.format),Al(t.moderation)&&(n.moderation=t.moderation),(t.promptMode==="auto"||t.promptMode==="direct")&&(n.promptMode=t.promptMode),t.model&&Fu(t.model)&&(n.imageModel=t.model);const o=Gm(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 Fs(e,t)}function qs(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 qc(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function $s(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(!Ls(o,r))break;const u=dc(c,i),p=qc(d,u.tag);o.push(p),l.push(p),i.add(p.tag),a=Os(a,p.tag),c=u.nextAttachmentOrdinal}return l.length===0?{result:l}:{result:l,patch:{trayItems:o,nextAttachmentOrdinal:c,retiredTags:a,providerUrlReference:null}}})}function kh(e,t,n){return $s(e,t)}function ro(e,t,n,r){const o=qs(e);return o?$s([{dataUrl:e,mimeType:o,origin:t}],n)[0]??null:null}function Ch(e,t,n){ro(e,"gallery",t)}async function jh(e,t,n){const r=n().activeReferenceLimit(),o=Math.max(0,r-n().trayItems.length),a=e.slice(0,o),i=a.filter(jr),l=a.filter(p=>!jr(p)),d=(await Promise.all(l.map(async p=>{try{const m=await ks(p,{preserveTransparency:Fl(p)}),h=qs(m);return h?{dataUrl:m,mimeType:h,originalName:p.name,byteSize:p.size,origin:"file"}:null}catch(m){return console.warn("[addReferences] compress failed",m),null}}))).filter(p=>p!==null),u=$s(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>u.length)&&n().showToast(M("toast.refLimitExceeded"),!0)}async function Th(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let o="";try{o=await Ts(e);const a=await vu({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 Ph(e,t){const n=t().metadataRestore;if(!n)return;const r=Nh(t(),n.metadata);if(te({imageToolModel:r.imageToolModel,quality:r.quality}),r.imageModel&&Nl(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 Us(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function Hs(e,t){t.length!==e.length&&te({insertedPrompts:t})}function $c(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:Qr(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=Us(o),l.videoContinuityLineage=null)}return{result:void 0,patch:l}}),Hs(r,n().insertedPrompts)}function Ah(e,t,n){const r=Dn(n())[e];r&&$c(r.tokenId,t,n)}function Rh(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:Qr(r.retiredTags,o),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Us(r),providerUrlReference:null}}}),Hs(n,t().insertedPrompts)}function Mh(e,t){const n=t().insertedPrompts;zn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Us(r),providerUrlReference:null}})),Hs(n,t().insertedPrompts)}function Lh(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(!Ls(a,t))return{result:!1};const i=dc(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=qc(n,i.tag),c=Os(Qr(e.retiredTags,r),l.tag);return{result:!0,patch:{trayItems:[l,...a],nextAttachmentOrdinal:i.nextAttachmentOrdinal,retiredTags:c,canvasReferenceImage:n.dataUrl,providerUrlReference:null}}}async function Oh(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=qs(o);if(!a){n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!zn(t,(l,c)=>Lh(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 Uc(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Fh(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(Uc(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!ro(r,"gallery",e)){t().showToast(M("toast.refSlotFull"),!0);return}t().showToast(M("toast.addedCurrentAsRef"))}async function Dh(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(M("toast.refSlotFull"),!0);return}let r;try{r=await Fn(Uc(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!ro(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=Ml();o[e.provider]={...o[e.provider],...Ia(e)};const a={...o[t.provider],...Ia(t)};r&&delete a[r],o[t.provider]=a,Hm(o),Vm(t),n(i=>{const l=t.provider==="api"?i.imageToolModel:null,c=At(t.provider,l,i.quality);return te({imageToolModel:l,quality:c}),{...t,imageToolModel:l,quality:c}})}function Gh(e,t,n){const r=qn(n);if(e===r.provider)return;const o=Pt(e)?Ml()[e]:void 0,a=Ju(r,e,o);$n(r,a,t)}function zh(e,t,n){const r=qn(n),o=lt({provider:Wu(r.provider,e),imageModel:e,videoModelSelected:!1});$n(r,o,t)}function qh(e,t,n){const r=qn(n),o=lt({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:Rt(e)||tt});$n(r,o,t)}function $h(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 Uh(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 Hh(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 Vh(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&&Hh(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const Kh=1e4;let Tn=[];async function Vs(e){const t=await $("/api/mcp/providers",{signal:e});return Tn=Array.isArray(t.providers)?t.providers:[],Tn}function Bh(e){return Mi("/api/mcp/providers",e)}function Wh(e,t){return Mi(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function Jh(){return Tn}async function Ow(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 Fw(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function Dw(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function Hc(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 Yh(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 Xh(e,t){let n=!1;const r=()=>n?!1:(n=!0,o(),a(),!0),o=jt(e,null,(i,l)=>{if(i==="done"){const c=Yh(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?.(Qe(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Yt(()=>{if(!r())return;const i=new Error("MCP generation timed out");i.code="MCP_STREAM_TIMEOUT",t.onError?.(i)});return r}async function Zh(e,t){const n=e.requestId??`mcp_ui_${Date.now()}`,r=Xh(n,t);try{const a=(await Vs()).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 $("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(o){throw r(),o}}function Vc(){const[e,t]=v.useState(()=>[...Tn]),[n,r]=v.useState(Tn.length===0),[o,a]=v.useState(null),i=v.useCallback(async()=>{try{const l=await Vs();t([...l]),a(null)}catch(l){a(l instanceof Error?l:new Error(String(l)))}finally{r(!1)}},[]);return v.useEffect(()=>{i();const l=window.setInterval(()=>{i()},Kh);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:o,refresh:i}}let Rr=null;function Kc(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 Qh(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 eg(e){try{await $(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function tg(e,t,n){let r=()=>{};const o=new Promise(i=>{r=i});if(await Zh(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(Kc(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 ng(e){const t=e();if((t.mcpProvider?Jh().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??Ue();if(xm(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 u=c?.name?_l(c.name):null;return d.filter(p=>typeof p=="string").map(p=>({filename:p,...u?{tag:u}:{}}))}).slice(0,3);let l=null;try{const c=await Qh(o);l=c.batchId;const d=Nm({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_${Date.now()}`);if(!d)return;await tg(d,e,!!l)}catch(c){e().showToast(Kc(c),!0)}finally{l&&await eg(l)}}function sn(e){Ln(null,null,"image"),te({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ue(),mcpCharacterElementId:null,...Rr?{generate:Rr}:{}})}function oo(e,t,n,r=null,o){if(!e){sn(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:Ue()}:{},count:1,multimode:!1,generate:()=>ng(n)})}function rg(e,t,n){Ln(n().mcpProvider??null,e,n().mcpMediaKind??"image"),te({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ue()})}function og(e,t,n,r,o){const a=Sm(o);let i=o?_s(o.inputRoles,r().mcpReferenceSelection):Ue();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 sg(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:Ue()}))}function ag(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 lg(e,t,n){const r=_s(n().mcpInputRoles??[],ws(e)),o=n().mcpReferenceSelection??Ue();wl(o,r)||t({mcpReferenceSelection:r})}function cg(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},o=Il(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??Ue(),i=_s(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!wm(r,o),d=!wl(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 dg(e,t){const n=Um();n.provider&&(oo(n.provider,e,t,n.model,n.kind),te({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function ug(e,t,n){sn(t),Gh(e,t,n)}function mg(e,t,n){n().provider!=="api"&&(e=null);const r=At(n().provider,e,n().quality);te({imageToolModel:e,quality:r}),t({imageToolModel:e,quality:r})}function pg(e,t,n){e=At(n().provider,n().imageToolModel,e),te({quality:e}),t({quality:e})}function fg(e,t){te({sizePreset:e}),t({sizePreset:e})}function hg(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 gg(e,t){te({grokAspectRatio:e}),t({grokAspectRatio:e})}function yg(e,t){te({grokResolution:e}),t({grokResolution:e})}function vg(e,t){te({format:e}),t({format:e})}function bg(e,t){te({moderation:e}),t({moderation:e})}function xg(e,t,n){sn(t),zh(e,t,n)}function Ig(e,t,n){sn(t),qh(e,t,n)}function Sg(e,t,n){sn(t),$h(e,t,n)}function wg(e,t,n){sn(t),Uh(e,t,n)}function _g(e){return Vh(e())}function Eg(e,t){Rm(e),t({reasoningEffort:e})}function Ng(e,t){Om(e),t({webSearchEnabled:e})}function kg(e,t){const n=In(e);te({count:n}),t({count:n})}function Cg(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 jg(e,t){const n=In(e);te({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function Tg(e,t){te({promptMode:e}),t({promptMode:e})}function Pg(e,t){te({prompt:e}),t({prompt:e})}function Ag(e,t){te({negativePrompt:e}),t({negativePrompt:e})}function Rg(e,t,n,r){const o={...r().naiOptionOverrides,[e]:t};kl(o),n({naiOptionOverrides:o})}function Mg(e){kl({}),e({naiOptionOverrides:{}})}function Lg(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 ho="starred";async function Og(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(ho))return"noop";if(r)return await t.updateAsset(r.id,{tags:[...new Set([...r.tags,ho])]}),"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:[ho],metadata:{origin:"star",mediaType:o}}),"created"}function Fg(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 Dg(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 Gg(e,t,n){n(r=>{const o=r.insertedPrompts.filter(m=>m.placement!=="after"),a=r.insertedPrompts.filter(m=>m.placement==="after"),i=[...o.map(m=>({kind:"prompt",prompt:m})),{kind:"main"},...a.map(m=>({kind:"prompt",prompt:m}))],l=i.findIndex(m=>m.kind==="prompt"&&m.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 u=i.findIndex(m=>m.kind==="main"),p=i.filter(m=>m.kind==="prompt").map((m,h)=>({...m.prompt,placement:h<u?"before":"after"}));return te({insertedPrompts:p}),{insertedPrompts:p}})}function zg(e){te({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function qg(e){e({promptLibraryLoading:!0});try{const t=await bu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function $g(e,t,n){try{await xu(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 Ug(e,t,n){try{await Iu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function Hg(e,t,n){try{await Su(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function Vg(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 wu({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 Kg(e,t,n){const r=e.filename;if(!r)return null;let o;try{o=(await iu(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 Og({...e,filename:r},{getAssets:as,createAsset:Ur,updateAsset:$i})!=="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 Bg(e,t,n){if(e){ic(e),t(r=>{const o=r.inFlight.map(a=>a.id===e?{...a,phase:"canceling"}:a);return Ae(o),{inFlight:o}});try{await Te(e),n().startInFlightPolling()}catch{n().showToast(M("toast.cancelFailed"),!0)}}}function Wg(e,t){const n=zl(),r=Cl(),o=Ll(),a=Jr(),i=en();e(l=>{const c=r?l.history.find(m=>m.filename===r)??null:null,d=c?rt(l.history,c):null,u=Mt(l.history)[0]??null,p=l.currentImage?.canvasVersion?rt(l.history,l.currentImage)??u:l.currentImage;return{inFlight:n,activeGenerations:n.length,...o,imageToolModel:o.provider==="api"?i.imageToolModel??null:null,quality:At(o.provider,i.imageToolModel,i.quality??l.quality),videoDuration:a.duration,videoResolution:a.resolution,videoAspectRatio:a.aspectRatio,currentImage:r&&p?.filename!==r?d??p:p}}),n.length>0&&t().startInFlightPolling()}function Jg(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):Yr([e,...n.history],n.loadedHistoryRetainLimit+1):n.history,loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,Math.min(n.history.length+1,n.loadedHistoryRetainLimit+1))}))}function Yg(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function Xg(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(el,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function Zg(e,t){try{localStorage.setItem(vs,e)}catch{}t({galleryScope:e})}function Qg(e,t){try{localStorage.setItem(il,e),localStorage.setItem(vs,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function ey(e,t){const n=e==="card-news"&&!dl?"classic":e;try{localStorage.setItem(tl,n)}catch{}t({uiMode:n})}function ty(e,t){try{localStorage.setItem(nl,e)}catch{}t({historyStripLayout:e})}function ny(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 ry(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 oy(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 sy(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 ay(e,t,n){t({graphNodes:De(e,n().graphEdges)}),n().scheduleGraphSave()}function iy(e,t,n){t({graphEdges:e,graphNodes:De(n().graphNodes,e)}),n().scheduleGraphSave()}function ly(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:Sn(t().graphNodes,[])}})}function cy(e,t,n,r){n({graphNodes:Bm(r().graphNodes,r().graphEdges,e,t)})}function dy(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(M("nodeBatch.stopQueued")))}function uy(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function my(e,t,n){t({canvasExportBackground:e}),El(e,n().canvasExportMatteColor)}function py(e,t,n){t({canvasExportMatteColor:e}),El(n().canvasExportBackground,e)}const ct=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let go=0;async function Bc(e){const{folders:t}=await is();e({assetsFolders:t})}const Ks=Bc;async function Bs(e,t,n){const r=e!==!1;if(!r&&n().assetsLoading)return;const o=++go;t({assetsLoading:!0,...r?{assetsLoadError:!1}:{}});try{const a=n().assetsFilters,i=await as({...a,cursor:r?null:n().assetsCursor}),l=r?await Promise.all([is(),ls()]):null;if(o!==go)return;t(c=>({assets:r?i.assets:[...c.assets,...i.assets.filter(d=>!c.assets.some(u=>u.id===d.id))],assetsCursor:i.nextCursor,assetsLoading:!1,...l?{assetsFolders:l[0].folders,assetsTags:l[1].tags}:{}}))}catch(a){ct(a),o===go&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function fy(e,t){!t().assetsCursor||t().assetsLoading||await Bs(!1,e,t)}function Ha(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),Bs(!0,t,n)}async function hy(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 Ur({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 gy(e,t,n){try{const{asset:r}=await $i(e,t);let o=null;try{o=(await ls()).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 yy(e,t){try{return await Nu(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return ct(n),!1}}async function vy(e,t,n){try{return await ku({name:e,parentId:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function by(e,t,n){try{return await Ui(e,{name:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function xy(e,t,n){try{return await Ui(e,{parentId:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function Iy(e,t){try{await Cu(e);const[{folders:n},{tags:r}]=await Promise.all([is(),ls()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return ct(n),!1}}function Sy(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(Du(e.imageModel)||Gu(e.imageModel)))return e.imageModel}async function Wc(e,t,n){if(!e.filename)return;const r=n();try{await Ur({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 wy(e,t,n){const r=n().assetGenItems.find(o=>o.requestId===e);r&&(r.mediaType==="video"?await Jc(r,t,n):await Wc(r,t,n))}async function _y(e,t,n,r){const o=n(),a=o.assetGenPrompt.trim(),i=await ss({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 Jc(l,t,n),n().showToast(M("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function Jc(e,t,n){if(!e.filename)return;const r=n();try{await Ur({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 Ey(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;rn(o,a);const i=Date.now(),l=[...n.inFlight,{id:o,prompt:r,startedAt:i}];Ae(l),e({assetGenLastError:null,activeGenerations:n.activeGenerations+1,inFlight:l}),t().startInFlightPolling();try{if(n.assetGenKind==="video"){await _y(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:Sy(n),requestId:o,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await Gi(c,{signal:a.signal}),u=Jo(d)?d.images[0]:null,p={image:u?u.image:d.image,filename:u?u.filename:d.filename,reasoningEffort:d.reasoningEffort,prompt:r,elapsed:d.elapsed,provider:d.provider,providerUrl:(u?u.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:(u?u.createdAt:d.createdAt)??Date.now()};await gt(p,e,t,{autoSelectStartedAt:i}),e(m=>({assetGenItems:[p,...m.assetGenItems]})),await Wc(p,e,t),t().showToast(M("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!tn(c)){const d=He(c,t()),u=d.code==="JOB_TRACKING_TIMEOUT"?d.message:c instanceof Error?c.message:String(c);e({assetGenLastError:u})}}finally{const c=t().inFlight.filter(d=>d.id!==o);Ae(c),on(o),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function Ny(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function ln(e){te({presetIds:e})}const ky=e=>({selectedPresetIds:en().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return ln(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(o=>o!==t);return ln(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(o=>o!==t):[...n.selectedPresetIds,t];return ln(r),{selectedPresetIds:r}}),clearPresets:()=>{ln([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=Ny(t);ln(n),e({selectedPresetIds:n})}});function Cy(){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)}),jy=e=>$("/api/sprite-recipes",{signal:e}),Ty=(e,t)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),Py=(e,t)=>$("/api/sprite-recipes",Un(e,"POST",t)),Ay=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,Un(t,"PATCH",n)),Ry=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),My=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Un({assetId:t},"POST",n)),Ly=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),Kt=new Map,Hn=e=>e instanceof Error?e.message:String(e),Yc=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function Oy(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await jy();e({spriteRecipes:n.map(Yc)}),t().activeSpriteRecipeId&&await Ws(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:Hn(n)})}finally{e({spriteRecipeLoading:!1})}}async function Ws(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await Ty(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:Hn(r)})}finally{t({spriteRecipeLoading:!1})}}async function Fy(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await Ay(n.activeSpriteRecipeId,n.spriteRecipeDraft):await Py(n.spriteRecipeDraft);return e(o=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[Yc(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 Xc(e,t,n){Kt.get(e)?.(),Kt.set(e,jt(e,null,(r,o)=>$y({event:r,data:{...o,requestId:e}},t,n)))}function Js(e){Kt.get(e)?.(),Kt.delete(e)}function Zc(e,t){return ot(e).code==="JOB_TRACKING_TIMEOUT"?He(e,t()).message:Hn(e)}async function Dy(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{Xc(r,e,t),await os(),await Ry(n,{requestId:r,async:!0})}catch(o){Js(r),e({spriteRecipeError:Zc(o,t),spriteRecipeGenerating:!1})}}async function Gy(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:o}=await My(r,e);t({activeSpriteRecipe:o,spriteRecipeDraft:o,spriteRecipeDirty:!1})}catch(o){t({spriteRecipeError:Hn(o)})}finally{t({spriteRecipeGenerating:!1})}}}async function zy(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const o=crypto.randomUUID();try{Xc(o,t,n),await os(),await Ly(r,{requestId:o,stateKeys:e,async:!0})}catch(a){Js(o),t({spriteRecipeError:Zc(a,n),spriteRecipeGenerating:!1})}}async function qy(e,t,n){Kt.get(e)?.(),Kt.delete(e),t({spriteRecipeGenerating:!1})}function $y(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")&&Js(String(e.data.requestId??"")),e.event==="error"){const a=String(e.data.message??"Generation failed"),i=Qe(e.data,a),l=ot(i).code==="JOB_TRACKING_TIMEOUT"?He(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&Ws(a,t)}}function Uy(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const je=en(),Zn=Jr(),Qn=Ll(),f=Ri((e,t,n)=>({...ky(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:Cy(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>Oy(e,t),selectSpriteRecipe:r=>Ws(r,e),updateSpriteRecipeDraft:r=>Uy(r,e),saveSpriteRecipe:()=>Fy(e,t),generateSpriteAnchor:()=>Dy(e,t),approveSpriteAnchor:r=>Gy(r,e,t),generateSpriteRows:r=>zy(r,e,t),cancelSpriteJob:r=>qy(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}),Ha({folderId:r},e,t)},loadAssetFolders:()=>Bc(e),retryAssetGenSave:r=>wy(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:()=>Ey(e,t),loadAssets:r=>Bs(r,e,t),loadMoreAssets:()=>fy(e,t),setAssetsFilters:r=>Ha(r,e,t),saveToAssets:r=>hy(r,e,t),updateAssetItem:(r,o)=>gy(r,o,e),deleteAssetItem:r=>yy(r,e),createAssetFolder:(r,o)=>vy(r,o,e),renameAssetFolder:(r,o)=>by(r,o,e),moveAssetFolder:(r,o)=>xy(r,o,e),deleteAssetFolder:r=>Iy(r,e),...Qn,imageToolModel:je.imageToolModel??null,quality:je.quality??"medium",sizePreset:je.sizePreset??"1024x1024",customW:je.customW??1920,customH:je.customH??1088,grokAspectRatio:je.grokAspectRatio??"1:1",grokResolution:je.grokResolution??"1k",format:je.format??"png",moderation:je.moderation??"low",count:je.count??1,multimode:je.multimode??!1,multimodeMaxImages:je.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:je.promptMode??"auto",prompt:je.prompt??"",negativePrompt:je.negativePrompt??"",naiOptionOverrides:Mm(),naiServerDefaults:null,insertedPrompts:je.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:Ue(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:Cs,activeReferenceLimit:()=>ac({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>Vp(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:Li(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:Aa().mode,canvasExportMatteColor:Aa().matteColor,syncCapabilities:()=>tp(e),addTrayAttachments:async r=>kh(r,e),addTrayAttachmentDataUrl:(r,o)=>ro(r,o,e),addTrayElement:r=>xr(r,e),addElementFromMention:r=>xr(r.id,e,t,r),syncElementCatalog:r=>hc(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>$c(r,e,t),clearTray:()=>Mh(e,t),addElementId:r=>{xr(r,e)},removeElementId:r=>Wp(r,e),addReferences:r=>jh(r,e,t),addReferenceDataUrl:r=>Ch(r,e),metadataRestore:null,readDroppedImageMetadata:(r,o=null)=>Th(r,o,e,t),applyMetadataRestore:()=>Ph(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>Yg(e,t),removeReference:r=>Ah(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>Rh(e,t),attachCanvasVersionReference:(r,o)=>Oh(r,e,t,o),useCurrentAsReference:()=>Fh(e,t),useImageAsReference:r=>Dh(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>Bg(r,e,t),startInFlightPolling:()=>{Tf(e,t)},reconcileInflight:async()=>{await Pf(e,t)},syncFromStorage:()=>Wg(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>Jg(r,e),addGeneratedHistoryItem:async r=>{await gt(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:$e,loadOlderHistory:async()=>ih(e,t),loadFavoriteHistory:async()=>lh(e,t),loadOlderFavoriteHistory:async()=>ch(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:jm(),toggleRightPanel:()=>Xg(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:Pa(vs),galleryDefaultScope:Pa(il),setGalleryScope:r=>Zg(r,e),setGalleryDefaultScope:r=>Qg(r,e),reasoningEffort:Am(),webSearchEnabled:Lm(),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:Tm(),setUIMode:r=>ey(r,e),historyStripLayout:Pm(),setHistoryStripLayout:r=>ty(r,e),locale:Ld(),setLocale:r=>{Md(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const o=t();e({graphHistoryPast:yp(o.graphHistoryPast,po(o.graphNodes,o.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),o=vp(r.graphHistoryPast,po(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Da(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),o=bp(r.graphHistoryPast,po(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Da(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>ay(r,e,t),setGraphEdges:r=>iy(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>Vf(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>ly(e,t),selectAllGraphNodes:()=>{e({graphNodes:Sn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,o)=>cy(r,o,e,t),clearNodeSelection:()=>{e({graphNodes:Sn(t().graphNodes,[])})},cancelNodeBatch:()=>dy(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await zc(e,t)},async switchSession(r){await Ih(r,e,t)},async reconcileGraphPending(){await Sh(e,t)},async createAndSwitchSession(r){await wh(r,e,t)},async renameCurrentSession(r){await _h(r,e,t)},async deleteSessionById(r){await Eh(r,e,t)},scheduleGraphSave(){oc(t,e)},async flushGraphSave(r="manual"){await pp(t,e,r)},addRootNode:()=>Of(e,t),createRootNodeFromHistoryItem:r=>Ff(r,e,t),addChildNode:r=>Df(r,e,t),addSiblingNode:r=>Gf(r,e,t),updateNodePrompt:(r,o)=>$f(r,o,e,t),addNodeReferences:async(r,o)=>Bf(r,o,e,t),addNodeReferenceDataUrl:(r,o)=>Pc(r,o,e,t),addNodeReferenceFromUrl:async(r,o,a)=>Wf(r,o,a,e,t),removeNodeReference:(r,o)=>Jf(r,o,e,t),clearNodeReferences:r=>Yf(r,e,t),duplicateBranchRoot:r=>qf(r,e,t),generateNode:r=>gf(r,e,t),generateNodeInPlace:r=>yf(r,e,t),generateNodeVariation:(r,o)=>vf(r,o,e,t),runGenerateNode:(r,o)=>bf(r,o,e,t),async runGenerateNodeInPlace(r,o={}){return Xp(r,o,e,t,Ae)},async runNodeBatch(r){await Zp(r,e,t)},deleteNode:r=>Uf(r,e,t),deleteNodes:r=>Hf(r,e,t),addChildNodeAt:(r,o,a)=>zf(r,o,a,e,t),connectNodes:(r,o,a,i)=>Kf(r,o,a,i,e,t),setProvider:r=>ug(r,e,t),setImageToolModel:r=>mg(r,e,t),setQuality:r=>pg(r,e,t),setSizePreset:r=>fg(r,e),setCustomSize:(r,o)=>hg(r,o,e,t),setGrokAspectRatio:r=>gg(r,e),setGrokResolution:r=>yg(r,e),setFormat:r=>vg(r,e),setModeration:r=>bg(r,e),setImageModel:r=>xg(r,e,t),videoDuration:Zn.duration,videoResolution:Zn.resolution,videoSingleRefMode:Zn.singleRefMode,videoAspectRatio:Zn.aspectRatio,videoReferenceVoices:[],videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>Ig(r,e,t),setComfyWorkflow:r=>Sg(r,e,t),setComfyVideoWorkflow:r=>wg(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),fn({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),fn({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),fn({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}),fn({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>_g(t),runVideoGenerate:async r=>{await xf(r,e,t)},animateImage:async(r,o)=>If(r,o,e,t),setReasoningEffort:r=>Eg(r,e),setWebSearchEnabled:r=>Ng(r,e),setCount:r=>kg(r,e),setMultimode:r=>Cg(r,e,t),setMultimodeMaxImages:r=>jg(r,e),setPromptMode:r=>Tg(r,e),setPrompt:r=>Pg(r,e),setNegativePrompt:r=>Ag(r,e),setNaiOption:(r,o)=>Rg(r,o,e,t),resetNaiOptions:()=>Mg(e),insertPromptToComposer:r=>Fg(r,e),removeInsertedPromptFromComposer:r=>Dg(r,e),moveInsertedPromptInComposer:(r,o)=>Gg(r,o,e),clearInsertedPrompts:()=>zg(e),selectHistory:r=>dh(r,e,t),showHistorySequence:r=>uh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>mh(r,e,t),trashHistoryItem:async r=>ph(r,e,t),trashHistorySequence:async r=>fh(r,e,t),restorePendingTrash:async()=>hh(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>gh(r,e,t),removeFromHistory:r=>yh(r,e,t),addHistoryItem:r=>vh(r,e,t),importLocalImageToHistory:async r=>bh(r,e,t),getResolvedSize:()=>Lg(t),generate:()=>pf(e,t),async generateMultimode(r){await rf(r,e,t)},cancelMultimode:()=>ff(e,t),async runGenerate(r){await of(r,e,t)},confirmCustomSizeAdjustment:()=>hf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){xh(e)},showToast:(r,o=!1)=>ny(r,o,e),dismissToast:r=>ry(r,e),showErrorCard:(r,o)=>oy(r,o,e),dismissErrorCard:r=>sy(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:()=>qg(e),savePromptToLibrary:r=>$g(r,e,t),deletePromptFromLibrary:r=>Ug(r,e,t),togglePromptFavorite:r=>Hg(r,e,t),importPromptsToLibrary:r=>Vg(r,e,t),toggleGalleryFavorite:r=>Kg(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)=>uy(r,o,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>my(r,e,t),setCanvasExportMatteColor:r=>py(r,e,t)})),Hy=/^[\p{L}\p{N}_-]$/u,Vy=new Set([" "," ","(","["]);function Ky(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(!Hy.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&&!Vy.has(a)&&a!==`
8
- `?null:{start:o,end:n,query:e.slice(r,n)}}function Fe({title:e,help:t,items:n,value:r,onChange:o,className:a}){const i=v.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 u=d.findIndex(h=>h.value===r),p=c.key==="ArrowRight"?1:-1,m=d[(u+p+d.length)%d.length];c.preventDefault(),o(m.value),i.current?.querySelector(`[data-value="${m.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 so=Od();function By(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Wy=(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}]}},Va=(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 Oe({items:e,groups:t,value:n,onChange:r,ariaLabel:o,ariaDescribedBy:a,className:i,id:l,disabled:c,portal:d=!1,triggerLabel:u,triggerSub:p,placeholder:m,title:h}){const b=v.useId(),I=v.useRef(null),x=v.useRef(null),y=v.useRef(null),[g,_]=v.useState(!1),[w,S]=v.useState({top:0,left:0,width:200,maxHeight:260}),{flat:N,rendered:P}=Wy(t,e),L=N.length===0,[U,j]=v.useState(()=>Math.max(0,N.findIndex(O=>O.value===n))),z=v.useRef({buffer:"",at:0}),q=N.find(O=>O.value===n),C=O=>`${b}-opt-${O}`,k=O=>O.searchText?O.searchText:typeof O.label=="string"?O.label:O.value,A=O=>{const ee=Date.now(),J=z.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 Ee=(ge+ie+N.length)%N.length,le=N[Ee];if(!(!le||le.disabled)&&k(le).toLowerCase().startsWith(me)){j(Ee);return}}};v.useEffect(()=>{if(!g)return;const O=ee=>{const J=ee.target;J instanceof Node&&(I.current?.contains(J)||y.current?.contains(J)||_(!1))};return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[g]),v.useLayoutEffect(()=>{if(!d||!g)return;const O=x.current?.getBoundingClientRect();if(O){const ge=Math.max(0,window.innerWidth-24),ie=Math.min(300,ge,Math.max(190,O.width)),Ee=Math.max(12,window.innerWidth-ie-12),le=Math.min(Math.max(12,O.left),Ee),Ie=window.innerHeight-O.bottom-12,Ce=O.top-12,Re=Ie>=160||Ie>=Ce?"down":"up",ce=Math.max(0,Re==="down"?Ie:Ce),be=Math.min(420,ce),D=8+N.length*44,ye=y.current?.scrollHeight??D,T=Math.min(ye,be);S({top:Re==="down"?O.bottom+4:Math.max(12,O.top-T-4),left:le,width:ie,maxHeight:be})}const ee=()=>_(!1),J=me=>{By(me,y.current)&&_(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,g]),v.useEffect(()=>{g&&y.current?.querySelector(`[data-index="${U}"]`)?.scrollIntoView({block:"nearest"})},[g,U]);const B=()=>{L||(j(Math.max(0,N.findIndex(O=>O.value===n))),_(!0))};v.useEffect(()=>{L&&(_(!1),j(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);j(ee)},oe=O=>{const ee=N[O];!ee||ee.disabled||(r(ee.value),_(!1),x.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(),j(Va(N,"first",U));else if(O.key==="End")O.preventDefault(),j(Va(N,"last",U));else if(O.key==="Enter"||O.key===" "){if(O.key===" "&&Date.now()-z.current.at<=1e3&&z.current.buffer){O.preventDefault(),A(" ");return}O.preventDefault(),oe(U)}else O.key==="Tab"?_(!1):O.key.length===1&&!O.metaKey&&!O.ctrlKey&&!O.altKey&&(O.preventDefault(),A(O.key))};let he=-1;const F=g&&!L?s.jsx("ul",{className:`ctl-select__list${d?" ctl-select__list--portal":""}`,role:"listbox",id:b,ref:y,style:d?{position:"fixed",top:w.top,left:w.left,width:w.width,maxHeight:w.maxHeight}:void 0,children:P.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:C(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:()=>j(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:x,className:`ctl-select__trigger${g?" is-open":""}`,role:"combobox","aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?b:void 0,"aria-activedescendant":g&&N[U]?C(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:u??q?.label??m??""}),p??q?.sub?s.jsx("span",{className:"ctl-select__value-sub",children:p??q?.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"})})]}),F?d?so.createPortal(F,document.body):F:null]})}function Jy({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 Qc({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 Ys({className:e,children:t,ariaLabel:n}){return s.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":n,children:t})}function Yy(){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 ed({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(Yy,{})})}function Xy(){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 Ka=12,Zy=240;function Qy(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 ev(e,t){const n=Qy(e,t),r=window.innerHeight-n.bottom,o=r<Zy?"top":"bottom",a=o==="bottom"?r:n.top;return{left:Math.max(Ka,Math.min(n.left,window.innerWidth-332)),top:o==="bottom"?n.bottom+6:Math.max(Ka,n.top-Math.min(320,a-8)),placement:o,maxHeight:Math.max(120,Math.min(320,a-12))}}function tv(){return window.matchMedia("(max-width: 640px)").matches}function nv({open:e,textareaRef:t,composingRef:n,caret:r,query:o,elements:a,ariaLabel:i,emptyLabel:l,kindLabel:c,onSelect:d,onClose:u,onActiveChange:p}){const m=v.useId(),[h,b]=v.useState(0),[I,x]=v.useState(null),[y,g]=v.useState(!1),_=v.useRef(null),w=v.useMemo(()=>{const L=o.trim().toLocaleLowerCase();return L?a.filter(U=>[U.name,...U.tags??[]].some(j=>j.toLocaleLowerCase().includes(L))):a},[a,o]),S=L=>{b(L),p?.(L)},N=()=>{const L=w[h];L&&d(L)};if(v.useLayoutEffect(()=>{if(!e||!t.current)return;const L=()=>{if(!t.current){u();return}g(tv()),x(ev(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,u]),v.useEffect(()=>{S(0)},[o,w.length]),v.useEffect(()=>{if(!e)return;const L=t.current;if(!L)return;L.setAttribute("aria-controls",m),L.setAttribute("aria-expanded","true");const U=j=>{if(document.activeElement===L&&!(n?.current||j.isComposing||j.keyCode===229)&&!(j.key==="Enter"&&(j.ctrlKey||j.metaKey))){if(j.key==="Escape"){j.preventDefault(),u("escape");return}j.key==="ArrowDown"||j.key==="ArrowUp"?(j.preventDefault(),S((h+(j.key==="ArrowDown"?1:-1)+w.length)%Math.max(1,w.length))):j.key==="Home"?(j.preventDefault(),S(0)):j.key==="End"?(j.preventDefault(),S(Math.max(0,w.length-1))):j.key==="Enter"?w.length&&(j.preventDefault(),N()):j.key==="Tab"&&w.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,m,h,w,u]),v.useEffect(()=>{const L=t.current,U=w[h];L&&U&&L.setAttribute("aria-activedescendant",`${m}-${U.id}`)},[h,w,m,t]),v.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const P=s.jsx("section",{className:`element-mention-menu${y?" is-mobile":""}`,style:y?void 0:{left:I.left,top:I.top,maxHeight:I.maxHeight},"aria-label":i,children:s.jsx("ul",{id:m,className:"element-mention-menu__list",role:"listbox",ref:_,children:w.length?w.map((L,U)=>s.jsxs("li",{id:`${m}-${L.id}`,role:"option","aria-selected":U===h,className:`element-mention-menu__option${U===h?" is-active":""}`,onPointerEnter:()=>S(U),onMouseDown:j=>{j.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 so.createPortal(P,document.body)}function rv(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function ov(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??rv(e.source.referenceFilenames[0])}function sv({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=ov(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 av({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(av,{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 lv=new Set(["character","product","style","scene"]);function cv(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&lv.has(t)?t:"character"}function dv(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 uv(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),o=new Set(n);return uc({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:cv(i),thumbnail:dv(i)??a.source.thumbnailUrl,missing:o.has(a.source.elementId)||t!==null&&!i}})}function mv(e){const t=uv(e.items,e.assets,e.missingElementIds);return t.length===0?null:s.jsx(Ys,{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 pv=["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 fv({prompt:e,retiredTags:t,textareaRef:n}){const{t:r}=V(),o=v.useRef(null),a=v.useRef(null),[i,l]=v.useState([]),c=v.useMemo(()=>Hp(e).filter(u=>Object.prototype.hasOwnProperty.call(t,u.tag)),[e,t]),d=v.useMemo(()=>[...new Set(c.map(u=>`@${u.tag}`))],[c]);return v.useLayoutEffect(()=>{const u=n.current,p=o.current,m=a.current?.firstChild;if(!u||!p||!(m instanceof Text)){l([]);return}const h=()=>{const I=getComputedStyle(u);pv.forEach(g=>{p.style[g]=I[g]}),p.scrollTop=u.scrollTop,p.scrollLeft=u.scrollLeft;const x=p.getBoundingClientRect(),y=[];for(const g of c){const _=document.createRange();_.setStart(m,g.start),_.setEnd(m,g.end),Array.from(_.getClientRects()).forEach((w,S)=>{y.push({key:`${g.start}-${g.end}-${S}`,left:w.left-x.left+p.scrollLeft,top:w.top-x.top+p.scrollTop,width:w.width,height:w.height})})}l(y)};h(),u.addEventListener("scroll",h,{passive:!0});const b=new ResizeObserver(h);return b.observe(u),()=>{u.removeEventListener("scroll",h),b.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(u=>s.jsx("span",{className:"dead-tag",style:u},u.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 ao(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 nn(o);t.addReferenceDataUrl(a);const i=Ic(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(uf(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 td(e){const t=await ao(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const hv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:ao,continueFromItemAsUrl:td},Symbol.toStringTag,{value:"Module"}));function gv({text:e,mode:t,onClose:n}){const{t:r}=V(),o=f(b=>b.savePromptToLibrary),[a,i]=v.useState(e.slice(0,30)),[l,c]=v.useState(e),[d,u]=v.useState(""),[p,m]=v.useState(!1),h=async()=>{l.trim()&&(m(!0),await o({name:a.trim()||l.slice(0,30),text:l.trim(),tags:d.split(",").map(b=>b.trim()).filter(Boolean),mode:t||void 0}),m(!1),n())};return s.jsxs("div",{className:"save-prompt-popover",onClick:b=>b.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:b=>i(b.target.value),placeholder:l.slice(0,30)})]}),s.jsxs("label",{children:[r("promptLibrary.content"),s.jsx("textarea",{value:l,onChange:b=>c(b.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:b=>u(b.target.value),placeholder:"cta, product, summer"})]})]}),s.jsx("div",{className:"save-prompt-popover__footer",children:s.jsx("button",{onClick:h,disabled:p||!l.trim(),className:"save-prompt-popover__save",children:r(p?"common.saving":"promptLibrary.save")})})]})}function yv({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(Jy,{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 vv({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),u=f(I=>I.storyboardActive),p=f(I=>I.toggleStoryboard),[m,h]=v.useState(!1),b=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 ao(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("gpt-5.6-luna"):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${b?" composer__tool--on":""}`,onClick:()=>d(b?"auto":"direct"),title:n("prompt.directModeTitle"),"aria-label":n("prompt.directModeTitle"),"aria-pressed":b,children:s.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"})}),s.jsx(yv,{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")}),m&&s.jsx(gv,{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${u?" composer__tool--on":""}`,onClick:p,title:n("prompt.storyboardTitle"),"aria-pressed":u,children:n("prompt.storyboard")})})]})}function Ba(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 bv(e){const{maxRefs:t,trayItemCount:n,captureAttachmentCaret:r,addFilesAtCaret:o}=e,{t:a}=V(),i=async(c,d)=>{const u=Math.max(0,t-n);if(u===0){f.getState().showToast(a("toast.refLimitTrayFull",{max:t}),!0);return}const p=c.slice(0,u),m=await o(p,d,!1);c.length>p.length&&f.getState().showToast(a("toast.refLimitPartial",{added:m,total:c.length,max:t}),!1)},l=c=>{const d=Ba(c.clipboardData?.items??null);d.length!==0&&(c.preventDefault(),i(d,r()))};return v.useEffect(()=>{const c=d=>{const u=d.target;if(["INPUT","TEXTAREA"].includes(u?.tagName??"")||u?.isContentEditable)return;const p=Ba(d.clipboardData?.items??null);p.length!==0&&(d.preventDefault(),i(p,f.getState().prompt.length))};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[o,t,a,n]),l}const nd="grok-imagine-video",xv="grok-imagine-video-1.5",rd=new Set([xv,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function Iv(e){return e.type.startsWith("audio/")}function Sv(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function wv(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,o=typeof r=="string"&&rd.has(r),a=r===nd;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(Iv(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(Sv(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 _v(e){const t=e.videoModelSelected;return typeof t=="string"&&rd.has(t)?"image/*,audio/*":t===nd?"image/*,video/mp4":"image/*"}function Ev(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 Nv({onImages:e}){const{t}=V(),n=f(o=>o.videoModelSelected),r=f(o=>o.showToast);return o=>{if(o.length===0)return;const a=wv(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(Ev(i,t),!0)}}function kv({variant:e,onSubmit:t}){const n=f(d=>d.provider),r=f(d=>d.negativePrompt),o=f(d=>d.setNegativePrompt),a=v.useRef(!1),{t:i}=V();if(v.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 yo="tray:";function vo(e){return`${e.start}:${e.end}:${e.query}`}function Cv(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):xr(e.id,f.setState,f.getState,e)}function jv(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):hc(e,f.setState,f.getState)}function Tv(e){const t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function Xs({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),u=f(E=>E),p=u.addElementId,m=u.elementCatalog??null,h=u.missingElementIds??[],[b,I]=v.useState([]),x=E=>{const W=b.find(Q=>Q.id===E);return W?Cv(W):(p?.(E),null)};v.useEffect(()=>{let E=!1;return Op().then(W=>{E||(I(W),jv(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{E=!0}},[]);const{t:y}=V(),g=f(E=>E.trayItems),_=f(E=>E.retiredTags),w=f(E=>E.removeTrayItem),S=f(E=>E.activeReferenceLimit()),N=f(E=>E.providerUrlReference),P=f(E=>E.setProviderUrlReference),L=f(E=>E.addReferences),U=f(E=>E.addReferenceDataUrl),j=f(E=>E.useImageAsReference),z=f(E=>E.readDroppedImageMetadata),q=f(E=>E.videoModelSelected),C=v.useRef(null),k=v.useRef(null),A=v.useRef(null),[B,se]=v.useState(!1),[oe,ae]=v.useState(null),he=v.useRef(!1),F=v.useRef(null),O=v.useRef(null),ee=f(E=>E.promptMode),J=f(mf),me=f(E=>E.multimodeMaxImages),ge=ee==="direct",ie=r==="nai",Ee=o.filter(E=>E.placement!=="after"),le=o.filter(E=>E.placement==="after"),Ie=[...Ee.map(E=>E.id),"__main_prompt__",...le.map(E=>E.id)],Ce=g.length<S,Re=J?g.length>0?y("multimode.promptPlaceholderWithRefs"):y("multimode.promptPlaceholder"):g.length>0?y("prompt.placeholderWithRefs"):y("prompt.placeholder"),ce=()=>{h.length>0||l()},be=()=>k.current?.selectionStart??f.getState().prompt.length,D=(E,W)=>{const Q=f.getState().trayItems.filter(H=>H.kind==="attachment"&&!E.has(H.tokenId));if(Q.length===0)return 0;const Se=f.getState().prompt,R=Math.max(0,Math.min(W,Se.length)),Y=Q.map(H=>`@${H.tag} `).join("");n(`${Se.slice(0,R)}${Y}${Se.slice(R)}`);const we=R+Y.length;return requestAnimationFrame(()=>k.current?.setSelectionRange(we,we)),Q.length},ye=(E,W)=>{const Q=`@${E} `,Se=f.getState().prompt,R=`${Se.slice(0,W.start)}${Q}${Se.slice(W.end)}`,Y=W.start+Q.length;n(R),requestAnimationFrame(()=>k.current?.setSelectionRange(Y,Y))},T=(E,W)=>{if(he.current)return;const Q=Ky(E,W);ae(Q&&vo(Q)!==O.current?Q:null)},ne=async(E,W,Q)=>{if(E.length===0)return 0;const Se=new Set(f.getState().trayItems.map(R=>R.tokenId));try{return Q&&E.length===1&&await z(E[0])?0:(await L(E),D(Se,W))}catch{return 0}},de=async E=>{const W=A.current??be();A.current=null,await ne(E,W,!0)},K=Nv({onImages:E=>{de(E)}}),G=()=>{Ce&&(A.current=be(),C.current?.click())},X=async(E,W)=>{const Q=new Set(f.getState().trayItems.map(Se=>Se.tokenId));try{const Se=E.url||E.image;if(!Se)return;const R={image:Se,url:E.url,filename:E.filename};if(xe(R)){const Y=await nn(Se);Y&&U(Y)}else await j(R);D(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))},Le=E=>{E.preventDefault(),B||se(!0)},Ge=E=>{E.currentTarget.contains(E.relatedTarget)||se(!1)},Ot=bv({maxRefs:S,trayItemCount:g.length,captureAttachmentCaret:be,addFilesAtCaret:ne}),Ke=v.useRef(null),dt=v.useRef(e);v.useLayoutEffect(()=>{const E=k.current;if(!E)return;(Ke.current===null||dt.current!==e)&&(Ke.current=Tv(window.getComputedStyle(E).maxHeight)??0,dt.current=e),E.style.height="auto";const W=Ke.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ut=(E,W)=>{const Q=Ie.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<Ie.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":y("prompt.moveBlockUp",{name:E.name}),title:y("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":y("prompt.moveBlockDown",{name:E.name}),title:y("prompt.moveBlockDown",{name:E.name}),children:"v"}),s.jsx("button",{type:"button",className:"composer__prompt-chip-remove",onClick:()=>a(E.id),"aria-label":y("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?y("multimode.composerAriaLabel",{count:me}):y("prompt.label"),onDrop:re,onDragOver:Le,onDragLeave:Ge,onPaste:Ot,children:[s.jsxs("div",{className:"composer__header",children:[s.jsx("span",{className:"section-title composer__label",children:y("prompt.label")}),s.jsxs("div",{className:"composer__header-meta",children:[J&&s.jsx("span",{className:"composer__mode-badge",children:y("multimode.composerBadge",{count:me})}),ge&&s.jsx("span",{className:"composer__direct-badge",children:y("prompt.directModeActive")}),N&&s.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>P(null),title:y("prompt.urlRefActiveTitle"),"aria-label":y("prompt.urlRefClear"),children:[s.jsx("span",{className:"composer__url-ref-dot","aria-hidden":"true"}),y("prompt.urlRefActive")]}),g.length>0&&s.jsx("span",{className:"composer__count",children:y("prompt.refCount",{count:g.length,max:S})})]})]}),s.jsx(sv,{items:g,limit:S,onRemove:w,onAdd:G}),Ee.length>0&&s.jsx("div",{className:"composer__prompt-chips",children:Ee.map(vt)}),c.length>0&&s.jsx(Ys,{ariaLabel:y("home.selectedPresets"),children:c.map(E=>{const W=vc(E);return W?s.jsx(Qc,{onRemove:()=>d(E),removeLabel:y("common.removeNamed",{name:W.name}),children:W.name},E):null})}),s.jsx(mv,{items:g,assets:m,missingElementIds:h,selectedLabel:y("element.selected"),unavailableLabel:y("common.elementUnavailable"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),mentionLabel:(E,W,Q)=>Q?y("element.unavailableAria",{name:E}):y("element.mentionAria",{name:E,kind:W}),removeLabel:E=>y("element.removeAria",{name:E}),onRemove:E=>u.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:y("nai.positivePrompt.label")}):null,s.jsxs("div",{className:"composer__prompt-stack",children:[s.jsx(fv,{prompt:t,retiredTags:_,textareaRef:k}),s.jsx("textarea",{id:`positive-prompt-${e}`,ref:k,className:"prompt-area composer__textarea",value:t,placeholder:ie?y("nai.positivePrompt.placeholder"):Re,"aria-describedby":ie?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{he.current=!0,ae(null)},onCompositionEnd:E=>{he.current=!1,F.current=E.currentTarget.value,queueMicrotask(()=>{F.current=null}),T(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{O.current=null,n(E.target.value),F.current!==E.target.value&&T(E.target.value,E.target.selectionStart)},onClick:E=>T(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=vo(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:y("nai.positivePrompt.hint",{count:t.length})}):null]}),s.jsx(kv,{variant:"classic",onSubmit:ce})]}),s.jsx(nv,{open:oe!==null,textareaRef:k,composingRef:he,caret:oe?.end??0,query:oe?.query??"",elements:[...g.filter(E=>E.kind==="attachment").map(E=>({id:`${yo}${E.tokenId}`,name:E.tag,kind:"reference",thumbnail:E.source.dataUrl})),...b.map(E=>{const W=lc(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:y("common.elementSuggestions"),emptyLabel:y("common.noMatchingElements"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),onSelect:E=>{const W=Wo(f.getState().trayItems,E.id);if(E.id.startsWith(yo)){const Se=E.id.slice(yo.length),R=f.getState().trayItems.find(Y=>Y.tokenId===Se);R&&oe&&ye(R.tag,oe),ae(null);return}if(x?.(E.id),W){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),ae(null);return}const Q=Wo(f.getState().trayItems,E.id);!Q||!oe||(ye(Q.tag,oe),ae(null))},onClose:E=>{E==="escape"&&oe&&(O.current=vo(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:y("prompt.afterBlocks")}),le.map(vt)]}),s.jsx(vv,{canAddMore:Ce,onAttach:G}),B&&s.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:y("prompt.dropHere",{max:S})}),s.jsx("input",{ref:C,type:"file",accept:_v({videoModelSelected:q}),multiple:!0,hidden:!0,onChange:E=>{const W=Array.from(E.target.files??[]);W.length>0?K(W):A.current=null,E.target.value=""}})]})}function Zs(){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 od(e,t=28){const n=e.trim().replace(/\s+/g," ");return n.length>t?`${n.slice(0,t)}...`:n}function Qs(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(Rv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o,variant:e.variant,panelId:e.panelId}):s.jsx(Pv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o})}function Pv(e){return s.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>s.jsx(Av,{f:t,...e},t.id))})}function Av({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:od(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 Rv(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(Mv,{f:o,determinateVideoId:n,validVideoProgress:r,...e},o.id))})}function Mv({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",u=Ov(e)??Fv(e.kind,a),p=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":`${u}, ${i}: ${c}`,children:[s.jsx("span",{className:`in-flight-placeholder${d?" in-flight-placeholder--video":""}`,"aria-hidden":"true",children:s.jsx(Dv,{video:d})}),s.jsxs("span",{className:"in-flight-rich-copy",children:[s.jsx("span",{className:"in-flight-rich-title",children:u}),s.jsx("span",{className:"in-flight-rich-prompt",title:c,children:od(e.prompt,54)}),s.jsxs("span",{className:"in-flight-rich-status",children:[s.jsx("span",{className:"in-flight-phase",children:p==null?i:`${i} · ${p}%`}),s.jsx(Lv,{progressPercent:p,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 Lv({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 Ov(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function Fv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function Dv({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 Wa="(max-width: 800px)";function yt(){const[e,t]=v.useState(()=>typeof window<"u"?window.matchMedia(Wa).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Wa),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const Gv=10,mt=12;function zv({anchorRef:e,panelId:t,focusOnOpen:n,onRequestClose:r,onPointerEnter:o,onPointerLeave:a}){const{t:i}=V(),l=v.useRef(null),c=v.useRef(null),d=v.useRef(null),[u,p]=v.useState({left:mt,top:mt,caretTop:24}),[m,h]=v.useState(!1);v.useLayoutEffect(()=>{const x=()=>{const _=e.current,w=l.current;if(!_||!w)return;const S=_.getBoundingClientRect(),N=_.closest(".sidebar")?.getBoundingClientRect(),P=w.getBoundingClientRect(),L=N?N.right:S.right,U=Math.max(mt,window.innerWidth-P.width-mt),j=Math.max(mt,window.innerHeight-P.height-mt),z=Math.min(Math.max(L+Gv,mt),U),q=Math.min(Math.max(S.bottom-P.height,mt),j),C=Math.min(Math.max(S.top+S.height/2-q,16),P.height-16);p({left:z,top:q,caretTop:C}),h(!0)},y=()=>{d.current!=null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(x)};x(),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0);const g=new ResizeObserver(y);return e.current&&g.observe(e.current),l.current&&g.observe(l.current),()=>{window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0),g.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),v.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),v.useEffect(()=>{const x=g=>{const _=g.target;_&&(e.current?.contains(_)||l.current?.contains(_))||r(!1)},y=g=>{g.key==="Escape"&&(g.preventDefault(),r(!0))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",y),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",y)}},[e,r]);const b=`${t}-title`,I={left:u.left,top:u.top,"--inflight-caret-top":`${u.caretTop}px`};return so.createPortal(s.jsxs("div",{ref:l,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":b,"data-positioned":m,style:I,onPointerEnter:o,onPointerLeave:a,children:[s.jsxs("header",{className:"inflight-popup__header",children:[s.jsx("h2",{ref:c,id:b,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(Qs,{variant:"popup",panelId:t}),s.jsx("footer",{className:"inflight-popup__footer",children:i("inflight.footerHint")})]}),document.body)}const qv=180,$v=180;function sd({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const o=f(j=>j.inFlight.length),a=yt(),{t:i}=V(),[l,c]=v.useState("closed"),[d,u]=v.useState(!1),p=v.useRef(null),m=v.useRef(null),h=v.useRef(null),b=e==="inline"?n:l!=="closed",I=()=>{m.current!=null&&window.clearTimeout(m.current),h.current!=null&&window.clearTimeout(h.current),m.current=null,h.current=null};if(v.useEffect(()=>I,[]),v.useLayoutEffect(()=>{if(o!==0)return;const j=document.activeElement;b&&j instanceof HTMLElement&&j.closest(".inflight-popup")&&p.current?.focus(),I(),c("closed"),u(!1),e==="inline"&&n&&r?.(!1)},[o,n,r,b,e]),o===0&&!(o===0&&e==="popup"&&b)||e==="popup"&&a)return null;const y=()=>window.matchMedia("(hover: hover) and (pointer: fine)").matches,g=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=null},_=()=>{e!=="popup"||l==="pinned"||!y()||(g(),m.current!=null&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>c("hover"),qv))},w=()=>{m.current!=null&&window.clearTimeout(m.current),m.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),$v))},S=j=>{I(),c("closed"),u(!1),j&&p.current?.focus()},N=j=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){S(!1);return}u(j.detail===0),c("pinned")},P=j=>{j.pointerType==="mouse"&&_()},L=o>99?"99+":String(o),U=b?"inflight.badgeClose":"inflight.badgeOpen";return s.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:P,onPointerLeave:w,children:[s.jsxs("button",{ref:p,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:N,"aria-live":"polite","aria-expanded":b,"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"&&b?s.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&b?s.jsx(zv,{anchorRef:p,panelId:t,focusOnOpen:d,onRequestClose:S,onPointerEnter:g,onPointerLeave:w}):null]})}function Uv(){const{t:e}=V(),t=f(m=>m.sessions),n=f(m=>m.activeSessionId),r=f(m=>m.switchSession),o=f(m=>m.createAndSwitchSession),a=f(m=>m.renameCurrentSession),i=f(m=>m.deleteSessionById),[l,c]=v.useState(!1),d=t.find(m=>m.id===n),u=()=>{const m=window.prompt(e("session.renamePrompt"),d?.title??e("session.newSession"));m&&m.trim()&&a(m.trim())},p=(m,h)=>{window.confirm(e("session.deleteConfirm",{title:h}))&&i(m)};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(m=>!m),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:u,title:e("session.renameTitle"),disabled:!d,children:s.jsx(Xy,{})})]}),l&&s.jsxs("ul",{className:"session-list",children:[t.map(m=>s.jsxs("li",{className:m.id===n?"is-active":"",children:[s.jsxs("button",{type:"button",className:"session-item",onClick:()=>{c(!1),r(m.id)},children:[s.jsx("span",{className:"session-item-title",children:m.title}),s.jsx("span",{className:"session-item-count",children:m.nodeCount})]}),s.jsx("button",{type:"button",className:"session-del",onClick:()=>p(m.id,m.title),title:e("session.deleteTitle"),children:"×"})]},m.id)),t.length===0&&s.jsx("li",{className:"session-empty",children:e("session.empty")})]})]})}function Gw(){return $("/api/comfy/workflows")}function zw(e){return $("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function qw(e){return $("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function $w(e){return $("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function Uw(e){return $(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Hv(e){return Kv(await $("/api/models",e?{signal:e}:{}))}function Vv(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function bn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ja(e){if(!hn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return bn();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 bn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return bn();t.executable=e.executable}return t}function Kv(e){return!hn(e)||e.ok!==!0||!hn(e.lanes)?bn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!hn(n)||!Vv(n.status)||!hn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return bn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Ja),video:n.models.video.map(Ja)}};return[t,r]}))}const ad={phase:"idle",catalog:null,observedAt:null,error:null},ft=new Set;let Pn=ad,Mr=0,pt=null,er=null;const Ya=()=>{ta()};function ea(){return Pn}function gn(e){Pn=e;for(const t of[...ft])ft.has(t)&&t()}function bo(e,t){return e===Mr&&pt===t&&!t.signal.aborted&&ft.size>0}function Bv(e){const t=e;return t?.status===401||t?.status===403?"app-auth":t?.code==="MODEL_CATALOG_INVALID"?"invalid":"request"}async function ta(){const e=++Mr;if(pt?.abort(),pt=null,ft.size===0){gn(ad);return}const t=new AbortController;if(pt=t,gn({...Pn,phase:"loading",error:null}),!!bo(e,t))try{const n=await Hv(t.signal);bo(e,t)&&gn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){bo(e,t)&&gn({...Pn,phase:"error",error:Bv(n)})}finally{e===Mr&&pt===t&&(pt=null)}}function Wv(e){const t=ft.size===0;return ft.add(e),t&&(typeof window<"u"&&(er=window,er.addEventListener("focus",Ya)),ta()),()=>{!ft.delete(e)||ft.size>0||(++Mr,pt?.abort(),pt=null,er?.removeEventListener("focus",Ya),er=null,gn({...Pn,phase:"idle",error:null}))}}function Vn(){return{...v.useSyncExternalStore(Wv,ea),refresh:ta}}function $t(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(m=>m.id===a):void 0,l=ds.comfy,c=r.image.some($t)||r.video.some($t),d=e.phase==="ready"&&n?.status==="ready"&&c,u=!!(d&&i&&$t(i)&&(o==="video"?l.video.supported:l.generate.supported)),p=m=>({code:m,laneAvailable:d,selectedAvailable:u,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"?p("loading"):e.phase==="error"?p("error"):!n||n.status==="key-missing"||n.status==="locked"?p("unavailable"):a&&!i?p("selected-missing"):r.image.length+r.video.length===0?p("empty"):n.status==="disconnected"?p("disconnected"):i?.executable===!1?p("selected-locked"):i?.description?.endsWith("(offline)")?p("selected-offline"):p(c?a?u?"ready":"unavailable":"choose":"unavailable")}const Jv={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 Bt(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":Jv[e.code]}const id=[{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"}],Xa=new Map(id.map(e=>[e.value,e.label])),Yv=new Set(["runway","higgsfield"]),tr="mcp:",nr="core:",xo="effort:",Io=Yi,cn=Vt;function Xv(e){oo(e,f.setState,f.getState)}function Zv(e){rg(e,f.setState,f.getState)}function Qv(e,t,n){og(e,t,f.setState,f.getState,n)}const So={image:[],video:[]};function wo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function eb(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function ld({compact:e=!1}={}){const{t}=V(),n=f(T=>T.provider),r=f(T=>T.imageModel),o=f(T=>T.videoModelSelected),a=f(T=>T.mcpProvider??null),i=f(T=>T.mcpModel??null),l=f(T=>T.mcpMediaKind??"image"),c=f(T=>T.setProvider),d=f(T=>T.setImageModel),u=f(T=>T.selectVideoModel),p=f(T=>T.setComfyWorkflow),m=f(T=>T.comfyWorkflow),h=f(T=>T.setComfyVideoWorkflow),b=f(T=>T.comfyVideoWorkflow),I=f(T=>T.setReasoningEffort),x=f(T=>T.reasoningEffort),{providers:y,loading:g,error:_}=Vc(),[w,S]=v.useState(So),[N,P]=v.useState(!1),[L,U]=v.useState(0),[j,z]=v.useState(!1),q=Vn(),C=q.catalog??{},k=C.comfy?.models??{image:[],video:[]};v.useEffect(()=>{dg(f.setState,f.getState)},[]);const A=a?y.find(T=>T.id===a)??null:null,B=!!(A?.enabled&&A.status.state==="connected");v.useEffect(()=>{if(!a||!B){S(So),P(!1);return}const T=new AbortController;return z(!0),P(!1),Hc(a,T.signal).then(ne=>{if(T.signal.aborted)return;S(ne);const de=f.getState(),G=(de.mcpMediaKind==="video"?ne.video:ne.image).find(X=>X.id===de.mcpModel);G&&cg(G.capabilities,f.setState,f.getState)}).catch(ne=>{ne.name!=="AbortError"&&(T.signal.aborted||(S(So),P(!0)))}).finally(()=>{T.signal.aborted||z(!1)}),()=>T.abort()},[a,B,L]);const se=v.useMemo(()=>y.filter(T=>T.enabled&&T.status.state==="connected"),[y]),oe=a?`${tr}${a}`:`${nr}${n}`,ae=zu(n),he=n==="comfy"?k.image.map(T=>({id:T.id,label:T.description?.endsWith("(offline)")?`${T.label} — ${t("comfy.statusOffline")}`:T.label,disabled:q.phase!=="ready"||C.comfy?.status!=="ready"||!$t(T),reason:T.lockReason})):[],F=n==="comfy"?k.video.map(T=>({id:T.id,label:T.description?.endsWith("(offline)")?`${T.label} — ${t("comfy.statusOffline")}`:T.label,reason:T.lockReason,disabled:q.phase!=="ready"||C.comfy?.status!=="ready"||!$t(T)})):[],O=Ku({provider:n,imageModel:r,videoModel:o,comfyWorkflow:m,comfyVideoWorkflow:b}),ee=a?i?Wn(l,i):"":O,J=!a&&(n==="oauth"||n==="api")&&!o,me=!!(i&&(w.image.some(T=>T.id===i)||w.video.some(T=>T.id===i))),ge=A?.executable===!1?A.lockReason??t("mcp.higgsfieldLocked"):null,ie=a?A?A.status.state!=="connected"?t("mcp.disconnectedSelection"):A.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,Ee=T=>{if(T.startsWith(nr)){const K=T.slice(nr.length);if(!Xa.has(K))return;c(K);return}const ne=T.slice(tr.length),de=y.find(K=>K.id===ne);!de||de.status.state!=="connected"||Xv(ne)},le=T=>{const ne=f.getState();if(ne.provider!==n||(ne.mcpProvider??null)!==a)return;const de=ea();if(ne.mcpProvider){if(T.startsWith(cn))return;const K=Em(T);if(K){const X=(K.kind==="video"?w.video:w.image).find(re=>re.id===K.model);Qv(K.model,K.kind,X?.capabilities)}else Zv(T||null);return}if(ne.provider==="comfy"){const K=T.startsWith(cn),G=K?T.slice(cn.length):T;if(!kt(de,K?{comfyVideoWorkflow:G}:{comfyWorkflow:G}).selectedAvailable)return;K?h(G):p(G||null);return}if(!T.startsWith(cn)){if(T.startsWith(xo)){I(T.slice(xo.length));return}if(T.startsWith(Io)){u(T.slice(Io.length));return}d(T)}},Ie=Object.keys(C).filter(T=>!Yv.has(T)),Ce=Ie.length>0?Ie:id.map(T=>T.value);Ce.includes("comfy")||Ce.push("comfy");const Re=[{label:t("mcp.coreProviders"),items:Ce.map(T=>{const ne=C[T],de=Xa.get(T),K=ne?eb(ne.status,t):null;return{value:`${nr}${T}`,label:de??wo(T),...K?{sub:K}:{},...ne?.reason?{title:ne.reason}:{},...de?{}:{disabled:!0}}})}];se.length>0&&Re.push({label:t("mcp.connectedProviders"),items:se.map(T=>({value:`${tr}${T.id}`,label:wo(T.id),sub:T.executable===!1?t("mcp.locked"):void 0}))}),a&&!se.some(T=>T.id===a)&&Re.push({items:[{value:`${tr}${a}`,label:wo(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:w.image.map(T=>({value:Wn("image",T.id),label:T.label}))}),ce.push({label:t("mcp.videoModels"),items:w.video.map(T=>({value:Wn("video",T.id),label:T.label}))});else{const T=C[n]?.models.video.length??0,ne=(n==="grok"||n==="grok-api")&&T>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"&&F.length>0&&ce.push({label:t("mcp.videoModels"),items:F.map(K=>({value:`${cn}${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:Uu.map(K=>({value:`${Io}${K.value}`,label:K.shortLabel}))}),J&&ce.push({label:t("sidebar.reasoningLabel"),items:zo.map(K=>({value:`${xo}${K.value}`,label:K.shortLabel,sub:K.value===x?"●":void 0}))});const de=new Set(ce.flatMap(K=>K.items.map(G=>G.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=zo.find(T=>T.value===x),D=n==="comfy"&&!a?kt(q,{comfyWorkflow:m,comfyVideoWorkflow:b}):null,ye=D?t(Bt(D,q)):null;return s.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[s.jsx(Oe,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:Re,value:oe,onChange:Ee,ariaLabel:t("mcp.providerLabel"),title:ie??t("mcp.providerLabel"),triggerSub:"",portal:!0}),s.jsx(Oe,{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(j?"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:D?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:D&&ye?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:ye}),q.phase==="error"?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{q.refresh()},children:t("comfy.display.refresh")}):null]}):ie??ge??(N?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>U(T=>T+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function cd(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function xn(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(cd):[]}}async function Lt(e,t){const n=await Ne(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 tb(){return Lt("/api/cardnews/image-templates")}function nb(){return Lt("/api/cardnews/role-templates")}async function rb(e){const t=await Lt("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:xn(t.plan)}}function ob(e){return Lt("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function sb(e){return Lt(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function ab(e){const n=(await Lt(`/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 Za(e){return Lt(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:xn(t.plan)}))}function ib(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function lb(e){return e[0]?.id||"academy-lesson-square"}function cb(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function db(e){return Math.round(e/16)*16}function Lr(e){return Math.min(xs,Math.max(1024,db(e)))}function Qa(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Lr(e.customW)}x${Lr(e.customH)}`}function dd(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 ub(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?dd(t.error)||M("cardNews.error"):void 0}}function mb(e){return new Promise(t=>setTimeout(t,e))}function _o(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:dd(o.error)}:r})}}const _e=Ri((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([tb(),nb()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:lb(n.templates),roleTemplateId:cb(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 rb({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:Qa(n)});e({activePlan:xn(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 ob({...o,size:Qa(n),quality:r.quality,moderation:r.moderation,model:r.imageModel,sessionId:r.activeSessionId});for(e(c=>({activePlan:c.activePlan?_o(c.activePlan,i):c.activePlan}));["queued","running"].includes(i.status);)await mb(900),i=await sb(i.jobId),e(c=>({activePlan:c.activePlan?_o(c.activePlan,i):c.activePlan}));const l=await Za(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?xn(l.plan):c.activePlan?_o(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 ab({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?ub(d,cd(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(u=>u.id===n?{...u,status:"error",error:c}:u)}:d.activePlan}))}},async loadSet(n){e({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:r}=await Za(n);e({activePlan:xn(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 pb(){const{t:e}=V(),t=_e(w=>w.hydrate),n=_e(w=>w.topic),r=_e(w=>w.audience),o=_e(w=>w.goal),a=_e(w=>w.contentBrief),i=_e(w=>w.outputSizePreset),l=_e(w=>w.customW),c=_e(w=>w.customH),d=_e(w=>w.setBriefField),u=_e(w=>w.setOutputSizePreset),p=_e(w=>w.setCustomSize),m=_e(w=>w.draft),h=_e(w=>w.loading),b=_e(w=>w.generating),I=_e(w=>w.draftError),x=_e(w=>w.generateSet),y=_e(w=>w.activePlan),g=y?.cards||[],_={total:g.length,done:g.filter(w=>w.status==="generated").length};return v.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:w=>d("topic",w.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:w=>d("audience",w.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:w=>d("goal",w.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:w=>d("contentBrief",w.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(w=>s.jsx("button",{type:"button",className:`option-btn${i===w?" active":""}`,onClick:()=>u(w),children:w==="custom"?e("cardNews.customSize"):w==="1024x1024"?"1024²":"2048²"},w))}),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:w=>p(Number.parseInt(w.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:w=>p(l,Number.parseInt(w.target.value,10)||c),"aria-label":e("size.height")})]}):null]}),s.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{m()},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:()=>{x()},disabled:!y||b||y.cards.every(w=>w.locked),children:[b?s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,b?e("cardNews.progress.generating",{done:_.done,total:_.total}):e("cardNews.batchGenerate")]})]})}function Wt({className:e}){return s.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function fb({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=Pe(e),c=xe(e),d=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?_n(e):{image:e.url||e.image,filename:e.filename})),u.dataTransfer.effectAllowed="copy"};return s.jsxs("div",{className:"sidebar-history__item",children:[s.jsx("button",{ref:u=>o(l,u),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(Wt,{}),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:u=>{u.preventDefault(),u.stopPropagation(),i(e)},"aria-label":r,title:r,children:"x"})]})}function hb({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=eh(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 u=e.items[d];return u&&xe(u)&&!u.thumb?s.jsx(Wt,{},Pe(u)):u?s.jsx("img",{src:u.thumb||u.url||u.image,alt:"",loading:"lazy",decoding:"async"},Pe(u)):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 ei="ima2.sidebarHistoryCollapsed";function ti(){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 gb({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 yb(){const e=f(y=>y.history),t=f(y=>y.currentImage),n=f(y=>y.selectHistory),r=f(y=>y.showHistorySequence),o=f(y=>y.trashHistoryItem),a=f(y=>y.trashHistorySequence),i=f(y=>y.inFlight),l=f(y=>y.multimodeSequences),c=f(y=>{const g=y.multimodePreviewFlightId;return g?g.startsWith("history:")?g.slice(8):y.multimodeSequences[g]?.sequenceId??null:null}),d=f(y=>y.openGallery),u=v.useRef({}),[p,m]=v.useState(()=>{try{return localStorage.getItem(ei)==="1"}catch{return!1}}),{t:h}=V(),b=Fc(t,c),I=v.useMemo(()=>Oc(e).slice(0,Mc),[e]);v.useEffect(()=>{!b||p||u.current[b]?.scrollIntoView({block:"nearest",inline:"nearest"})},[b,p,I]),v.useEffect(()=>{try{localStorage.setItem(ei,p?"1":"0")}catch{}},[p]);const x=(y,g)=>{u.current[y]=g};return s.jsxs("section",{className:`sidebar-history${p?" 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:()=>m(y=>!y),title:h(p?"history.expandRecent":"history.collapseRecent"),"aria-expanded":!p,children:h(p?"history.expandRecentShort":"history.collapseRecentShort")})]})]}),p?null:s.jsxs("div",{className:"sidebar-history__grid",children:[i.map(y=>{const g=l[y.id];if(y.kind==="multimode"&&g){const _=[s.jsx(gb,{count:g.requested},`coll-sk-${y.id}`)];for(let w=0;w<g.requested;w++)g.images[w]||_.push(s.jsx(ti,{},`sk-${y.id}-${w}`));return _}return s.jsx(ti,{},`sk-${y.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(y=>y.type==="sequence"?s.jsx(hb,{entry:y,active:b===y.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteSequenceAria",{count:y.items.length}),setRef:x,onSelect:r,onDelete:g=>{a(g)}},y.key):s.jsx(fb,{item:y.item,active:b===y.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteImageAria"),setRef:x,onSelect:n,onDelete:g=>{o(g)}},y.key))]})]})}const vb="sidebar-inflight-panel";function bb(){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"&&Qt?"agent":t==="node"&&Zt?"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(xb,{}),i==="classic"?c?s.jsx(s.Fragment,{children:s.jsx(yb,{})}):s.jsxs(s.Fragment,{children:[s.jsx(Xs,{}),s.jsxs("div",{className:"sidebar-generate-with-inflight",children:[s.jsx(Zs,{}),s.jsx(sd,{variant:"popup",panelId:vb})]})]}):i==="card-news"?s.jsx(s.Fragment,{children:s.jsx(pb,{})}):i==="node"?s.jsxs(s.Fragment,{children:[s.jsx(Uv,{}),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(Qs,{})]}):null]})}function xb(){const e=yt();return s.jsx(s.Fragment,{children:s.jsxs("div",{className:"logo",children:[s.jsx("div",{className:"logo-mark","aria-hidden":"true"}),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(Sb,{}),s.jsx(ld,{compact:e})]})]})})}function Ib(){return s.jsx("aside",{className:"sidebar",children:s.jsx("div",{className:"sidebar__scroll",children:s.jsx(bb,{})})})}function Sb(){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 wb=1024,_b=1024,Eb="blank-canvas.png";function ni(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function Nb(e){const t=ni(e?.width,wb),n=ni(e?.height,_b),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],Eb,{type:"image/png"})}const rr=1024;function kb(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 Cb(){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]=v.useState(!1),l=v.useCallback(async()=>{if(!a){i(!0);try{const c=kb(r()),d=await Nb(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 jb(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 Tb(e,t){try{const n=await Ne("/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 Qe(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 Pb(e,t){const n=fe();return ue()?Promise.reject(Xe(n-1)):(Tt(),new Promise((r,o)=>{let a=!1,i=()=>{},l=()=>{};const c=m=>{a||(a=!0,i(),l(),t.removeEventListener("abort",u),m())},d=()=>{Te(e.requestId).catch(()=>{})},u=()=>c(()=>{d(),o(new DOMException("Aborted","AbortError"))});if(l=jt(e.requestId,null,(m,h)=>{m==="done"?c(()=>r(h)):m==="error"&&c(()=>o(Qe(h,"Video extension failed")))}),i=Yt(()=>c(()=>{d(),o(new Error("Video extension stream timed out"))})),t.aborted)return u();t.addEventListener("abort",u,{once:!0}),os().then(()=>{if(n!==fe())throw Xe(n);if(ue())throw Xe(n-1);return Tb(e,t)}).catch(m=>c(()=>o(m)))}))}let xt={source:null,status:"idle"},dn=null,ri=0;const Xo=new Set;function or(e,t){xt={source:e,status:t};for(const n of Xo)n()}const Dt={getSnapshot:()=>xt,subscribe(e){return Xo.add(e),()=>{Xo.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 dn=t,ri=fe(),or(e.sourceVideoId,"pending"),Pb(e,t.signal).then(n=>(dn=null,or(e.sourceVideoId,"idle"),n),n=>{dn=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(){dn?.abort()},releaseView(){!ue()&&ri===fe()&&dn?.abort()}};async function Ab(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 Qe(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 Rb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),Ut=[];function Mb(e){return Ut.length>0&&Ut[Ut.length-1]===e}function Ve(e,t,n={}){const r=v.useRef(null),o=v.useRef(t);o.current=t;const a=v.useId(),{trap:i=!0,autoFocus:l=!0,restoreFocus:c=!0}=n;return v.useEffect(()=>{if(!e)return;Ut.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=r.current,p=()=>Array.from(u?.querySelectorAll(Rb)??[]).filter(x=>!x.hidden&&x.getAttribute("aria-hidden")!=="true");l&&window.requestAnimationFrame(()=>{(u?.querySelector("[data-modal-initial-focus]")??p()[0]??u)?.focus()});const m=x=>typeof c=="function"?c(x):c,h=x=>{if(!Mb(a))return;if(x.key==="Escape"){x.preventDefault(),o.current("escape");return}if(!i||x.key!=="Tab")return;const y=p();if(y.length===0){x.preventDefault(),u?.focus();return}const g=y[0],_=y[y.length-1];x.shiftKey&&document.activeElement===g?(x.preventDefault(),_.focus()):!x.shiftKey&&document.activeElement===_&&(x.preventDefault(),g.focus())};document.addEventListener("keydown",h);let b="programmatic";const I=o.current;return o.current=x=>{b=x??"programmatic",I(x)},()=>{const x=Ut.indexOf(a);x!==-1&&Ut.splice(x,1),document.removeEventListener("keydown",h),m(b)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const Lb={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 Ob(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function na(e){return Ob(e)?String(e):null}function Fb(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function oi(e){return e?e.replace("x","×"):null}function Db(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=na(n);o&&e.push({label:t,value:o,...r})}function Eo(e,t,n,r={}){typeof n!="number"||n<=0||Z(e,t,n,r)}function Gb(e,t,n){const r=Db(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function zb(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 qb(e){return e?Lb[e]??e:null}function $b(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const o=na(r);if(!o)return;const a=$b(o);!a||t.has(a)||(t.add(a),e.push({label:n,value:o,copyValue:o,pre:!0}))}function si(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function ai(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 Ub(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 Hb({item:e,onClose:t,onCopy:n}){const{t:r,locale:o}=V(),a=Ve(!0,t),i=v.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=qb(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),oi(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(_=>!!_),u=[],p=[];Z(p,r("metadata.fields.provider"),c,{compact:!0}),Z(p,r("metadata.fields.model"),e.model,{compact:!0}),Z(p,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Z(p,r("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),p.length&&u.push({title:r("metadata.sections.provider"),fields:p,compact:!0});const m=[];Z(m,r("metadata.fields.quality"),e.quality,{compact:!0}),Z(m,r("metadata.fields.size"),oi(e.size),{compact:!0}),Z(m,r("metadata.fields.format"),e.format,{compact:!0}),Z(m,r("metadata.fields.moderation"),e.moderation,{compact:!0}),Z(m,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Z(m,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Z(m,r("metadata.fields.kind"),e.kind,{compact:!0}),Z(m,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),m.length&&u.push({title:r("metadata.sections.settings"),fields:m,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"),si(e.usage,"input_tokens"),{compact:!0}),Eo(h,r("metadata.fields.cachedTokens"),ai(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),si(e.usage,"output_tokens"),{compact:!0}),Eo(h,r("metadata.fields.reasoningTokens"),ai(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),Eo(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&&u.push({title:r("metadata.sections.usage"),fields:h,compact:!0});const b=[];Z(b,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Z(b,r("metadata.fields.createdAt"),Fb(e.createdAt,o)),Z(b,r("metadata.fields.sessionId"),e.sessionId),Z(b,r("metadata.fields.nodeId"),e.nodeId),Z(b,r("metadata.fields.parentNodeId"),e.parentNodeId),Z(b,r("metadata.fields.clientNodeId"),e.clientNodeId),Z(b,r("metadata.fields.refsCount"),e.refsCount),Z(b,r("metadata.fields.sequence"),zb(e)),Z(b,r("metadata.fields.setId"),e.setId),Z(b,r("metadata.fields.cardId"),e.cardId),b.length&&u.push({title:r("metadata.sections.lineage"),fields:b});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:na(e.video?.xaiVideoRequestId)??void 0}),Z(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&u.push({title:r("metadata.sections.video"),fields:I});const x=[];Z(x,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Z(x,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Z(x,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Z(x,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Z(x,r("metadata.fields.latestContinuityPrompt"),l?.revisedPrompt,{copyValue:l?.revisedPrompt,pre:!0}),x.length&&u.push({title:r("metadata.sections.videoContinuity"),fields:x});const y=[],g=new Set;return sr(y,g,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),sr(y,g,r("metadata.fields.revisedPrompt"),e.revisedPrompt),sr(y,g,r("metadata.fields.prompt"),e.prompt),sr(y,g,r("metadata.fields.composerPrompt"),e.composerPrompt),Gb(y,r("metadata.fields.insertedPrompts"),e.composerInsertedPrompts),y.length&&u.push({title:r("metadata.sections.prompts"),fields:y}),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:[u.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(w=>s.jsxs("div",{className:Ub(w),children:[s.jsx("dt",{children:w.label}),s.jsxs("dd",{children:[w.pre?s.jsx("pre",{children:w.value}):s.jsx("span",{children:w.value}),w.copyValue?s.jsx("button",{type:"button",onClick:()=>n(w.copyValue),"aria-label":r("metadata.copyField",{label:w.label}),children:r("metadata.copy")}):null]})]},`${_.title}:${w.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 Vb(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function ud(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 Kb(e,t){const n=Vb(e);if(!n||ud(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 Bb=[2,4,8,16],Wb=["sublime","photo","photo_denoiser"];function Jb({pending:e,onSubmit:t,onClose:n}){const{t:r}=V(),o=Ve(!0,n,{trap:!1,restoreFocus:y=>y!=="outsidePointer"}),[a,i]=v.useState(2),[l,c]=v.useState(""),[d,u]=v.useState(10),[p,m]=v.useState(10),[h,b]=v.useState(30),I={scaleFactor:a,...l?{flavor:l}:{},sharpen:d,smartGrain:p,ultraDetail:h},x=ud("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:Bb.map(y=>s.jsxs("button",{type:"button",className:`option-btn${a===y?" active":""}`,"aria-pressed":a===y,onClick:()=>i(y),children:[y,"x"]},y))}),s.jsxs("label",{className:"upscale-popover__field",children:[s.jsx("span",{children:r("result.upscaleFlavor")}),s.jsxs("select",{value:l,onChange:y=>c(y.target.value),children:[s.jsx("option",{value:"",children:r("result.upscaleFlavorAuto")}),Wb.map(y=>s.jsx("option",{value:y,children:y},y))]})]}),[["sharpen",d,u],["smartGrain",p,m],["ultraDetail",h,b]].map(([y,g,_])=>s.jsxs("label",{className:"upscale-popover__field",children:[s.jsxs("span",{children:[y," ",s.jsx("output",{children:g})]}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:g,onChange:w=>_(Number(w.target.value))})]},y)),x?s.jsx("p",{className:"element-detail__error",role:"alert",children:x}):null,s.jsxs("div",{className:"upscale-popover__actions",children:[s.jsx("button",{type:"button",className:"action-btn action-btn--primary",disabled:e||!!x,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 Yb="canvas-mode-context",Xb="Canvas Mode",ii=36e5,Zb=["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 Qb({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=V(),r=f(G=>G.currentImage),o=f(G=>G.showToast),a=f(G=>G.insertPromptToComposer),i=f(G=>G.createRootNodeFromHistoryItem),l=f(G=>G.trashHistoryItem),c=f(G=>G.saveToAssets),d=f(G=>G.permanentlyDeleteHistoryItemByClick),u=f(G=>G.canvasOpen),p=f(G=>G.openCanvas),[m,h]=v.useState(!1),[b,I]=v.useState(!1),x=v.useSyncExternalStore(Dt.subscribe,Dt.getSnapshot),[y,g]=v.useState("idle"),[_,w]=v.useState(!1),[S,N]=v.useState(!1),[P,L]=v.useState(!1),[U,j]=v.useState(!1),z=v.useRef(null);v.useEffect(()=>{let G=!0;return Vs().then(X=>{G&&j(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const q=async G=>{if(!C?.filename||P)return;const X=Kb(C.filename,G);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)}};v.useEffect(()=>Dt.releaseView,[]);const C=e??r,k=C?.filename??null;v.useEffect(()=>{Dt.select(k)},[k]);const A=x.status==="pending"||x.source===k?x.status:"idle";if(!C)return null;const B=xe(C),se=B?C.url||C.image:"",oe=!!C.filename,ae=!!C.filename&&!B,he=B&&!!C.filename,O=!!((C.provider==="grok"||C.provider==="grok-api")&&!B&&C.providerUrl&&C.createdAt&&Date.now()-C.createdAt<ii),ee=async()=>{if(!(!C.filename||b)){I(!0);try{await f.getState().animateImage(C.filename,C.prompt??void 0)&&o(n("toast.animateDone"))}catch(G){const X=G instanceof Error?G.message:n("toast.animateFailed");o(X,!0)}finally{I(!1)}}},J=async()=>{if(!C.filename||A==="pending"||A==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const X=Dt.start({requestId:G,sourceVideoId:C.filename,prompt:C.prompt?.trim()||void 0,provider:C.provider==="grok-api"?"grok-api":"grok",model:C.model??void 0});if(!X)return;const re=await X;f.getState().addHistoryItem(jb(re,C)),o(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Le=ot(X).code;Le==="JOB_TRACKING_TIMEOUT"||Le==="LAN_TOKEN_REQUIRED"?He(X,f.getState()):re||o(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},me=()=>Dt.cancel(),ge=async()=>{if(!C.filename||y==="pending")return;const G=window.prompt(n("result.editVideoPrompt"))?.trim();if(!G)return;const X=new AbortController;z.current=X,g("pending");try{const re=await Ab({videoUrl:C.filename,prompt:G,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...C,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:G,userPrompt:G,model:re.model||"grok-imagine-video",format:"mp4"}),g("idle"),o(n("toast.animateDone"))}catch(re){const Le=re instanceof DOMException&&re.name==="AbortError";g(Le?"idle":"error"),Le||o(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{z.current===X&&(z.current=null)}},ie=()=>z.current?.abort(),Ee=()=>{const G=document.createElement("a");G.href=C.image,G.download=C.filename||"generated.png",G.click()},le=async G=>{const re=await(await fetch(G)).blob();let Le;if(re.type==="image/png")Le=re;else{const Ge=new Image;Ge.crossOrigin="anonymous";const Ot=URL.createObjectURL(re);await new Promise((dt,ut)=>{Ge.onload=()=>dt(),Ge.onerror=ut,Ge.src=Ot});const Ke=document.createElement("canvas");Ke.width=Ge.naturalWidth,Ke.height=Ge.naturalHeight,Ke.getContext("2d").drawImage(Ge,0,0),URL.revokeObjectURL(Ot),Le=await new Promise((dt,ut)=>Ke.toBlob(vt=>vt?dt(vt):ut(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Le})])},Ie=async()=>{try{if(B){const G=await nn(se);await le(G)}else await le(C.image);o(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{o(n("toast.copyFailed"),!0)}},Ce=async()=>{try{const G=await Jl(se);await le(G),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},Re=async()=>{try{const G=await Yl(se);await le(G),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},ce=async()=>{if(C.prompt)try{await navigator.clipboard.writeText(C.prompt),o(n("toast.promptCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},be=async G=>{try{await navigator.clipboard.writeText(G),o(n("toast.metadataCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},D=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await ao(C)}catch{}u&&e&&a({id:Yb,name:Xb,text:Zb});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),o(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ye=async()=>{if(B||!C.providerUrl||!C.createdAt||Date.now()-C.createdAt>=ii){o(n("toast.continueAsUrlExpired"),!0);return}try{await td(C)}catch{}const G=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');G&&(G.focus(),G.setSelectionRange(G.value.length,G.value.length)),o(n("toast.continueAsUrlStarted"))},T=async()=>{if(!(!C.filename||m)){h(!0);try{const G=await mu({filename:C.filename});o(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const X=G instanceof Error?G.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(C),o(n("toast.nodeRootCreated"))},de=async()=>{try{await l(C)}finally{t?.()}},K=async()=>{try{await d(C)}finally{t?.()}};return s.jsxs("div",{className:"result-actions",children:[s.jsx("button",{type:"button",className:"action-btn",onClick:Ee,children:n("result.download")}),s.jsx("button",{type:"button",className:`action-btn${B?" action-btn--frame":""}`,onClick:Ie,children:n(B?"result.copyLastFrame":"result.copyImage")}),B&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:Ce,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 G=await c(C);o(n(G?"chain.savedToAssets":"chain.saveToAssetsFailed"),!G)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),s.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:D,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:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),U&&C.filename&&(B?s.jsx("button",{type:"button",className:"action-btn",disabled:P,onClick:()=>{q({})},title:n("result.upscaleTitle"),children:n(P?"inflight.streaming":"result.upscale")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",disabled:P,onClick:()=>N(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),S?s.jsx(Jb,{pending:P,onSubmit:G=>{q(G)},onClose:()=>N(!1)}):null]})),he&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",onClick:J,disabled:A==="pending"||A==="tracking-expired","aria-busy":A==="pending",title:n(A==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:A==="pending"?n("inflight.streaming"):A==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),A==="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:y==="pending","aria-busy":y==="pending",title:n("result.editVideoTitle"),children:n(y==="pending"?"inflight.streaming":y==="error"?"gallery.retry":"result.editVideo")}),y==="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:()=>w(!0),title:n("result.infoTitle"),children:n("result.info")}),!u&&s.jsx("button",{type:"button",className:"action-btn",onClick:p,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"})})}),C.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:()=>{T()},title:n("result.sendToComfyUITitle"),disabled:m,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(Hb,{item:C,onClose:()=>w(!1),onCopy:G=>{be(G)}})]})}const ex=["auto","flat","detailed","mono"],it={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function tx(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 nx(e){return`${Math.round(e/1024)}KB`}function rx(){const{t:e}=V(),t=f(z=>z.vectorizeTarget),n=f(z=>z.setVectorizeTarget),r=f(z=>z.addAssetGenDerivedItem),o=f(z=>z.selectedProjectId),a=f(z=>z.showToast),i=v.useRef(null),l=v.useRef(t?.filename??null);l.current=t?.filename??null;const c=v.useCallback(()=>{i.current?.abort(),i.current=null,n(null)},[n]),d=Ve(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(it.colorPrecision),[b,I]=v.useState(it.filterSpeckle),[x,y]=v.useState(it.cornerThreshold),[g,_]=v.useState(!1),[w,S]=v.useState(null),[N,P]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),S(null),P(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const L=v.useCallback(()=>{if(!t?.filename||g)return;const z=t.filename,q=new AbortController;i.current=q,_(!0),S(null),Eu({source:z,preset:u,...m!==it.colorPrecision?{colorPrecision:m}:{},...b!==it.filterSpeckle?{filterSpeckle:b}:{},...x!==it.cornerThreshold?{cornerThreshold:x}:{},projectId:o,signal:q.signal}).then(C=>{if(!(i.current!==q||l.current!==z)){if(!C.filePath)throw new Error(e("vectorize.saveError"));P({filePath:C.filePath,pathCount:C.pathCount,bytes:C.bytes}),r(tx(t,C.filePath)),a(e("vectorize.saved"))}}).catch(C=>{if(C instanceof DOMException&&C.name==="AbortError"||i.current!==q||l.current!==z)return;const k=C instanceof Error?C.message:e("vectorize.saveError");S(k),a(k,!0)}).finally(()=>{i.current!==q||l.current!==z||(i.current=null,_(!1))})},[t,g,u,m,b,x,o,r,a,e]);if(!t)return null;const U=t.url||t.image,j=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:z=>z.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:j?s.jsx("img",{src:j,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:ex.map(z=>s.jsx("button",{type:"button",className:u===z?"is-active":"","aria-pressed":u===z,onClick:()=>p(z),children:e(`vectorize.preset_${z}`)},z))}),N?s.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(N.pathCount),size:nx(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:m}),s.jsx("input",{type:"range",min:1,max:8,value:m,onChange:z=>h(Number(z.target.value))})]}),s.jsxs("label",{children:[e("vectorize.filterSpeckle")," ",s.jsx("output",{children:b}),s.jsx("input",{type:"range",min:0,max:32,value:b,onChange:z=>I(Number(z.target.value))})]}),s.jsxs("label",{children:[e("vectorize.cornerThreshold")," ",s.jsx("output",{children:x}),s.jsx("input",{type:"range",min:0,max:180,value:x,onChange:z=>y(Number(z.target.value))})]}),s.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(it.colorPrecision),I(it.filterSpeckle),y(it.cornerThreshold)},children:e("vectorize.reset")})]})]}),s.jsxs("footer",{className:"keying-panel__actions",children:[w?s.jsx("span",{className:"keying-panel__save-error",role:"alert",children:w}):null,s.jsx("button",{type:"button",className:"assetgen-generate",disabled:g||!t.filename,onClick:L,children:e(g?"vectorize.running":"vectorize.run")}),j?s.jsx("a",{className:"assetgen-popup__close",href:j,download:N?.filePath,children:e("vectorize.download")}):null,s.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function ox({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 sx(){const e=f(m=>{const h=m.multimodePreviewFlightId;return h?m.multimodeSequences[h]??null:null}),t=f(m=>m.cancelMultimode),n=f(m=>{const h=m.multimodePreviewFlightId;return!!(h&&(m.activeFlightIds.has(h)||m.inFlight.some(b=>b.id===h)))}),r=f(m=>m.selectHistory),o=f(m=>m.currentImage),a=f(m=>m.openCanvas),{t:i}=V(),l=m=>{r(m)},c=m=>{r(m),a()};if(!e)return null;const d=new Map,u=e.partials.filter(m=>m.index==null);for(const m of e.partials)m.index!=null&&d.set(m.index,m);const p=Array.from({length:e.requested},(m,h)=>{const b=e.images[h],I=d.get(h)??(b?void 0:u.shift());return{index:h,image:b,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:p.map(({index:m,image:h,partial:b})=>{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?x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l(h))}:void 0,children:[s.jsx("div",{className:"multimode-sequence__badge",children:i("multimode.stageLabel",{index:m+1})}),h?s.jsx("img",{src:h.url??h.image,alt:i("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):b?s.jsx("img",{src:b.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??m)})})]})}function ax({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 Sr(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 Hw(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const wt=1,md=5,ar=.22;function lx(e){return Math.min(md,Math.max(wt,e))}function cx(e){const[t,n]=v.useState(1),[r,o]=v.useState({x:0,y:0}),[a,i]=v.useState(null),l=v.useRef(0),c=v.useRef(null),d=v.useCallback(()=>{cancelAnimationFrame(l.current),l.current=0,c.current=null,n(1),o({x:0,y:0}),i(null)},[]);v.useEffect(()=>{d()},[d,e]),v.useEffect(()=>()=>{cancelAnimationFrame(l.current)},[]);const u=v.useCallback(x=>{n(y=>{const g=lx(y+x);return g<=wt?(o({x:0,y:0}),wt):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?ar:-ar)},[u]),m=v.useCallback(()=>{if(t>wt){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=wt||x.button!==0||(x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),i({pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,baseX:r.x,baseY:r.y}))},[r.x,r.y,t]),b=v.useCallback(x=>{if(!a||a.pointerId!==x.pointerId)return;const y={x:a.baseX+x.clientX-a.startX,y:a.baseY+x.clientY-a.startY};c.current=y,cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{o(y),c.current=null})},[a]),I=v.useCallback(x=>{!a||a.pointerId!==x.pointerId||(cancelAnimationFrame(l.current),l.current=0,c.current&&(o(c.current),c.current=null),i(null),x.currentTarget.releasePointerCapture(x.pointerId))},[a]);return{zoom:t,pan:r,reset:d,zoomIn:()=>u(ar),zoomOut:()=>u(-ar),handleWheel:p,handleDoubleClick:m,handlePointerDown:h,handlePointerMove:b,handlePointerUp:I}}const dx=v.lazy(()=>Me(()=>import("./index-Co3ZHk9P.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function ux(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function mx(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function px(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 Zo(){const e=f(F=>F.currentImage),t=f(F=>F.importLocalImageToHistory),n=f(F=>{const O=F.multimodePreviewFlightId;return O?F.multimodeSequences[O]??null:null}),r=f(F=>F.selectHistoryShortcutTarget),o=f(F=>F.trashHistoryItem),a=f(F=>F.permanentlyDeleteHistoryItemByShortcut),i=f(F=>F.markGeneratedResultsSeen),l=f(F=>F.activeGenerations),c=f(F=>F.canvasOpen),d=f(F=>F.openCanvas),u=f(F=>F.showToast),p=f(F=>F.history),m=f(F=>F.galleryFavorites),h=f(F=>F.toggleGalleryFavorite),{t:b}=V(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:w}=Cb(),S=v.useRef(null),N=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,P=cx(N),L=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},U=F=>{if(F.key==="Delete"||F.key==="Backspace"){if(!e||F.target!==F.currentTarget||Sr(F.target))return;if(F.preventDefault(),F.shiftKey){a(e);return}o(e);return}F.key!=="ArrowLeft"&&F.key!=="ArrowRight"&&F.key!=="Home"&&F.key!=="End"||F.target===F.currentTarget&&(Sr(F.target)||(F.preventDefault(),F.key==="ArrowLeft"?r("previous"):F.key==="ArrowRight"?r("next"):F.key==="Home"?r("first"):F.key==="End"&&r("last")))},j=F=>{Sr(F.target)||(i(),F.currentTarget.focus())},z=v.useCallback(()=>{window.requestAnimationFrame(()=>S.current?.focus())},[]),q=async()=>{const F=e?.filename;if(!(!e||!F||y===F)){g(F);try{await h(e)}finally{g(O=>O===F?null:O)}}},C=v.useCallback(F=>{Array.from(F.dataTransfer.types).includes("Files")&&(F.preventDefault(),x(O=>O||!0))},[]),k=v.useCallback(F=>{F.currentTarget.contains(F.relatedTarget)||x(!1)},[]),A=v.useCallback(async F=>{if(!Array.from(F.dataTransfer.types).includes("Files"))return;F.preventDefault(),x(!1);const O=Array.from(F.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(v.Suspense,{fallback:s.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:s.jsx(dx,{currentImage:e})}),s.jsx(rx,{})]});const B=ux(e?.quality),se=mx(e?.size),oe=Bi(e?.model,e?.provider),ae=e?px(e):null,he=ix(e?.filename,p,m,e?.isFavorite);return s.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:C,onDragLeave:k,onDrop:A,children:[I?s.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:s.jsx("span",{className:"canvas__drop-hint",children:b("canvas.drop.hint")})}):null,s.jsx("div",{className:`progress-bar${l>0?" active":""}`}),n?s.jsx(sx,{}):e&&ae?s.jsxs("div",{ref:S,className:"result-container visible",tabIndex:0,onMouseDown:j,onKeyDown:U,"aria-label":b("canvas.imageViewerAria"),children:[s.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${P.zoom>wt?" canvas-annotation-frame--zoomed":""}`,onWheel:P.handleWheel,onDoubleClick:P.handleDoubleClick,onPointerDown:P.handlePointerDown,onPointerMove:P.handlePointerMove,onPointerUp:P.handlePointerUp,onPointerCancel:P.handlePointerUp,children:[e.filename?s.jsx(ed,{variant:"result",active:he,busy:y===e.filename,label:b(he?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:q}):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(${P.pan.x}px, ${P.pan.y}px) scale(${P.zoom})`}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify(_n(e))),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}):s.jsxs(s.Fragment,{children:[s.jsx("img",{className:"result-img",src:ae,alt:b("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${P.pan.x}px, ${P.pan.y}px) scale(${P.zoom})`},onDoubleClick:F=>{F.stopPropagation(),d()}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}),s.jsx(ax,{zoom:P.zoom,minZoom:wt,maxZoom:md,onZoomIn:P.zoomIn,onZoomOut:P.zoomOut,onReset:P.reset,labels:{controls:b("viewer.controls"),zoomIn:b("viewer.zoomIn"),zoomOut:b("viewer.zoomOut"),reset:b("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,Sc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Zu(e.reasoningEffort),B,se,oe]).filter(F=>!!F).join(" · ")}),s.jsx(Qb,{onAfterDeleteFocus:z}),e.prompt?s.jsx(ox,{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:b("canvas.blank.title")}),s.jsx("span",{children:b("canvas.blank.subtitle")})]}),s.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{w()},disabled:_,children:b(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function fx(){return s.jsxs("div",{className:"classic-workspace",children:[s.jsx("div",{className:"classic-workspace__stage",children:s.jsx(Zo,{})}),s.jsxs("div",{className:"classic-workspace__dock",children:[s.jsx(Xs,{variant:"bottom"}),s.jsx(Zs,{})]})]})}const pd="ima2.customSizeSlots";function hx(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 gx(){try{const e=localStorage.getItem(pd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?qt(t.filter(hx)):[]}catch{return[]}}function yx(e){try{localStorage.setItem(pd,JSON.stringify(qt(e)))}catch{}}function vx(e,t,n){return Kr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function un(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function bx(){const e=f(A=>A.sizePreset),t=f(A=>A.setSizePreset),n=f(A=>A.customW),r=f(A=>A.customH),o=f(A=>A.setCustomSize),{t:a}=V(),[i,l]=v.useState(String(n)),[c,d]=v.useState(String(r)),[u,p]=v.useState(e==="custom"),[m,h]=v.useState(()=>gx()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=Is(i,c,n,r),w=gm().filter(A=>A.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function S(A){h(A),yx(A)}function N(){const A=nt(i,n),B=nt(c,r);o(A,B),l(String(A)),d(String(B))}function P(A){A.key==="Enter"&&(A.preventDefault(),N())}function L(){t("custom"),p(!0),I(m.length>=zt?m[0]?.id??null:null)}function U(A){t(A),A!=="custom"&&(p(!1),I(null))}function j(A){t("custom"),o(A.w,A.h),l(String(A.w)),d(String(A.h)),p(!1),I(A.id)}function z(A){y(A.id);const B=cm(A);B&&(l(String(B.w)),d(String(B.h)))}function q(){const A=vx(_.w,_.h,x),B=m.length>=zt&&b?um(m,b,A):dm(m,A);S(B),t("custom"),o(_.w,_.h),l(String(_.w)),d(String(_.h)),I(A.id),p(!1)}const C=_.reasons.length>0?_.reasons.map(A=>a(`size.adjustedReasons.${A}`)).join(", "):a("size.noAdjustment"),k=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${Ea}×${Ea}`}):null;return s.jsxs("div",{className:"option-group size-picker",children:[s.jsx("div",{className:"section-title",children:a("size.title")}),s.jsx(Fe,{title:"",items:un(mm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(pm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(fm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(hm),value:e,onChange:U}),s.jsxs("div",{className:"option-row size-picker__quick-row",children:[un(w).map(A=>s.jsxs("button",{type:"button",className:`option-btn${e===A.value?" active":""}`,onClick:()=>U(A.value),children:[A.label,A.sub?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:A.sub})]}):null]},A.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")})]})]}),m.length>0?s.jsx("div",{className:"option-row size-picker__slot-row",children:m.map(A=>s.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===A.w&&r===A.h?" active":""}`,onClick:()=>j(A),children:[A.w,"×",A.h,s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:A.ratio||a("size.customSlot")})]},A.id))}):null,u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"size-picker__ratio-row",children:im.map(A=>s.jsx("button",{type:"button",className:`size-picker__ratio${x===A.id?" active":""}`,onClick:()=>z(A),children:A.id==="free"?a("size.ratioFree"):A.label},A.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:A=>l(A.target.value.replace(/\D/g,"")),onBlur:N,onKeyDown:P,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:A=>d(A.target.value.replace(/\D/g,"")),onBlur:N,onKeyDown:P,placeholder:a("size.height")})]}),s.jsxs("div",{className:"size-picker__preview",children:[s.jsx("span",{children:a("size.normalizedPreview")}),s.jsx("strong",{children:lm(_.w,_.h)})]}),s.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:C}),k?s.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:k}):null,m.length>=zt?s.jsxs("div",{className:"size-picker__replace-row",children:[s.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(A=>s.jsxs("button",{type:"button",className:`size-picker__replace${b===A.id?" active":""}`,onClick:()=>I(A.id),children:[A.w,"×",A.h]},A.id))]}):null,s.jsx("button",{type:"button",className:"size-picker__save",onClick:q,children:m.length>=zt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),s.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const No=[1,2,4];function xx(){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,[u,p]=v.useState(!No.includes(c)),[m,h]=v.useState(String(c));v.useEffect(()=>{p(!No.includes(c)),h(String(c))},[l,c]);function b(g=m){const _=Uo(Number.parseInt(g,10));d(_),h(String(_))}function I(g){p(!1),h(String(g)),d(g)}function x(g){const _=Uo(c+g);p(!0),h(String(_)),d(_)}function y(g){g.key==="Enter"&&(g.preventDefault(),b())}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:[No.map(g=>s.jsx("button",{type:"button",className:`option-btn${c===g&&!u?" active":""}`,onClick:()=>I(g),children:g},g)),s.jsx("button",{type:"button",className:`option-btn${u?" active":""}`,onClick:()=>{p(g=>!g),h(String(c))},children:i("count.customPlus")})]}),u?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"count-picker__custom",children:[s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(-1),"aria-label":i("count.decrease"),children:"-"}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"count-picker__input",value:m,onChange:g=>h(g.target.value.replace(/\D/g,"")),onBlur:()=>b(),onKeyDown:y,"aria-label":i("count.customLabel")}),s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(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 Ix={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}},Sx={512:.045,"1K":.067,"2K":.101,"4K":.151},wx={512:.134,"1K":.134,"2K":.134,"4K":.24};function _x(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function Ex(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),o=_x(r),i=t==="nano-banana-pro"?wx:Sx;return i[o]??i["1K"]??.003}function Nx(e,t,n,r){return n==="gemini-api"?Ex(t,r):Ix[e]?.[t]??0}function kx(){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",u=Nx(n,i,t,l),p=t==="api"&&c?e("imageToolModel.costUnavailable"):d?e("cost.free"):r?e("cost.multimodeApprox",{amount:(u*o).toFixed(3),count:o}):e("cost.approx",{amount:u.toFixed(3)}),m=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:m?{color:m}:void 0,children:p})]})}function fd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const o=async()=>{try{const a=await zd();if(n)return;t(a),a.status==="starting"&&(r=setTimeout(o,3e3))}catch{n||t(null)}};return o(),()=>{n=!0,r&&clearTimeout(r)}},[]),e}function Cx(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let o=!1;return qd().then(a=>{o||t(a)}).catch(()=>{o||r(!0)}),()=>{o=!0}},[]),{data:e,error:n}}function hd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(ue())return;const n=fe();let r=!1,o=null;const a=async()=>{if(!(r||ue()||n!==fe()))try{const l=await Ne("/api/grok/status");if(r)return;const c=await l.json();if(r||ue()||n!==fe())return;t(c),c.status!=="ready"&&(o=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,o&&clearTimeout(o),window.removeEventListener(_t,i)};return window.addEventListener(_t,i),a(),i},[]),e}function gd(){const[e,t]=v.useState(null),[n,r]=v.useState(null),o=v.useRef(!1),a=v.useCallback(async()=>{if(!o.current||ue())return;const i=fe();try{const c=await(await Ne("/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 v.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 yd(){const{t:e}=V(),t=fd(),{data:n}=Cx(),r=hd(),{data:o}=gd(),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",u=r?r.status==="offline"?e("provider.grokOffline"):r.status==="no_image_model"?e("provider.grokNoImageModel"):r.status==="error"?e("provider.grokNotReady"):"":e("provider.grokNotReady"),p=o?.xai?.valid===!0,m=o?.gemini?.valid===!0||o?.vertex?.valid===!0,h=o?.atlascloud?.valid===!0,b=o?.minimax?.valid===!0,I=o?.nai?.valid===!0,x=Vn(),y=kt(x,null);return{oauth:{ok:a,reason:i,hint:l},api:{ok:c,reason:c?"":e("provider.apiInvalid")},grok:{ok:d,reason:u,hint:d?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:p,reason:p?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:m,reason:m?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:h,reason:h?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:b,reason:b?"":e("provider.minimaxApiKeyRequired")},nai:{ok:I,reason:I?"":e("provider.naiApiKeyRequired")},comfy:{ok:y.laneAvailable,reason:e(y.laneAvailable?"comfy.display.available":Bt(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function jx({open:e,providerLabel:t,reason:n,hint:r,onClose:o}){const{t:a}=V(),i=Ve(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:",ko="mcp:",Tx={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"}},Co=cs.map(e=>Tx[e]);function jo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function To({tone:e}){return s.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function li(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 Po({mcpProviders:e}){const{t}=V(),n=f(j=>j.provider),r=f(j=>j.mcpProvider??null),o=f(j=>j.setProvider),a=yd(),i=Vn(),l=f(j=>j.comfyWorkflow),c=f(j=>j.comfyVideoWorkflow),d=kt(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),u=n==="comfy"&&!r,p=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[m,h]=v.useState(null),b=j=>{const z=a[j.value];return j.value==="comfy"?u?t(Bt(d,i)):z.reason:z.ok?t("provider.statusReady"):z.reason},I=j=>j.enabled?j.status.state==="connected"?j.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):j.status.state==="connecting"?t("mcp.connecting"):j.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Co.map(j=>{const z=a[j.value];return{value:`${ir}${j.value}`,searchText:`${j.provider} ${j.value==="comfy"?t("comfy.display.localMethod"):j.method}`,label:s.jsxs("span",{className:"provider-option",children:[s.jsx(To,{tone:j.value==="comfy"&&u?p:z.ok?"ok":"bad"}),s.jsxs("span",{children:[j.provider," ",j.value==="comfy"?t("comfy.display.localMethod"):j.method]})]}),sub:b(j)}})}],y=e.filter(j=>j.enabled).map(j=>({value:`${ko}${j.id}`,searchText:jo(j.id),label:s.jsxs("span",{className:"provider-option",children:[s.jsx(To,{tone:li(j)}),s.jsx("span",{children:jo(j.id)})]}),sub:I(j)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${ko}${r}`:`${ir}${n}`,_=r?null:Co.find(j=>j.value===n)??null,w=r?e.find(j=>j.id===r)??null:null,S=_?.value==="comfy",N=S?t(Bt(d,i)):_?b(_):w?I(w):t("provider.statusDisconnected"),P=S?p:_?a[_.value].ok?"ok":"bad":w?li(w):"bad",L=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",U=j=>{if(j.startsWith(ir)){const C=j.slice(ir.length);if(!Pt(C))return;const k=Co.find(B=>B.value===C),A=a[C];if(C==="comfy"){o(C);return}if(!A.ok){h({label:k?`${k.provider} ${k.method}`:C,reason:A.reason,hint:A.hint});return}o(C);return}const z=j.slice(ko.length),q=e.find(C=>C.id===z);if(!q||!q.enabled||q.status.state!=="connected"){h({label:jo(z),reason:!q||!q.enabled?t("mcp.disabledProvider"):t("mcp.disconnectedSelection")});return}oo(z,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(Oe,{groups:x,value:g,onChange:U,triggerSub:S?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),s.jsxs("div",{className:"provider-status-line","data-tone":P,role:"status","aria-live":"polite",children:[s.jsx(To,{tone:P}),s.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),s.jsx("span",{className:"provider-status-line__value",children:N})]}),S&&i.observedAt!==null?s.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,S&&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(S?"comfy.display.localMethod":"provider.authMethodTitle"),children:[s.jsx("span",{children:L}),P!=="bad"&&!S?s.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),s.jsx(jx,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const Px=[{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"}],Ax=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function Rx(){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:Px.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:Ax.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))})]})}const Mx=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function Lx(){const{t:e}=V(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return s.jsx(Fe,{title:e("quality.grokModelTitle"),items:Mx,value:t,onChange:n})}function vd({values:e,value:t,defaultValue:n,onChange:r,allowAuto:o=!1,disabled:a,ariaLabel:i}){const{t:l}=V(),c=v.useId();if(e.length===0)return null;const d=t??n??e[0],u=e.reduce((b,I,x)=>Math.abs(I-d)<Math.abs(e[b]-d)?x:b,0),p=t===null,m=e[0],h=e[e.length-1];return s.jsxs("div",{className:`ctl-duration${p?" is-auto":""}${a?" is-disabled":""}`,children:[s.jsxs("div",{className:"ctl-duration__head",children:[s.jsx("output",{htmlFor:c,className:"ctl-duration__value",children:p?`${l("size.autoLabel")} · ${e[u]}s`:`${e[u]}s`}),o?s.jsx("button",{type:"button",className:`option-btn ctl-duration__auto${p?" active":""}`,"aria-pressed":p,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:u,disabled:a,"aria-label":i,"aria-valuetext":`${e[u]}s`,onChange:b=>r(e[Number(b.target.value)]??e[0])}),s.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[s.jsxs("span",{children:[m,"s"]}),s.jsxs("span",{children:[h,"s"]})]})]})}const ci=3;function Ox(){const{t:e}=V(),t=f(p=>p.videoModelSelected),n=f(p=>p.videoReferenceVoices),r=f(p=>p.toggleVideoReferenceVoice),[o,a]=v.useState([]),[i,l]=v.useState("");v.useEffect(()=>{let p=!0;return Oi().then(m=>{p&&a(m.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{p=!1}},[]);const c=Rt(t)===tt,d=n.length>=ci,u=()=>{const p=i.trim();!p||d||n.includes(p)||(r(p),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:ci}):e("video.voiceNeeds15")}),s.jsx("div",{className:"option-row",role:"group","aria-label":e("video.voiceSection"),children:o.map(p=>{const m=n.includes(p);return s.jsxs("button",{type:"button",className:`option-btn${m?" active":""}`,"aria-pressed":m,disabled:!c||!m&&d,onClick:()=>r(p),children:[p,m?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:`<AUDIO_${n.indexOf(p)}>`})]}):null]},p)})}),s.jsx("input",{type:"text",className:"text-input",value:i,disabled:!c||d,placeholder:e("video.voiceCustomPlaceholder"),onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())},onBlur:u,"aria-label":e("video.voiceCustomPlaceholder")})]})}const Fx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],Dx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),di=[3,5,8,10,12,15],Gx=[{value:hs,label:"Grok V",sub:"Fast"},{value:tt,label:"Grok V1.5",sub:"HD"}];function zx(){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),u=f(k=>k.videoAspectRatio),p=f(k=>k.setVideoAspectRatio),m=f(k=>k.videoTopic),h=f(k=>k.setVideoTopic),b=f(k=>k.showToast),I=f(k=>k.videoContinuityLineage),x=f(k=>k.selectedPresetIds),y=f(k=>k.removePreset),g=x.map(k=>vc(k)).filter(k=>k?.category==="camera-motion"),_=Vu(r,o),w=xa(t,_),S=Sc(I),N=lo(t,"1080p",_),P=lo(tt,"1080p",_),L=Fx.map(k=>k.value==="1080p"?{...k,disabled:!P}:k);v.useEffect(()=>{lo(t,c,_)||d("720p")},[_,c,d,t]),v.useEffect(()=>{i!==null&&i>w&&l(w)},[i,w,l]);const U=k=>{const A=xa(k,_);i!==null&&i>A&&b(e("video.durationClampedToModel",{seconds:A})),n(k)},j=k=>{if(k==="1080p"){if(!P)return;N||n(tt)}d(k)},[z,q]=v.useState(null);v.useEffect(()=>{Ne("/api/config/grok-planner").then(k=>k.json()).then(q).catch(()=>{})},[]);const C=async k=>{const A=z?.model;q(B=>B?{...B,model:k}:null);try{const B=await Ne("/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(q(se=>se&&A?{...se,model:A}:se),B?.code==="LAN_TOKEN_REQUIRED")return;b(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:Gx.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})})]}),S?s.jsxs("div",{className:"provider-compat-note",role:"note",children:[s.jsx("strong",{children:e("common.continuity")}),s.jsx("span",{children:S})]}):null,s.jsx(Ox,{}),g.length>0&&s.jsx(Ys,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(k=>s.jsx(Qc,{onRemove:()=>y(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:m,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(vd,{values:di.filter(k=>k<=w),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??di[0])})]}),r===1&&s.jsx(Fe,{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(Fe,{title:e("video.resolutionTitle"),help:P?void 0:e("video.resolution1080Help"),items:L,value:c,onChange:j}),s.jsx(Fe,{title:e("video.aspectTitle"),items:Dx,value:u,onChange:p}),z&&s.jsx("div",{className:"video-controls__pills",children:s.jsx(Oe,{className:"video-controls__pill",items:z.options.map(k=>({value:k,label:k})),value:z.model,onChange:k=>{C(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:Ar})]})]})}const ui=e=>Symbol.iterator in e,mi=e=>"entries"in e,pi=(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},qx=(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 $x(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:ui(e)&&ui(t)?mi(e)&&mi(t)?pi(e,t):qx(e,t):pi({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Ux(e){const t=pn.useRef(void 0);return n=>{const r=e(n);return $x(t.current,r)?t.current:t.current=r}}const Hx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function Vx(){const{t:e}=V(),t=f(Ux(Qm)),n=f(u=>u.setNaiOption),r=f(u=>u.resetNaiOptions),o=f(u=>u.imageModel),a=f(u=>u.setImageModel),i=f(u=>u.sizePreset),l=f(u=>u.setSizePreset),c=Ho(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(Oe,{items:Ki.map(u=>({value:u.value,label:u.shortLabel})),value:o,onChange:u=>{Ho(u)||(n("straightAlpha",!1),n("qualityPresetId","standard")),a(u)},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:Hx.map(u=>s.jsxs("button",{type:"button",className:`option-btn${i===u.value?" active":""}`,onClick:()=>l(u.value),children:[u.label==="nai.size.portrait"?e("nai.size.portrait"):u.label==="nai.size.landscape"?e("nai.size.landscape"):e("nai.size.square"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:u.value.replace("x","×")})]},u.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(Oe,{items:fl.map(u=>({value:u,label:u})),value:t.sampler,onChange:u=>n("sampler",u),ariaLabel:e("nai.field.sampler")})]}),s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.noiseSchedule")}),s.jsx(Oe,{items:hl.map(u=>({value:u,label:u})),value:t.noiseSchedule,onChange:u=>n("noiseSchedule",u),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:u=>n("autoSmea",u.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:u=>n("steps",Number(u.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:u=>n("scale",Number(u.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:Cr.min,max:Cr.max,step:.01,value:t.cfgRescale,onChange:u=>n("cfgRescale",Number(u.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:u=>n("decrisper",u.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(Oe,{items:gl.map(u=>({value:u,label:e(`nai.ucPreset.${u}`)})),value:t.ucPresetId,onChange:u=>n("ucPresetId",u),ariaLabel:e("nai.field.ucPreset")})]}),c?s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.qualityPreset")}),s.jsx(Oe,{items:yl.map(u=>({value:u,label:e(`nai.qualityPreset.${u}`)})),value:t.qualityPresetId,onChange:u=>n("qualityPresetId",u),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:u=>n("varietyPlus",u.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:u=>n("straightAlpha",u.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:u=>{const p=u.target.value.replace(/\D/g,"");n("seed",p===""?null:Math.min(Number(p),vl))}})]}),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 Kx="",bd=3;function fi(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 Bx(e,t){return e[t]??null}function xd(e,t,n){const r=!t||e.some(o=>o.filename===t);return[{value:Kx,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 Ao({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(Oe,{id:e,items:xd(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 Wx({index:e,images:t,selection:n,disabled:r,onChange:o,t:a}){const i=Bx(n.references,e),l=new Set(n.references.filter((b,I)=>I!==e).map(b=>b.filename)),c=i?.dataUrl?{filename:i.filename,current:!1,label:i.displayName??a("mcp.referenceLocalFallback"),source:"local"}:null,d=[...c?[c]:[],...t.filter(b=>!l.has(b.filename))],u=b=>{const I=[...n.references];b?I[e]={filename:b,...i?.tag?{tag:i.tag}:{}}:I.splice(e,1),o({...n,references:I})},p=b=>{if(!i)return;const I=[...n.references],{tag:x,...y}=i;I[e]={...y,...b?{tag:b}:{}},o({...n,references:I})},m=!!(i?.tag&&!Ss(i.tag)),h=`mcp-reference-tag-error-${e}`;return s.jsxs("div",{className:"mcp-reference-slot__reference",children:[s.jsx(Oe,{items:xd(d,i?.filename??"",a),value:i?.filename??"",onChange:u,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:b=>p(b.target.value),"aria-label":a("mcp.referenceTagAria",{index:e+1}),placeholder:a("mcp.referenceTagPlaceholder"),"aria-invalid":m,"aria-describedby":m?h:void 0,maxLength:32,disabled:r||!i}),m?s.jsx("p",{id:h,className:"settings-row__microcopy",role:"alert",children:a("mcp.referenceTagInvalid")}):null]})]})}function Jx({selection:e,disabled:t,onChange:n,t:r}){const o=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=bd,c=async d=>{const u=d.target.files?.[0];if(d.target.value="",!!u){if(!/^image\/(?:png|jpeg|webp)$/i.test(u.type)){i(r("mcp.referenceLocalInvalidType"));return}try{const p=await Ts(u),m=`local:${globalThis.crypto.randomUUID()}`;n({...e,references:[...e.references,{filename:m,displayName:u.name,dataUrl:p}]}),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 Yx({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:bd},(a,i)=>s.jsx(Wx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:o},i)),s.jsx(Jx,{selection:t,disabled:n,onChange:r,t:o})]})}function Xx({inputRoles:e,disabled:t}){const{t:n}=V(),r=f(p=>p.history),o=f(p=>p.currentImage),a=f(p=>p.assets),i=f(p=>p.mcpReferenceSelection)??Ue(),l=v.useMemo(()=>fi(r,o,a,!1),[r,o,a]),c=v.useMemo(()=>fi(r,o,a,!0),[r,o,a]),d=p=>lg(p,f.setState,f.getState),u=i.startFrameFilename?void 0:n("mcp.endFrameNeedsStart");return s.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?s.jsx(Ao,{id:"mcp-start-frame",label:n("mcp.startFrameLabel"),value:i.startFrameFilename,candidates:l,disabled:t,t:n,onChange:p=>d({...i,startFrameFilename:p||null,...p?{}:{endFrameFilename:null}})}):null,e.includes("end_image")?s.jsx(Ao,{id:"mcp-end-frame",label:n("mcp.endFrameLabel"),value:i.endFrameFilename,candidates:l,disabled:t||!i.startFrameFilename,title:u,help:u,t:n,onChange:p=>d({...i,endFrameFilename:p||null})}):null,e.includes("image_references")?s.jsx(Yx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?s.jsx(Ao,{id:"mcp-video-reference",label:n("mcp.videoReferenceLabel"),value:i.referenceVideoFilename,candidates:c,disabled:t,t:n,help:n("mcp.videoReferenceCostNote"),onChange:p=>d({...i,referenceVideoFilename:p||null})}):null]})}function Zx(e){return Array.isArray(e)&&e.includes("image_references")}function Qx(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function Vw(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 Kw(e){return e.length>3}function eI({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(!Zx(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=Qx({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 hi=new Set(["duration","resolution","quality","mode"]);function gi(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ra(e){return e.options&&e.options.length>0?gi(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):gi([e.min,...e.default!==void 0?[e.default]:[],e.max])}function yi(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 tI(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function nI(e){return[...ra(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function rI({parameter:e,value:t,disabled:n,onChange:r}){const{t:o}=V();if(e.name==="duration"&&e.type==="number"){const l=nI(e);if(l.length>1){const c=yi(e.name,o);return s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:c}),s.jsx(vd,{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=ra(e);if(a.length===0)return null;const i=yi(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:tI(l,o)},`${typeof l}:${String(l)}`))]})]})}function vi({entries:e,parameters:t,disabled:n,onParameter:r}){return s.jsx(s.Fragment,{children:e.map(o=>s.jsx(rI,{parameter:o,value:t[o.name],disabled:n,onChange:a=>r(o.name,a)},o.name))})}function oI({entry:e,ratio:t,parameters:n,disabled:r,onRatio:o,onParameter:a}){const{t:i}=V(),l=e.capabilities.aspectRatios.filter(m=>m!=="auto"),c=e.capabilities.parameters.filter(m=>ra(m).length>0),d=c.filter(m=>hi.has(m.name)),u=c.filter(m=>!hi.has(m.name)),p=e.capabilities.inputRoles.some(m=>m==="start_image"||m==="end_image"||m==="image_references"||m==="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(m=>s.jsx("button",{type:"button",className:`option-btn${t===m?" active":""}`,"aria-pressed":t===m,disabled:r,onClick:()=>o(m),children:m},m))]})]}):null,s.jsx(vi,{entries:d,parameters:n,disabled:r,onParameter:a}),p?s.jsxs("div",{className:"mcp-tool-inputs",children:[s.jsx("div",{className:"section-title",children:i("mcp.toolInputsLabel")}),s.jsx(Xx,{inputRoles:e.capabilities.inputRoles,disabled:r}),s.jsx(eI,{inputRoles:e.capabilities.inputRoles,disabled:r})]}):null,u.length>0?s.jsxs("details",{className:"mcp-advanced-presets",children:[s.jsx("summary",{children:i("mcp.advancedPresetsLabel")}),s.jsx(vi,{entries:u,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:[]},sI={};function aI(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function iI({record:e}){const{t}=V(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),o=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??sI,[c,d]=v.useState(lr),[u,p]=v.useState("idle"),[m,h]=v.useState(0),b=e?.executable===!1,I=e?.status.state==="connected";if(v.useEffect(()=>{if(!n||!I){d(lr),p("idle");return}const _=new AbortController;return d(lr),p("loading"),Hc(n,_.signal).then(w=>{_.signal.aborted||(d(w),p("ready"))}).catch(w=>{w.name!=="AbortError"&&(_.signal.aborted||(d(lr),p("error")))}),()=>_.abort()},[n,I,m]),!n)return null;const x=o==="video"?c.video:c.image,y=x.find(_=>_.id===r)??null,g=_=>sg(_,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:[aI(n)," · MCP"]}),s.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>oo(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),I?null:s.jsx("p",{className:"option-help",children:t("mcp.disconnectedSelection")}),b?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")}),u==="loading"?s.jsx("p",{className:"option-help",role:"status",children:t("mcp.loadingModels")}):u==="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")})]}):u==="ready"&&x.length===0?s.jsx("p",{className:"option-help",children:t("mcp.noModels")}):y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mcp-selected-model",children:[s.jsx("strong",{children:y.label}),y.description?s.jsx("span",{children:y.description}):null]}),s.jsx(oI,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>ag(_,f.setState),onParameter:(_,w)=>ig(_,w,f.setState,f.getState)})]}):s.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function lI(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"?`${Vt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!$t(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 cI(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(Vt),o=r?e.slice(Vt.length):e;kt(ea(),r?{comfyVideoWorkflow:o}:{comfyWorkflow:o}).selectedAvailable&&(r?n.setComfyVideoWorkflow(o):n.setComfyWorkflow(o))}function dI(){const{t:e}=V(),t=v.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(),u=kt(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${Vt}${l}`:i??"",m=lI(d,u,p,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(Bt(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),s.jsx(Oe,{id:r,groups:m,value:p,onChange:h=>cI(h,{provider:o,mcpProvider:a}),ariaLabel:e("comfy.display.chooseWorkflow"),ariaDescribedBy:n,placeholder:e("comfy.display.chooseWorkflow"),portal:!0}),u.selected?s.jsxs("p",{className:"option-help",children:[e(u.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage"),": ",u.selected.label,s.jsx("br",{}),s.jsx("code",{children:u.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 uI=[{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"}],mI=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Or={"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 pI(e){for(const[t,n]of Object.entries(Or))for(const[r,o]of Object.entries(n))if(o===e)return{ratio:t,res:r};return null}function fI(e,t){const n=e/t;let r="1:1",o=1/0;const a=[...Object.keys(Or),"1:8","8:1","1:4","4:1"];for(const c of a){const[d,u]=c.split(":").map(Number),p=Math.abs(n-d/u);p<o&&(o=p,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 Id(){const{t:e}=V(),t=f(D=>D.provider),n=f(D=>D.imageToolModel),r=f(D=>D.setImageToolModel),o=f(D=>D.quality),a=f(D=>D.setQuality),i=f(D=>D.format),l=f(D=>D.setFormat),c=f(D=>D.moderation),d=f(D=>D.setModeration),u=f(D=>D.multimode),p=f(D=>D.setMultimode),m=f(D=>D.imageModel),h=f(D=>D.setImageModel),b=f(D=>D.selectVideoModel),I=f(D=>D.sizePreset),x=f(D=>D.customW),y=f(D=>D.customH),g=f(D=>D.setSizePreset),_=f(D=>D.setCustomSize),w=f(D=>D.uiMode),S=f(D=>D.videoModelSelected),N=f(D=>D.mcpProvider??null),{providers:P}=Vc(),L=w==="classic",U=t==="grok"||t==="grok-api",j=t==="agy",z=t==="gemini-api",q=j||z,C=t==="nai",k=t==="comfy",A=U||q||C,B=I==="custom"?`${x}x${y}`:"1024x1024",se=z&&I==="auto",oe=z&&!se?pI(B):null,ae=oe??{ratio:"",res:""},he=z&&!se&&I==="custom"&&!oe,F=m==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[O,ee]=v.useState(!1),[J,me]=v.useState(String(x)),[ge,ie]=v.useState(String(y)),Ee=(D,ye)=>{const T=Or[D||"1:1"]?.[ye||"1K"]||"1024x1024",[ne,de]=T.split("x").map(Number);ee(!1),g("custom"),_(ne,de)},le=()=>{const D=Number(J),ye=Number(ge);!Number.isFinite(D)||!Number.isFinite(ye)||D<=0||ye<=0||(g("custom"),_(D,ye),ee(!1))},Ie=[{value:"low",label:e("quality.lowLabel"),sub:e("quality.lowSub")},{value:"medium",label:e("quality.mediumLabel"),sub:e("quality.mediumSub")},{value:"high",label:e("quality.highLabel"),sub:e("quality.highSub")},...t==="api"&&n?[{value:"xhigh",label:e("quality.xhighLabel")},{value:"max",label:e("quality.maxLabel")}]:[]],Ce=[{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")}:j?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:z?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:C?{title:e("nai.compatTitle"),body:e("nai.compatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},be=D=>{D==="video"?b("grok-imagine-video"):h(m)};return N?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Po,{mcpProviders:P}),s.jsx(iI,{record:P.find(D=>D.id===N)??null})]}):k?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Po,{mcpProviders:P}),s.jsx(dI,{})]}):s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Po,{mcpProviders:P}),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${S?"":" active"}`,onClick:()=>be("image"),children:e("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${S?" active":""}`,onClick:()=>be("video"),children:e("grokMode.video")})]})}),S?s.jsx(zx,{}):s.jsxs(s.Fragment,{children:[j?null:U?s.jsxs(s.Fragment,{children:[s.jsx(Lx,{}),s.jsx(Rx,{})]}):C?s.jsx(Vx,{}):z?s.jsxs(s.Fragment,{children:[s.jsx(Fe,{title:e("quality.grokModelTitle"),items:Re,value:F,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((D,ye)=>s.jsx("div",{className:"option-row",children:D.map(T=>s.jsx("button",{type:"button",className:`option-btn${ae.ratio===T.value?" active":""}`,onClick:()=>Ee(T.value,ae.res),children:T.label},T.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:mI.map(D=>s.jsxs("button",{type:"button",className:`option-btn${ae.res===D.value?" active":""}`,onClick:()=>Ee(ae.ratio,D.value),children:[s.jsx("span",{children:D.label}),s.jsx("br",{}),s.jsx("small",{children:Or[ae.ratio]?.[D.value]?.replace("x","×")||""})]},D.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(D=>!D),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:D=>me(D.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:D=>ie(D.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 D=fI(Number(J),Number(ge));return`${D.ratio} · ${D.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(Oe,{ariaLabel:e("imageToolModel.title"),items:[{value:"",label:e("imageToolModel.default")},...Vi],value:n??"",onChange:D=>r(D||null),portal:!0})]}),s.jsx(Fe,{className:Ie.length>3?"quality-options-expanded":"",title:e("quality.title"),items:Ie,value:o,onChange:a}),s.jsx(bx,{})]}),A?null:s.jsxs(s.Fragment,{children:[s.jsx(Fe,{title:e("format.title"),items:uI,value:i,onChange:l}),s.jsx(Fe,{title:e("moderation.title"),items:Ce,value:c,onChange:d}),s.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),L&&!q&&!C&&s.jsx("div",{className:"option-group multimode-toggle",children:s.jsxs("button",{type:"button",className:`multimode-toggle__button${u?" active":""}`,"aria-pressed":u,title:e("multimode.tooltip"),onClick:()=>p(!u),children:[s.jsx("span",{children:e("multimode.label")}),s.jsx("span",{children:e("multimode.shortHint")})]})}),q||C?null:s.jsx(xx,{}),C?null:s.jsx(kx,{})]})]})}const hI=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-CGcqRRsJ.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),gI=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-gGHOSb6l.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),yI=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-CaVBCWhI.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.GenerationRequestLogPanel})));function vI(){const e=f(y=>y.rightPanelOpen),t=f(y=>y.toggleRightPanel),n=f(y=>y.promptLibraryOpen),r=f(y=>y.setPromptLibraryOpen),o=f(y=>y.promptBuilderOpen),a=f(y=>y.togglePromptBuilder),i=f(y=>y.workspaceProfile),{t:l}=V(),[c,d]=v.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);v.useEffect(()=>{if(typeof window>"u")return;const y=window.matchMedia("(max-width: 800px)"),g=()=>d(y.matches);return y.addEventListener("change",g),()=>y.removeEventListener("change",g)},[]);const[u,p]=v.useState(!1),m=oh(i)&&!c,h=c?e:!0,b=Ve(c&&e,t),I=u?"log":o&&m?"builder":n?"library":"settings",x=y=>{p(y==="log"),y==="builder"?(o||a(),n&&r(!1)):y==="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:b,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:[m?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:()=>x("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${m?"":" right-panel-tabs__button--full"}${I==="log"?" active":""}`,onClick:()=>x("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:()=>x("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:()=>x("settings"),children:l("panel.detailSettings")})]}),I==="builder"&&m?s.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(gI,{variant:"sidebar"})})}):I==="library"?s.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(hI,{variant:"embedded"})})}):I==="log"?s.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(yI,{})})}):s.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:s.jsx(Id,{})})]})]})]})}function bI(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 xI({id:e}){const{t}=V();return s.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function II({id:e,count:t}){const{t:n}=V(),r=Math.min(t,4);return s.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":n("history.generatingCollection",{count:t}),children:Array.from({length:r},(o,a)=>s.jsx("div",{className:"collection-mini collection-mini--skeleton"},a))},`coll-${e}`)}function SI({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&&(Ze(l.url)||Ze(l.image))?s.jsx(Wt,{className:"collection-mini"},c):s.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function wI(e){const t=v.useRef(null),n=v.useRef(new Map),[r,o]=v.useState(()=>new Set);v.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 u=new Set(d);for(const p of c){const m=p.target.dataset.historyLazyKey;m&&u.add(m)}return u})},{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=v.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 _I(){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=v.useRef({}),[c,d]=v.useState(null),u=wI(c),{t:p}=V(),m=t?Pe(t):null,h=v.useMemo(()=>Ir(e.filter(vn)),[e]),b=v.useMemo(()=>{const g=[];for(const _ of a){const w=i[_.id];if(_.kind==="multimode"&&w){g.push({type:"collection-skeleton",id:_.id,count:w.requested});for(let S=0;S<w.requested;S++)w.images[S]||g.push({type:"skeleton",id:`${_.id}_${S}`,count:1})}else g.push({type:"skeleton",id:_.id,count:1})}return g},[a,i]),{completedSequences:I,sequenceFirstKeys:x}=v.useMemo(()=>{const g=new Map,_=new Set;for(const w of h)if(w.sequenceId&&(w.sequenceTotalRequested??0)>1){g.has(w.sequenceId)||_.add(Pe(w));const S=g.get(w.sequenceId)||[];S.push(w),g.set(w.sequenceId,S)}return{completedSequences:g,sequenceFirstKeys:_}},[h]);v.useEffect(()=>{m&&l.current[m]?.scrollIntoView({block:"nearest",inline:"nearest"})},[m,h]);const y=(g,_)=>{const w=u.supported?u.visibleKeys.has(g):!0;return s.jsx("div",{ref:S=>{l.current[g]=S,u.register(g,S)},className:"history-thumb","data-history-lazy-key":g,"aria-hidden":w?void 0:!0,style:{padding:0,overflow:"hidden"},children:w?_:null},g)};return s.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:bI,"data-layout":n,children:[s.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:o,"aria-label":p("history.openGalleryAria"),title:p("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"})]})}),b.map(g=>g.type==="collection-skeleton"?s.jsx(II,{id:g.id,count:g.count},`coll-${g.id}`):s.jsx(xI,{id:g.id},g.id)),h.map(g=>{const _=Pe(g),w=m===_;if(g.sequenceId&&I.has(g.sequenceId)&&x.has(_)){const S=I.get(g.sequenceId);return[y(`coll-${g.sequenceId}`,s.jsx(SI,{sequenceId:g.sequenceId,images:S})),...S.map(N=>{const P=Pe(N),L=m===P;return xe(N)?y(P,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(_n(N))),U.dataTransfer.effectAllowed="copy"},children:[N.thumb?s.jsx("img",{src:N.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Wt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(P,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)&&!x.has(_)?null:xe(g)?y(_,s.jsxs("div",{className:`history-thumb history-thumb--video${w?" active":""}`,onClick:()=>r(g),draggable:!0,onDragStart:S=>{S.dataTransfer.setData("application/ima2-ref",JSON.stringify(_n(g))),S.dataTransfer.effectAllowed="copy"},children:[g.thumb?s.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Wt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(_,s.jsx("img",{src:g.thumb||g.url||g.image,alt:"",className:`history-thumb${w?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(g),draggable:!0,onDragStart:S=>{S.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:g.url||g.image,filename:g.filename})),S.dataTransfer.effectAllowed="copy"}}))})]})}const bi=3e3;function EI(){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]=v.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),l=v.useRef(new Map);v.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)}},[]),v.useEffect(()=>{const d=l.current,u=new Set([...t.map(p=>`toast-${p.id}`),...n.map(p=>`error-card-${p.id}`)]);for(const[p,m]of d)(!u.has(p)||!a)&&(clearTimeout(m),d.delete(p));if(a){for(const p of t){const m=`toast-${p.id}`;if(d.has(m))continue;const h=setTimeout(()=>{d.delete(m),r(p.id)},bi);d.set(m,h)}for(const p of n){const m=`error-card-${p.id}`;if(d.has(m))continue;const h=setTimeout(()=>{d.delete(m),o(p.id)},bi);d.set(m,h)}}},[o,r,n,a,t]),v.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 u=We[d.code],p=d.cardKey??u?.cardKey??"errorCard.unknown",m=e(`${p}.title`),h=e(`${p}.body`),b=d.cta??u?.cta;return{kind:"error-card",id:d.id,key:`error-card-${d.id}`,message:d.fallbackMessage?`${m}: ${h} ${d.fallbackMessage}`:`${m}: ${h}`,error:!0,createdAt:d.createdAt,cta:b,cardKey:p}})].sort((d,u)=>d.createdAt-u.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 u=["toast","visible",d.error?"error":"",d.error?"toast--card":""].filter(Boolean).join(" ");return s.jsxs("div",{className:u,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 NI(){return null}function kI(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 CI(e,t,n){async function r(i){if(i.setId)try{await _e.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 jI=["ArrowLeft","ArrowRight","Home","End"];function TI(){return v.useCallback(e=>{if(!jI.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 Ro({className:e,ariaLabel:t,tabs:n,value:r,onChange:o}){const a=TI(),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 PI({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 AI=[{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 RI(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 Ne(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 Me(async()=>{const{continueFromItem:c}=await Promise.resolve().then(()=>hv);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 MI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function LI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function OI(e){return{modelLabel:Bi(e.model,e.provider),derivation:MI(e),sourceLabel:LI(e)}}function FI(e){return!e.modelLabel&&!e.derivation}function DI({view:e,size:t="sm"}){const{t:n}=V();return FI(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 GI({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 zI({item:e,active:t,itemRef:n,onSelect:r,onDelete:o,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>AI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await RI(p,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]),u=p=>{p.dataTransfer.setData("application/ima2-ref",JSON.stringify(xe(e)?_n(e):{image:e.url||e.image,filename:e.filename})),p.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:u,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(Wt,{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(p=>s.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:m=>{d(p.id,m)},title:l(p.labelKey),"aria-label":l(p.labelKey),children:s.jsx(GI,{id:p.id})},p.id))}):null,e.filename&&a&&s.jsx(ed,{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:p=>o(e,p),title:l("gallery.deleteTitle"),"aria-label":l("gallery.deleteAria"),children:"×"}),s.jsx(DI,{view:OI(e)})]})}function qI(e,t,n){const r=new Array(e);return new Proxy(r,{get(o,a,i){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let d=o[c];if(!d){const u=t[c*2];d=o[c]={index:c,key:n(c),start:u,size:t[c*2+1],end:u+t[c*2+1],lane:0}}return d}}if(a==="length")return e}return Reflect.get(o,a,i)}})}function Gt(e,t,n){let r=n.initialDeps??[],o,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==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 xi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const $I=(e,t)=>Math.abs(e-t)<1.01,UI=(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 mn;const Mo=()=>{if(mn!==void 0)return mn;if(typeof navigator>"u")return mn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return mn=!0;const e=navigator.maxTouchPoints;return mn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Ii=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},HI=e=>e,VI=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},KI=(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(Ii(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(Ii(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Fr={passive:!0},BI=typeof window>"u"?!0:"onscrollend"in window,WI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const o=e.targetWindow;if(!o)return;const a=e.options.useScrollendEvent&&BI;let i=0;const l=a?null:UI(o,()=>t(i,!1),e.options.isScrollingResetDelay),c=p=>()=>{i=n(r),l?.(),t(i,p)},d=c(!0),u=c(!1);return r.addEventListener("scroll",d,Fr),a&&r.addEventListener("scrollend",u,Fr),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u),l?.cancel()}},JI=(e,t)=>WI(e,t,n=>{const{horizontal:r,isRtl:o}=e.options;return r?n.scrollLeft*(o&&-1||1):n.scrollTop}),YI=(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"]},XI=(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})},ZI=XI;class QI{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=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.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,u]of this.elementsCache)if(u===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,o;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:HI,rangeExtractor:VI,onChange:()=>{},measureElement:YI,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 m in n){const h=n[m];h!==void 0&&(a[m]=h)}const i=this.options;let l=null,c=null,d=!1;if(i!==void 0&&i.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const m=i.count,h=a.count,b=this.getMeasurements(),I=m>0?((r=b[0])==null?void 0:r.key)??i.getItemKey(0):null,x=m>0?((o=b[m-1])==null?void 0:o.key)??i.getItemKey(m-1):null;if(h!==m||m>0&&h>0&&(a.getItemKey(0)!==I||a.getItemKey(h-1)!==x)){d=!0;const _=m>0?this.getVirtualItemForOffset(this.getScrollOffset())??b[0]:null;_&&(l=[_.key,this.getScrollOffset()-_.start]);const w=a.followOnAppend===!0?"auto":a.followOnAppend||null;w&&h>m&&this.isAtEnd(i.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==x)&&(c=w)}}this.options=a,d&&(this.pendingMin=0,this.itemSizeCacheVersion++);let u=!1,p=0;if(l&&this.scrollOffset!==null){const[m,h]=l,b=this.getMeasurements(),{count:I,getItemKey:x}=this.options;let y=0;for(;y<I&&x(y)!==m;)y++;if(y<I){const g=b[y];if(g){const _=Math.max(0,g.start+h);_!==this.scrollOffset&&(p=_-this.scrollOffset,this.scrollOffset=_,u=!0)}}}(u||c)&&(this.pendingScrollAnchor=[u?l[0]:null,u?l[1]:0,c,p])},this.notify=n=>{var r,o;(o=(r=this.options).onChange)==null||o.call(r,this,n)},this.maybeNotify=Gt(()=>(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.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,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(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,i)=>{if(i&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!Mo()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",i,Fr),a.addEventListener("touchend",l,Fr),this.unsubs.push(()=>{a.removeEventListener("touchstart",i),a.removeEventListener("touchend",l),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 o=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,o&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=o;a!==null&&!l&&(Mo()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},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=Gt(()=>[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=Gt(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:o,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d},u)=>{const p=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const m=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const y=n*2;let g=this._flatMeasurements;if(!g||g.length<y){const S=new Float64Array(y);g&&m>0&&S.set(g.subarray(0,m*2)),g=S,this._flatMeasurements=g}let _;if(m===0)_=r+o;else{const S=m-1;_=g[S*2]+g[S*2+1]+d}for(let S=m;S<n;S++){const N=a(S),P=p.get(N),L=typeof P=="number"?P:this.options.estimateSize(S);g[S*2]=_,g[S*2+1]=L,_+=L+d}const w=qI(n,g,a);return this.measurementsCache=w,w}const h=this.measurementsCache.slice(0,m),b=new Array(l).fill(void 0),I=new Float64Array(l);let x=0;for(let y=0;y<m;y++){const g=h[y];g&&(b[g.lane]===void 0&&x++,b[g.lane]=y,I[g.lane]=g.end)}for(let y=m;y<n;y++){const g=a(y),_=this.laneAssignments.get(y);let w,S;const N=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){w=_;const j=b[w],z=j!==void 0?h[j]:void 0;S=z?z.end+d:r+o}else if(x===l){let j=0,z=I[0],q=b[0];for(let C=1;C<l;C++){const k=I[C];(k<z||k===z&&b[C]<q)&&(j=C,z=k,q=b[C])}w=j,S=z+d,N&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,S=r+o,N&&this.laneAssignments.set(y,w);const P=p.get(g),L=typeof P=="number"?P:this.options.estimateSize(y),U=S+L;h[y]={index:y,start:S,size:L,end:U,key:g,lane:w},b[w]===void 0&&x++,b[w]=y,I[w]=U}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Gt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,o,a)=>n.length===0||r===0?(this.range=null,null):(this.range=tS(n,r,o,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Gt(()=>{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;if(!this.isIndexInRange(n))return;let i,l,c;const d=this._flatMeasurements;if(this.options.lanes===1&&d!==null)c=this.options.getItemKey(n),l=d[n*2],i=d[n*2+1];else{const m=this.measurementsCache[n];if(!m)return;c=m.key,l=m.start,i=m.size}const u=this.itemSizeCache.get(c)??i,p=r-u;if(p!==0){const m=this.options.anchorTo==="end"&&((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=m?this.getTotalSize():0,b=this.getScrollOffset()+this.scrollAdjustments,x=!this.itemSizeCache.has(c)?l<b:l+u<=b&&this.scrollDirection!=="backward",y=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:i,end:l+i,lane:0},p,this):x);(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++;let g=!1;m?g=this.applyScrollAdjustment(this.getTotalSize()-h):y&&(g=this.applyScrollAdjustment(p)),this.notify(g)}},this.getVirtualItems=Gt(()=>[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=>{const r=this.getMeasurements();if(r.length===0)return;const o=this._flatMeasurements,a=this.options.lanes===1&&o!=null,i=Sd(0,r.length-1,a?l=>o[l*2]:l=>xi(r[l]).start,n);return xi(r[i])},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;const r=this.getMeasurements();let o;if(r.length===0)o=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?o=i[a*2]+i[a*2+1]:o=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&a.some(l=>l===null);){const l=r[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-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){return t===0?!1:Mo()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=t,!1):(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&&$I(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 Sd=(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 eS(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 tS(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=eS(o,a,n);let u=d;const p=n+t;for(;u<a&&o[u*2]+o[u*2+1]<p;)u++;return{startIndex:d,endIndex:u}}let l=Sd(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(p=>p<n+t);){const p=e[c];d[p.lane]=p.end,c++}const u=Array(r).fill(n+t);for(;l>=0&&u.some(p=>p>=n);){const p=e[l];u[p.lane]=p.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const Lo=typeof document<"u"?v.useLayoutEffect:v.useEffect;function nS({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const o=v.useReducer(u=>u+1,0)[1],a=v.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=u=>{const p=a.current;if(!p.enabled||!p.container)return;const m=u.getTotalSize();if(m!==p.lastSize){p.lastSize=m;const h=u.options.horizontal?"width":"height";p.container.style[h]=`${m}px`}},l=u=>{const p=a.current;if(!p.enabled||!p.container)return;i(u);const m=!!u.options.horizontal,h=p.mode==="transform",b=m?"left":"top",I=u.options.scrollMargin,x=u.getVirtualItems();for(const y of x){const g=y.start-I,_=u.elementsCache.get(y.key);_&&p.lastPositions.get(_)!==g&&(p.lastPositions.set(_,g),h?_.style.transform=m?`translate3d(${g}px, 0, 0)`:`translate3d(0, ${g}px, 0)`:_.style[b]=`${g}px`)}},c={...r,onChange:(u,p)=>{var m;const h=a.current;let b=!0;if(h.enabled){l(u);const I=u.range,x=h.prevRange;b=!x||x.isScrolling!==u.isScrolling||x.startIndex!==I?.startIndex||x.endIndex!==I?.endIndex,b&&(h.prevRange=I?{startIndex:I.startIndex,endIndex:I.endIndex,isScrolling:u.isScrolling}:null)}b&&(e&&p?so.flushSync(o):o()),(m=r.onChange)==null||m.call(r,u,p)}},[d]=v.useState(()=>{const u=new QI(c);return Object.assign(u,{containerRef:p=>{const m=a.current;if(m.container=p,m.lastSize=null,p&&m.enabled){const h=u.getTotalSize();m.lastSize=h;const b=u.options.horizontal?"width":"height";p.style[b]=`${h}px`}}})});return d.setOptions(c),Lo(()=>d._didMount(),[]),Lo(()=>(i(d),d._willUpdate())),Lo(()=>{l(d)}),d}function rS(e){return nS({observeElementRect:KI,observeElementOffset:JI,scrollToFn:ZI,...e})}const Dr=170,Gr=10,wd=36,oS=44;function sS(e){const t=Math.max(Dr,e-wd);return Math.max(1,Math.floor((t+Gr)/(Dr+Gr)))}function aS(e,t){const n=Math.max(Dr,e-wd);return Math.max(Dr,Math.floor((n-Gr*Math.max(0,t-1))/t))+Gr}function iS(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 lS({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:o}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>sS(i||960),[i]),d=v.useMemo(()=>aS(i||960,c),[i,c]),u=v.useMemo(()=>iS(e,c),[e,c]);v.useEffect(()=>{const m=a.current;if(!m)return;const h=()=>l(m.clientWidth);h();const b=new ResizeObserver(h);return b.observe(m),()=>b.disconnect()},[]);const p=rS({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?oS:d,overscan:6});return v.useEffect(()=>{if(!t)return;const m=u.findIndex(h=>h.type==="items"&&h.items.some(b=>Pe(b)===t));m>=0&&p.scrollToIndex(m,{align:"center"})},[u,t,p]),s.jsx("div",{ref:a,className:"gallery__virtual",style:{height:p.getTotalSize()},children:p.getVirtualItems().map(m=>{const h=u[m.index];return h?s.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${m.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((b,I)=>o(b,h.id,I))})},h.id):null})})}function Si({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 cS({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 dS({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 wi="ima2.storageNoticeDismissed.0.09.23";function uS(e){const t=v.useRef(null),n=v.useRef(new Map),[r,o]=v.useState(()=>new Set);v.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 u=new Set(d);for(const p of c){const m=p.target.dataset.galleryLazyKey;m&&u.add(m)}return u})},{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=v.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 mS(){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),u=f(R=>R.galleryScope),p=f(R=>R.setGalleryScope),m=f(R=>R.historyNextCursor),h=f(R=>R.historyLoadingOlder),b=f(R=>R.favoriteHistoryNextCursor),I=f(R=>R.favoriteHistoryLoadingOlder),x=f(R=>R.loadOlderHistory),y=f(R=>R.loadFavoriteHistory),g=f(R=>R.loadOlderFavoriteHistory),_=f(hp),[w,S]=v.useState(""),[N,P]=v.useState("date"),[L,U]=v.useState(!1),[j,z]=v.useState(()=>new Set),q=v.useRef(new Set),[C,k]=v.useState([]),[A,B]=v.useState([]),[se,oe]=v.useState(!1),[ae,he]=v.useState(!1),[F,O]=v.useState(!1),[ee,J]=v.useState(0),[me,ge]=v.useState(null),[ie,Ee]=v.useState(()=>{try{return localStorage.getItem(wi)==="1"}catch{return!1}}),le=v.useRef(null),Ie=v.useRef({}),[Ce,Re]=v.useState(null),ce=v.useRef(0),be=v.useRef({open:!1,selectedKey:null}),D=v.useMemo(()=>Ir(o.filter(vn)),[o]),ye=v.useCallback(R=>{le.current=R,Re(R)},[]),T=uS(Ce),ne=Ve(n,r);v.useEffect(()=>{n||S("")},[n]),v.useEffect(()=>{if(!n)return;let R=!1;return(async()=>{try{const Y=await lu();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]),v.useEffect(()=>{if(!n||N!=="session")return;let R=!1;return k([]),B([]),oe(!0),he(!1),O(!1),(async()=>{try{const Y=await au({limit:500,sessionId:u==="current-session"?_:void 0});if(R)return;O(Y.nextCursor!==null||Y.total>=500);const we=H=>{const pe=H.kind,at=pe==="classic"||pe==="edit"||pe==="generate"||pe==="card-news-card"||pe==="card-news-set"?pe:null,aa=H.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(H.filename??"");return{image:H.url,url:H.url,filename:H.filename,thumb:H.thumb??(aa?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:Ir(H.items.filter(vn).map(we))})).filter(H=>H.items.length>0)),B(Ir(Y.loose.filter(vn).map(we)))}catch{R||he(!0)}finally{R||oe(!1)}})(),()=>{R=!0}},[n,N,u,_,ee]),v.useEffect(()=>{!n||N==="session"||!L||y()},[n,N,L,y]);const de=v.useMemo(()=>{const R=w.trim().toLowerCase().normalize("NFC");return D.filter(Y=>L&&!Y.isFavorite?!1:R?(Y.prompt??"").toLowerCase().normalize("NFC").includes(R)||(Y.filename??"").toLowerCase().normalize("NFC").includes(R):!0)},[D,w,L]),K=v.useMemo(()=>L?C.map(R=>({...R,items:R.items.filter(Y=>Y.isFavorite)})).filter(R=>R.items.length>0):C,[C,L]),G=v.useMemo(()=>L?A.filter(R=>R.isFavorite):A,[A,L]),X=v.useMemo(()=>{const R=new Map;for(const Y of de){const we=kI(Y.createdAt,t);R.has(we)||R.set(we,[]),R.get(we).push(Y)}return Array.from(R.entries())},[de,t]),re=N==="session"?K.reduce((R,Y)=>R+Y.items.length,0)+G.length:de.length;v.useLayoutEffect(()=>{const R=i?Pe(i):null;if(!n){be.current={open:!1,selectedKey:R};return}const Y=be.current,we=!Y.open||Y.selectedKey!==R;be.current={open:!0,selectedKey:R};const H=R?Ie.current[R]:null;if(we&&H){H.scrollIntoView({block:"center"});return}le.current&&(le.current.scrollTop=ce.current)},[n,i?.filename,i?.image,N,re,X.length,K.length,G.length]);async function Le(R,Y){Y.stopPropagation();const we=Pe(R);await l(R),delete Ie.current[we],window.requestAnimationFrame(()=>le.current?.focus())}async function Ge(R){const Y=R.filename;if(!(!Y||q.current.has(Y))){q.current.add(Y),z(new Set(q.current));try{const we=await d(R);if(we===null)return;k(H=>H.map(pe=>({...pe,items:pe.items.map(at=>at.filename===Y?{...at,isFavorite:we}:at)}))),B(H=>H.map(pe=>pe.filename===Y?{...pe,isFavorite:we}:pe))}finally{q.current.delete(Y),z(new Set(q.current))}}}async function Ot(){try{await cu(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ke,handleCopyCardNewsSetPath:dt,handleDownloadCardNewsManifest:ut}=CI(r,c,e);function vt(){Ee(!0);try{localStorage.setItem(wi,"1")}catch{}}if(!n)return null;const E=R=>R==="earlier"||R==="today"||R==="yesterday"||R==="thisWeek"?e(`gallery.${R}`):R,W=(R,Y,we)=>{const H=i?.image===R.image,pe=Pe(R),at=Ft=>{Ie.current[pe]=Ft,T.register(pe,Ft)};return(T.supported?T.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(PI,{item:R,onOpen:Ft=>{Ke(Ft)},onCopyPath:dt,onDownloadManifest:ut})},`${Y}-${pe}`):s.jsx(zI,{item:R,active:H,itemRef:at,onSelect:Ft=>{a(Ft),r()},onDelete:Le,onToggleFavorite:Ge,favoriteBusy:!!(R.filename&&j.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",Se=i?Pe(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}),w||L?e("gallery.totalFiltered",{n:D.length}):""]}),s.jsx(Ro,{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(Ro,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:N,onChange:P,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),s.jsx(Ro,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:u,onChange:p,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:w,onChange:R=>S(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(dS,{status:me,dismissed:ie,onOpenFolder:Ot,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:[F?s.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,s.jsx(cS,{groups:K,loose:G,favoritesOnly:L,galleryScope:u,setGalleryScope:p,renderTile:W,t:e}),s.jsx(Si,{showSessions:Q,favoritesOnly:L,query:w,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):de.length===0?s.jsx("div",{className:"gallery__empty",children:D.length===0?e("gallery.emptyAll"):e(L?"gallery.emptyFavorites":"gallery.noResults")}):s.jsxs(s.Fragment,{children:[s.jsx(lS,{dateGroups:X,selectedKey:Se,scrollElement:Ce,localizeBucket:E,renderTile:W}),s.jsx(Si,{showSessions:Q,favoritesOnly:L,query:w,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function pS(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 fS(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=V(),o=Ve(!!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(pS(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 hS(){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=Ve(!!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 gS=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Ct(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Ht(e){return!e||typeof e!="object"||Array.isArray(e)?Ct():e}function Qo(e){return typeof e!="string"||!e.trim()?Ct():e}function _d(e){return e===void 0?{}:typeof e!="boolean"?Ct():{executable:e}}function yS(e){const t=Ht(e),n=Ht(t.status);return typeof t.enabled!="boolean"||!gS.has(n.state)?Ct():{id:Qo(t.id),enabled:t.enabled,..._d(t.executable),status:{state:n.state}}}function _i(e){return Array.isArray(e)?e.map(t=>{const n=Ht(t);return{id:Qo(n.id),label:Qo(n.label),..._d(n.executable)}}):Ct()}function Ei(e,t){const n=Ht(e);if(n.ok!==!0||!Array.isArray(n.providers))return Ct();const r=n.providers.map(yS);if(t===null)return{providers:r,catalog:null};const o=Ht(t),a=Ht(o.models);return o.ok!==!0?Ct():{providers:r,catalog:{image:_i(a.image),video:_i(a.video)}}}function vS(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 bS(){const{t:e}=V(),t=f(u=>u.mcpProvider??""),n=f(u=>u.mcpModel??null),r=f(u=>u.mcpMediaKind??"image"),[o,a]=v.useState(0),[i,l]=v.useState({selection:{provider:t,model:n,kind:r},phase:"loading",observedAt:null,providers:[],catalog:null});if(v.useEffect(()=>{const u=new AbortController,p={provider:t,model:n,kind:r};return l({selection:p,phase:"loading",observedAt:null,providers:[],catalog:null}),t&&(async()=>{try{const h=await Bh(u.signal),I=Ei(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Wh(t,u.signal):null,y=Ei(h,x);u.signal.aborted||l({...y,selection:p,phase:"ready",observedAt:Date.now()})}catch{u.signal.aborted||l({selection:p,phase:"error",observedAt:null,providers:[],catalog:null})}})(),()=>u.abort()},[t,n,r,o]),!t)return null;const c=vS(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(u=>u+1),children:e("readiness.mcp.refresh")})]})}const Ni={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 xS(){const{t:e}=V(),t=f(S=>S.readinessPopupOpen),n=f(S=>S.closeReadinessPopup),r=f(S=>S.openSettings),o=f(S=>S.provider),a=f(S=>S.mcpProvider??null),i=f(S=>S.imageModel),l=f(S=>S.reasoningEffort),c=f(S=>S.webSearchEnabled),d=f(S=>S.comfyWorkflow),u=f(S=>S.comfyVideoWorkflow),p=yd(),m=Vn(),h=o==="grok",b=et.find(S=>S.value===i),I=Ve(t,n);if(!t)return null;const x=p[o],y=kt(m,{comfyWorkflow:d,comfyVideoWorkflow:u}),g=o==="comfy"&&!a,_=g?y.selectedAvailable:x.ok,w=()=>{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:S=>S.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(bS,{}):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?Bt(y,m):_?"readiness.ready":"readiness.blocked")}),s.jsx("small",{children:g?e("comfy.display.controlsHelp"):_?e("readiness.readyBody"):x.reason})]}),!g&&x.hint?s.jsx("p",{className:"modal__hint",children:x.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:Ni.comfy})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.workflowsTitle")}),s.jsx("dd",{children:y.selected?.label??e("comfy.display.chooseWorkflow")})]}),y.selected?s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colId")}),s.jsx("dd",{children:y.selected.id})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colKind")}),s.jsx("dd",{children:e(y.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage")})]})]}):null,m.observedAt!==null?s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colStatus")}),s.jsx("dd",{children:e("comfy.display.lastChecked",{time:new Date(m.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:Ni[o]??"GPT API"})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.model")}),s.jsx("dd",{children:b?e(b.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:w,children:e(g?"comfy.display.manage":"readiness.openAccount")})]})]})})}const ki="ima2.onboardingDismissed";function IS(){const{t:e}=V(),t=f(x=>x.openSettings),n=fd(),r=hd(),{data:o}=gd(),[a,i]=v.useState(()=>{try{return localStorage.getItem(ki)==="1"}catch{return!1}}),l=n!==null&&r!==null&&o!=null,c=n?.status==="auth_required"||n?.status==="offline",d=r?.status==="offline"||r?.status==="error",u=o?!o.gemini?.configured&&!o.vertex?.configured:!1,m=!a&&(l&&c&&d&&u),h=()=>{try{localStorage.setItem(ki,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=Ve(m,h);return m?s.jsx("div",{className:"modal-backdrop",role:"presentation",children:s.jsxs("div",{ref:I,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[s.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),s.jsx("div",{className:"modal__body",children:s.jsx("p",{children:e("onboarding.body")})}),s.jsxs("div",{className:"modal__actions",children:[s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:h,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),s.jsx("button",{type:"button",className:"modal__btn",onClick:b,children:e("onboarding.login")})]})]})}):null}function SS(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=V(),[o,a]=v.useState(Date.now());return v.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 _S(){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 zr=null;function ES(e){zr=e}function NS(){const e=zr;zr=null,e?.isConnected&&e.focus()}function Ci(){zr=null}function kS(){const{t:e}=V(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),o=r==="agent"&&Qt?"agent":r==="node"&&Zt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=yt(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&ES(p.current),t(u==="library"?"library":u==="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("div",{className:"logo-mark","aria-hidden":"true"}),s.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[s.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),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(ld,{compact:!0})})]})}const CS={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},ji={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function jS(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=CS[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function TS(){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 PS(){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 AS(){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 RS(){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 MS(){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 LS(){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 OS(){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 FS=[{id:"home",mode:"home",icon:PS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:TS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:AS,labelKey:"nav.node",enabled:Zt},{id:"agent",mode:"agent",icon:RS,labelKey:"nav.agent",enabled:Qt},{id:"assets",mode:"assets",icon:LS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:OS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:MS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function DS(){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=v.useRef(null),c=v.useCallback(I=>{const x=l.current;if(!x||!I)return;const y=x.getBoundingClientRect(),g=I.getBoundingClientRect();g.left<y.left?x.scrollLeft-=y.left-g.left:g.right>y.right&&(x.scrollLeft+=g.right-y.right)},[]);v.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=v.useCallback(I=>{if(I.settingsAction){r?(a(),history.replaceState(null,"",ji[t]||"#create")):(o(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",ji[I.mode]||"#create"))},[t,r,n,o,a]);v.useEffect(()=>{const I=()=>{const x=jS();x&&(x.settings?o():(r&&a(),n(x.mode)))};return I(),window.addEventListener("popstate",I),window.addEventListener("hashchange",I),()=>{window.removeEventListener("popstate",I),window.removeEventListener("hashchange",I)}},[]);const u=FS.filter(I=>I.enabled),p=u.filter(I=>!I.bottom),m=u.filter(I=>I.bottom),h=I=>I.settingsAction?r:!r&&I.mode===t,b=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:u.map(b)}):s.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[s.jsx("div",{className:"nav-rail__top",children:p.map(b)}),s.jsx("div",{className:"nav-rail__bottom",children:m.map(b)})]})}const GS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-CGcqRRsJ.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Be=["prompt","controls","library"],ur="mobile-inflight-panel",mr=e=>`mobile-sheet-tab-${e}`,pr=e=>`mobile-sheet-panel-${e}`;function zS(){const{t:e}=V(),t=f(S=>S.composeSheetOpen),n=f(S=>S.composeSheetTab),r=f(S=>S.setComposeSheetTab),o=f(S=>S.closeComposeSheet),a=f(S=>S.inFlight.length),i=f(S=>S.settingsOpen),l=f(S=>S.uiMode),c=l==="agent"&&Qt?"agent":l==="node"&&Zt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=yt(),[u,p]=v.useState(!1),m=v.useRef(a),h=v.useRef(!1),b=v.useRef(null),I=v.useRef({}),x=v.useRef(!1),y=S=>{r(S),requestAnimationFrame(()=>I.current[S]?.focus())},g=(S,N)=>{const P=Be.indexOf(N),L=S.key==="ArrowRight"?Be[(P+1)%Be.length]:S.key==="ArrowLeft"?Be[(P-1+Be.length)%Be.length]:S.key==="Home"?Be[0]:S.key==="End"?Be[Be.length-1]:null;L&&(S.preventDefault(),y(L))},_=Ve(t,o,{autoFocus:!1});v.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&p(!1)},[t,n,o,d,i,c]),v.useLayoutEffect(()=>{const S=m.current>0&&a===0;m.current=a,S&&(p(!1),h.current&&b.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),v.useLayoutEffect(()=>{if(t){x.current=!0;const S=requestAnimationFrame(()=>I.current[n]?.focus());return()=>cancelAnimationFrame(S)}x.current&&(x.current=!1,NS())},[t,n]);const w=d&&!i&&c==="classic";return v.useEffect(()=>{w||(x.current=!1,f.getState().composeSheetOpen&&o(),Ci())},[w]),v.useEffect(()=>()=>Ci(),[]),w?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:Be.map(S=>s.jsx("button",{ref:N=>{I.current[S]=N},id:mr(S),type:"button",role:"tab","aria-selected":n===S,"aria-controls":pr(S),tabIndex:n===S?0:-1,className:`mobile-sheet-tabs__button${n===S?" active":""}`,onClick:()=>r(S),onKeyDown:N=>g(N,S),children:e(`sheet.tabs.${S}`)},S))}),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:S=>{const N=document.getElementById(ur);h.current=N?.contains(S.target)??!1},children:n==="prompt"?s.jsxs(s.Fragment,{children:[s.jsx(Xs,{}),a>0?s.jsxs("section",{className:"compose-sheet__inflight",hidden:!u,children:[s.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{b.current?.querySelector(".inflight-badge")?.focus(),p(!1)},"aria-expanded":u,"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(Qs,{variant:"inline",panelId:ur}),s.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,s.jsxs("div",{ref:b,className:"compose-sheet__actions",children:[s.jsx(Zs,{}),s.jsx(sd,{variant:"inline",panelId:ur,expanded:u,onToggle:p})]})]}):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(Id,{}):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(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:s.jsx(GS,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const qS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function $S(){const e=f(r=>r.uiMode),t=f(r=>!!r.currentImage||!!r.multimodePreviewFlightId),n=f(r=>r.selectHistoryShortcutTarget);v.useEffect(()=>{if(e!=="classic")return;const r=o=>{const a=qS[o.key];a&&(o.defaultPrevented||Sr(o.target)||t&&(o.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const fr=64,Ed="Image Gen";let oa=Ed,es=!1,ht=null,sa="",ts=!1;function Nd(){return navigator}function kd(){if(typeof document>"u")return null;if(ht)return ht;const e=document.querySelector('link[rel~="icon"]');if(e)return ht=e,sa=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),ht=t,ts=!0,t}function US(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="#0a0a0a",HS(n,6,6,52,52,12),n.fill(),n.strokeStyle="#ffffff",n.lineWidth=5,n.beginPath(),n.arc(30,32,14,0,Math.PI*2),n.stroke(),n.fillStyle="#ffffff",n.beginPath(),n.arc(30,32,5,0,Math.PI*2),n.fill(),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")):sa}function HS(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 VS(e){const t=Nd();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function KS(){const e=Nd();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function BS(e){document.title=`(${e}) ${oa}`;const t=kd();t&&(t.href=US(e)),VS(e)}function Ti(){document.title=oa,ht&&(ts?(ht.remove(),ht=null,ts=!1):ht.href=sa),KS()}function Pi(){es||typeof document>"u"||(es=!0,oa=document.title||Ed,kd())}function WS(e){v.useEffect(()=>(Pi(),()=>{es&&Ti()}),[]),v.useEffect(()=>{Pi(),e>0?BS(e):Ti()},[e])}function JS(){v.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 YS=v.lazy(()=>Me(()=>import("./NodeCanvas-B1R-fOYq.js"),__vite__mapDeps([8,1,2,7,9,10,11])).then(e=>({default:e.NodeCanvas}))),XS=v.lazy(()=>Me(()=>import("./SettingsWorkspace-BhbAnrYw.js"),__vite__mapDeps([12,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),ZS=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-BfR-FMwo.js"),__vite__mapDeps([13,1,2])).then(e=>({default:e.CardNewsWorkspace}))),QS=v.lazy(()=>Me(()=>import("./AgentWorkspace-CxbtxZYs.js"),__vite__mapDeps([14,1,2,10])).then(e=>({default:e.AgentWorkspace}))),ew=v.lazy(()=>Me(()=>import("./AssetsWorkspace-BuiwpbQQ.js"),__vite__mapDeps([15,1,2,9,10,16,17])).then(e=>({default:e.AssetsWorkspace}))),tw=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-BIYh26wL.js").then(e=>e.A),__vite__mapDeps([18,1,2,9,10,16,19])).then(e=>({default:e.AssetGenWorkspace}))),nw=v.lazy(()=>Me(()=>import("./HomeWorkspace-x-oJypd7.js"),__vite__mapDeps([20,1,2])).then(e=>({default:e.HomeWorkspace}))),rw=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-CGcqRRsJ.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function ow(){return s.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function sw(){$S(),JS();const{locale:e}=V(),t=f(S=>S.hydrateHistory),n=f(S=>S.loadSessions),r=f(S=>S.syncCapabilities),o=f(S=>S.startInFlightPolling),a=f(S=>S.reconcileInflight),i=f(S=>S.syncFromStorage),l=f(S=>S.settingsOpen),c=f(S=>S.unseenGeneratedCount),d=f(S=>S.historyStripLayout),u=f(S=>S.workspaceProfile),p=f(S=>S.uiMode),m=p==="agent"&&Qt?"agent":p==="node"&&Zt?"node":p==="home"?"home":p==="assets"?"assets":p==="asset-gen"?"asset-gen":"classic",h=m==="agent",b=m==="assets",I=m==="asset-gen",x=m==="home",y=yt(),g=Gn(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",w=!_&&!h&&!b&&!I&&!x;return WS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!ue())return r(),t(),n(),a(),o(),Tt(),pa(()=>a()),fa(S=>{S==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{kn(),pa(()=>{}),fa(()=>{})}},[t,n,a,o,r]),v.useEffect(()=>{const S=N=>{const P=N.detail?.assetId;P&&f.getState().openAssetDetail(P)};return window.addEventListener("ima2:open-assets-detail",S),()=>window.removeEventListener("ima2:open-assets-detail",S)},[]),v.useEffect(()=>{const S=N=>{N.key&&(N.key==="ima2.inFlight"||N.key==="ima2.selectedFilename"||N.key===ys||N.key===gs||N.key===bs)&&i()};return window.addEventListener("storage",S),()=>window.removeEventListener("storage",S)},[i]),v.useEffect(()=>{const S=()=>{fp(f.getState)};return window.addEventListener("beforeunload",S),()=>{window.removeEventListener("beforeunload",S)}},[]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`app${u==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${w&&d==="horizontal"?" app--history-horizontal":""}${w&&d==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":d,"data-mobile":y?"1":void 0,"data-ui-mode":m,children:[s.jsx(DS,{}),x?null:s.jsx(Ib,{}),s.jsx(kS,{}),w?s.jsx(_I,{}):null,s.jsx(v.Suspense,{fallback:s.jsx(ow,{}),children:l?s.jsx(XS,{}):m==="classic"?_?s.jsx(fx,{}):s.jsx(Zo,{}):m==="node"?s.jsx(YS,{}):m==="card-news"?s.jsx(ZS,{}):m==="agent"?s.jsx(QS,{}):m==="assets"?s.jsx(ew,{}):m==="asset-gen"?s.jsx(tw,{}):m==="home"?s.jsx(nw,{}):s.jsx(Zo,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:s.jsx(vI,{})]}),s.jsx(fS,{}),s.jsx(SS,{}),s.jsx(EI,{}),s.jsx(NI,{}),s.jsx(mS,{}),s.jsx(hS,{}),s.jsx(xS,{}),s.jsx(IS,{}),s.jsx(zS,{}),s.jsx(_S,{}),m==="card-news"?s.jsx(v.Suspense,{fallback:null,children:s.jsx(rw,{})}):null]})}const Bw=Object.freeze(Object.defineProperty({__proto__:null,default:sw},Symbol.toStringTag,{value:"Module"}));export{Nu as $,Gu as A,Mu as B,Fe as C,Vc as D,Ow as E,Fw as F,Ru as G,Dw as H,et as I,Gw as J,Uw as K,ta as L,zw as M,qw as N,Au as O,$w as P,_e as Q,zo as R,gv as S,bI as T,Aw as U,Uu as V,yv as W,tm as X,ot as Y,Xy as Z,Mw as _,f as a,Cw as a0,Lp as a1,rS as a2,ed as a3,Hw as a4,Kw as a5,Vw as a6,Pw as a7,Lw as a8,rx as a9,Sr as aA,gw as aB,pw as aC,iw as aD,yw as aE,mw as aF,Cb as aG,uw as aH,sx as aI,Ri as aJ,M as aK,lw as aL,dw as aM,cw as aN,xw as aO,vw as aP,Iw as aQ,Sw as aR,bw as aS,ww as aT,_w as aU,Ew as aV,Nw as aW,kw as aX,Bw as aY,as as aa,cc as ab,TI as ac,Qs as ad,Tw as ae,jt as af,jw as ag,to as ah,Ys as ai,Qc as aj,kv as ak,Pe as al,yd as am,TS as an,AS as ao,Zt as ap,RS as aq,Qt as ar,LS as as,ji as at,Yy as au,Qb as av,ox as aw,Jo as ax,hw as ay,fw as az,OI as b,wp as c,De as d,Nt as e,Zu as f,Bi as g,Rw as h,Ze as i,lc as j,Ve as k,Op as l,_u as m,Ip as n,$ as o,yt as p,Vl as q,so as r,Ne as s,Oe as t,V as u,fd as v,sp as w,hd as x,Cx as y,gd as z};
4
+ `)}function Cm(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(Cm);return t.every(n=>n!==null)?t:null}function Es(e){return e.map(t=>({id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}))}function jm(e){const t=Mn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function Tm(){try{const e=localStorage.getItem(tl);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function Am(){try{const e=localStorage.getItem(nl);if(e==="agent")return Qt?e:"classic";if(e==="card-news")return ul?e:"classic";if(e==="node")return Zt?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function Pm(){try{const e=localStorage.getItem(rl);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function Aa(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function Pa(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(ol);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 Nl(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(ol,JSON.stringify({mode:e,matteColor:t}))}catch{}}function kl(e){try{localStorage.setItem(gs,e)}catch{}}function Rm(){try{const e=localStorage.getItem(sl);if(el(e))return e}catch{}return Xu}function Mm(e){try{localStorage.setItem(sl,e)}catch{}}function Lm(){try{const e=localStorage.getItem(cl);return e?xl(JSON.parse(e)):{}}catch{return{}}}function Cl(e){try{localStorage.setItem(cl,JSON.stringify(e))}catch{}}function Om(){try{const e=localStorage.getItem(al);if(e==="false")return!1;if(e==="true")return!0}catch{}return em}function Fm(e){try{localStorage.setItem(al,String(e))}catch{}}const Ra={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function Jr(){try{const e=localStorage.getItem(bs);if(!e)return Ra;const t=JSON.parse(e);return{model:Rt(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 Ra}}function fn(e){try{const t=Jr();localStorage.setItem(bs,JSON.stringify({...t,...e}))}catch{}}function jl(){try{const e=localStorage.getItem(qo);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function st(e){try{e?localStorage.setItem(qo,e):localStorage.removeItem(qo)}catch{}}function Dm(){try{const e=localStorage.getItem($o);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function Ns(e){try{e?localStorage.setItem($o,e):localStorage.removeItem($o)}catch{}}function Gm(e,t){return`${e}x${t}`}function In(e){return Uo(e)}const Tl=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(Tl.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 Al(e){return e==="low"||e==="medium"||e==="high"||e==="xhigh"||e==="max"}function Pl(e){return e==="png"||e==="jpeg"||e==="webp"}function Rl(e){return e==="low"||e==="auto"}function qm(e){return At(e)}function $m(e){return e==="auto"||e==="direct"}function Um(e){return typeof e=="string"&&Tl.has(e)}function en(){try{const e=localStorage.getItem(ys);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=Br(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=Wr(t.mcpParameters)),"imageToolModel"in t&&(n.imageToolModel=t.provider==="api"&&us(t.imageToolModel)?t.imageToolModel:null),Al(t.quality)&&(n.quality=Pt(t.provider,n.imageToolModel,t.quality)),Um(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)),Pl(t.format)&&(n.format=t.format),Rl(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=In(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=In(t.multimodeMaxImages)),$m(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 Hm(){return Em(en())}function Ln(e,t,n="image"){te({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function te(e){try{const t=en();localStorage.setItem(ys,JSON.stringify({...t,...e}))}catch{}}function Ml(){const e=localStorage.getItem(dl);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ll(){try{const e=Ml();return e?.version===1?Go(e.lanes):{}}catch{return{}}}function Vm(e){try{let t=null;try{t=Ml()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Go(t.lanes):{},...Go(e)};localStorage.setItem(dl,JSON.stringify({version:1,lanes:r}))}catch{}}function Ol(){const e=en(),t=Jr();let n=null;try{n=localStorage.getItem(gs)}catch{}return lt({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Km(e){kl(e.imageModel),fn({model:e.videoModelSelected}),te({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Bm(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 Fl(e){return e.filter(t=>t.selected).map(t=>t.id)}function Sn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function Wm(e,t,n,r){const o=new Set(Bm(e,t,n));if(!o.size)return e;if(!r)return Sn(e,o);const a=e.find(c=>c.id===n),i=e.some(c=>o.has(c.id)&&c.selected),l=new Set(Fl(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of o)l.add(c);return Sn(e,l)}const Jm={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Ma=16777216;function La(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>Ma){const i=Math.sqrt(Ma/(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 mo(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 ks(e,t={}){const n={...Jm,...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}=La(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 u=await mo(l,"image/png"),p=await Jn(u);if(Yn(p)>n.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return p}for(const u of n.qualityLadder){const p=await mo(l,"image/jpeg",u),m=await Jn(p);if(Yn(m)<=n.maxB64Bytes)return m}const d=La(a,i,2048);l.width=d.w,l.height=d.h,c.drawImage(o,0,0,d.w,d.h);for(const u of[.7,.5,.35]){const p=await mo(l,"image/jpeg",u),m=await Jn(p);if(Yn(m)<=n.maxB64Bytes)return m}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{o.close?.()}}function jr(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 Dl(e){return(e.type||"").toLowerCase()==="image/png"}const Gl=18e4;function Ym(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)wn(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function wn(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 zl(e){const t=await Promise.all(e.map(n=>Di({kind:n.kind,sessionId:n.sessionId,includeTerminal:!0})));return{jobs:t.flatMap(n=>n.jobs),terminalJobs:t.flatMap(n=>n.terminalJobs??[])}}function Tr(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:Bo(e.kind)??Bo(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 Xm(e){const t=typeof e.errorCode=="string"&&e.errorCode?e.errorCode:"UNKNOWN",n=new Error(t==="JOB_TRACKING_TIMEOUT"?Gi: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 tn(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Oa(e){return e.filename||e.image}function Fa(e,t){const n=new Map(e.map(r=>[Oa(r),r]));for(const r of t)n.set(Oa(r),r);return[...n.values()].sort((r,o)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(o.sequenceIndex??Number.MAX_SAFE_INTEGER))}function ql({includeExpired:e=!1}={}){try{const t=localStorage.getItem(il);if(!t)return[];const n=JSON.parse(t);if(!Array.isArray(n))return[];const r=Date.now();return n.filter(o=>o&&typeof o.id=="string"&&typeof o.prompt=="string"&&typeof o.startedAt=="number"&&(e||r-o.startedAt<Gl)).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:Bo(o.kind)}))}catch{return[]}}function Bo(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 $e=500,Cs=5;function Zm(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?Es(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:Zm(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 $l(e,t){const n=qe(t);return e.filter(r=>qe(r)!==n)}function Ul(e,t){const n=qe(t);return e.find(r=>qe(r)===n)}function Hl(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 Vl(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 Yr(e,t){return e.slice(0,Math.max($e,t))}function js(e){return e.replace(/^data:[^;]+;base64,/,"")}async function Fn(e,t="reference.png"){const n=await Ne(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 ks(o,{preserveTransparency:!1})}function Qm(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(il,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function ep(e){return bm(e.naiServerDefaults,e.naiOptionOverrides)}function Xr(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=Is(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 tp(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):Cs}async function np(e){try{const t=await Fi();e({referenceLimit:tp(t.limits?.maxRefCount),naiServerDefaults:xl(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 rp(e){const t=await Ne(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 op(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 sp(e){return e?.type==="elementReferenceNode"||e?.data?.nodeType==="element-reference"}function Kl(e,t){const n=new Map(e.map(r=>[r.id,r]));return t.filter(r=>!sp(n.get(r.source)))}function Bl(e,t,n){return Kl(e,t).filter(r=>r.target===n)}function ap(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 Ow(e,t){const n=new Map,r=new Map;for(const i of e)n.set(i.id,0);for(const i of t){n.set(i.target,(n.get(i.target)??0)+1);const l=r.get(i.source)??[];l.push(i.target),r.set(i.source,l)}const o=e.filter(i=>(n.get(i.id)??0)===0).map(i=>i.id);let a=0;for(let i=0;i<o.length;i++){a+=1;for(const l of r.get(o[i])??[]){const c=(n.get(l)??0)-1;n.set(l,c),c===0&&o.push(l)}}return a<e.length}function De(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const o=Bl(e,t,r.id),i=(o[0]?n.get(o[0].source):null)?.data.serverNodeId??null,l=new Set(i?[i]:[]),c=[];for(const p of o.slice(1)){const m=n.get(p.source)?.data.serverNodeId;!m||l.has(m)||(l.add(m),c.push(m))}const d=r.data.extraParentServerNodeIds??[];return r.data.parentServerNodeId===i&&d.length===c.length&&d.every((p,m)=>p===c[m])?r:{...r,data:{...r.data,parentServerNodeId:i,extraParentServerNodeIds:c}}})}const Wl="ima2.nodeRefs.v1";function As(){try{const e=localStorage.getItem(Wl);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Jl(e){try{localStorage.setItem(Wl,JSON.stringify(e))}catch{}}function ip(e,t){if(!e)return[];const n=As()[e]?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function Zr(e,t,n){if(!e)return;const r=As(),o={...r[e]??{}};n.length===0?delete o[t]:o[t]=n,r[e]=o,Jl(r)}function Ps(e,t){Zr(e,t,[])}function lp(e,t){if(!e)return;const n=As(),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,Jl(n)}const cp=/\.(mp4|webm|mov)$/i;function Ze(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return cp.test(t)||e.startsWith("data:video/")}function xe(e){return e?e.mediaType==="video"?!0:Ze(e.filename)||Ze(e.url)||Ze(e.image):!1}const dp=15e3;function Rs(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",u),a.onloadedmetadata=null,a.onseeked=null,a.onerror=null,a.src="",a.load()},d=p=>{i||(i=!0,c(),p())};function u(){d(()=>o(Object.assign(new Error("frame extraction aborted"),{code:"VIDEO_FRAME_EXTRACT_ABORTED"})))}if(n.signal?.aborted){u();return}n.signal?.addEventListener("abort",u),l=setTimeout(()=>{d(()=>o(new Error("frame extraction timed out")))},dp),a.onloadedmetadata=()=>{const p=a.duration;if(!Number.isFinite(p)||p<=0){d(()=>o(new Error("video duration is unavailable")));return}a.currentTime=Math.max(0,t(p))},a.onseeked=()=>{try{const p=document.createElement("canvas");p.width=a.videoWidth,p.height=a.videoHeight;const m=p.getContext("2d");if(!m){d(()=>o(new Error("canvas 2d context unavailable")));return}m.drawImage(a,0,0);const h=p.toDataURL("image/jpeg",.85);d(()=>r(h))}catch(p){d(()=>o(p))}},a.onerror=()=>{d(()=>o(new Error("Failed to load video for frame extraction")))},a.src=e})}function nn(e,t){return Rs(e,n=>n-.1,t)}function Yl(e,t){return Rs(e,n=>Math.min(n*.3,.4),t)}function Xl(e,t){return Rs(e,n=>n/2,t)}function Zl(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:ip(e.id,r.id),video:o.video??null};return{id:r.id,type:o.nodeType==="element-reference"?"elementReferenceNode":"imageNode",position:{x:r.x,y:r.y},data:c}}),n=e.edges.map(r=>{const o=r.data??{};return{id:r.id,source:r.source,target:r.target,sourceHandle:typeof o.sourceHandle=="string"?o.sourceHandle:null,targetHandle:typeof o.targetHandle=="string"?o.targetHandle:null}});return{graphNodes:De(t,n),graphEdges:n,graphVersion:e.graphVersion}}const up=800;let Ye=null,vr=!1,br=!1,It=null,Ql=0;function ec(){try{const e=sessionStorage.getItem(Sa);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(Sa,t),t}catch{return"tab_unavailable"}}function tc(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 nc(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 rc(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 Xt({sessionId:n,limit:$e})).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,p=(d?o.find(m=>(m.sessionId??null)===n&&(m.requestId??null)===d):null)??o.find(m=>(m.sessionId??null)===n&&(m.clientNodeId??null)===l.id&&(!c||(m.createdAt??0)>=c));return p?(a=!0,{...l,data:{...l.data,status:"ready",imageUrl:p.url,serverNodeId:p.nodeId??l.data.serverNodeId,size:p.size??l.data.size??null,elapsed:p.elapsed??l.data.elapsed,reasoningEffort:p.reasoningEffort??l.data.reasoningEffort,video:p.video??l.data.video??null,pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0}}):l});a&&(t({graphNodes:i}),sc(e,t,"recovery"))}async function mp(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await $i(n),{graphNodes:o,graphEdges:a,graphVersion:i}=Zl(r);t({graphNodes:o,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(M("toast.sessionReloadedElsewhere"),!0),await rc(e,t).catch(()=>{})}async function pp(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(p=>({id:p.id,x:p.position.x,y:p.position.y,data:tc(p.data)})),d=nc(i),u=`gs_${Date.now().toString(36)}_${++Ql}`;try{const p=await vu(r,o,c,d,{saveId:u,saveReason:n,tabId:ec()});return e().activeSessionId!==r?"skipped":(lp(r,e().graphNodes.map(m=>m.id)),t({activeSessionGraphVersion:p.graphVersion}),"saved")}catch(p){return p.status===409?(await mp(e,t),"conflict"):(console.warn("[sessions] save failed:",p),"failed")}}async function oc(e,t,n){return vr?(br=!0,It||"skipped"):(vr=!0,It=(async()=>{let r=n,o="skipped";do{if(br=!1,o=await pp(e,t,r),o==="conflict"||o==="failed")break;r="queued"}while(br);return o})().finally(()=>{vr=!1,It=null}),It)}function sc(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(Ye&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=null,oc(e,t,n)},up)))}async function fp(e,t,n="manual"){let r=!1;if(Ye&&(clearTimeout(Ye),Ye=null,r=!0),vr){if(br=!0,(It?await It:"skipped")==="failed")throw new Error(M("modal.graphSaveFailed"));return}if(r&&await oc(e,t,n)==="failed")throw new Error(M("modal.graphSaveFailed"))}function hp(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;Ye&&(clearTimeout(Ye),Ye=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:tc(i.data)})),r=nc(t.graphEdges),o=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{Ne(o,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++Ql}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":ec()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function gt(e,t,n,r={}){const o=xe(e)?void 0:await op(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=Ul(l.history,i),d=Hl(i,c),u=$l(l.history,d),p=Yr([d,...u],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:p,...h?{currentImage:d}:{},loadedHistoryRetainLimit:Math.max(l.loadedHistoryRetainLimit,Math.min(l.history.length+1,l.loadedHistoryRetainLimit+1)),unseenGeneratedCount:l.unseenGeneratedCount+1})}function gp(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const yp=30;function po(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function vp(e,t,n=yp){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function bp(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 xp(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 Ip=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function Da(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 Ip)l[c]=a.data[c];return{...o,data:l}}),edges:e.edges}}function Sp(e){return e.data.status==="ready"&&!!e.data.imageUrl}function wp(e,t,n){const r=new Set(n),o=new Set(e.map(p=>p.id)),a=new Map,i=new Map;for(const p of r)o.has(p)&&(a.set(p,0),i.set(p,[]));for(const p of t)!r.has(p.source)||!r.has(p.target)||(i.get(p.source)?.push(p.target),a.set(p.target,(a.get(p.target)??0)+1));const l=e.map(p=>p.id),c=l.filter(p=>r.has(p)&&(a.get(p)??0)===0),d=[];for(let p=0;p<c.length;p++){const m=c[p];d.push(m);for(const h of i.get(m)??[])a.set(h,(a.get(h)??0)-1),(a.get(h)??0)===0&&c.push(h)}const u=new Set(d);return d.concat(l.filter(p=>r.has(p)&&!u.has(p)))}function _p(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 Ep(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 Np(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 kp(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 u of i.get(l[d])??[]){const p=(a.get(u)??0)-1;a.set(u,p),p===0&&l.push(u)}}return[...a.keys()].filter(d=>!c.has(d))}function He(e,t){const{code:n,spec:r,message:o}=ot(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return Ri(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 Cp=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],jp=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function Tp(e){if(Cp.includes(e))return"auth";const t=We[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||jp.includes(e)?"retry":"fix-input"}function ac(e){const{code:t,message:n}=ot(e),r=Tp(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const Ap=Vi.grok.video,Pp=3;function Rp(e,t){return Vi[e]?.[t]}function ic(e){if(e.mcpProvider)return Pp;if(e.videoModelSelected)return Math.min(e.serverLimit,Ap);if(At(e.provider)&&!ds[e.provider].generate.references)return 0;const t=Rp(e.provider,"image");return t===void 0?e.serverLimit:Math.min(e.serverLimit,t)}function Ms(e,t={}){const n=t.provider??e.provider,r=t.imageModel??e.imageModel;if(n!=="nai")return{};const o={...e.naiOptionOverrides};Ho(r)||(delete o.straightAlpha,delete o.qualityPresetId),o.seed===null&&delete o.seed;const a=e.negativePrompt.trim();return{...o,...a?{negativePrompt:a}:{}}}const Ar=new Map;function rn(e,t){Ar.set(e,t)}function on(e){Ar.delete(e)}function lc(e){Ar.get(e)?.abort(),Ar.delete(e)}const Mp="element-source:",Lp=500;function Op(e){return`${Mp}${e}`}function Fw(e,t){const n=Op(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function cc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function Fp(e=as){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:Lp});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 dc(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function Dw(e){const t=e.filePath??(e.kind==="element"?cc(e)??"":""),n=dc(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 Ga=32,za="Image_",Dp=/@([\p{L}\p{N}_-]+)/gu,Gp=new Set([" "," ",`
5
+ `,"(","["]);function uc(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${za}${r}`);)r+=1;return{tag:`${za}${r}`,nextAttachmentOrdinal:r+1}}function zp(e,t){const n=new Set(t),r=e.slice(0,Ga)||"Element";if(!n.has(r))return r;let o=2;for(;;){const a=`_${o}`,i=`${r.slice(0,Ga-a.length)}${a}`;if(!n.has(i))return i;o+=1}}function Dn(e){return e.trayItems.filter(t=>t.kind==="attachment")}function mc(e){return e.trayItems.filter(t=>t.kind==="element")}function qp(e){return Dn(e).map(t=>t.source.dataUrl)}function $p(e){return mc(e).map(t=>t.source.elementId)}function Up(e){const t={trayItems:e};return{referenceImages:qp(t),selectedElementIds:$p(t)}}function Ls(e,t){return e.length<t}function Qr(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 Hp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Os(e,t){if(!Hp(e,t))return e;const n={...e};return delete n[t],n}function Vp(e){const t=[];for(const n of e.matchAll(Dp)){const r=n.index,o=r>0?e[r-1]:void 0;o!==void 0&&!Gp.has(o)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function Kp(e){return e.reduce((t,n)=>t+(n.kind==="attachment"?1:n.source.referenceFilenames.length),0)}function Fs(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:hc(a,l),...Up(a)}}),n}function Bp(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function pc(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 Wp(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function fc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function xr(e,t,n,r){return r&&(r.id!==e||r.kind!=="element")?null:Fs(t,(o,a)=>{if(!Ls(o.trayItems,a))return{result:null};if(o.trayItems.some(p=>p.kind==="element"&&p.source.elementId===e))return{result:null};const i=o,l=Wp(i,e,r),c=l?El(l.name):null;if(!l||!c)return{result:null};const d=zp(c,o.trayItems.map(p=>p.tag)),u={kind:"element",tokenId:crypto.randomUUID(),tag:d,insertedAt:Date.now(),source:{elementId:e,nameAtInsertion:l.name,referenceFilenames:fc(l)}};return{result:u,patch:{trayItems:[...o.trayItems,u],retiredTags:Os(o.retiredTags,d),elementCatalog:pc(i.elementCatalog,l)}}})}function hc(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 Wo(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function Jp(e,t,n){Fs(t,r=>{const o=Wo(r.trayItems,e);return o?{result:void 0,patch:{trayItems:r.trayItems.filter(a=>a.tokenId!==o.tokenId),retiredTags:Qr(r.retiredTags,[o])}}:{result:void 0}})}function gc(e,t,n){const r=Bp(e);t(o=>({elementCatalog:r,missingElementIds:hc(o.trayItems,r)}))}function yc(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 u=d.data;a.set(d.id,{nodeId:d.id,elementId:typeof u.elementId=="string"&&u.elementId?u.elementId:null,name:typeof u.elementName=="string"&&u.elementName||typeof u.elementId=="string"&&u.elementId||"element",missing:u.missing===!0})}}else i.push(d.id)}}}return[...a.values()]}const bt=new Set;async function Yp(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 Eu(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=pc(n().elementCatalog,c),u=c.updatedAt??c.createdAt;a.push(c.id),i[c.id]=u,typeof c.notes=="string"&&c.notes.trim()&&o.push(`${c.name}: ${c.notes.trim()}`),t({elementCatalog:d,graphNodes:n().graphNodes.map(p=>p.id===l.nodeId?{...p,data:{...p.data,resolvedRevision:u,missing:!1}}:p)});for(const p of fc(c))try{const m=await rp(dc(p));r.includes(m)||r.push(m)}catch{}}return{ok:!0,referenceDataUrls:r,notes:o,elementIds:a,revisions:i}}function Xp(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 Zp(e,t,n,r,o){if(bt.has(e))return null;bt.add(e);const a=r().graphNodes,i=De(a,r().graphEdges);i.some((q,C)=>q!==a[C])&&n({graphNodes:i});const l=i.find(q=>q.id===e);if(!l)return bt.delete(e),null;const c=yc(r().graphNodes,r().graphEdges,[e]),d=await Yp(c,n,r);if(d.ok===!1)return r().showToast(M("node.elementMissing",{name:d.name}),!0),bt.delete(e),null;const{prompt:u,parentServerNodeId:p}=l.data;if(!u.trim())return r().showToast(M("toast.promptRequired"),!0),bt.delete(e),null;const m=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:m.provider,b=ic({provider:h,serverLimit:m.referenceLimit,videoModelSelected:!!m.videoModelSelected,mcpProvider:m.mcpProvider??null}),I=Xp(l.data.referenceImages??[],d.referenceDataUrls,b),x=typeof l.data.model=="string"&&l.data.model?l.data.model:m.imageModel,y=t.sizeOverride??(typeof l.data.size=="string"&&l.data.size?l.data.size:m.getResolvedSize()),g=t.parentServerNodeIdOverride!==void 0?t.parentServerNodeIdOverride:p,_=(l.data.extraParentServerNodeIds??[]).filter(q=>q&&q!==g);if(Bl(i,r().graphEdges,e).length>0&&!g)return r().showToast(M("node.parentImageRequired"),!0),bt.delete(e),null;const S=m.activeSessionId,N=Date.now(),A=Math.random().toString(36).slice(2,6),L=`fn_${e}_${N}_${A}`,U=new AbortController;rn(L,U);const j=[...m.inFlight,{id:L,prompt:u,startedAt:N,kind:"node",sessionId:S,clientNodeId:e}];o(j),n({graphNodes:r().graphNodes.map(q=>q.id===e?{...q,data:{...q.data,status:"pending",pendingRequestId:L,recoveryRequestId:L,pendingPhase:"queued",pendingStartedAt:N,partialImageUrl:null,error:void 0,errorInfo:null,size:y}}:q),activeGenerations:m.activeGenerations+1,inFlight:j}),r().startInFlightPolling();let z=!0;try{const q=await Tu({parentNodeId:g,..._.length?{extraParentNodeIds:_}:{},prompt:u,quality:Pt(h,m.imageToolModel,m.quality),size:y,format:m.format,moderation:m.moderation,provider:h,model:x,...h==="api"&&m.imageToolModel?{imageToolModel:m.imageToolModel}:{},reasoningEffort:m.reasoningEffort,storyboard:m.storyboardActive||void 0,requestId:L,sessionId:S,clientNodeId:e,contextMode:"parent-plus-refs",searchMode:m.webSearchEnabled?"on":"off",webSearchEnabled:m.webSearchEnabled,...Ms(m,{provider:h,imageModel:x}),...I.length?{references:I.map(js)}:{},...d.elementIds.length?{elementIds:d.elementIds,elementRevisions:d.revisions,elementNotes:d.notes}:{}},{onPartial:C=>{r().activeSessionId===S&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"pending",partialImageUrl:C.image,pendingPhase:"partial"}}:k)})},onPhase:C=>{r().activeSessionId===S&&C.phase&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,pendingPhase:C.phase??k.data.pendingPhase}}:k)})}},{signal:U.signal});return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(C=>{if(C.id!==e)return C;const k={...C.data};return delete k.partialImageUrl,{...C,data:{...k,serverNodeId:q.nodeId,imageUrl:q.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:q.elapsed,reasoningEffort:q.reasoningEffort,webSearchCalls:q.webSearchCalls,model:q.model??null,imageToolModel:q.imageToolModel??null,size:q.size??null,errorInfo:null}}})}),z=!0,t.suppressToast||r().showToast(M("toast.nodeCreated",{id:q.nodeId.slice(0,8),elapsed:q.elapsed}))),q.nodeId}catch(q){if(tn(q))return r().activeSessionId===S&&(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)}),z=!0),null;const C=q instanceof Error?q.message:M("toast.nodeCreateFailed");return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:C,errorInfo:ac(q)}}:k)}),z=!0,He(q,r())),null}finally{bt.delete(e);const q=r().inFlight.filter(C=>C.id!==L);o(q),on(L),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:q}),r().activeSessionId===S&&z&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function Qp(e,t,n){if(n().nodeBatchRunning)return;const r=Fl(n().graphNodes).filter(x=>n().graphNodes.find(y=>y.id===x)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(M("nodeBatch.noneSelected"),!0);return}const o=Kl(n().graphNodes,n().graphEdges),a=Np(n().graphNodes,o,r);if(a.length>0){n().showToast(M("nodeBatch.parentRequired",{count:a.length}),!0);return}const i=kp(n().graphNodes,n().graphEdges,r);if(i.length>0){n().showToast(M("nodeBatch.cycleBlocked",{count:i.length}),!0);return}const l=wp(n().graphNodes,o,r),c=new Set(r),d=l.filter(x=>{if(e==="regenerate-all")return!0;const y=n().graphNodes.find(g=>g.id===x);return y?!Sp(y):!1});if(d.length===0){n().showToast(M("nodeBatch.nothingToRun"));return}const p=yc(n().graphNodes,n().graphEdges,d).find(x=>x.missing);if(p){n().showToast(M("node.elementMissing",{name:p.name}),!0);return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});let m=0,h=0,b=0;const I=new Set;try{for(const x of d){if(n().nodeBatchStopping)break;if(I.has(x)){b+=1;continue}const y=De(n().graphNodes,n().graphEdges);y.some((N,A)=>N!==n().graphNodes[A])&&t({graphNodes:y});const g=y.find(N=>N.id===x)?.data.parentServerNodeId??null;if(!(n().videoModelSelected?await n().runVideoGenerate(x).then(()=>n().graphNodes.find(A=>A.id===x)?.data.serverNodeId??null):await n().runGenerateNodeInPlace(x,{parentServerNodeIdOverride:g,suppressToast:!0}))){h+=1;for(const N of Ep(o,x))I.add(N);continue}m+=1;const w=new Set(_p(o,c)),S=n().graphNodes.map(N=>w.has(N.id)?{...N,data:{...N.data,status:"stale",error:M("nodeBatch.staleBecauseParentChanged")}}:N);t({graphNodes:De(S,n().graphEdges)})}h>0?n().showToast(M("nodeBatch.partialFinished",{done:m,failed:h,skipped:b,total:d.length}),!0):n().showToast(M("nodeBatch.finished",{done:m,total:d.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function Jo(e){return Array.isArray(e.images)}function ef(e,t){return e.modes.includes("both")||e.modes.includes(t)}function eo(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||!ef(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 tf=[{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"]}],nf=[{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"]}],rf=[{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"]}],vc=[...tf,...nf,...rf];function bc(e){return vc.find(t=>t.id===e)}function to(){return[...vc]}function xc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ic(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function of(e,t,n){const r=n();if(r.uiMode!=="classic")return;const o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=eo({catalog:to(),presetIds:r.selectedPresetIds,provider:Ic(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Es(r.insertedPrompts),d=e??r.getResolvedSize(),u=`mm_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;rn(u,p);const m=Date.now(),h=m,b=In(r.multimodeMaxImages),I=[...r.inFlight,{id:u,prompt:i,startedAt:m,kind:"multimode",composerPrompt:l,composerInsertedPrompts:c}],x={sequenceId:u,requestId:u,requested:b,returned:0,images:[],partials:[],status:"pending"};Pe(I),t({activeGenerations:r.activeGenerations+1,inFlight:I,activeFlightIds:new Set([...r.activeFlightIds,u]),multimodeSequences:{...r.multimodeSequences,[u]:x},multimodePreviewFlightId:u}),n().startInFlightPolling();try{const y={prompt:i,quality:r.quality,size:d,format:r.format,moderation:r.moderation,provider:r.provider,maxImages:b,model:Qi(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:xc(r),...Ms(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(js)}:{}},g=await su(y,{onPartial:S=>{t(N=>{const A=N.multimodeSequences[u];return A?{multimodeSequences:{...N.multimodeSequences,[u]:{...A,partials:[...A.partials,{image:S.image,index:S.index??null}].slice(-b)}}}:{}})},onImage:S=>{t(N=>{const A=N.multimodeSequences[u];if(!A)return{};const L=Fa(A.images,[S]);return L.length===A.images.length?{}:{multimodeSequences:{...N.multimodeSequences,[u]:{...A,sequenceId:S.sequenceId??A.sequenceId,returned:L.length,images:L,status:"partial"}}}})}},{signal:p.signal}),_=g.images.map(S=>({...S,prompt:i,elapsed:Number.parseFloat(g.elapsed),provider:g.provider,usage:g.usage,requestId:S.requestId??g.requestId??u,composerPrompt:l,composerInsertedPrompts:c,quality:g.quality,size:g.size,model:g.model??null,imageToolModel:g.imageToolModel??null}));for(const S of _)await gt(S,t,n,{autoSelectStartedAt:h});t(S=>({multimodeSequences:{...S.multimodeSequences,[u]:(()=>{const N=S.multimodeSequences[u],A=Fa(N?.images??[],_);return{sequenceId:g.sequenceId,requestId:u,requested:g.requested,returned:A.length,images:A,partials:[],status:g.status,elapsed:g.elapsed}})()}}));const w=g.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(M(w,{returned:g.returned,requested:g.requested,elapsed:g.elapsed}))}catch(y){y.name==="AbortError"||tn(y)?t(g=>{const _=g.multimodeSequences[u];return _?{multimodeSequences:{...g.multimodeSequences,[u]:{..._,status:"canceled"}}}:{}}):(t(g=>{const _=g.multimodeSequences[u];return _?{multimodeSequences:{...g.multimodeSequences,[u]:{..._,status:"error",error:y.message}}}:{}}),He(y,n()))}finally{const y=n().inFlight.filter(g=>g.id!==u);Pe(y),on(u),t(g=>{const _=new Set(g.activeFlightIds);_.delete(u);let w=g.multimodePreviewFlightId;const S=g.multimodeSequences[u]?.status,N=S==="complete"||S==="partial";if(w===u&&!N){const L=[..._];w=L.length>0?L[L.length-1]:null}const A={...g.multimodeSequences};return N&&w!==u&&delete A[u],{activeGenerations:Math.max(0,g.activeGenerations-1),inFlight:y,activeFlightIds:_,multimodePreviewFlightId:w,multimodeSequences:A}})}}async function sf(e,t,n){const r=n(),o=Rn(r.prompt,r.insertedPrompts);if(!o)return;const a=eo({catalog:to(),presetIds:r.selectedPresetIds,provider:Ic(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${o}`:o,l=r.prompt,c=Es(r.insertedPrompts),d=e??r.getResolvedSize(),u=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;rn(u,p);const m=Date.now(),h=m,b=[...r.inFlight,{id:u,prompt:i,startedAt:m,composerPrompt:l,composerInsertedPrompts:c}];Pe(b),t({activeGenerations:r.activeGenerations+1,inFlight:b}),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:Qi(r),...r.provider==="api"&&r.imageToolModel?{imageToolModel:r.imageToolModel}:{},reasoningEffort:r.reasoningEffort,storyboard:r.storyboardActive||void 0,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:xc(r),...Ms(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(js)}:{}},x=await zi(I,{signal:p.signal});if(Jo(x)&&x.images.length>1){for(const y of x.images){const g={image:y.image,filename:y.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:y.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:y.createdAt??Date.now()};await gt(g,t,n,{autoSelectStartedAt:h})}n().showToast(M("toast.generatedBatch",{count:x.images.length,elapsed:x.elapsed}))}else{let y;if(Jo(x)){const g=x.images[0];y={image:g.image,filename:g.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:g.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:g.createdAt??Date.now()}}else y={image:x.image,filename:x.filename,reasoningEffort:x.reasoningEffort,prompt:i,composerPrompt:l,composerInsertedPrompts:c,elapsed:x.elapsed,provider:x.provider,providerUrl:x.providerUrl??null,usage:x.usage,requestId:x.requestId??u,quality:x.quality,size:x.size,model:x.model??null,imageToolModel:x.imageToolModel??null,createdAt:x.createdAt??Date.now()};await gt(y,t,n,{autoSelectStartedAt:h}),n().showToast(M("toast.generatedSingle",{elapsed:x.elapsed}))}}catch(I){!(I instanceof Error&&I.name==="AbortError")&&!tn(I)&&He(I,n())}finally{const I=n().inFlight.filter(x=>x.id!==u);Pe(I),on(u),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:I})}}function af(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 lf(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,o=await Ne(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 cf(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(!af(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 df=cf({fetchGeneratedFrame:lf,extractFromElement:(e,t,n)=>t==="last"?nn(e,n):t==="first"?Yl(e,n):Xl(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 uf(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 Sc(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:uf(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 _n(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 mf(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 wc(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 _c(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"&&At(e.provider)&&ds[e.provider].multimode.supported?"multimode":"image"}function pf(e){return e.mcpProvider?e.multimode:_c(e)==="multimode"}async function ff(e,t){const n=t();if(!Rn(n.prompt,n.insertedPrompts)||Ds(t))return;const o=_c(n);if(o==="video")return t().runVideoGenerate();const a=o==="multimode",i=Xr(n,{kind:a?"multimode":"classic"});if(i){e({customSizeConfirm:i});return}if(a){await t().generateMultimode();return}await t().runGenerate()}function hf(e,t){const n=t().multimodePreviewFlightId;n&&(lc(n),t().cancelInFlightJob(n),e(r=>{const o=r.multimodeSequences[n];return o?{multimodeSequences:{...r.multimodeSequences,[n]:{...o,status:"canceled"}}}:{}}))}function Ds(e){return(e().missingElementIds??[]).length>0?(e().showToast(M("toast.missingElements"),!0),!0):!1}async function gf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Ds(t))return;const r=Gm(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 yf(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=Xr(n(),{kind:"node",clientId:e});if(a){t({customSizeConfirm:a});return}await n().runGenerateNode(e)}async function vf(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=Xr(n(),{kind:"node-in-place",clientId:e});if(o){t({customSizeConfirm:o});return}await n().runGenerateNodeInPlace(e)}async function bf(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=Xr(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 xf(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 Ec(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Nc(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 kc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function If(e,t,n){const r=e?n().graphNodes.find(w=>w.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=eo({catalog:to(),presetIds:l.selectedPresetIds,provider:kc(l.provider),mode:"video"}),d=c.promptFragment?`${c.promptFragment} ${i}`:i;let u,p,m=r?r.data.videoContinuity??null:n().videoContinuityLineage,h;if(r&&o.length===0&&r.data.parentServerNodeId){const w=n().graphNodes.find(S=>S.data.serverNodeId===r.data.parentServerNodeId);if(w?.data.imageUrl)if(Ze(w.data.imageUrl))try{const S=w.data.imageUrl.replace(/^\/generated\//,"");p=(await df.extractFrame({kind:"generated",filename:S},"last")).dataUrl,m=w.data.videoContinuity??Sc({filename:S,prompt:w.data.prompt,userPrompt:w.data.prompt,revisedPrompt:w.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=S}catch{n().showToast(M("video.continuationFallbackT2V"),!0)}else u=w.data.imageUrl.replace(/^\/generated\//,"")}const b=Date.now(),I=b,x=`vid_${b}_${Math.random().toString(36).slice(2,6)}`,y=new AbortController;rn(x,y);const g=n().activeSessionId,_=[...n().inFlight,{id:x,prompt:d,startedAt:b,kind:"video",sessionId:g,clientNodeId:e??null}];Pe(_),r&&t({graphNodes:n().graphNodes.map(w=>w.id===e?{...w,data:{...w.data,status:"pending",pendingRequestId:x,pendingPhase:"queued",pendingStartedAt:b,partialImageUrl:null,error:void 0,errorInfo:null}}:w)}),t({inFlight:_,activeGenerations:_.length,videoProgress:0}),n().startInFlightPolling();try{const w=n().providerUrlReference,S={prompt:d,requestId:x,...Nc(n()),referenceImages:o.length>0&&!a?o:void 0,sourceImage:a?o[0]:o.length>0?void 0:p,sourceFilename:o.length===0&&!p?u:void 0,continueFromVideo:h,continuityLineage:m,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:Ec(n()),sessionId:g,clientNodeId:e??null,...w?{providerUrl:w}:{}},N=await ss(S,{onPlanning:()=>t({inFlight:n().inFlight.map(A=>A.id===x?{...A,phase:"planning"}:A)}),onSubmitted:()=>t({inFlight:n().inFlight.map(A=>A.id===x?{...A,phase:"streaming"}:A)}),onProgress:({progress:A})=>t({videoProgress:A??null})},{signal:y.signal});if(r&&N&&n().activeSessionId===g&&(t({graphNodes:n().graphNodes.map(A=>A.id===e?{...A,data:{...A.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??m,video:{...N.video??{},...N.videoSeries?.topic?{topic:N.videoSeries.topic}:{}}}}:A)}),n().scheduleGraphSave(),n().flushGraphSave("video-node-complete")),N){const A={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??x,createdAt:Date.now(),sessionId:g};await gt(A,t,n,{autoSelectStartedAt:I})}}catch(w){if(tn(w))r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(S=>S.id===e?{...S,data:{...S.data,status:S.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0,errorInfo:null}}:S)});else{const S=ot(w).code==="JOB_TRACKING_TIMEOUT",N=S?He(w,n()).message:w instanceof Error?w.message:"Video generation failed",A=S?{...ac(w),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:A}}:L)}),S||n().showToast(N,!0)}}finally{const w=n().inFlight.filter(S=>S.id!==x);Pe(w),on(x),t({inFlight:w,activeGenerations:w.length,videoProgress:null}),n().startInFlightPolling()}}async function Sf(e,t,n,r){const o=t?.trim();if(!o)throw r().showToast(Pr,!0),new Error(Pr);if(Ds(r))return!1;const a=r(),i=eo({catalog:to(),presetIds:a.selectedPresetIds,provider:kc(a.provider),mode:"video"}),l=i.promptFragment?`${i.promptFragment} ${o}`:o,c=Date.now(),d=c,u=`vid_${c}_${Math.random().toString(36).slice(2,6)}`,p=new AbortController;rn(u,p);const m=[...r().inFlight,{id:u,prompt:l,startedAt:c,kind:"video",sessionId:r().activeSessionId,clientNodeId:null}];Pe(m),n({inFlight:m,activeGenerations:m.length,videoProgress:0}),r().startInFlightPolling();try{const h={prompt:l,presetIds:i.appliedPresetIds,elementIds:Ec(r()),requestId:u,...Nc(r()),mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},b=await ss(h,{onPlanning:()=>n({inFlight:r().inFlight.map(x=>x.id===u?{...x,phase:"planning"}:x)}),onSubmitted:()=>n({inFlight:r().inFlight.map(x=>x.id===u?{...x,phase:"streaming"}:x)}),onProgress:({progress:x})=>n({videoProgress:x??null})},{signal:p.signal}),I={image:b.url,filename:b.filename,url:b.url,mediaType:"video",prompt:l,elapsed:b.elapsed,video:b.video??{},videoSeries:b.videoSeries??null,videoContinuity:b.videoContinuity??null,revisedPrompt:b.revisedPrompt??null,requestId:b.requestId??u,createdAt:Date.now(),sessionId:r().activeSessionId};await gt(I,n,r,{autoSelectStartedAt:d})}catch(h){return tn(h)||(ot(h).code==="JOB_TRACKING_TIMEOUT"?He(h,r()):r().showToast(h instanceof Error?h.message:"Video generation failed",!0)),!1}finally{const h=r().inFlight.filter(b=>b.id!==u);Pe(h),on(u),n({inFlight:h,activeGenerations:h.length,videoProgress:null}),r().startInFlightPolling()}return!0}function Yo(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 En(e){const t=new Map([...ql({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,Yo(r)])),memory:new Map(e.inFlight.map(n=>[n.id,n])),scopes:Ym({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function Gs(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function Cc(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&&wn(r,e.scopes)}).map(([n])=>n))}function wf(e,t,n){const r=Tr(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 Yo(o)===Yo(e)?e:o}function _f(e,t,n,r,o){if(t&&(o.mode==="reconcile"||!n))return[wn(Tr(t),r.scopes)?wf(e,t,o.mode):e];if(n)return wn(Tr(n),r.scopes)?(n.status==="error"&&o.terminalErrors.push(Xm(n)),[]):[e];const a=o.now-e.startedAt;return(o.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function jc(e,t,n,r){if(!Gs(e,t))return null;const o=En(t),a=Cc(e,o),i=new Map(n.jobs.map(p=>[p.requestId,p])),l=new Map(n.terminalJobs.map(p=>[p.requestId,p])),c=[],d=[...o.local.values()].flatMap(p=>a.has(p.id)?_f(p,i.get(p.id),l.get(p.id),e,{...r,terminalErrors:c}):[p]),u=new Set;for(const[p,m]of i){const h=Tr(m);wn(h,e.scopes)&&(u.add(p),!((h.kind??"classic")==="classic"&&e.uiMode==="node")&&(h.kind==="node"&&(e.uiMode!=="node"||(h.sessionId??null)!==e.activeSessionId)||!e.local.has(p)&&!o.local.has(p)&&d.push(h)))}return{inFlight:d,terminalErrors:c,eligibleIds:a,serverActiveIds:u}}let Nn=0;function kn(){if(Nn+=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,kn)}function Ef(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)He(o,n())}function Nf(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:Yr([...o,...n.history],Math.max($e,n.history.length+o.length)),currentImage:n.currentImage??o[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+o.length)}):{}})}function kf(e,t,n){const r=En(n()),o=Cc(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<Gl);i.length!==r.local.size&&(Pe(i),t({inFlight:i,activeGenerations:i.length}))}async function Cf(e,t,n,r,o){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await Xt({limit:$e,since:a});if(!o()||!Gs(e,r()))return;Nf(i.map(On),n),t&&kf(t,n,r)}catch{}}function jf(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function Tf(e,t,n){if(ue()){kn();return}const r=fe(),o=Nn,a=()=>!ue()&&r===fe()&&o===Nn,i=En(t());let l=null;if(!jf(t(),n))try{const c=await zl(i.scopes);if(!a())return;const d=jc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;Ef(d,e,t),l={snapshot:En(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&Gs(i,t())&&await Cf(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&kn()}function Af(e,t){if(typeof window>"u"||ue())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(_t,kn),n.__ima2InflightTimer=window.setInterval(()=>Tf(e,t,n),1500))}async function Pf(e,t){if(ue())return;const n=fe(),r=Nn;try{const o=En(t()),a=await zl(o.scopes);if(ue()||n!==fe()||r!==Nn)return;const i=jc(o,t(),a,{mode:"reconcile",now:Date.now()});if(!i)return;Pe(i.inFlight),e({inFlight:i.inFlight,activeGenerations:i.inFlight.length});for(const l of i.terminalErrors)He(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const Nt=()=>"nc_"+Math.random().toString(36).slice(2,10);function qa(e,t){return{x:e*360,y:t*320}}const Rf=360,Tc=320;function Mf(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 zs(e){const t=e.filter(r=>!r.data.parentServerNodeId);if(t.length===0)return qa(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:qa(0,0).x,y:n+Tc}}function Ac(e,t,n){const r=Mf(e.id,t,n),o=e.position.x+Rf;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+Tc}}const Cn="source-right",jn="target-left";function no(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function Lf(e,t){return e&&e.startsWith(`${t}-`)?e:null}function Of(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 Ff(e,t){const n=Nt();t().recordGraphHistory("add-root");const r={id:n,type:"imageNode",position:zs(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 Df(e,t,n){const r=Nt();n().recordGraphHistory("add-root-from-history");const o={id:r,type:"imageNode",position:zs(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 Gf(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:Ac(r,n().graphNodes,n().graphEdges),data:{clientId:o,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:Ze(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:no(e,o,Cn,jn),source:e,target:o,sourceHandle:Cn,targetHandle:jn};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&Ze(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 nn(l);t({graphNodes:n().graphNodes.map(d=>d.id===o?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return o}function zf(e,t,n){const r=n().graphNodes.find(u=>u.id===e);if(!r)return e;n().recordGraphHistory("add-sibling");const o=n().graphEdges.find(u=>u.target===e);if(!o){const u=Nt(),p={id:u,type:"imageNode",position:zs(n().graphNodes),data:{clientId:u,serverNodeId:null,parentServerNodeId:null,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}};return t({graphNodes:[...n().graphNodes,p]}),n().scheduleGraphSave(),u}const a=o.source,i=n().graphNodes.find(u=>u.id===a);if(!i)return e;const l=Nt(),c={id:l,type:"imageNode",position:Ac(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:no(a,l,Cn,jn),source:a,target:l,sourceHandle:Cn,targetHandle:jn};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function qf(e,t,n,r,o){const a=o().graphNodes.find(p=>p.id===e);if(!a)return e;o().recordGraphHistory("add-child-at");const i=Nt(),l=Lf(n,"source")??Cn,c=Of(l)??jn,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}},u={id:no(e,i,l,c),source:e,target:i,sourceHandle:l,targetHandle:c};return r({graphNodes:[...o().graphNodes,d],graphEdges:[...o().graphEdges,u]}),o().scheduleGraphSave(),i}function $f(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 Uf(e,t,n,r){n({graphNodes:r().graphNodes.map(o=>o.id===e?{...o,data:{...o.data,prompt:t}}:o)}),r().scheduleGraphSave()}function Hf(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&&Te(o),Ps(n().activeSessionId,e);const a=n().graphNodes.filter(l=>l.id!==e),i=n().graphEdges.filter(l=>l.source!==e&&l.target!==e);t({graphNodes:De(a,i),graphEdges:i}),n().scheduleGraphSave()}function Vf(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)Ps(n().activeSessionId,i);for(const i of n().graphNodes)r.has(i.id)&&i.data?.pendingRequestId&&Te(i.data.pendingRequestId);const o=n().graphNodes.filter(i=>!r.has(i.id)),a=n().graphEdges.filter(i=>!r.has(i.source)&&!r.has(i.target));t({graphNodes:De(o,a),graphEdges:a}),n().scheduleGraphSave()}function Kf(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(p=>p.target===c.id),u=d?n().graphNodes.find(p=>p.id===d.source):null;return{...c,data:{...c.data,parentServerNodeId:u?.data.serverNodeId??null}}});t({graphNodes:De(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(M("edge.disconnected"))}function Bf(e,t,n,r,o,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(ap(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:no(e,t,n,r),source:e,target:t,sourceHandle:n,targetHandle:r}];o({graphNodes:De(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function Wf(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(jr),u=c.filter(h=>!jr(h)),m=(await Promise.all(u.map(async h=>{try{return await ks(h,{preserveTransparency:Dl(h)})}catch(b){return console.warn("[addNodeReferences] compress failed",b),null}}))).filter(h=>!!h);if(m.length>0){const h=r().activeSessionId;n({graphNodes:r().graphNodes.map(b=>{if(b.id!==e)return b;const I=[...b.data.referenceImages??[],...m].slice(0,r().referenceLimit);return Zr(h,e,I),{...b,data:{...b.data,referenceImages:I}}})}),r().scheduleGraphSave()}d.length>0&&r().showToast(M("toast.refHeicUnsupported"),!0),u.length-m.length>0&&r().showToast(M("toast.refTooLarge"),!0),t.length>l&&r().showToast(M("toast.refLimitExceeded"),!0)}function Pc(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 Zr(r().activeSessionId,e,l),{...a,data:{...a.data,referenceImages:l}}})}),r().scheduleGraphSave())}async function Jf(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=Ze(t)||Ze(n)?await nn(t):await Fn(t,n||"node-reference.png")}catch{o().showToast(M("toast.currentImageLoadFailed"),!0);return}Pc(e,i,r,o)}function Yf(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 Zr(r().activeSessionId,e,a),{...o,data:{...o.data,referenceImages:a}}})}),r().scheduleGraphSave()}function Xf(e,t,n){Ps(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const $a=10;function Rc(e,t){return t?t.filename&&e.filename===t.filename?!0:e.image===t.image:!1}function Zf(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(t=>!!t)}function Mt(e){return e.filter(t=>!t.canvasVersion)}function rt(e,t){if(!t)return null;const n=Mt(e);if(!t.canvasVersion)return n.find(a=>Rc(a,t))??null;const r=Zf(t);return n.find(a=>a.filename?r.includes(a.filename):!1)??null}function Qf(e,t){const n=Mt(e),r=rt(e,t);return n.findIndex(o=>Rc(o,r))}function eh(e,t,n){const r=Mt(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=Qf(e,t);if(o<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-$a:$a,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 Mc(e,t){const n=Mt(e),r=n.findIndex(o=>o.filename===t);return r<0?null:n[r+1]??n[r-1]??null}function Ae(e){return e.filename||e.image}function vn(e){return!e.canvasVersion}function Ir(e){const t=new Set;return e.filter(n=>{const r=Ae(n);return t.has(r)?!1:(t.add(r),!0)})}const Lc=72,Ua=10;function Oc(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 th(e){return e<=1?1:e===2?2:4}function Fc(e){const t=new Set,n=new Map,r=[];for(const o of e){if(!vn(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=Ae(o);t.has(a)||(t.add(a),r.push({type:"image",key:a,item:o}))}for(const o of n.values())o.items.sort(Oc);return r}function Dc(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Ae(e):null}function fo(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function nh(e,t,n,r,o=Lc){const a=Fc(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 fo(i);if(n==="last")return fo(l);const c=Dc(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const u=n==="pagePrevious"?-Ua:n==="pageNext"?Ua:n==="previous"?-1:1,p=Math.max(0,Math.min(a.length-1,d+u));if(p===d)return null;const m=a[p];return m?fo(m):null}const Gc={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},rh={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},oh={default:Gc,"prompt-studio":rh};function Gn(e,t){return oh[e]??Gc}function sh(e,t){return Gn(e).promptBuilderSurface!=="off"}const ah="history:";function zc(e,t,n){if(!t||n||!t.startsWith(ah)||!(t in e))return e;const r={...e};return delete r[t],r}function ih(e){const t=e.multimodePreviewFlightId;return t?t.startsWith("history:")?t.slice(8):e.multimodeSequences[t]?.sequenceId??null:null}async function lh(e,t){const n=t().historyNextCursor;if(!(!n||t().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const r=await Xt({limit:$e,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 ch(e,t){try{const n=await Xt({limit:$e,favoritesOnly:!0}),r=n.items.map(On);e(o=>{const a=Vl(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 dh(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await Xt({limit:$e,cursor:n,favoritesOnly:!0}),o=r.items.map(On);e(a=>{const i=Vl(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 uh(e,t,n){const r=Date.now(),o=n().history,a=e.canvasVersion?rt(o,e)??Mt(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,u=i&&a&&!d?jm(a):{},p=n().multimodePreviewFlightId,m=p?n().multimodeSequences[p]:null,h=m&&a&&m.images.some(b=>b.filename===a.filename);t(b=>({currentImage:a,lastHistorySelectedAt:r,unseenGeneratedCount:0,multimodePreviewFlightId:h?p:null,multimodeSequences:zc(b.multimodeSequences,p,!!h),...u}))}function mh(e,t,n){const r=Date.now(),o=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(Oc);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:{...zc(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:o,partials:[],status:c}}}))}function ph(e,t,n){const r=n(),o=Gn(r.workspaceProfile);if(r.uiMode==="classic"&&o.multimodeHistoryGrouping==="sequence"){const i=nh(r.history,r.currentImage,e,ih(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=eh(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function fh(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?Mc(n().history,o):a;try{await qi(o),t(d=>{const u=Qm(d.multimodeSequences,o),p=d.multimodePreviewFlightId&&!u[d.multimodePreviewFlightId]?null:d.multimodePreviewFlightId;return{history:d.history.filter(m=>m.filename!==o),currentImage:c,multimodePreviewFlightId:p,multimodeSequences:u,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 hh(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 qi(d);t(d=>{const u={...d.multimodeSequences};return delete u[`history:${e}`],delete u[e],{history:d.history.filter(p=>!p.filename||!a.has(p.filename)),currentImage:l?null:d.currentImage,multimodePreviewFlightId:c?null:d.multimodePreviewFlightId,multimodeSequences:u,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 gh(e,t){const n=t().trashPending;if(n)try{await mu(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 yh(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?Mc(n().history,o):i;try{await uu(o),t(u=>({history:u.history.filter(p=>p.filename!==o),currentImage:d,trashPending:u.trashPending?.filename===o?null:u.trashPending})),c&&st(d?.filename??null),n().showToast(M("gallery.permanentDeleted",{filename:o}))}catch(u){console.error("[history] permanent delete failed",u),n().showToast(M("gallery.deleteFailed"),!0)}}function vh(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 bh(e,t,n){const r=n(),o={...e,createdAt:e.createdAt||Date.now()},a=Ul(r.history,o),i=Hl(o,a),l=$l(r.history,i);t({history:Yr([i,...l],r.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(r.loadedHistoryRetainLimit,Math.min(r.history.length+1,r.loadedHistoryRetainLimit+1))})}async function xh(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 au(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 Ih(e,t){(async()=>{try{const n=await Xt({limit:$e}),r=n.items.map(On);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:$e}),r.length>0){const o=jl(),a=o?r.find(c=>c.filename===o):null,i=Mt(r),l=(a?rt(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max($e,r.length)}),l?.filename!==o&&st(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function qc(e,t){try{const{sessions:n}=await fu();if(e({sessions:n}),!t().activeSessionId){const o=Dm(),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 qc(e,t)}}async function Sh(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 $i(e),{graphNodes:o,graphEdges:a,graphVersion:i}=Zl(r);t({activeSessionId:e,activeSessionGraphVersion:i,graphNodes:o,graphEdges:a,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),Ns(e),await n().reconcileGraphPending().catch(()=>{})}catch(r){console.warn("[sessions] switch failed:",r),t({sessionLoading:!1}),n().showToast(M("toast.sessionLoadFailed"),!0)}}}async function wh(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 Di({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 u=d.data?.pendingRequestId;if(!u||d.data.status!=="pending"&&d.data.status!=="reconciling")return d;if(a.has(u)){const h=a.get(u)??null;return{...d,data:{...d.data,status:"reconciling",pendingPhase:h}}}const p=d.data.pendingStartedAt??0;if(p&&i-p<l)return{...d,data:{...d.data,status:"reconciling"}};const m=!!d.data.imageUrl||!!d.data.serverNodeId;return{...d,data:{...d.data,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,status:m?"ready":"stale",error:m?void 0:M("session.assetAbortedError")}}});e({graphNodes:c})}await rc(t,e).catch(()=>{})}async function _h(e,t,n){e==null&&(e=M("session.untitled"));try{const{session:r}=await hu(e);t({sessions:[r,...n().sessions],activeSessionId:r.id,activeSessionGraphVersion:r.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),Ns(r.id)}catch(r){console.warn("[sessions] create failed:",r),n().showToast(M("toast.sessionCreateFailed"),!0)}}async function Eh(e,t,n){const r=n().activeSessionId;if(r)try{await gu(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 Nh(e,t,n){try{await yu(e);const r=n().sessions.filter(o=>o.id!==e);t({sessions:r}),n().activeSessionId===e&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),Ns(null),r.length>0?await n().switchSession(r[0].id):await n().createAndSwitchSession(M("session.firstGraph")))}catch{n().showToast(M("toast.sessionDeleteFailed"),!0)}}function kh(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),n.imageToolModel=e.provider==="api"&&us(t.imageToolModel)?t.imageToolModel:null,n.quality=Pt(e.provider,n.imageToolModel,Al(t.quality)?t.quality:e.quality),Pl(t.format)&&(n.format=t.format),Rl(t.moderation)&&(n.moderation=t.moderation),(t.promptMode==="auto"||t.promptMode==="direct")&&(n.promptMode=t.promptMode),t.model&&Du(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 Fs(e,t)}function qs(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 $c(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function $s(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(!Ls(o,r))break;const u=uc(c,i),p=$c(d,u.tag);o.push(p),l.push(p),i.add(p.tag),a=Os(a,p.tag),c=u.nextAttachmentOrdinal}return l.length===0?{result:l}:{result:l,patch:{trayItems:o,nextAttachmentOrdinal:c,retiredTags:a,providerUrlReference:null}}})}function Ch(e,t,n){return $s(e,t)}function ro(e,t,n,r){const o=qs(e);return o?$s([{dataUrl:e,mimeType:o,origin:t}],n)[0]??null:null}function jh(e,t,n){ro(e,"gallery",t)}async function Th(e,t,n){const r=n().activeReferenceLimit(),o=Math.max(0,r-n().trayItems.length),a=e.slice(0,o),i=a.filter(jr),l=a.filter(p=>!jr(p)),d=(await Promise.all(l.map(async p=>{try{const m=await ks(p,{preserveTransparency:Dl(p)}),h=qs(m);return h?{dataUrl:m,mimeType:h,originalName:p.name,byteSize:p.size,origin:"file"}:null}catch(m){return console.warn("[addReferences] compress failed",m),null}}))).filter(p=>p!==null),u=$s(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>u.length)&&n().showToast(M("toast.refLimitExceeded"),!0)}async function Ah(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let o="";try{o=await Ts(e);const a=await bu({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 Ph(e,t){const n=t().metadataRestore;if(!n)return;const r=kh(t(),n.metadata);if(te({imageToolModel:r.imageToolModel,quality:r.quality}),r.imageModel&&kl(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 Us(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function Hs(e,t){t.length!==e.length&&te({insertedPrompts:t})}function Uc(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:Qr(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=Us(o),l.videoContinuityLineage=null)}return{result:void 0,patch:l}}),Hs(r,n().insertedPrompts)}function Rh(e,t,n){const r=Dn(n())[e];r&&Uc(r.tokenId,t,n)}function Mh(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:Qr(r.retiredTags,o),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Us(r),providerUrlReference:null}}}),Hs(n,t().insertedPrompts)}function Lh(e,t){const n=t().insertedPrompts;zn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:Us(r),providerUrlReference:null}})),Hs(n,t().insertedPrompts)}function Oh(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(!Ls(a,t))return{result:!1};const i=uc(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=$c(n,i.tag),c=Os(Qr(e.retiredTags,r),l.tag);return{result:!0,patch:{trayItems:[l,...a],nextAttachmentOrdinal:i.nextAttachmentOrdinal,retiredTags:c,canvasReferenceImage:n.dataUrl,providerUrlReference:null}}}async function Fh(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=qs(o);if(!a){n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!zn(t,(l,c)=>Oh(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 Hc(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Dh(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(Hc(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!ro(r,"gallery",e)){t().showToast(M("toast.refSlotFull"),!0);return}t().showToast(M("toast.addedCurrentAsRef"))}async function Gh(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(M("toast.refSlotFull"),!0);return}let r;try{r=await Fn(Hc(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(M("toast.currentImageLoadFailed"),!0);return}if(!ro(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=Ll();o[e.provider]={...o[e.provider],...Ia(e)};const a={...o[t.provider],...Ia(t)};r&&delete a[r],o[t.provider]=a,Vm(o),Km(t),n(i=>{const l=t.provider==="api"?i.imageToolModel:null,c=Pt(t.provider,l,i.quality);return te({imageToolModel:l,quality:c}),{...t,imageToolModel:l,quality:c}})}function zh(e,t,n){const r=qn(n);if(e===r.provider)return;const o=At(e)?Ll()[e]:void 0,a=Yu(r,e,o);$n(r,a,t)}function qh(e,t,n){const r=qn(n),o=lt({provider:Ju(r.provider,e),imageModel:e,videoModelSelected:!1});$n(r,o,t)}function $h(e,t,n){const r=qn(n),o=lt({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:Rt(e)||tt});$n(r,o,t)}function Uh(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 Hh(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 Vh(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 Kh(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&&Vh(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const Bh=1e4;let Tn=[];async function Vs(e){const t=await $("/api/mcp/providers",{signal:e});return Tn=Array.isArray(t.providers)?t.providers:[],Tn}function Wh(e){return Li("/api/mcp/providers",e)}function Jh(e,t){return Li(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function Yh(){return Tn}async function Gw(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 zw(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function qw(e){return(await $(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function Vc(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 Xh(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 Zh(e,t){let n=!1;const r=()=>n?!1:(n=!0,o(),a(),!0),o=jt(e,null,(i,l)=>{if(i==="done"){const c=Xh(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?.(Qe(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Yt(()=>{if(!r())return;const i=new Error("MCP generation timed out");i.code="MCP_STREAM_TIMEOUT",t.onError?.(i)});return r}async function Qh(e,t){const n=e.requestId??`mcp_ui_${Date.now()}`,r=Zh(n,t);try{const a=(await Vs()).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 $("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(o){throw r(),o}}function Kc(){const[e,t]=v.useState(()=>[...Tn]),[n,r]=v.useState(Tn.length===0),[o,a]=v.useState(null),i=v.useCallback(async()=>{try{const l=await Vs();t([...l]),a(null)}catch(l){a(l instanceof Error?l:new Error(String(l)))}finally{r(!1)}},[]);return v.useEffect(()=>{i();const l=window.setInterval(()=>{i()},Bh);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:o,refresh:i}}let Rr=null;function Bc(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 eg(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 tg(e){try{await $(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function ng(e,t,n){let r=()=>{};const o=new Promise(i=>{r=i});if(await Qh(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(Bc(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 rg(e){const t=e();if((t.mcpProvider?Yh().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??Ue();if(Im(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 u=c?.name?El(c.name):null;return d.filter(p=>typeof p=="string").map(p=>({filename:p,...u?{tag:u}:{}}))}).slice(0,3);let l=null;try{const c=await eg(o);l=c.batchId;const d=km({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_${Date.now()}`);if(!d)return;await ng(d,e,!!l)}catch(c){e().showToast(Bc(c),!0)}finally{l&&await tg(l)}}function sn(e){Ln(null,null,"image"),te({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ue(),mcpCharacterElementId:null,...Rr?{generate:Rr}:{}})}function oo(e,t,n,r=null,o){if(!e){sn(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:Ue()}:{},count:1,multimode:!1,generate:()=>rg(n)})}function og(e,t,n){Ln(n().mcpProvider??null,e,n().mcpMediaKind??"image"),te({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:Ue()})}function sg(e,t,n,r,o){const a=wm(o);let i=o?_s(o.inputRoles,r().mcpReferenceSelection):Ue();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 ag(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:Ue()}))}function ig(e,t){te({mcpRatio:e}),t({mcpRatio:e})}function lg(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 cg(e,t,n){const r=_s(n().mcpInputRoles??[],ws(e)),o=n().mcpReferenceSelection??Ue();_l(o,r)||t({mcpReferenceSelection:r})}function dg(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},o=Sl(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??Ue(),i=_s(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!_m(r,o),d=!_l(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 ug(e,t){const n=Hm();n.provider&&(oo(n.provider,e,t,n.model,n.kind),te({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function mg(e,t,n){sn(t),zh(e,t,n)}function pg(e,t,n){n().provider!=="api"&&(e=null);const r=Pt(n().provider,e,n().quality);te({imageToolModel:e,quality:r}),t({imageToolModel:e,quality:r})}function fg(e,t,n){e=Pt(n().provider,n().imageToolModel,e),te({quality:e}),t({quality:e})}function hg(e,t){te({sizePreset:e}),t({sizePreset:e})}function gg(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 yg(e,t){te({grokAspectRatio:e}),t({grokAspectRatio:e})}function vg(e,t){te({grokResolution:e}),t({grokResolution:e})}function bg(e,t){te({format:e}),t({format:e})}function xg(e,t){te({moderation:e}),t({moderation:e})}function Ig(e,t,n){sn(t),qh(e,t,n)}function Sg(e,t,n){sn(t),$h(e,t,n)}function wg(e,t,n){sn(t),Uh(e,t,n)}function _g(e,t,n){sn(t),Hh(e,t,n)}function Eg(e){return Kh(e())}function Ng(e,t){Mm(e),t({reasoningEffort:e})}function kg(e,t){Fm(e),t({webSearchEnabled:e})}function Cg(e,t){const n=In(e);te({count:n}),t({count:n})}function jg(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 Tg(e,t){const n=In(e);te({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function Ag(e,t){te({promptMode:e}),t({promptMode:e})}function Pg(e,t){te({prompt:e}),t({prompt:e})}function Rg(e,t){te({negativePrompt:e}),t({negativePrompt:e})}function Mg(e,t,n,r){const o={...r().naiOptionOverrides,[e]:t};Cl(o),n({naiOptionOverrides:o})}function Lg(e){Cl({}),e({naiOptionOverrides:{}})}function Og(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 ho="starred";async function Fg(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(ho))return"noop";if(r)return await t.updateAsset(r.id,{tags:[...new Set([...r.tags,ho])]}),"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:[ho],metadata:{origin:"star",mediaType:o}}),"created"}function Dg(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 Gg(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 zg(e,t,n){n(r=>{const o=r.insertedPrompts.filter(m=>m.placement!=="after"),a=r.insertedPrompts.filter(m=>m.placement==="after"),i=[...o.map(m=>({kind:"prompt",prompt:m})),{kind:"main"},...a.map(m=>({kind:"prompt",prompt:m}))],l=i.findIndex(m=>m.kind==="prompt"&&m.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 u=i.findIndex(m=>m.kind==="main"),p=i.filter(m=>m.kind==="prompt").map((m,h)=>({...m.prompt,placement:h<u?"before":"after"}));return te({insertedPrompts:p}),{insertedPrompts:p}})}function qg(e){te({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function $g(e){e({promptLibraryLoading:!0});try{const t=await xu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function Ug(e,t,n){try{await Iu(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 Hg(e,t,n){try{await Su(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function Vg(e,t,n){try{await wu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function Kg(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 _u({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 Bg(e,t,n){const r=e.filename;if(!r)return null;let o;try{o=(await lu(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 Fg({...e,filename:r},{getAssets:as,createAsset:Ur,updateAsset:Ui})!=="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 Wg(e,t,n){if(e){lc(e),t(r=>{const o=r.inFlight.map(a=>a.id===e?{...a,phase:"canceling"}:a);return Pe(o),{inFlight:o}});try{await Te(e),n().startInFlightPolling()}catch{n().showToast(M("toast.cancelFailed"),!0)}}}function Jg(e,t){const n=ql(),r=jl(),o=Ol(),a=Jr(),i=en();e(l=>{const c=r?l.history.find(m=>m.filename===r)??null:null,d=c?rt(l.history,c):null,u=Mt(l.history)[0]??null,p=l.currentImage?.canvasVersion?rt(l.history,l.currentImage)??u:l.currentImage;return{inFlight:n,activeGenerations:n.length,...o,imageToolModel:o.provider==="api"?i.imageToolModel??null:null,quality:Pt(o.provider,i.imageToolModel,i.quality??l.quality),videoDuration:a.duration,videoResolution:a.resolution,videoAspectRatio:a.aspectRatio,currentImage:r&&p?.filename!==r?d??p:p}}),n.length>0&&t().startInFlightPolling()}function Yg(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):Yr([e,...n.history],n.loadedHistoryRetainLimit+1):n.history,loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,Math.min(n.history.length+1,n.loadedHistoryRetainLimit+1))}))}function Xg(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function Zg(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(tl,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function Qg(e,t){try{localStorage.setItem(vs,e)}catch{}t({galleryScope:e})}function ey(e,t){try{localStorage.setItem(ll,e),localStorage.setItem(vs,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function ty(e,t){const n=e==="card-news"&&!ul?"classic":e;try{localStorage.setItem(nl,n)}catch{}t({uiMode:n})}function ny(e,t){try{localStorage.setItem(rl,e)}catch{}t({historyStripLayout:e})}function ry(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 oy(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 sy(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 ay(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 iy(e,t,n){t({graphNodes:De(e,n().graphEdges)}),n().scheduleGraphSave()}function ly(e,t,n){t({graphEdges:e,graphNodes:De(n().graphNodes,e)}),n().scheduleGraphSave()}function cy(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:Sn(t().graphNodes,[])}})}function dy(e,t,n,r){n({graphNodes:Wm(r().graphNodes,r().graphEdges,e,t)})}function uy(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(M("nodeBatch.stopQueued")))}function my(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function py(e,t,n){t({canvasExportBackground:e}),Nl(e,n().canvasExportMatteColor)}function fy(e,t,n){t({canvasExportMatteColor:e}),Nl(n().canvasExportBackground,e)}const ct=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let go=0;async function Wc(e){const{folders:t}=await is();e({assetsFolders:t})}const Ks=Wc;async function Bs(e,t,n){const r=e!==!1;if(!r&&n().assetsLoading)return;const o=++go;t({assetsLoading:!0,...r?{assetsLoadError:!1}:{}});try{const a=n().assetsFilters,i=await as({...a,cursor:r?null:n().assetsCursor}),l=r?await Promise.all([is(),ls()]):null;if(o!==go)return;t(c=>({assets:r?i.assets:[...c.assets,...i.assets.filter(d=>!c.assets.some(u=>u.id===d.id))],assetsCursor:i.nextCursor,assetsLoading:!1,...l?{assetsFolders:l[0].folders,assetsTags:l[1].tags}:{}}))}catch(a){ct(a),o===go&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function hy(e,t){!t().assetsCursor||t().assetsLoading||await Bs(!1,e,t)}function Ha(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),Bs(!0,t,n)}async function gy(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 Ur({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 yy(e,t,n){try{const{asset:r}=await Ui(e,t);let o=null;try{o=(await ls()).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 vy(e,t){try{return await ku(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return ct(n),!1}}async function by(e,t,n){try{return await Cu({name:e,parentId:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function xy(e,t,n){try{return await Hi(e,{name:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function Iy(e,t,n){try{return await Hi(e,{parentId:t}),await Ks(n),!0}catch(r){return ct(r),!1}}async function Sy(e,t){try{await ju(e);const[{folders:n},{tags:r}]=await Promise.all([is(),ls()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return ct(n),!1}}function wy(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(Gu(e.imageModel)||zu(e.imageModel)))return e.imageModel}async function Jc(e,t,n){if(!e.filename)return;const r=n();try{await Ur({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 _y(e,t,n){const r=n().assetGenItems.find(o=>o.requestId===e);r&&(r.mediaType==="video"?await Yc(r,t,n):await Jc(r,t,n))}async function Ey(e,t,n,r){const o=n(),a=o.assetGenPrompt.trim(),i=await ss({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 Yc(l,t,n),n().showToast(M("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function Yc(e,t,n){if(!e.filename)return;const r=n();try{await Ur({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 Ny(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;rn(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 Ey(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:wy(n),requestId:o,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await zi(c,{signal:a.signal}),u=Jo(d)?d.images[0]:null,p={image:u?u.image:d.image,filename:u?u.filename:d.filename,reasoningEffort:d.reasoningEffort,prompt:r,elapsed:d.elapsed,provider:d.provider,providerUrl:(u?u.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:(u?u.createdAt:d.createdAt)??Date.now()};await gt(p,e,t,{autoSelectStartedAt:i}),e(m=>({assetGenItems:[p,...m.assetGenItems]})),await Jc(p,e,t),t().showToast(M("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!tn(c)){const d=He(c,t()),u=d.code==="JOB_TRACKING_TIMEOUT"?d.message:c instanceof Error?c.message:String(c);e({assetGenLastError:u})}}finally{const c=t().inFlight.filter(d=>d.id!==o);Pe(c),on(o),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function ky(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function ln(e){te({presetIds:e})}const Cy=e=>({selectedPresetIds:en().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return ln(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(o=>o!==t);return ln(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(o=>o!==t):[...n.selectedPresetIds,t];return ln(r),{selectedPresetIds:r}}),clearPresets:()=>{ln([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=ky(t);ln(n),e({selectedPresetIds:n})}});function jy(){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)}),Ty=e=>$("/api/sprite-recipes",{signal:e}),Ay=(e,t)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),Py=(e,t)=>$("/api/sprite-recipes",Un(e,"POST",t)),Ry=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}`,Un(t,"PATCH",n)),My=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),Ly=(e,t,n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Un({assetId:t},"POST",n)),Oy=(e,t={},n)=>$(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Un({...t,async:!0},"POST",n)),Kt=new Map,Hn=e=>e instanceof Error?e.message:String(e),Xc=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function Fy(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await Ty();e({spriteRecipes:n.map(Xc)}),t().activeSpriteRecipeId&&await Ws(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:Hn(n)})}finally{e({spriteRecipeLoading:!1})}}async function Ws(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await Ay(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:Hn(r)})}finally{t({spriteRecipeLoading:!1})}}async function Dy(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await Ry(n.activeSpriteRecipeId,n.spriteRecipeDraft):await Py(n.spriteRecipeDraft);return e(o=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[Xc(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 Zc(e,t,n){Kt.get(e)?.(),Kt.set(e,jt(e,null,(r,o)=>Uy({event:r,data:{...o,requestId:e}},t,n)))}function Js(e){Kt.get(e)?.(),Kt.delete(e)}function Qc(e,t){return ot(e).code==="JOB_TRACKING_TIMEOUT"?He(e,t()).message:Hn(e)}async function Gy(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{Zc(r,e,t),await os(),await My(n,{requestId:r,async:!0})}catch(o){Js(r),e({spriteRecipeError:Qc(o,t),spriteRecipeGenerating:!1})}}async function zy(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:o}=await Ly(r,e);t({activeSpriteRecipe:o,spriteRecipeDraft:o,spriteRecipeDirty:!1})}catch(o){t({spriteRecipeError:Hn(o)})}finally{t({spriteRecipeGenerating:!1})}}}async function qy(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const o=crypto.randomUUID();try{Zc(o,t,n),await os(),await Oy(r,{requestId:o,stateKeys:e,async:!0})}catch(a){Js(o),t({spriteRecipeError:Qc(a,n),spriteRecipeGenerating:!1})}}async function $y(e,t,n){Kt.get(e)?.(),Kt.delete(e),t({spriteRecipeGenerating:!1})}function Uy(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")&&Js(String(e.data.requestId??"")),e.event==="error"){const a=String(e.data.message??"Generation failed"),i=Qe(e.data,a),l=ot(i).code==="JOB_TRACKING_TIMEOUT"?He(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&Ws(a,t)}}function Hy(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const je=en(),Zn=Jr(),Qn=Ol(),f=Mi((e,t,n)=>({...Cy(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:jy(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>Fy(e,t),selectSpriteRecipe:r=>Ws(r,e),updateSpriteRecipeDraft:r=>Hy(r,e),saveSpriteRecipe:()=>Dy(e,t),generateSpriteAnchor:()=>Gy(e,t),approveSpriteAnchor:r=>zy(r,e,t),generateSpriteRows:r=>qy(r,e,t),cancelSpriteJob:r=>$y(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}),Ha({folderId:r},e,t)},loadAssetFolders:()=>Wc(e),retryAssetGenSave:r=>_y(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:()=>Ny(e,t),loadAssets:r=>Bs(r,e,t),loadMoreAssets:()=>hy(e,t),setAssetsFilters:r=>Ha(r,e,t),saveToAssets:r=>gy(r,e,t),updateAssetItem:(r,o)=>yy(r,o,e),deleteAssetItem:r=>vy(r,e),createAssetFolder:(r,o)=>by(r,o,e),renameAssetFolder:(r,o)=>xy(r,o,e),moveAssetFolder:(r,o)=>Iy(r,o,e),deleteAssetFolder:r=>Sy(r,e),...Qn,imageToolModel:je.imageToolModel??null,quality:je.quality??"medium",sizePreset:je.sizePreset??"1024x1024",customW:je.customW??1920,customH:je.customH??1088,grokAspectRatio:je.grokAspectRatio??"1:1",grokResolution:je.grokResolution??"1k",format:je.format??"png",moderation:je.moderation??"low",count:je.count??1,multimode:je.multimode??!1,multimodeMaxImages:je.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:je.promptMode??"auto",prompt:je.prompt??"",negativePrompt:je.negativePrompt??"",naiOptionOverrides:Lm(),naiServerDefaults:null,insertedPrompts:je.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:Ue(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:Cs,activeReferenceLimit:()=>ic({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>Kp(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:Oi(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:Pa().mode,canvasExportMatteColor:Pa().matteColor,syncCapabilities:()=>np(e),addTrayAttachments:async r=>Ch(r,e),addTrayAttachmentDataUrl:(r,o)=>ro(r,o,e),addTrayElement:r=>xr(r,e),addElementFromMention:r=>xr(r.id,e,t,r),syncElementCatalog:r=>gc(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>Uc(r,e,t),clearTray:()=>Lh(e,t),addElementId:r=>{xr(r,e)},removeElementId:r=>Jp(r,e),addReferences:r=>Th(r,e,t),addReferenceDataUrl:r=>jh(r,e),metadataRestore:null,readDroppedImageMetadata:(r,o=null)=>Ah(r,o,e,t),applyMetadataRestore:()=>Ph(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>Xg(e,t),removeReference:r=>Rh(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>Mh(e,t),attachCanvasVersionReference:(r,o)=>Fh(r,e,t,o),useCurrentAsReference:()=>Dh(e,t),useImageAsReference:r=>Gh(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>Wg(r,e,t),startInFlightPolling:()=>{Af(e,t)},reconcileInflight:async()=>{await Pf(e,t)},syncFromStorage:()=>Jg(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>Yg(r,e),addGeneratedHistoryItem:async r=>{await gt(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:$e,loadOlderHistory:async()=>lh(e,t),loadFavoriteHistory:async()=>ch(e,t),loadOlderFavoriteHistory:async()=>dh(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:Tm(),toggleRightPanel:()=>Zg(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:Aa(vs),galleryDefaultScope:Aa(ll),setGalleryScope:r=>Qg(r,e),setGalleryDefaultScope:r=>ey(r,e),reasoningEffort:Rm(),webSearchEnabled:Om(),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:Am(),setUIMode:r=>ty(r,e),historyStripLayout:Pm(),setHistoryStripLayout:r=>ny(r,e),locale:Od(),setLocale:r=>{Ld(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const o=t();e({graphHistoryPast:vp(o.graphHistoryPast,po(o.graphNodes,o.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),o=bp(r.graphHistoryPast,po(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Da(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),o=xp(r.graphHistoryPast,po(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!o)return!1;const a=Da(o.restored,r.graphNodes);return e({graphNodes:De(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:o.past,graphHistoryFuture:o.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>iy(r,e,t),setGraphEdges:r=>ly(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>Kf(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>cy(e,t),selectAllGraphNodes:()=>{e({graphNodes:Sn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,o)=>dy(r,o,e,t),clearNodeSelection:()=>{e({graphNodes:Sn(t().graphNodes,[])})},cancelNodeBatch:()=>uy(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await qc(e,t)},async switchSession(r){await Sh(r,e,t)},async reconcileGraphPending(){await wh(e,t)},async createAndSwitchSession(r){await _h(r,e,t)},async renameCurrentSession(r){await Eh(r,e,t)},async deleteSessionById(r){await Nh(r,e,t)},scheduleGraphSave(){sc(t,e)},async flushGraphSave(r="manual"){await fp(t,e,r)},addRootNode:()=>Ff(e,t),createRootNodeFromHistoryItem:r=>Df(r,e,t),addChildNode:r=>Gf(r,e,t),addSiblingNode:r=>zf(r,e,t),updateNodePrompt:(r,o)=>Uf(r,o,e,t),addNodeReferences:async(r,o)=>Wf(r,o,e,t),addNodeReferenceDataUrl:(r,o)=>Pc(r,o,e,t),addNodeReferenceFromUrl:async(r,o,a)=>Jf(r,o,a,e,t),removeNodeReference:(r,o)=>Yf(r,o,e,t),clearNodeReferences:r=>Xf(r,e,t),duplicateBranchRoot:r=>$f(r,e,t),generateNode:r=>yf(r,e,t),generateNodeInPlace:r=>vf(r,e,t),generateNodeVariation:(r,o)=>bf(r,o,e,t),runGenerateNode:(r,o)=>xf(r,o,e,t),async runGenerateNodeInPlace(r,o={}){return Zp(r,o,e,t,Pe)},async runNodeBatch(r){await Qp(r,e,t)},deleteNode:r=>Hf(r,e,t),deleteNodes:r=>Vf(r,e,t),addChildNodeAt:(r,o,a)=>qf(r,o,a,e,t),connectNodes:(r,o,a,i)=>Bf(r,o,a,i,e,t),setProvider:r=>mg(r,e,t),setImageToolModel:r=>pg(r,e,t),setQuality:r=>fg(r,e,t),setSizePreset:r=>hg(r,e),setCustomSize:(r,o)=>gg(r,o,e,t),setGrokAspectRatio:r=>yg(r,e),setGrokResolution:r=>vg(r,e),setFormat:r=>bg(r,e),setModeration:r=>xg(r,e),setImageModel:r=>Ig(r,e,t),videoDuration:Zn.duration,videoResolution:Zn.resolution,videoSingleRefMode:Zn.singleRefMode,videoAspectRatio:Zn.aspectRatio,videoReferenceVoices:[],videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>Sg(r,e,t),setComfyWorkflow:r=>wg(r,e,t),setComfyVideoWorkflow:r=>_g(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),fn({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),fn({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),fn({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}),fn({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>Eg(t),runVideoGenerate:async r=>{await If(r,e,t)},animateImage:async(r,o)=>Sf(r,o,e,t),setReasoningEffort:r=>Ng(r,e),setWebSearchEnabled:r=>kg(r,e),setCount:r=>Cg(r,e),setMultimode:r=>jg(r,e,t),setMultimodeMaxImages:r=>Tg(r,e),setPromptMode:r=>Ag(r,e),setPrompt:r=>Pg(r,e),setNegativePrompt:r=>Rg(r,e),setNaiOption:(r,o)=>Mg(r,o,e,t),resetNaiOptions:()=>Lg(e),insertPromptToComposer:r=>Dg(r,e),removeInsertedPromptFromComposer:r=>Gg(r,e),moveInsertedPromptInComposer:(r,o)=>zg(r,o,e),clearInsertedPrompts:()=>qg(e),selectHistory:r=>uh(r,e,t),showHistorySequence:r=>mh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>ph(r,e,t),trashHistoryItem:async r=>fh(r,e,t),trashHistorySequence:async r=>hh(r,e,t),restorePendingTrash:async()=>gh(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>yh(r,e,t),removeFromHistory:r=>vh(r,e,t),addHistoryItem:r=>bh(r,e,t),importLocalImageToHistory:async r=>xh(r,e,t),getResolvedSize:()=>Og(t),generate:()=>ff(e,t),async generateMultimode(r){await of(r,e,t)},cancelMultimode:()=>hf(e,t),async runGenerate(r){await sf(r,e,t)},confirmCustomSizeAdjustment:()=>gf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){Ih(e)},showToast:(r,o=!1)=>ry(r,o,e),dismissToast:r=>oy(r,e),showErrorCard:(r,o)=>sy(r,o,e),dismissErrorCard:r=>ay(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:()=>$g(e),savePromptToLibrary:r=>Ug(r,e,t),deletePromptFromLibrary:r=>Hg(r,e,t),togglePromptFavorite:r=>Vg(r,e,t),importPromptsToLibrary:r=>Kg(r,e,t),toggleGalleryFavorite:r=>Bg(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)=>my(r,o,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>py(r,e,t),setCanvasExportMatteColor:r=>fy(r,e,t)})),Vy=/^[\p{L}\p{N}_-]$/u,Ky=new Set([" "," ","(","["]);function By(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(!Vy.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&&!Ky.has(a)&&a!==`
8
+ `?null:{start:o,end:n,query:e.slice(r,n)}}function Fe({title:e,help:t,items:n,value:r,onChange:o,className:a}){const i=v.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 u=d.findIndex(h=>h.value===r),p=c.key==="ArrowRight"?1:-1,m=d[(u+p+d.length)%d.length];c.preventDefault(),o(m.value),i.current?.querySelector(`[data-value="${m.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 so=Fd();function Wy(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Jy=(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}]}},Va=(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 Oe({items:e,groups:t,value:n,onChange:r,ariaLabel:o,ariaDescribedBy:a,className:i,id:l,disabled:c,portal:d=!1,triggerLabel:u,triggerSub:p,placeholder:m,title:h}){const b=v.useId(),I=v.useRef(null),x=v.useRef(null),y=v.useRef(null),[g,_]=v.useState(!1),[w,S]=v.useState({top:0,left:0,width:200,maxHeight:260}),{flat:N,rendered:A}=Jy(t,e),L=N.length===0,[U,j]=v.useState(()=>Math.max(0,N.findIndex(O=>O.value===n))),z=v.useRef({buffer:"",at:0}),q=N.find(O=>O.value===n),C=O=>`${b}-opt-${O}`,k=O=>O.searchText?O.searchText:typeof O.label=="string"?O.label:O.value,P=O=>{const ee=Date.now(),J=z.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 Ee=(ge+ie+N.length)%N.length,le=N[Ee];if(!(!le||le.disabled)&&k(le).toLowerCase().startsWith(me)){j(Ee);return}}};v.useEffect(()=>{if(!g)return;const O=ee=>{const J=ee.target;J instanceof Node&&(I.current?.contains(J)||y.current?.contains(J)||_(!1))};return document.addEventListener("pointerdown",O),()=>document.removeEventListener("pointerdown",O)},[g]),v.useLayoutEffect(()=>{if(!d||!g)return;const O=x.current?.getBoundingClientRect();if(O){const ge=Math.max(0,window.innerWidth-24),ie=Math.min(300,ge,Math.max(190,O.width)),Ee=Math.max(12,window.innerWidth-ie-12),le=Math.min(Math.max(12,O.left),Ee),Ie=window.innerHeight-O.bottom-12,Ce=O.top-12,Re=Ie>=160||Ie>=Ce?"down":"up",ce=Math.max(0,Re==="down"?Ie:Ce),be=Math.min(420,ce),D=8+N.length*44,ye=y.current?.scrollHeight??D,T=Math.min(ye,be);S({top:Re==="down"?O.bottom+4:Math.max(12,O.top-T-4),left:le,width:ie,maxHeight:be})}const ee=()=>_(!1),J=me=>{Wy(me,y.current)&&_(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,g]),v.useEffect(()=>{g&&y.current?.querySelector(`[data-index="${U}"]`)?.scrollIntoView({block:"nearest"})},[g,U]);const B=()=>{L||(j(Math.max(0,N.findIndex(O=>O.value===n))),_(!0))};v.useEffect(()=>{L&&(_(!1),j(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);j(ee)},oe=O=>{const ee=N[O];!ee||ee.disabled||(r(ee.value),_(!1),x.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(),j(Va(N,"first",U));else if(O.key==="End")O.preventDefault(),j(Va(N,"last",U));else if(O.key==="Enter"||O.key===" "){if(O.key===" "&&Date.now()-z.current.at<=1e3&&z.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 F=g&&!L?s.jsx("ul",{className:`ctl-select__list${d?" ctl-select__list--portal":""}`,role:"listbox",id:b,ref:y,style:d?{position:"fixed",top:w.top,left:w.left,width:w.width,maxHeight:w.maxHeight}:void 0,children:A.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:C(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:()=>j(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:x,className:`ctl-select__trigger${g?" is-open":""}`,role:"combobox","aria-haspopup":"listbox","aria-expanded":g,"aria-controls":g?b:void 0,"aria-activedescendant":g&&N[U]?C(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:u??q?.label??m??""}),p??q?.sub?s.jsx("span",{className:"ctl-select__value-sub",children:p??q?.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"})})]}),F?d?so.createPortal(F,document.body):F:null]})}function Yy({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 ed({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 Ys({className:e,children:t,ariaLabel:n}){return s.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":n,children:t})}function Xy(){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 td({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(Xy,{})})}function Zy(){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 Ka=12,Qy=240;function ev(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 tv(e,t){const n=ev(e,t),r=window.innerHeight-n.bottom,o=r<Qy?"top":"bottom",a=o==="bottom"?r:n.top;return{left:Math.max(Ka,Math.min(n.left,window.innerWidth-332)),top:o==="bottom"?n.bottom+6:Math.max(Ka,n.top-Math.min(320,a-8)),placement:o,maxHeight:Math.max(120,Math.min(320,a-12))}}function nv(){return window.matchMedia("(max-width: 640px)").matches}function rv({open:e,textareaRef:t,composingRef:n,caret:r,query:o,elements:a,ariaLabel:i,emptyLabel:l,kindLabel:c,onSelect:d,onClose:u,onActiveChange:p}){const m=v.useId(),[h,b]=v.useState(0),[I,x]=v.useState(null),[y,g]=v.useState(!1),_=v.useRef(null),w=v.useMemo(()=>{const L=o.trim().toLocaleLowerCase();return L?a.filter(U=>[U.name,...U.tags??[]].some(j=>j.toLocaleLowerCase().includes(L))):a},[a,o]),S=L=>{b(L),p?.(L)},N=()=>{const L=w[h];L&&d(L)};if(v.useLayoutEffect(()=>{if(!e||!t.current)return;const L=()=>{if(!t.current){u();return}g(nv()),x(tv(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,u]),v.useEffect(()=>{S(0)},[o,w.length]),v.useEffect(()=>{if(!e)return;const L=t.current;if(!L)return;L.setAttribute("aria-controls",m),L.setAttribute("aria-expanded","true");const U=j=>{if(document.activeElement===L&&!(n?.current||j.isComposing||j.keyCode===229)&&!(j.key==="Enter"&&(j.ctrlKey||j.metaKey))){if(j.key==="Escape"){j.preventDefault(),u("escape");return}j.key==="ArrowDown"||j.key==="ArrowUp"?(j.preventDefault(),S((h+(j.key==="ArrowDown"?1:-1)+w.length)%Math.max(1,w.length))):j.key==="Home"?(j.preventDefault(),S(0)):j.key==="End"?(j.preventDefault(),S(Math.max(0,w.length-1))):j.key==="Enter"?w.length&&(j.preventDefault(),N()):j.key==="Tab"&&w.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,m,h,w,u]),v.useEffect(()=>{const L=t.current,U=w[h];L&&U&&L.setAttribute("aria-activedescendant",`${m}-${U.id}`)},[h,w,m,t]),v.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const A=s.jsx("section",{className:`element-mention-menu${y?" is-mobile":""}`,style:y?void 0:{left:I.left,top:I.top,maxHeight:I.maxHeight},"aria-label":i,children:s.jsx("ul",{id:m,className:"element-mention-menu__list",role:"listbox",ref:_,children:w.length?w.map((L,U)=>s.jsxs("li",{id:`${m}-${L.id}`,role:"option","aria-selected":U===h,className:`element-mention-menu__option${U===h?" is-active":""}`,onPointerEnter:()=>S(U),onMouseDown:j=>{j.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 so.createPortal(A,document.body)}function ov(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function sv(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??ov(e.source.referenceFilenames[0])}function av({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=sv(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 iv({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 lv({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(iv,{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 cv=new Set(["character","product","style","scene"]);function dv(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&cv.has(t)?t:"character"}function uv(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 mv(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),o=new Set(n);return mc({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:dv(i),thumbnail:uv(i)??a.source.thumbnailUrl,missing:o.has(a.source.elementId)||t!==null&&!i}})}function pv(e){const t=mv(e.items,e.assets,e.missingElementIds);return t.length===0?null:s.jsx(Ys,{ariaLabel:e.selectedLabel,children:t.map(n=>{const r=e.kindLabel(n.kind);return s.jsx(lv,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const fv=["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 hv({prompt:e,retiredTags:t,textareaRef:n}){const{t:r}=V(),o=v.useRef(null),a=v.useRef(null),[i,l]=v.useState([]),c=v.useMemo(()=>Vp(e).filter(u=>Object.prototype.hasOwnProperty.call(t,u.tag)),[e,t]),d=v.useMemo(()=>[...new Set(c.map(u=>`@${u.tag}`))],[c]);return v.useLayoutEffect(()=>{const u=n.current,p=o.current,m=a.current?.firstChild;if(!u||!p||!(m instanceof Text)){l([]);return}const h=()=>{const I=getComputedStyle(u);fv.forEach(g=>{p.style[g]=I[g]}),p.scrollTop=u.scrollTop,p.scrollLeft=u.scrollLeft;const x=p.getBoundingClientRect(),y=[];for(const g of c){const _=document.createRange();_.setStart(m,g.start),_.setEnd(m,g.end),Array.from(_.getClientRects()).forEach((w,S)=>{y.push({key:`${g.start}-${g.end}-${S}`,left:w.left-x.left+p.scrollLeft,top:w.top-x.top+p.scrollTop,width:w.width,height:w.height})})}l(y)};h(),u.addEventListener("scroll",h,{passive:!0});const b=new ResizeObserver(h);return b.observe(u),()=>{u.removeEventListener("scroll",h),b.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(u=>s.jsx("span",{className:"dead-tag",style:u},u.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 ao(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 nn(o);t.addReferenceDataUrl(a);const i=Sc(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(mf(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 nd(e){const t=await ao(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const gv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:ao,continueFromItemAsUrl:nd},Symbol.toStringTag,{value:"Module"}));function yv({text:e,mode:t,onClose:n}){const{t:r}=V(),o=f(b=>b.savePromptToLibrary),[a,i]=v.useState(e.slice(0,30)),[l,c]=v.useState(e),[d,u]=v.useState(""),[p,m]=v.useState(!1),h=async()=>{l.trim()&&(m(!0),await o({name:a.trim()||l.slice(0,30),text:l.trim(),tags:d.split(",").map(b=>b.trim()).filter(Boolean),mode:t||void 0}),m(!1),n())};return s.jsxs("div",{className:"save-prompt-popover",onClick:b=>b.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:b=>i(b.target.value),placeholder:l.slice(0,30)})]}),s.jsxs("label",{children:[r("promptLibrary.content"),s.jsx("textarea",{value:l,onChange:b=>c(b.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:b=>u(b.target.value),placeholder:"cta, product, summer"})]})]}),s.jsx("div",{className:"save-prompt-popover__footer",children:s.jsx("button",{onClick:h,disabled:p||!l.trim(),className:"save-prompt-popover__save",children:r(p?"common.saving":"promptLibrary.save")})})]})}function vv({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(Yy,{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 bv({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),u=f(I=>I.storyboardActive),p=f(I=>I.toggleStoryboard),[m,h]=v.useState(!1),b=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 ao(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("gpt-5.6-luna"):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${b?" composer__tool--on":""}`,onClick:()=>d(b?"auto":"direct"),title:n("prompt.directModeTitle"),"aria-label":n("prompt.directModeTitle"),"aria-pressed":b,children:s.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"})}),s.jsx(vv,{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")}),m&&s.jsx(yv,{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${u?" composer__tool--on":""}`,onClick:p,title:n("prompt.storyboardTitle"),"aria-pressed":u,children:n("prompt.storyboard")})})]})}function Ba(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 xv(e){const{maxRefs:t,trayItemCount:n,captureAttachmentCaret:r,addFilesAtCaret:o}=e,{t:a}=V(),i=async(c,d)=>{const u=Math.max(0,t-n);if(u===0){f.getState().showToast(a("toast.refLimitTrayFull",{max:t}),!0);return}const p=c.slice(0,u),m=await o(p,d,!1);c.length>p.length&&f.getState().showToast(a("toast.refLimitPartial",{added:m,total:c.length,max:t}),!1)},l=c=>{const d=Ba(c.clipboardData?.items??null);d.length!==0&&(c.preventDefault(),i(d,r()))};return v.useEffect(()=>{const c=d=>{const u=d.target;if(["INPUT","TEXTAREA"].includes(u?.tagName??"")||u?.isContentEditable)return;const p=Ba(d.clipboardData?.items??null);p.length!==0&&(d.preventDefault(),i(p,f.getState().prompt.length))};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[o,t,a,n]),l}const rd="grok-imagine-video",Iv="grok-imagine-video-1.5",od=new Set([Iv,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function Sv(e){return e.type.startsWith("audio/")}function wv(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function _v(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,o=typeof r=="string"&&od.has(r),a=r===rd;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(Sv(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(wv(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 Ev(e){const t=e.videoModelSelected;return typeof t=="string"&&od.has(t)?"image/*,audio/*":t===rd?"image/*,video/mp4":"image/*"}function Nv(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 kv({onImages:e}){const{t}=V(),n=f(o=>o.videoModelSelected),r=f(o=>o.showToast);return o=>{if(o.length===0)return;const a=_v(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(Nv(i,t),!0)}}function Cv({variant:e,onSubmit:t}){const n=f(d=>d.provider),r=f(d=>d.negativePrompt),o=f(d=>d.setNegativePrompt),a=v.useRef(!1),{t:i}=V();if(v.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 yo="tray:";function vo(e){return`${e.start}:${e.end}:${e.query}`}function jv(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):xr(e.id,f.setState,f.getState,e)}function Tv(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):gc(e,f.setState,f.getState)}function Av(e){const t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function Xs({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),u=f(E=>E),p=u.addElementId,m=u.elementCatalog??null,h=u.missingElementIds??[],[b,I]=v.useState([]),x=E=>{const W=b.find(Q=>Q.id===E);return W?jv(W):(p?.(E),null)};v.useEffect(()=>{let E=!1;return Fp().then(W=>{E||(I(W),Tv(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{E=!0}},[]);const{t:y}=V(),g=f(E=>E.trayItems),_=f(E=>E.retiredTags),w=f(E=>E.removeTrayItem),S=f(E=>E.activeReferenceLimit()),N=f(E=>E.providerUrlReference),A=f(E=>E.setProviderUrlReference),L=f(E=>E.addReferences),U=f(E=>E.addReferenceDataUrl),j=f(E=>E.useImageAsReference),z=f(E=>E.readDroppedImageMetadata),q=f(E=>E.videoModelSelected),C=v.useRef(null),k=v.useRef(null),P=v.useRef(null),[B,se]=v.useState(!1),[oe,ae]=v.useState(null),he=v.useRef(!1),F=v.useRef(null),O=v.useRef(null),ee=f(E=>E.promptMode),J=f(pf),me=f(E=>E.multimodeMaxImages),ge=ee==="direct",ie=r==="nai",Ee=o.filter(E=>E.placement!=="after"),le=o.filter(E=>E.placement==="after"),Ie=[...Ee.map(E=>E.id),"__main_prompt__",...le.map(E=>E.id)],Ce=g.length<S,Re=J?g.length>0?y("multimode.promptPlaceholderWithRefs"):y("multimode.promptPlaceholder"):g.length>0?y("prompt.placeholderWithRefs"):y("prompt.placeholder"),ce=()=>{h.length>0||l()},be=()=>k.current?.selectionStart??f.getState().prompt.length,D=(E,W)=>{const Q=f.getState().trayItems.filter(H=>H.kind==="attachment"&&!E.has(H.tokenId));if(Q.length===0)return 0;const Se=f.getState().prompt,R=Math.max(0,Math.min(W,Se.length)),Y=Q.map(H=>`@${H.tag} `).join("");n(`${Se.slice(0,R)}${Y}${Se.slice(R)}`);const we=R+Y.length;return requestAnimationFrame(()=>k.current?.setSelectionRange(we,we)),Q.length},ye=(E,W)=>{const Q=`@${E} `,Se=f.getState().prompt,R=`${Se.slice(0,W.start)}${Q}${Se.slice(W.end)}`,Y=W.start+Q.length;n(R),requestAnimationFrame(()=>k.current?.setSelectionRange(Y,Y))},T=(E,W)=>{if(he.current)return;const Q=By(E,W);ae(Q&&vo(Q)!==O.current?Q:null)},ne=async(E,W,Q)=>{if(E.length===0)return 0;const Se=new Set(f.getState().trayItems.map(R=>R.tokenId));try{return Q&&E.length===1&&await z(E[0])?0:(await L(E),D(Se,W))}catch{return 0}},de=async E=>{const W=P.current??be();P.current=null,await ne(E,W,!0)},K=kv({onImages:E=>{de(E)}}),G=()=>{Ce&&(P.current=be(),C.current?.click())},X=async(E,W)=>{const Q=new Set(f.getState().trayItems.map(Se=>Se.tokenId));try{const Se=E.url||E.image;if(!Se)return;const R={image:Se,url:E.url,filename:E.filename};if(xe(R)){const Y=await nn(Se);Y&&U(Y)}else await j(R);D(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))},Le=E=>{E.preventDefault(),B||se(!0)},Ge=E=>{E.currentTarget.contains(E.relatedTarget)||se(!1)},Ot=xv({maxRefs:S,trayItemCount:g.length,captureAttachmentCaret:be,addFilesAtCaret:ne}),Ke=v.useRef(null),dt=v.useRef(e);v.useLayoutEffect(()=>{const E=k.current;if(!E)return;(Ke.current===null||dt.current!==e)&&(Ke.current=Av(window.getComputedStyle(E).maxHeight)??0,dt.current=e),E.style.height="auto";const W=Ke.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ut=(E,W)=>{const Q=Ie.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<Ie.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":y("prompt.moveBlockUp",{name:E.name}),title:y("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":y("prompt.moveBlockDown",{name:E.name}),title:y("prompt.moveBlockDown",{name:E.name}),children:"v"}),s.jsx("button",{type:"button",className:"composer__prompt-chip-remove",onClick:()=>a(E.id),"aria-label":y("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?y("multimode.composerAriaLabel",{count:me}):y("prompt.label"),onDrop:re,onDragOver:Le,onDragLeave:Ge,onPaste:Ot,children:[s.jsxs("div",{className:"composer__header",children:[s.jsx("span",{className:"section-title composer__label",children:y("prompt.label")}),s.jsxs("div",{className:"composer__header-meta",children:[J&&s.jsx("span",{className:"composer__mode-badge",children:y("multimode.composerBadge",{count:me})}),ge&&s.jsx("span",{className:"composer__direct-badge",children:y("prompt.directModeActive")}),N&&s.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>A(null),title:y("prompt.urlRefActiveTitle"),"aria-label":y("prompt.urlRefClear"),children:[s.jsx("span",{className:"composer__url-ref-dot","aria-hidden":"true"}),y("prompt.urlRefActive")]}),g.length>0&&s.jsx("span",{className:"composer__count",children:y("prompt.refCount",{count:g.length,max:S})})]})]}),s.jsx(av,{items:g,limit:S,onRemove:w,onAdd:G}),Ee.length>0&&s.jsx("div",{className:"composer__prompt-chips",children:Ee.map(vt)}),c.length>0&&s.jsx(Ys,{ariaLabel:y("home.selectedPresets"),children:c.map(E=>{const W=bc(E);return W?s.jsx(ed,{onRemove:()=>d(E),removeLabel:y("common.removeNamed",{name:W.name}),children:W.name},E):null})}),s.jsx(pv,{items:g,assets:m,missingElementIds:h,selectedLabel:y("element.selected"),unavailableLabel:y("common.elementUnavailable"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),mentionLabel:(E,W,Q)=>Q?y("element.unavailableAria",{name:E}):y("element.mentionAria",{name:E,kind:W}),removeLabel:E=>y("element.removeAria",{name:E}),onRemove:E=>u.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:y("nai.positivePrompt.label")}):null,s.jsxs("div",{className:"composer__prompt-stack",children:[s.jsx(hv,{prompt:t,retiredTags:_,textareaRef:k}),s.jsx("textarea",{id:`positive-prompt-${e}`,ref:k,className:"prompt-area composer__textarea",value:t,placeholder:ie?y("nai.positivePrompt.placeholder"):Re,"aria-describedby":ie?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{he.current=!0,ae(null)},onCompositionEnd:E=>{he.current=!1,F.current=E.currentTarget.value,queueMicrotask(()=>{F.current=null}),T(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{O.current=null,n(E.target.value),F.current!==E.target.value&&T(E.target.value,E.target.selectionStart)},onClick:E=>T(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=vo(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:y("nai.positivePrompt.hint",{count:t.length})}):null]}),s.jsx(Cv,{variant:"classic",onSubmit:ce})]}),s.jsx(rv,{open:oe!==null,textareaRef:k,composingRef:he,caret:oe?.end??0,query:oe?.query??"",elements:[...g.filter(E=>E.kind==="attachment").map(E=>({id:`${yo}${E.tokenId}`,name:E.tag,kind:"reference",thumbnail:E.source.dataUrl})),...b.map(E=>{const W=cc(E);return{id:E.id,name:E.name,kind:typeof E.metadata?.elementKind=="string"?E.metadata.elementKind:"character",thumbnail:W?`/generated/${W.split("/").map(encodeURIComponent).join("/")}`:void 0,tags:E.tags}})],ariaLabel:y("common.elementSuggestions"),emptyLabel:y("common.noMatchingElements"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),onSelect:E=>{const W=Wo(f.getState().trayItems,E.id);if(E.id.startsWith(yo)){const Se=E.id.slice(yo.length),R=f.getState().trayItems.find(Y=>Y.tokenId===Se);R&&oe&&ye(R.tag,oe),ae(null);return}if(x?.(E.id),W){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),ae(null);return}const Q=Wo(f.getState().trayItems,E.id);!Q||!oe||(ye(Q.tag,oe),ae(null))},onClose:E=>{E==="escape"&&oe&&(O.current=vo(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:y("prompt.afterBlocks")}),le.map(vt)]}),s.jsx(bv,{canAddMore:Ce,onAttach:G}),B&&s.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:y("prompt.dropHere",{max:S})}),s.jsx("input",{ref:C,type:"file",accept:Ev({videoModelSelected:q}),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 Zs(){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 sd(e,t=28){const n=e.trim().replace(/\s+/g," ");return n.length>t?`${n.slice(0,t)}...`:n}function Qs(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(Mv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o,variant:e.variant,panelId:e.panelId}):s.jsx(Pv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:o})}function Pv(e){return s.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>s.jsx(Rv,{f:t,...e},t.id))})}function Rv({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:sd(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 Mv(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(Lv,{f:o,determinateVideoId:n,validVideoProgress:r,...e},o.id))})}function Lv({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",u=Fv(e)??Dv(e.kind,a),p=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":`${u}, ${i}: ${c}`,children:[s.jsx("span",{className:`in-flight-placeholder${d?" in-flight-placeholder--video":""}`,"aria-hidden":"true",children:s.jsx(Gv,{video:d})}),s.jsxs("span",{className:"in-flight-rich-copy",children:[s.jsx("span",{className:"in-flight-rich-title",children:u}),s.jsx("span",{className:"in-flight-rich-prompt",title:c,children:sd(e.prompt,54)}),s.jsxs("span",{className:"in-flight-rich-status",children:[s.jsx("span",{className:"in-flight-phase",children:p==null?i:`${i} · ${p}%`}),s.jsx(Ov,{progressPercent:p,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 Ov({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 Fv(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function Dv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function Gv({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 Wa="(max-width: 800px)";function yt(){const[e,t]=v.useState(()=>typeof window<"u"?window.matchMedia(Wa).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Wa),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const zv=10,mt=12;function qv({anchorRef:e,panelId:t,focusOnOpen:n,onRequestClose:r,onPointerEnter:o,onPointerLeave:a}){const{t:i}=V(),l=v.useRef(null),c=v.useRef(null),d=v.useRef(null),[u,p]=v.useState({left:mt,top:mt,caretTop:24}),[m,h]=v.useState(!1);v.useLayoutEffect(()=>{const x=()=>{const _=e.current,w=l.current;if(!_||!w)return;const S=_.getBoundingClientRect(),N=_.closest(".sidebar")?.getBoundingClientRect(),A=w.getBoundingClientRect(),L=N?N.right:S.right,U=Math.max(mt,window.innerWidth-A.width-mt),j=Math.max(mt,window.innerHeight-A.height-mt),z=Math.min(Math.max(L+zv,mt),U),q=Math.min(Math.max(S.bottom-A.height,mt),j),C=Math.min(Math.max(S.top+S.height/2-q,16),A.height-16);p({left:z,top:q,caretTop:C}),h(!0)},y=()=>{d.current!=null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(x)};x(),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0);const g=new ResizeObserver(y);return e.current&&g.observe(e.current),l.current&&g.observe(l.current),()=>{window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0),g.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),v.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),v.useEffect(()=>{const x=g=>{const _=g.target;_&&(e.current?.contains(_)||l.current?.contains(_))||r(!1)},y=g=>{g.key==="Escape"&&(g.preventDefault(),r(!0))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",y),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",y)}},[e,r]);const b=`${t}-title`,I={left:u.left,top:u.top,"--inflight-caret-top":`${u.caretTop}px`};return so.createPortal(s.jsxs("div",{ref:l,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":b,"data-positioned":m,style:I,onPointerEnter:o,onPointerLeave:a,children:[s.jsxs("header",{className:"inflight-popup__header",children:[s.jsx("h2",{ref:c,id:b,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(Qs,{variant:"popup",panelId:t}),s.jsx("footer",{className:"inflight-popup__footer",children:i("inflight.footerHint")})]}),document.body)}const $v=180,Uv=180;function ad({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const o=f(j=>j.inFlight.length),a=yt(),{t:i}=V(),[l,c]=v.useState("closed"),[d,u]=v.useState(!1),p=v.useRef(null),m=v.useRef(null),h=v.useRef(null),b=e==="inline"?n:l!=="closed",I=()=>{m.current!=null&&window.clearTimeout(m.current),h.current!=null&&window.clearTimeout(h.current),m.current=null,h.current=null};if(v.useEffect(()=>I,[]),v.useLayoutEffect(()=>{if(o!==0)return;const j=document.activeElement;b&&j instanceof HTMLElement&&j.closest(".inflight-popup")&&p.current?.focus(),I(),c("closed"),u(!1),e==="inline"&&n&&r?.(!1)},[o,n,r,b,e]),o===0&&!(o===0&&e==="popup"&&b)||e==="popup"&&a)return null;const y=()=>window.matchMedia("(hover: hover) and (pointer: fine)").matches,g=()=>{h.current!=null&&window.clearTimeout(h.current),h.current=null},_=()=>{e!=="popup"||l==="pinned"||!y()||(g(),m.current!=null&&window.clearTimeout(m.current),m.current=window.setTimeout(()=>c("hover"),$v))},w=()=>{m.current!=null&&window.clearTimeout(m.current),m.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),Uv))},S=j=>{I(),c("closed"),u(!1),j&&p.current?.focus()},N=j=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){S(!1);return}u(j.detail===0),c("pinned")},A=j=>{j.pointerType==="mouse"&&_()},L=o>99?"99+":String(o),U=b?"inflight.badgeClose":"inflight.badgeOpen";return s.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:A,onPointerLeave:w,children:[s.jsxs("button",{ref:p,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:N,"aria-live":"polite","aria-expanded":b,"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"&&b?s.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&b?s.jsx(qv,{anchorRef:p,panelId:t,focusOnOpen:d,onRequestClose:S,onPointerEnter:g,onPointerLeave:w}):null]})}function Hv(){const{t:e}=V(),t=f(m=>m.sessions),n=f(m=>m.activeSessionId),r=f(m=>m.switchSession),o=f(m=>m.createAndSwitchSession),a=f(m=>m.renameCurrentSession),i=f(m=>m.deleteSessionById),[l,c]=v.useState(!1),d=t.find(m=>m.id===n),u=()=>{const m=window.prompt(e("session.renamePrompt"),d?.title??e("session.newSession"));m&&m.trim()&&a(m.trim())},p=(m,h)=>{window.confirm(e("session.deleteConfirm",{title:h}))&&i(m)};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(m=>!m),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:u,title:e("session.renameTitle"),disabled:!d,children:s.jsx(Zy,{})})]}),l&&s.jsxs("ul",{className:"session-list",children:[t.map(m=>s.jsxs("li",{className:m.id===n?"is-active":"",children:[s.jsxs("button",{type:"button",className:"session-item",onClick:()=>{c(!1),r(m.id)},children:[s.jsx("span",{className:"session-item-title",children:m.title}),s.jsx("span",{className:"session-item-count",children:m.nodeCount})]}),s.jsx("button",{type:"button",className:"session-del",onClick:()=>p(m.id,m.title),title:e("session.deleteTitle"),children:"×"})]},m.id)),t.length===0&&s.jsx("li",{className:"session-empty",children:e("session.empty")})]})]})}function $w(){return $("/api/comfy/workflows")}function Uw(e){return $("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function Hw(e){return $("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function Vw(e){return $("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function Kw(e){return $(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Vv(e){return Bv(await $("/api/models",e?{signal:e}:{}))}function Kv(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function bn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function hn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ja(e){if(!hn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return bn();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 bn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return bn();t.executable=e.executable}return t}function Bv(e){return!hn(e)||e.ok!==!0||!hn(e.lanes)?bn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!hn(n)||!Kv(n.status)||!hn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return bn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Ja),video:n.models.video.map(Ja)}};return[t,r]}))}const id={phase:"idle",catalog:null,observedAt:null,error:null},ft=new Set;let An=id,Mr=0,pt=null,er=null;const Ya=()=>{ta()};function ea(){return An}function gn(e){An=e;for(const t of[...ft])ft.has(t)&&t()}function bo(e,t){return e===Mr&&pt===t&&!t.signal.aborted&&ft.size>0}function Wv(e){const t=e;return t?.status===401||t?.status===403?"app-auth":t?.code==="MODEL_CATALOG_INVALID"?"invalid":"request"}async function ta(){const e=++Mr;if(pt?.abort(),pt=null,ft.size===0){gn(id);return}const t=new AbortController;if(pt=t,gn({...An,phase:"loading",error:null}),!!bo(e,t))try{const n=await Vv(t.signal);bo(e,t)&&gn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){bo(e,t)&&gn({...An,phase:"error",error:Wv(n)})}finally{e===Mr&&pt===t&&(pt=null)}}function Jv(e){const t=ft.size===0;return ft.add(e),t&&(typeof window<"u"&&(er=window,er.addEventListener("focus",Ya)),ta()),()=>{!ft.delete(e)||ft.size>0||(++Mr,pt?.abort(),pt=null,er?.removeEventListener("focus",Ya),er=null,gn({...An,phase:"idle",error:null}))}}function Vn(){return{...v.useSyncExternalStore(Jv,ea),refresh:ta}}function $t(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(m=>m.id===a):void 0,l=ds.comfy,c=r.image.some($t)||r.video.some($t),d=e.phase==="ready"&&n?.status==="ready"&&c,u=!!(d&&i&&$t(i)&&(o==="video"?l.video.supported:l.generate.supported)),p=m=>({code:m,laneAvailable:d,selectedAvailable:u,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"?p("loading"):e.phase==="error"?p("error"):!n||n.status==="key-missing"||n.status==="locked"?p("unavailable"):a&&!i?p("selected-missing"):r.image.length+r.video.length===0?p("empty"):n.status==="disconnected"?p("disconnected"):i?.executable===!1?p("selected-locked"):i?.description?.endsWith("(offline)")?p("selected-offline"):p(c?a?u?"ready":"unavailable":"choose":"unavailable")}const Yv={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 Bt(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":Yv[e.code]}const ld=[{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"}],Xa=new Map(ld.map(e=>[e.value,e.label])),Xv=new Set(["runway","higgsfield"]),tr="mcp:",nr="core:",xo="effort:",Io=Xi,cn=Vt;function Zv(e){oo(e,f.setState,f.getState)}function Qv(e){og(e,f.setState,f.getState)}function eb(e,t,n){sg(e,t,f.setState,f.getState,n)}const So={image:[],video:[]};function wo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function tb(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function cd({compact:e=!1}={}){const{t}=V(),n=f(T=>T.provider),r=f(T=>T.imageModel),o=f(T=>T.videoModelSelected),a=f(T=>T.mcpProvider??null),i=f(T=>T.mcpModel??null),l=f(T=>T.mcpMediaKind??"image"),c=f(T=>T.setProvider),d=f(T=>T.setImageModel),u=f(T=>T.selectVideoModel),p=f(T=>T.setComfyWorkflow),m=f(T=>T.comfyWorkflow),h=f(T=>T.setComfyVideoWorkflow),b=f(T=>T.comfyVideoWorkflow),I=f(T=>T.setReasoningEffort),x=f(T=>T.reasoningEffort),{providers:y,loading:g,error:_}=Kc(),[w,S]=v.useState(So),[N,A]=v.useState(!1),[L,U]=v.useState(0),[j,z]=v.useState(!1),q=Vn(),C=q.catalog??{},k=C.comfy?.models??{image:[],video:[]};v.useEffect(()=>{ug(f.setState,f.getState)},[]);const P=a?y.find(T=>T.id===a)??null:null,B=!!(P?.enabled&&P.status.state==="connected");v.useEffect(()=>{if(!a||!B){S(So),A(!1);return}const T=new AbortController;return z(!0),A(!1),Vc(a,T.signal).then(ne=>{if(T.signal.aborted)return;S(ne);const de=f.getState(),G=(de.mcpMediaKind==="video"?ne.video:ne.image).find(X=>X.id===de.mcpModel);G&&dg(G.capabilities,f.setState,f.getState)}).catch(ne=>{ne.name!=="AbortError"&&(T.signal.aborted||(S(So),A(!0)))}).finally(()=>{T.signal.aborted||z(!1)}),()=>T.abort()},[a,B,L]);const se=v.useMemo(()=>y.filter(T=>T.enabled&&T.status.state==="connected"),[y]),oe=a?`${tr}${a}`:`${nr}${n}`,ae=qu(n),he=n==="comfy"?k.image.map(T=>({id:T.id,label:T.description?.endsWith("(offline)")?`${T.label} — ${t("comfy.statusOffline")}`:T.label,disabled:q.phase!=="ready"||C.comfy?.status!=="ready"||!$t(T),reason:T.lockReason})):[],F=n==="comfy"?k.video.map(T=>({id:T.id,label:T.description?.endsWith("(offline)")?`${T.label} — ${t("comfy.statusOffline")}`:T.label,reason:T.lockReason,disabled:q.phase!=="ready"||C.comfy?.status!=="ready"||!$t(T)})):[],O=Bu({provider:n,imageModel:r,videoModel:o,comfyWorkflow:m,comfyVideoWorkflow:b}),ee=a?i?Wn(l,i):"":O,J=!a&&(n==="oauth"||n==="api")&&!o,me=!!(i&&(w.image.some(T=>T.id===i)||w.video.some(T=>T.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,Ee=T=>{if(T.startsWith(nr)){const K=T.slice(nr.length);if(!Xa.has(K))return;c(K);return}const ne=T.slice(tr.length),de=y.find(K=>K.id===ne);!de||de.status.state!=="connected"||Zv(ne)},le=T=>{const ne=f.getState();if(ne.provider!==n||(ne.mcpProvider??null)!==a)return;const de=ea();if(ne.mcpProvider){if(T.startsWith(cn))return;const K=Nm(T);if(K){const X=(K.kind==="video"?w.video:w.image).find(re=>re.id===K.model);eb(K.model,K.kind,X?.capabilities)}else Qv(T||null);return}if(ne.provider==="comfy"){const K=T.startsWith(cn),G=K?T.slice(cn.length):T;if(!kt(de,K?{comfyVideoWorkflow:G}:{comfyWorkflow:G}).selectedAvailable)return;K?h(G):p(G||null);return}if(!T.startsWith(cn)){if(T.startsWith(xo)){I(T.slice(xo.length));return}if(T.startsWith(Io)){u(T.slice(Io.length));return}d(T)}},Ie=Object.keys(C).filter(T=>!Xv.has(T)),Ce=Ie.length>0?Ie:ld.map(T=>T.value);Ce.includes("comfy")||Ce.push("comfy");const Re=[{label:t("mcp.coreProviders"),items:Ce.map(T=>{const ne=C[T],de=Xa.get(T),K=ne?tb(ne.status,t):null;return{value:`${nr}${T}`,label:de??wo(T),...K?{sub:K}:{},...ne?.reason?{title:ne.reason}:{},...de?{}:{disabled:!0}}})}];se.length>0&&Re.push({label:t("mcp.connectedProviders"),items:se.map(T=>({value:`${tr}${T.id}`,label:wo(T.id),sub:T.executable===!1?t("mcp.locked"):void 0}))}),a&&!se.some(T=>T.id===a)&&Re.push({items:[{value:`${tr}${a}`,label:wo(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:w.image.map(T=>({value:Wn("image",T.id),label:T.label}))}),ce.push({label:t("mcp.videoModels"),items:w.video.map(T=>({value:Wn("video",T.id),label:T.label}))});else{const T=C[n]?.models.video.length??0,ne=(n==="grok"||n==="grok-api")&&T>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"&&F.length>0&&ce.push({label:t("mcp.videoModels"),items:F.map(K=>({value:`${cn}${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:Hu.map(K=>({value:`${Io}${K.value}`,label:K.shortLabel}))}),J&&ce.push({label:t("sidebar.reasoningLabel"),items:zo.map(K=>({value:`${xo}${K.value}`,label:K.shortLabel,sub:K.value===x?"●":void 0}))});const de=new Set(ce.flatMap(K=>K.items.map(G=>G.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=zo.find(T=>T.value===x),D=n==="comfy"&&!a?kt(q,{comfyWorkflow:m,comfyVideoWorkflow:b}):null,ye=D?t(Bt(D,q)):null;return s.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[s.jsx(Oe,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:Re,value:oe,onChange:Ee,ariaLabel:t("mcp.providerLabel"),title:ie??t("mcp.providerLabel"),triggerSub:"",portal:!0}),s.jsx(Oe,{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(j?"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:D?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:D&&ye?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:ye}),q.phase==="error"?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{q.refresh()},children:t("comfy.display.refresh")}):null]}):ie??ge??(N?s.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>U(T=>T+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function dd(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function xn(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(dd):[]}}async function Lt(e,t){const n=await Ne(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 nb(){return Lt("/api/cardnews/image-templates")}function rb(){return Lt("/api/cardnews/role-templates")}async function ob(e){const t=await Lt("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:xn(t.plan)}}function sb(e){return Lt("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ab(e){return Lt(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function ib(e){const n=(await Lt(`/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 Za(e){return Lt(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:xn(t.plan)}))}function lb(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function cb(e){return e[0]?.id||"academy-lesson-square"}function db(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function ub(e){return Math.round(e/16)*16}function Lr(e){return Math.min(xs,Math.max(1024,ub(e)))}function Qa(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Lr(e.customW)}x${Lr(e.customH)}`}function ud(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 mb(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?ud(t.error)||M("cardNews.error"):void 0}}function pb(e){return new Promise(t=>setTimeout(t,e))}function _o(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:ud(o.error)}:r})}}const _e=Mi((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([nb(),rb()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:cb(n.templates),roleTemplateId:db(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 ob({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:Qa(n)});e({activePlan:xn(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 sb({...o,size:Qa(n),quality:r.quality,moderation:r.moderation,model:r.imageModel,sessionId:r.activeSessionId});for(e(c=>({activePlan:c.activePlan?_o(c.activePlan,i):c.activePlan}));["queued","running"].includes(i.status);)await pb(900),i=await ab(i.jobId),e(c=>({activePlan:c.activePlan?_o(c.activePlan,i):c.activePlan}));const l=await Za(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?xn(l.plan):c.activePlan?_o(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 ib({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?mb(d,dd(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(u=>u.id===n?{...u,status:"error",error:c}:u)}:d.activePlan}))}},async loadSet(n){e({loading:!0,error:null,selectedTextFieldId:null});try{const{plan:r}=await Za(n);e({activePlan:xn(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 fb(){const{t:e}=V(),t=_e(w=>w.hydrate),n=_e(w=>w.topic),r=_e(w=>w.audience),o=_e(w=>w.goal),a=_e(w=>w.contentBrief),i=_e(w=>w.outputSizePreset),l=_e(w=>w.customW),c=_e(w=>w.customH),d=_e(w=>w.setBriefField),u=_e(w=>w.setOutputSizePreset),p=_e(w=>w.setCustomSize),m=_e(w=>w.draft),h=_e(w=>w.loading),b=_e(w=>w.generating),I=_e(w=>w.draftError),x=_e(w=>w.generateSet),y=_e(w=>w.activePlan),g=y?.cards||[],_={total:g.length,done:g.filter(w=>w.status==="generated").length};return v.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:w=>d("topic",w.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:w=>d("audience",w.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:w=>d("goal",w.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:w=>d("contentBrief",w.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(w=>s.jsx("button",{type:"button",className:`option-btn${i===w?" active":""}`,onClick:()=>u(w),children:w==="custom"?e("cardNews.customSize"):w==="1024x1024"?"1024²":"2048²"},w))}),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:w=>p(Number.parseInt(w.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:w=>p(l,Number.parseInt(w.target.value,10)||c),"aria-label":e("size.height")})]}):null]}),s.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{m()},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:()=>{x()},disabled:!y||b||y.cards.every(w=>w.locked),children:[b?s.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,b?e("cardNews.progress.generating",{done:_.done,total:_.total}):e("cardNews.batchGenerate")]})]})}function Wt({className:e}){return s.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function hb({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=Ae(e),c=xe(e),d=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?_n(e):{image:e.url||e.image,filename:e.filename})),u.dataTransfer.effectAllowed="copy"};return s.jsxs("div",{className:"sidebar-history__item",children:[s.jsx("button",{ref:u=>o(l,u),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(Wt,{}),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:u=>{u.preventDefault(),u.stopPropagation(),i(e)},"aria-label":r,title:r,children:"x"})]})}function gb({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:o,onSelect:a,onDelete:i}){const l=th(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 u=e.items[d];return u&&xe(u)&&!u.thumb?s.jsx(Wt,{},Ae(u)):u?s.jsx("img",{src:u.thumb||u.url||u.image,alt:"",loading:"lazy",decoding:"async"},Ae(u)):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 ei="ima2.sidebarHistoryCollapsed";function ti(){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 yb({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 vb(){const e=f(y=>y.history),t=f(y=>y.currentImage),n=f(y=>y.selectHistory),r=f(y=>y.showHistorySequence),o=f(y=>y.trashHistoryItem),a=f(y=>y.trashHistorySequence),i=f(y=>y.inFlight),l=f(y=>y.multimodeSequences),c=f(y=>{const g=y.multimodePreviewFlightId;return g?g.startsWith("history:")?g.slice(8):y.multimodeSequences[g]?.sequenceId??null:null}),d=f(y=>y.openGallery),u=v.useRef({}),[p,m]=v.useState(()=>{try{return localStorage.getItem(ei)==="1"}catch{return!1}}),{t:h}=V(),b=Dc(t,c),I=v.useMemo(()=>Fc(e).slice(0,Lc),[e]);v.useEffect(()=>{!b||p||u.current[b]?.scrollIntoView({block:"nearest",inline:"nearest"})},[b,p,I]),v.useEffect(()=>{try{localStorage.setItem(ei,p?"1":"0")}catch{}},[p]);const x=(y,g)=>{u.current[y]=g};return s.jsxs("section",{className:`sidebar-history${p?" 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:()=>m(y=>!y),title:h(p?"history.expandRecent":"history.collapseRecent"),"aria-expanded":!p,children:h(p?"history.expandRecentShort":"history.collapseRecentShort")})]})]}),p?null:s.jsxs("div",{className:"sidebar-history__grid",children:[i.map(y=>{const g=l[y.id];if(y.kind==="multimode"&&g){const _=[s.jsx(yb,{count:g.requested},`coll-sk-${y.id}`)];for(let w=0;w<g.requested;w++)g.images[w]||_.push(s.jsx(ti,{},`sk-${y.id}-${w}`));return _}return s.jsx(ti,{},`sk-${y.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(y=>y.type==="sequence"?s.jsx(gb,{entry:y,active:b===y.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteSequenceAria",{count:y.items.length}),setRef:x,onSelect:r,onDelete:g=>{a(g)}},y.key):s.jsx(hb,{item:y.item,active:b===y.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteImageAria"),setRef:x,onSelect:n,onDelete:g=>{o(g)}},y.key))]})]})}const bb="sidebar-inflight-panel";function xb(){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"&&Qt?"agent":t==="node"&&Zt?"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(Ib,{}),i==="classic"?c?s.jsx(s.Fragment,{children:s.jsx(vb,{})}):s.jsxs(s.Fragment,{children:[s.jsx(Xs,{}),s.jsxs("div",{className:"sidebar-generate-with-inflight",children:[s.jsx(Zs,{}),s.jsx(ad,{variant:"popup",panelId:bb})]})]}):i==="card-news"?s.jsx(s.Fragment,{children:s.jsx(fb,{})}):i==="node"?s.jsxs(s.Fragment,{children:[s.jsx(Hv,{}),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(Qs,{})]}):null]})}function Ib(){const e=yt();return s.jsx(s.Fragment,{children:s.jsxs("div",{className:"logo",children:[s.jsx("div",{className:"logo-mark","aria-hidden":"true"}),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(wb,{}),s.jsx(cd,{compact:e})]})]})})}function Sb(){return s.jsx("aside",{className:"sidebar",children:s.jsx("div",{className:"sidebar__scroll",children:s.jsx(xb,{})})})}function wb(){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 _b=1024,Eb=1024,Nb="blank-canvas.png";function ni(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function kb(e){const t=ni(e?.width,_b),n=ni(e?.height,Eb),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],Nb,{type:"image/png"})}const rr=1024;function Cb(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 jb(){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]=v.useState(!1),l=v.useCallback(async()=>{if(!a){i(!0);try{const c=Cb(r()),d=await kb(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 Tb(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 Ab(e,t){try{const n=await Ne("/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 Qe(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 Pb(e,t){const n=fe();return ue()?Promise.reject(Xe(n-1)):(Tt(),new Promise((r,o)=>{let a=!1,i=()=>{},l=()=>{};const c=m=>{a||(a=!0,i(),l(),t.removeEventListener("abort",u),m())},d=()=>{Te(e.requestId).catch(()=>{})},u=()=>c(()=>{d(),o(new DOMException("Aborted","AbortError"))});if(l=jt(e.requestId,null,(m,h)=>{m==="done"?c(()=>r(h)):m==="error"&&c(()=>o(Qe(h,"Video extension failed")))}),i=Yt(()=>c(()=>{d(),o(new Error("Video extension stream timed out"))})),t.aborted)return u();t.addEventListener("abort",u,{once:!0}),os().then(()=>{if(n!==fe())throw Xe(n);if(ue())throw Xe(n-1);return Ab(e,t)}).catch(m=>c(()=>o(m)))}))}let xt={source:null,status:"idle"},dn=null,ri=0;const Xo=new Set;function or(e,t){xt={source:e,status:t};for(const n of Xo)n()}const Dt={getSnapshot:()=>xt,subscribe(e){return Xo.add(e),()=>{Xo.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 dn=t,ri=fe(),or(e.sourceVideoId,"pending"),Pb(e,t.signal).then(n=>(dn=null,or(e.sourceVideoId,"idle"),n),n=>{dn=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(){dn?.abort()},releaseView(){!ue()&&ri===fe()&&dn?.abort()}};async function Rb(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 Qe(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 Mb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),Ut=[];function Lb(e){return Ut.length>0&&Ut[Ut.length-1]===e}function Ve(e,t,n={}){const r=v.useRef(null),o=v.useRef(t);o.current=t;const a=v.useId(),{trap:i=!0,autoFocus:l=!0,restoreFocus:c=!0}=n;return v.useEffect(()=>{if(!e)return;Ut.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=r.current,p=()=>Array.from(u?.querySelectorAll(Mb)??[]).filter(x=>!x.hidden&&x.getAttribute("aria-hidden")!=="true");l&&window.requestAnimationFrame(()=>{(u?.querySelector("[data-modal-initial-focus]")??p()[0]??u)?.focus()});const m=x=>typeof c=="function"?c(x):c,h=x=>{if(!Lb(a))return;if(x.key==="Escape"){x.preventDefault(),o.current("escape");return}if(!i||x.key!=="Tab")return;const y=p();if(y.length===0){x.preventDefault(),u?.focus();return}const g=y[0],_=y[y.length-1];x.shiftKey&&document.activeElement===g?(x.preventDefault(),_.focus()):!x.shiftKey&&document.activeElement===_&&(x.preventDefault(),g.focus())};document.addEventListener("keydown",h);let b="programmatic";const I=o.current;return o.current=x=>{b=x??"programmatic",I(x)},()=>{const x=Ut.indexOf(a);x!==-1&&Ut.splice(x,1),document.removeEventListener("keydown",h),m(b)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const Ob={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 Fb(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function na(e){return Fb(e)?String(e):null}function Db(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function oi(e){return e?e.replace("x","×"):null}function Gb(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=na(n);o&&e.push({label:t,value:o,...r})}function Eo(e,t,n,r={}){typeof n!="number"||n<=0||Z(e,t,n,r)}function zb(e,t,n){const r=Gb(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function qb(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 $b(e){return e?Ob[e]??e:null}function Ub(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const o=na(r);if(!o)return;const a=Ub(o);!a||t.has(a)||(t.add(a),e.push({label:n,value:o,copyValue:o,pre:!0}))}function si(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function ai(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 Hb(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 Vb({item:e,onClose:t,onCopy:n}){const{t:r,locale:o}=V(),a=Ve(!0,t),i=v.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=$b(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),oi(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(_=>!!_),u=[],p=[];Z(p,r("metadata.fields.provider"),c,{compact:!0}),Z(p,r("metadata.fields.model"),e.model,{compact:!0}),Z(p,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Z(p,r("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),p.length&&u.push({title:r("metadata.sections.provider"),fields:p,compact:!0});const m=[];Z(m,r("metadata.fields.quality"),e.quality,{compact:!0}),Z(m,r("metadata.fields.size"),oi(e.size),{compact:!0}),Z(m,r("metadata.fields.format"),e.format,{compact:!0}),Z(m,r("metadata.fields.moderation"),e.moderation,{compact:!0}),Z(m,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Z(m,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Z(m,r("metadata.fields.kind"),e.kind,{compact:!0}),Z(m,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),m.length&&u.push({title:r("metadata.sections.settings"),fields:m,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"),si(e.usage,"input_tokens"),{compact:!0}),Eo(h,r("metadata.fields.cachedTokens"),ai(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),si(e.usage,"output_tokens"),{compact:!0}),Eo(h,r("metadata.fields.reasoningTokens"),ai(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),Eo(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&&u.push({title:r("metadata.sections.usage"),fields:h,compact:!0});const b=[];Z(b,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Z(b,r("metadata.fields.createdAt"),Db(e.createdAt,o)),Z(b,r("metadata.fields.sessionId"),e.sessionId),Z(b,r("metadata.fields.nodeId"),e.nodeId),Z(b,r("metadata.fields.parentNodeId"),e.parentNodeId),Z(b,r("metadata.fields.clientNodeId"),e.clientNodeId),Z(b,r("metadata.fields.refsCount"),e.refsCount),Z(b,r("metadata.fields.sequence"),qb(e)),Z(b,r("metadata.fields.setId"),e.setId),Z(b,r("metadata.fields.cardId"),e.cardId),b.length&&u.push({title:r("metadata.sections.lineage"),fields:b});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:na(e.video?.xaiVideoRequestId)??void 0}),Z(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&u.push({title:r("metadata.sections.video"),fields:I});const x=[];Z(x,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Z(x,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Z(x,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Z(x,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Z(x,r("metadata.fields.latestContinuityPrompt"),l?.revisedPrompt,{copyValue:l?.revisedPrompt,pre:!0}),x.length&&u.push({title:r("metadata.sections.videoContinuity"),fields:x});const y=[],g=new Set;return sr(y,g,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),sr(y,g,r("metadata.fields.revisedPrompt"),e.revisedPrompt),sr(y,g,r("metadata.fields.prompt"),e.prompt),sr(y,g,r("metadata.fields.composerPrompt"),e.composerPrompt),zb(y,r("metadata.fields.insertedPrompts"),e.composerInsertedPrompts),y.length&&u.push({title:r("metadata.sections.prompts"),fields:y}),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:[u.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(w=>s.jsxs("div",{className:Hb(w),children:[s.jsx("dt",{children:w.label}),s.jsxs("dd",{children:[w.pre?s.jsx("pre",{children:w.value}):s.jsx("span",{children:w.value}),w.copyValue?s.jsx("button",{type:"button",onClick:()=>n(w.copyValue),"aria-label":r("metadata.copyField",{label:w.label}),children:r("metadata.copy")}):null]})]},`${_.title}:${w.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 Kb(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function md(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 Bb(e,t){const n=Kb(e);if(!n||md(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 Wb=[2,4,8,16],Jb=["sublime","photo","photo_denoiser"];function Yb({pending:e,onSubmit:t,onClose:n}){const{t:r}=V(),o=Ve(!0,n,{trap:!1,restoreFocus:y=>y!=="outsidePointer"}),[a,i]=v.useState(2),[l,c]=v.useState(""),[d,u]=v.useState(10),[p,m]=v.useState(10),[h,b]=v.useState(30),I={scaleFactor:a,...l?{flavor:l}:{},sharpen:d,smartGrain:p,ultraDetail:h},x=md("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:Wb.map(y=>s.jsxs("button",{type:"button",className:`option-btn${a===y?" active":""}`,"aria-pressed":a===y,onClick:()=>i(y),children:[y,"x"]},y))}),s.jsxs("label",{className:"upscale-popover__field",children:[s.jsx("span",{children:r("result.upscaleFlavor")}),s.jsxs("select",{value:l,onChange:y=>c(y.target.value),children:[s.jsx("option",{value:"",children:r("result.upscaleFlavorAuto")}),Jb.map(y=>s.jsx("option",{value:y,children:y},y))]})]}),[["sharpen",d,u],["smartGrain",p,m],["ultraDetail",h,b]].map(([y,g,_])=>s.jsxs("label",{className:"upscale-popover__field",children:[s.jsxs("span",{children:[y," ",s.jsx("output",{children:g})]}),s.jsx("input",{type:"range",min:0,max:100,step:5,value:g,onChange:w=>_(Number(w.target.value))})]},y)),x?s.jsx("p",{className:"element-detail__error",role:"alert",children:x}):null,s.jsxs("div",{className:"upscale-popover__actions",children:[s.jsx("button",{type:"button",className:"action-btn action-btn--primary",disabled:e||!!x,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 Xb="canvas-mode-context",Zb="Canvas Mode",ii=36e5,Qb=["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 ex({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=V(),r=f(G=>G.currentImage),o=f(G=>G.showToast),a=f(G=>G.insertPromptToComposer),i=f(G=>G.createRootNodeFromHistoryItem),l=f(G=>G.trashHistoryItem),c=f(G=>G.saveToAssets),d=f(G=>G.permanentlyDeleteHistoryItemByClick),u=f(G=>G.canvasOpen),p=f(G=>G.openCanvas),[m,h]=v.useState(!1),[b,I]=v.useState(!1),x=v.useSyncExternalStore(Dt.subscribe,Dt.getSnapshot),[y,g]=v.useState("idle"),[_,w]=v.useState(!1),[S,N]=v.useState(!1),[A,L]=v.useState(!1),[U,j]=v.useState(!1),z=v.useRef(null);v.useEffect(()=>{let G=!0;return Vs().then(X=>{G&&j(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const q=async G=>{if(!C?.filename||A)return;const X=Bb(C.filename,G);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)}};v.useEffect(()=>Dt.releaseView,[]);const C=e??r,k=C?.filename??null;v.useEffect(()=>{Dt.select(k)},[k]);const P=x.status==="pending"||x.source===k?x.status:"idle";if(!C)return null;const B=xe(C),se=B?C.url||C.image:"",oe=!!C.filename,ae=!!C.filename&&!B,he=B&&!!C.filename,O=!!((C.provider==="grok"||C.provider==="grok-api")&&!B&&C.providerUrl&&C.createdAt&&Date.now()-C.createdAt<ii),ee=async()=>{if(!(!C.filename||b)){I(!0);try{await f.getState().animateImage(C.filename,C.prompt??void 0)&&o(n("toast.animateDone"))}catch(G){const X=G instanceof Error?G.message:n("toast.animateFailed");o(X,!0)}finally{I(!1)}}},J=async()=>{if(!C.filename||P==="pending"||P==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const X=Dt.start({requestId:G,sourceVideoId:C.filename,prompt:C.prompt?.trim()||void 0,provider:C.provider==="grok-api"?"grok-api":"grok",model:C.model??void 0});if(!X)return;const re=await X;f.getState().addHistoryItem(Tb(re,C)),o(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Le=ot(X).code;Le==="JOB_TRACKING_TIMEOUT"||Le==="LAN_TOKEN_REQUIRED"?He(X,f.getState()):re||o(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},me=()=>Dt.cancel(),ge=async()=>{if(!C.filename||y==="pending")return;const G=window.prompt(n("result.editVideoPrompt"))?.trim();if(!G)return;const X=new AbortController;z.current=X,g("pending");try{const re=await Rb({videoUrl:C.filename,prompt:G,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...C,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:G,userPrompt:G,model:re.model||"grok-imagine-video",format:"mp4"}),g("idle"),o(n("toast.animateDone"))}catch(re){const Le=re instanceof DOMException&&re.name==="AbortError";g(Le?"idle":"error"),Le||o(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{z.current===X&&(z.current=null)}},ie=()=>z.current?.abort(),Ee=()=>{const G=document.createElement("a");G.href=C.image,G.download=C.filename||"generated.png",G.click()},le=async G=>{const re=await(await fetch(G)).blob();let Le;if(re.type==="image/png")Le=re;else{const Ge=new Image;Ge.crossOrigin="anonymous";const Ot=URL.createObjectURL(re);await new Promise((dt,ut)=>{Ge.onload=()=>dt(),Ge.onerror=ut,Ge.src=Ot});const Ke=document.createElement("canvas");Ke.width=Ge.naturalWidth,Ke.height=Ge.naturalHeight,Ke.getContext("2d").drawImage(Ge,0,0),URL.revokeObjectURL(Ot),Le=await new Promise((dt,ut)=>Ke.toBlob(vt=>vt?dt(vt):ut(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Le})])},Ie=async()=>{try{if(B){const G=await nn(se);await le(G)}else await le(C.image);o(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{o(n("toast.copyFailed"),!0)}},Ce=async()=>{try{const G=await Yl(se);await le(G),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},Re=async()=>{try{const G=await Xl(se);await le(G),o(n("toast.frameCopied"))}catch{o(n("toast.copyFailed"),!0)}},ce=async()=>{if(C.prompt)try{await navigator.clipboard.writeText(C.prompt),o(n("toast.promptCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},be=async G=>{try{await navigator.clipboard.writeText(G),o(n("toast.metadataCopied"))}catch{o(n("clipboard.writeFailed"),!0)}},D=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await ao(C)}catch{}u&&e&&a({id:Xb,name:Zb,text:Qb});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),o(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},ye=async()=>{if(B||!C.providerUrl||!C.createdAt||Date.now()-C.createdAt>=ii){o(n("toast.continueAsUrlExpired"),!0);return}try{await nd(C)}catch{}const G=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');G&&(G.focus(),G.setSelectionRange(G.value.length,G.value.length)),o(n("toast.continueAsUrlStarted"))},T=async()=>{if(!(!C.filename||m)){h(!0);try{const G=await pu({filename:C.filename});o(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const X=G instanceof Error?G.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(C),o(n("toast.nodeRootCreated"))},de=async()=>{try{await l(C)}finally{t?.()}},K=async()=>{try{await d(C)}finally{t?.()}};return s.jsxs("div",{className:"result-actions",children:[s.jsx("button",{type:"button",className:"action-btn",onClick:Ee,children:n("result.download")}),s.jsx("button",{type:"button",className:`action-btn${B?" action-btn--frame":""}`,onClick:Ie,children:n(B?"result.copyLastFrame":"result.copyImage")}),B&&s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:Ce,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 G=await c(C);o(n(G?"chain.savedToAssets":"chain.saveToAssetsFailed"),!G)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),s.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:D,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:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),U&&C.filename&&(B?s.jsx("button",{type:"button",className:"action-btn",disabled:A,onClick:()=>{q({})},title:n("result.upscaleTitle"),children:n(A?"inflight.streaming":"result.upscale")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"action-btn",disabled:A,onClick:()=>N(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),S?s.jsx(Yb,{pending:A,onSubmit:G=>{q(G)},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:y==="pending","aria-busy":y==="pending",title:n("result.editVideoTitle"),children:n(y==="pending"?"inflight.streaming":y==="error"?"gallery.retry":"result.editVideo")}),y==="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:()=>w(!0),title:n("result.infoTitle"),children:n("result.info")}),!u&&s.jsx("button",{type:"button",className:"action-btn",onClick:p,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"})})}),C.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:()=>{T()},title:n("result.sendToComfyUITitle"),disabled:m,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(Vb,{item:C,onClose:()=>w(!1),onCopy:G=>{be(G)}})]})}const tx=["auto","flat","detailed","mono"],it={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function nx(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 rx(e){return`${Math.round(e/1024)}KB`}function ox(){const{t:e}=V(),t=f(z=>z.vectorizeTarget),n=f(z=>z.setVectorizeTarget),r=f(z=>z.addAssetGenDerivedItem),o=f(z=>z.selectedProjectId),a=f(z=>z.showToast),i=v.useRef(null),l=v.useRef(t?.filename??null);l.current=t?.filename??null;const c=v.useCallback(()=>{i.current?.abort(),i.current=null,n(null)},[n]),d=Ve(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(it.colorPrecision),[b,I]=v.useState(it.filterSpeckle),[x,y]=v.useState(it.cornerThreshold),[g,_]=v.useState(!1),[w,S]=v.useState(null),[N,A]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),S(null),A(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const L=v.useCallback(()=>{if(!t?.filename||g)return;const z=t.filename,q=new AbortController;i.current=q,_(!0),S(null),Nu({source:z,preset:u,...m!==it.colorPrecision?{colorPrecision:m}:{},...b!==it.filterSpeckle?{filterSpeckle:b}:{},...x!==it.cornerThreshold?{cornerThreshold:x}:{},projectId:o,signal:q.signal}).then(C=>{if(!(i.current!==q||l.current!==z)){if(!C.filePath)throw new Error(e("vectorize.saveError"));A({filePath:C.filePath,pathCount:C.pathCount,bytes:C.bytes}),r(nx(t,C.filePath)),a(e("vectorize.saved"))}}).catch(C=>{if(C instanceof DOMException&&C.name==="AbortError"||i.current!==q||l.current!==z)return;const k=C instanceof Error?C.message:e("vectorize.saveError");S(k),a(k,!0)}).finally(()=>{i.current!==q||l.current!==z||(i.current=null,_(!1))})},[t,g,u,m,b,x,o,r,a,e]);if(!t)return null;const U=t.url||t.image,j=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:z=>z.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:j?s.jsx("img",{src:j,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:tx.map(z=>s.jsx("button",{type:"button",className:u===z?"is-active":"","aria-pressed":u===z,onClick:()=>p(z),children:e(`vectorize.preset_${z}`)},z))}),N?s.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(N.pathCount),size:rx(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:m}),s.jsx("input",{type:"range",min:1,max:8,value:m,onChange:z=>h(Number(z.target.value))})]}),s.jsxs("label",{children:[e("vectorize.filterSpeckle")," ",s.jsx("output",{children:b}),s.jsx("input",{type:"range",min:0,max:32,value:b,onChange:z=>I(Number(z.target.value))})]}),s.jsxs("label",{children:[e("vectorize.cornerThreshold")," ",s.jsx("output",{children:x}),s.jsx("input",{type:"range",min:0,max:180,value:x,onChange:z=>y(Number(z.target.value))})]}),s.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(it.colorPrecision),I(it.filterSpeckle),y(it.cornerThreshold)},children:e("vectorize.reset")})]})]}),s.jsxs("footer",{className:"keying-panel__actions",children:[w?s.jsx("span",{className:"keying-panel__save-error",role:"alert",children:w}):null,s.jsx("button",{type:"button",className:"assetgen-generate",disabled:g||!t.filename,onClick:L,children:e(g?"vectorize.running":"vectorize.run")}),j?s.jsx("a",{className:"assetgen-popup__close",href:j,download:N?.filePath,children:e("vectorize.download")}):null,s.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function sx({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 ax(){const e=f(m=>{const h=m.multimodePreviewFlightId;return h?m.multimodeSequences[h]??null:null}),t=f(m=>m.cancelMultimode),n=f(m=>{const h=m.multimodePreviewFlightId;return!!(h&&(m.activeFlightIds.has(h)||m.inFlight.some(b=>b.id===h)))}),r=f(m=>m.selectHistory),o=f(m=>m.currentImage),a=f(m=>m.openCanvas),{t:i}=V(),l=m=>{r(m)},c=m=>{r(m),a()};if(!e)return null;const d=new Map,u=e.partials.filter(m=>m.index==null);for(const m of e.partials)m.index!=null&&d.set(m.index,m);const p=Array.from({length:e.requested},(m,h)=>{const b=e.images[h],I=d.get(h)??(b?void 0:u.shift());return{index:h,image:b,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:p.map(({index:m,image:h,partial:b})=>{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?x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l(h))}:void 0,children:[s.jsx("div",{className:"multimode-sequence__badge",children:i("multimode.stageLabel",{index:m+1})}),h?s.jsx("img",{src:h.url??h.image,alt:i("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):b?s.jsx("img",{src:b.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??m)})})]})}function ix({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 Sr(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function lx(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 Bw(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const wt=1,pd=5,ar=.22;function cx(e){return Math.min(pd,Math.max(wt,e))}function dx(e){const[t,n]=v.useState(1),[r,o]=v.useState({x:0,y:0}),[a,i]=v.useState(null),l=v.useRef(0),c=v.useRef(null),d=v.useCallback(()=>{cancelAnimationFrame(l.current),l.current=0,c.current=null,n(1),o({x:0,y:0}),i(null)},[]);v.useEffect(()=>{d()},[d,e]),v.useEffect(()=>()=>{cancelAnimationFrame(l.current)},[]);const u=v.useCallback(x=>{n(y=>{const g=cx(y+x);return g<=wt?(o({x:0,y:0}),wt):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?ar:-ar)},[u]),m=v.useCallback(()=>{if(t>wt){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=wt||x.button!==0||(x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),i({pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,baseX:r.x,baseY:r.y}))},[r.x,r.y,t]),b=v.useCallback(x=>{if(!a||a.pointerId!==x.pointerId)return;const y={x:a.baseX+x.clientX-a.startX,y:a.baseY+x.clientY-a.startY};c.current=y,cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{o(y),c.current=null})},[a]),I=v.useCallback(x=>{!a||a.pointerId!==x.pointerId||(cancelAnimationFrame(l.current),l.current=0,c.current&&(o(c.current),c.current=null),i(null),x.currentTarget.releasePointerCapture(x.pointerId))},[a]);return{zoom:t,pan:r,reset:d,zoomIn:()=>u(ar),zoomOut:()=>u(-ar),handleWheel:p,handleDoubleClick:m,handlePointerDown:h,handlePointerMove:b,handlePointerUp:I}}const ux=v.lazy(()=>Me(()=>import("./index-D_LpLGWV.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function mx(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function px(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function fx(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 Zo(){const e=f(F=>F.currentImage),t=f(F=>F.importLocalImageToHistory),n=f(F=>{const O=F.multimodePreviewFlightId;return O?F.multimodeSequences[O]??null:null}),r=f(F=>F.selectHistoryShortcutTarget),o=f(F=>F.trashHistoryItem),a=f(F=>F.permanentlyDeleteHistoryItemByShortcut),i=f(F=>F.markGeneratedResultsSeen),l=f(F=>F.activeGenerations),c=f(F=>F.canvasOpen),d=f(F=>F.openCanvas),u=f(F=>F.showToast),p=f(F=>F.history),m=f(F=>F.galleryFavorites),h=f(F=>F.toggleGalleryFavorite),{t:b}=V(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:w}=jb(),S=v.useRef(null),N=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,A=dx(N),L=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},U=F=>{if(F.key==="Delete"||F.key==="Backspace"){if(!e||F.target!==F.currentTarget||Sr(F.target))return;if(F.preventDefault(),F.shiftKey){a(e);return}o(e);return}F.key!=="ArrowLeft"&&F.key!=="ArrowRight"&&F.key!=="Home"&&F.key!=="End"||F.target===F.currentTarget&&(Sr(F.target)||(F.preventDefault(),F.key==="ArrowLeft"?r("previous"):F.key==="ArrowRight"?r("next"):F.key==="Home"?r("first"):F.key==="End"&&r("last")))},j=F=>{Sr(F.target)||(i(),F.currentTarget.focus())},z=v.useCallback(()=>{window.requestAnimationFrame(()=>S.current?.focus())},[]),q=async()=>{const F=e?.filename;if(!(!e||!F||y===F)){g(F);try{await h(e)}finally{g(O=>O===F?null:O)}}},C=v.useCallback(F=>{Array.from(F.dataTransfer.types).includes("Files")&&(F.preventDefault(),x(O=>O||!0))},[]),k=v.useCallback(F=>{F.currentTarget.contains(F.relatedTarget)||x(!1)},[]),P=v.useCallback(async F=>{if(!Array.from(F.dataTransfer.types).includes("Files"))return;F.preventDefault(),x(!1);const O=Array.from(F.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(v.Suspense,{fallback:s.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:s.jsx(ux,{currentImage:e})}),s.jsx(ox,{})]});const B=mx(e?.quality),se=px(e?.size),oe=Wi(e?.model,e?.provider),ae=e?fx(e):null,he=lx(e?.filename,p,m,e?.isFavorite);return s.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:C,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:b("canvas.drop.hint")})}):null,s.jsx("div",{className:`progress-bar${l>0?" active":""}`}),n?s.jsx(ax,{}):e&&ae?s.jsxs("div",{ref:S,className:"result-container visible",tabIndex:0,onMouseDown:j,onKeyDown:U,"aria-label":b("canvas.imageViewerAria"),children:[s.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${A.zoom>wt?" canvas-annotation-frame--zoomed":""}`,onWheel:A.handleWheel,onDoubleClick:A.handleDoubleClick,onPointerDown:A.handlePointerDown,onPointerMove:A.handlePointerMove,onPointerUp:A.handlePointerUp,onPointerCancel:A.handlePointerUp,children:[e.filename?s.jsx(td,{variant:"result",active:he,busy:y===e.filename,label:b(he?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:q}):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(${A.pan.x}px, ${A.pan.y}px) scale(${A.zoom})`}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify(_n(e))),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}):s.jsxs(s.Fragment,{children:[s.jsx("img",{className:"result-img",src:ae,alt:b("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${A.pan.x}px, ${A.pan.y}px) scale(${A.zoom})`},onDoubleClick:F=>{F.stopPropagation(),d()}},N??void 0),s.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}),s.jsx(ix,{zoom:A.zoom,minZoom:wt,maxZoom:pd,onZoomIn:A.zoomIn,onZoomOut:A.zoomOut,onReset:A.reset,labels:{controls:b("viewer.controls"),zoomIn:b("viewer.zoomIn"),zoomOut:b("viewer.zoomOut"),reset:b("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,wc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Qu(e.reasoningEffort),B,se,oe]).filter(F=>!!F).join(" · ")}),s.jsx(ex,{onAfterDeleteFocus:z}),e.prompt?s.jsx(sx,{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:b("canvas.blank.title")}),s.jsx("span",{children:b("canvas.blank.subtitle")})]}),s.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{w()},disabled:_,children:b(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function hx(){return s.jsxs("div",{className:"classic-workspace",children:[s.jsx("div",{className:"classic-workspace__stage",children:s.jsx(Zo,{})}),s.jsxs("div",{className:"classic-workspace__dock",children:[s.jsx(Xs,{variant:"bottom"}),s.jsx(Zs,{})]})]})}const fd="ima2.customSizeSlots";function gx(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 yx(){try{const e=localStorage.getItem(fd);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?qt(t.filter(gx)):[]}catch{return[]}}function vx(e){try{localStorage.setItem(fd,JSON.stringify(qt(e)))}catch{}}function bx(e,t,n){return Kr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function un(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function xx(){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]=v.useState(String(n)),[c,d]=v.useState(String(r)),[u,p]=v.useState(e==="custom"),[m,h]=v.useState(()=>yx()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=Is(i,c,n,r),w=ym().filter(P=>P.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function S(P){h(P),vx(P)}function N(){const P=nt(i,n),B=nt(c,r);o(P,B),l(String(P)),d(String(B))}function A(P){P.key==="Enter"&&(P.preventDefault(),N())}function L(){t("custom"),p(!0),I(m.length>=zt?m[0]?.id??null:null)}function U(P){t(P),P!=="custom"&&(p(!1),I(null))}function j(P){t("custom"),o(P.w,P.h),l(String(P.w)),d(String(P.h)),p(!1),I(P.id)}function z(P){y(P.id);const B=dm(P);B&&(l(String(B.w)),d(String(B.h)))}function q(){const P=bx(_.w,_.h,x),B=m.length>=zt&&b?mm(m,b,P):um(m,P);S(B),t("custom"),o(_.w,_.h),l(String(_.w)),d(String(_.h)),I(P.id),p(!1)}const C=_.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:`${Ea}×${Ea}`}):null;return s.jsxs("div",{className:"option-group size-picker",children:[s.jsx("div",{className:"section-title",children:a("size.title")}),s.jsx(Fe,{title:"",items:un(pm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(fm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(hm),value:e,onChange:U}),s.jsx(Fe,{title:"",items:un(gm),value:e,onChange:U}),s.jsxs("div",{className:"option-row size-picker__quick-row",children:[un(w).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")})]})]}),m.length>0?s.jsx("div",{className:"option-row size-picker__slot-row",children:m.map(P=>s.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===P.w&&r===P.h?" active":""}`,onClick:()=>j(P),children:[P.w,"×",P.h,s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:P.ratio||a("size.customSlot")})]},P.id))}):null,u?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"size-picker__ratio-row",children:lm.map(P=>s.jsx("button",{type:"button",className:`size-picker__ratio${x===P.id?" active":""}`,onClick:()=>z(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:A,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:A,placeholder:a("size.height")})]}),s.jsxs("div",{className:"size-picker__preview",children:[s.jsx("span",{children:a("size.normalizedPreview")}),s.jsx("strong",{children:cm(_.w,_.h)})]}),s.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:C}),k?s.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:k}):null,m.length>=zt?s.jsxs("div",{className:"size-picker__replace-row",children:[s.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(P=>s.jsxs("button",{type:"button",className:`size-picker__replace${b===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:q,children:m.length>=zt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),s.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const No=[1,2,4];function Ix(){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,[u,p]=v.useState(!No.includes(c)),[m,h]=v.useState(String(c));v.useEffect(()=>{p(!No.includes(c)),h(String(c))},[l,c]);function b(g=m){const _=Uo(Number.parseInt(g,10));d(_),h(String(_))}function I(g){p(!1),h(String(g)),d(g)}function x(g){const _=Uo(c+g);p(!0),h(String(_)),d(_)}function y(g){g.key==="Enter"&&(g.preventDefault(),b())}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:[No.map(g=>s.jsx("button",{type:"button",className:`option-btn${c===g&&!u?" active":""}`,onClick:()=>I(g),children:g},g)),s.jsx("button",{type:"button",className:`option-btn${u?" active":""}`,onClick:()=>{p(g=>!g),h(String(c))},children:i("count.customPlus")})]}),u?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"count-picker__custom",children:[s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(-1),"aria-label":i("count.decrease"),children:"-"}),s.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"count-picker__input",value:m,onChange:g=>h(g.target.value.replace(/\D/g,"")),onBlur:()=>b(),onKeyDown:y,"aria-label":i("count.customLabel")}),s.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(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 Sx={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}},wx={512:.045,"1K":.067,"2K":.101,"4K":.151},_x={512:.134,"1K":.134,"2K":.134,"4K":.24};function Ex(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function Nx(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),o=Ex(r),i=t==="nano-banana-pro"?_x:wx;return i[o]??i["1K"]??.003}function kx(e,t,n,r){return n==="gemini-api"?Nx(t,r):Sx[e]?.[t]??0}function Cx(){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",u=kx(n,i,t,l),p=t==="api"&&c?e("imageToolModel.costUnavailable"):d?e("cost.free"):r?e("cost.multimodeApprox",{amount:(u*o).toFixed(3),count:o}):e("cost.approx",{amount:u.toFixed(3)}),m=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:m?{color:m}:void 0,children:p})]})}const li="ima2:oauth-changed",jx=3e3,Tx=15e3;function hd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const o=async()=>{r&&clearTimeout(r),r=null;try{const i=await qd();if(n)return;t(i),i.status==="starting"?r=setTimeout(o,jx):i.status!=="ready"&&(r=setTimeout(o,Tx))}catch{n||t(null)}},a=()=>{o()};return window.addEventListener(li,a),o(),()=>{n=!0,window.removeEventListener(li,a),r&&clearTimeout(r)}},[]),e}function Ax(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let o=!1;return $d().then(a=>{o||t(a)}).catch(()=>{o||r(!0)}),()=>{o=!0}},[]),{data:e,error:n}}function gd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(ue())return;const n=fe();let r=!1,o=null;const a=async()=>{if(!(r||ue()||n!==fe()))try{const l=await Ne("/api/grok/status");if(r)return;const c=await l.json();if(r||ue()||n!==fe())return;t(c),c.status!=="ready"&&(o=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,o&&clearTimeout(o),window.removeEventListener(_t,i)};return window.addEventListener(_t,i),a(),i},[]),e}function yd(){const[e,t]=v.useState(null),[n,r]=v.useState(null),o=v.useRef(!1),a=v.useCallback(async()=>{if(!o.current||ue())return;const i=fe();try{const c=await(await Ne("/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 v.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 vd(){const{t:e}=V(),t=hd(),{data:n}=Ax(),r=gd(),{data:o}=yd(),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",u=r?r.status==="offline"?e("provider.grokOffline"):r.status==="no_image_model"?e("provider.grokNoImageModel"):r.status==="error"?e("provider.grokNotReady"):"":e("provider.grokNotReady"),p=o?.xai?.valid===!0,m=o?.gemini?.valid===!0||o?.vertex?.valid===!0,h=o?.atlascloud?.valid===!0,b=o?.minimax?.valid===!0,I=o?.nai?.valid===!0,x=Vn(),y=kt(x,null);return{oauth:{ok:a,reason:i,hint:l},api:{ok:c,reason:c?"":e("provider.apiInvalid")},grok:{ok:d,reason:u,hint:d?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:p,reason:p?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:m,reason:m?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:h,reason:h?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:b,reason:b?"":e("provider.minimaxApiKeyRequired")},nai:{ok:I,reason:I?"":e("provider.naiApiKeyRequired")},comfy:{ok:y.laneAvailable,reason:e(y.laneAvailable?"comfy.display.available":Bt(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function Px({open:e,providerLabel:t,reason:n,hint:r,onClose:o}){const{t:a}=V(),i=Ve(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:",ko="mcp:",Rx={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"}},Co=cs.map(e=>Rx[e]);function jo(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function To({tone:e}){return s.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function ci(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 Ao({mcpProviders:e}){const{t}=V(),n=f(j=>j.provider),r=f(j=>j.mcpProvider??null),o=f(j=>j.setProvider),a=vd(),i=Vn(),l=f(j=>j.comfyWorkflow),c=f(j=>j.comfyVideoWorkflow),d=kt(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),u=n==="comfy"&&!r,p=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[m,h]=v.useState(null),b=j=>{const z=a[j.value];return j.value==="comfy"?u?t(Bt(d,i)):z.reason:z.ok?t("provider.statusReady"):z.reason},I=j=>j.enabled?j.status.state==="connected"?j.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):j.status.state==="connecting"?t("mcp.connecting"):j.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Co.map(j=>{const z=a[j.value];return{value:`${ir}${j.value}`,searchText:`${j.provider} ${j.value==="comfy"?t("comfy.display.localMethod"):j.method}`,label:s.jsxs("span",{className:"provider-option",children:[s.jsx(To,{tone:j.value==="comfy"&&u?p:z.ok?"ok":"bad"}),s.jsxs("span",{children:[j.provider," ",j.value==="comfy"?t("comfy.display.localMethod"):j.method]})]}),sub:b(j)}})}],y=e.filter(j=>j.enabled).map(j=>({value:`${ko}${j.id}`,searchText:jo(j.id),label:s.jsxs("span",{className:"provider-option",children:[s.jsx(To,{tone:ci(j)}),s.jsx("span",{children:jo(j.id)})]}),sub:I(j)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${ko}${r}`:`${ir}${n}`,_=r?null:Co.find(j=>j.value===n)??null,w=r?e.find(j=>j.id===r)??null:null,S=_?.value==="comfy",N=S?t(Bt(d,i)):_?b(_):w?I(w):t("provider.statusDisconnected"),A=S?p:_?a[_.value].ok?"ok":"bad":w?ci(w):"bad",L=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",U=j=>{if(j.startsWith(ir)){const C=j.slice(ir.length);if(!At(C))return;const k=Co.find(B=>B.value===C),P=a[C];if(C==="comfy"){o(C);return}if(!P.ok){h({label:k?`${k.provider} ${k.method}`:C,reason:P.reason,hint:P.hint});return}o(C);return}const z=j.slice(ko.length),q=e.find(C=>C.id===z);if(!q||!q.enabled||q.status.state!=="connected"){h({label:jo(z),reason:!q||!q.enabled?t("mcp.disabledProvider"):t("mcp.disconnectedSelection")});return}oo(z,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(Oe,{groups:x,value:g,onChange:U,triggerSub:S?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),s.jsxs("div",{className:"provider-status-line","data-tone":A,role:"status","aria-live":"polite",children:[s.jsx(To,{tone:A}),s.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),s.jsx("span",{className:"provider-status-line__value",children:N})]}),S&&i.observedAt!==null?s.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,S&&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(S?"comfy.display.localMethod":"provider.authMethodTitle"),children:[s.jsx("span",{children:L}),A!=="bad"&&!S?s.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),s.jsx(Px,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const Mx=[{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"}],Lx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function Ox(){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:Mx.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:Lx.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))})]})}const Fx=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function Dx(){const{t:e}=V(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return s.jsx(Fe,{title:e("quality.grokModelTitle"),items:Fx,value:t,onChange:n})}function bd({values:e,value:t,defaultValue:n,onChange:r,allowAuto:o=!1,disabled:a,ariaLabel:i}){const{t:l}=V(),c=v.useId();if(e.length===0)return null;const d=t??n??e[0],u=e.reduce((b,I,x)=>Math.abs(I-d)<Math.abs(e[b]-d)?x:b,0),p=t===null,m=e[0],h=e[e.length-1];return s.jsxs("div",{className:`ctl-duration${p?" is-auto":""}${a?" is-disabled":""}`,children:[s.jsxs("div",{className:"ctl-duration__head",children:[s.jsx("output",{htmlFor:c,className:"ctl-duration__value",children:p?`${l("size.autoLabel")} · ${e[u]}s`:`${e[u]}s`}),o?s.jsx("button",{type:"button",className:`option-btn ctl-duration__auto${p?" active":""}`,"aria-pressed":p,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:u,disabled:a,"aria-label":i,"aria-valuetext":`${e[u]}s`,onChange:b=>r(e[Number(b.target.value)]??e[0])}),s.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[s.jsxs("span",{children:[m,"s"]}),s.jsxs("span",{children:[h,"s"]})]})]})}const di=3;function Gx(){const{t:e}=V(),t=f(p=>p.videoModelSelected),n=f(p=>p.videoReferenceVoices),r=f(p=>p.toggleVideoReferenceVoice),[o,a]=v.useState([]),[i,l]=v.useState("");v.useEffect(()=>{let p=!0;return Fi().then(m=>{p&&a(m.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{p=!1}},[]);const c=Rt(t)===tt,d=n.length>=di,u=()=>{const p=i.trim();!p||d||n.includes(p)||(r(p),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:di}):e("video.voiceNeeds15")}),s.jsx("div",{className:"option-row",role:"group","aria-label":e("video.voiceSection"),children:o.map(p=>{const m=n.includes(p);return s.jsxs("button",{type:"button",className:`option-btn${m?" active":""}`,"aria-pressed":m,disabled:!c||!m&&d,onClick:()=>r(p),children:[p,m?s.jsxs(s.Fragment,{children:[s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:`<AUDIO_${n.indexOf(p)}>`})]}):null]},p)})}),s.jsx("input",{type:"text",className:"text-input",value:i,disabled:!c||d,placeholder:e("video.voiceCustomPlaceholder"),onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())},onBlur:u,"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})),ui=[3,5,8,10,12,15],$x=[{value:hs,label:"Grok V",sub:"Fast"},{value:tt,label:"Grok V1.5",sub:"HD"}];function Ux(){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),u=f(k=>k.videoAspectRatio),p=f(k=>k.setVideoAspectRatio),m=f(k=>k.videoTopic),h=f(k=>k.setVideoTopic),b=f(k=>k.showToast),I=f(k=>k.videoContinuityLineage),x=f(k=>k.selectedPresetIds),y=f(k=>k.removePreset),g=x.map(k=>bc(k)).filter(k=>k?.category==="camera-motion"),_=Ku(r,o),w=xa(t,_),S=wc(I),N=lo(t,"1080p",_),A=lo(tt,"1080p",_),L=zx.map(k=>k.value==="1080p"?{...k,disabled:!A}:k);v.useEffect(()=>{lo(t,c,_)||d("720p")},[_,c,d,t]),v.useEffect(()=>{i!==null&&i>w&&l(w)},[i,w,l]);const U=k=>{const P=xa(k,_);i!==null&&i>P&&b(e("video.durationClampedToModel",{seconds:P})),n(k)},j=k=>{if(k==="1080p"){if(!A)return;N||n(tt)}d(k)},[z,q]=v.useState(null);v.useEffect(()=>{Ne("/api/config/grok-planner").then(k=>k.json()).then(q).catch(()=>{})},[]);const C=async k=>{const P=z?.model;q(B=>B?{...B,model:k}:null);try{const B=await Ne("/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(q(se=>se&&P?{...se,model:P}:se),B?.code==="LAN_TOKEN_REQUIRED")return;b(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:$x.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})})]}),S?s.jsxs("div",{className:"provider-compat-note",role:"note",children:[s.jsx("strong",{children:e("common.continuity")}),s.jsx("span",{children:S})]}):null,s.jsx(Gx,{}),g.length>0&&s.jsx(Ys,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(k=>s.jsx(ed,{onRemove:()=>y(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:m,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(bd,{values:ui.filter(k=>k<=w),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??ui[0])})]}),r===1&&s.jsx(Fe,{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(Fe,{title:e("video.resolutionTitle"),help:A?void 0:e("video.resolution1080Help"),items:L,value:c,onChange:j}),s.jsx(Fe,{title:e("video.aspectTitle"),items:qx,value:u,onChange:p}),z&&s.jsx("div",{className:"video-controls__pills",children:s.jsx(Oe,{className:"video-controls__pill",items:z.options.map(k=>({value:k,label:k})),value:z.model,onChange:k=>{C(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 mi=e=>Symbol.iterator in e,pi=e=>"entries"in e,fi=(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},Hx=(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 Vx(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:mi(e)&&mi(t)?pi(e)&&pi(t)?fi(e,t):Hx(e,t):fi({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Kx(e){const t=pn.useRef(void 0);return n=>{const r=e(n);return Vx(t.current,r)?t.current:t.current=r}}const Bx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function Wx(){const{t:e}=V(),t=f(Kx(ep)),n=f(u=>u.setNaiOption),r=f(u=>u.resetNaiOptions),o=f(u=>u.imageModel),a=f(u=>u.setImageModel),i=f(u=>u.sizePreset),l=f(u=>u.setSizePreset),c=Ho(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(Oe,{items:Bi.map(u=>({value:u.value,label:u.shortLabel})),value:o,onChange:u=>{Ho(u)||(n("straightAlpha",!1),n("qualityPresetId","standard")),a(u)},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:Bx.map(u=>s.jsxs("button",{type:"button",className:`option-btn${i===u.value?" active":""}`,onClick:()=>l(u.value),children:[u.label==="nai.size.portrait"?e("nai.size.portrait"):u.label==="nai.size.landscape"?e("nai.size.landscape"):e("nai.size.square"),s.jsx("br",{}),s.jsx("span",{className:"option-sub",children:u.value.replace("x","×")})]},u.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(Oe,{items:hl.map(u=>({value:u,label:u})),value:t.sampler,onChange:u=>n("sampler",u),ariaLabel:e("nai.field.sampler")})]}),s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.noiseSchedule")}),s.jsx(Oe,{items:gl.map(u=>({value:u,label:u})),value:t.noiseSchedule,onChange:u=>n("noiseSchedule",u),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:u=>n("autoSmea",u.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:u=>n("steps",Number(u.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:u=>n("scale",Number(u.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:Cr.min,max:Cr.max,step:.01,value:t.cfgRescale,onChange:u=>n("cfgRescale",Number(u.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:u=>n("decrisper",u.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(Oe,{items:yl.map(u=>({value:u,label:e(`nai.ucPreset.${u}`)})),value:t.ucPresetId,onChange:u=>n("ucPresetId",u),ariaLabel:e("nai.field.ucPreset")})]}),c?s.jsxs("label",{className:"nai-controls__row",children:[s.jsx("span",{children:e("nai.field.qualityPreset")}),s.jsx(Oe,{items:vl.map(u=>({value:u,label:e(`nai.qualityPreset.${u}`)})),value:t.qualityPresetId,onChange:u=>n("qualityPresetId",u),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:u=>n("varietyPlus",u.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:u=>n("straightAlpha",u.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:u=>{const p=u.target.value.replace(/\D/g,"");n("seed",p===""?null:Math.min(Number(p),bl))}})]}),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 Jx="",xd=3;function hi(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 Yx(e,t){return e[t]??null}function Id(e,t,n){const r=!t||e.some(o=>o.filename===t);return[{value:Jx,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 Po({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(Oe,{id:e,items:Id(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 Xx({index:e,images:t,selection:n,disabled:r,onChange:o,t:a}){const i=Yx(n.references,e),l=new Set(n.references.filter((b,I)=>I!==e).map(b=>b.filename)),c=i?.dataUrl?{filename:i.filename,current:!1,label:i.displayName??a("mcp.referenceLocalFallback"),source:"local"}:null,d=[...c?[c]:[],...t.filter(b=>!l.has(b.filename))],u=b=>{const I=[...n.references];b?I[e]={filename:b,...i?.tag?{tag:i.tag}:{}}:I.splice(e,1),o({...n,references:I})},p=b=>{if(!i)return;const I=[...n.references],{tag:x,...y}=i;I[e]={...y,...b?{tag:b}:{}},o({...n,references:I})},m=!!(i?.tag&&!Ss(i.tag)),h=`mcp-reference-tag-error-${e}`;return s.jsxs("div",{className:"mcp-reference-slot__reference",children:[s.jsx(Oe,{items:Id(d,i?.filename??"",a),value:i?.filename??"",onChange:u,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:b=>p(b.target.value),"aria-label":a("mcp.referenceTagAria",{index:e+1}),placeholder:a("mcp.referenceTagPlaceholder"),"aria-invalid":m,"aria-describedby":m?h:void 0,maxLength:32,disabled:r||!i}),m?s.jsx("p",{id:h,className:"settings-row__microcopy",role:"alert",children:a("mcp.referenceTagInvalid")}):null]})]})}function Zx({selection:e,disabled:t,onChange:n,t:r}){const o=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=xd,c=async d=>{const u=d.target.files?.[0];if(d.target.value="",!!u){if(!/^image\/(?:png|jpeg|webp)$/i.test(u.type)){i(r("mcp.referenceLocalInvalidType"));return}try{const p=await Ts(u),m=`local:${globalThis.crypto.randomUUID()}`;n({...e,references:[...e.references,{filename:m,displayName:u.name,dataUrl:p}]}),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 Qx({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:xd},(a,i)=>s.jsx(Xx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:o},i)),s.jsx(Zx,{selection:t,disabled:n,onChange:r,t:o})]})}function eI({inputRoles:e,disabled:t}){const{t:n}=V(),r=f(p=>p.history),o=f(p=>p.currentImage),a=f(p=>p.assets),i=f(p=>p.mcpReferenceSelection)??Ue(),l=v.useMemo(()=>hi(r,o,a,!1),[r,o,a]),c=v.useMemo(()=>hi(r,o,a,!0),[r,o,a]),d=p=>cg(p,f.setState,f.getState),u=i.startFrameFilename?void 0:n("mcp.endFrameNeedsStart");return s.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?s.jsx(Po,{id:"mcp-start-frame",label:n("mcp.startFrameLabel"),value:i.startFrameFilename,candidates:l,disabled:t,t:n,onChange:p=>d({...i,startFrameFilename:p||null,...p?{}:{endFrameFilename:null}})}):null,e.includes("end_image")?s.jsx(Po,{id:"mcp-end-frame",label:n("mcp.endFrameLabel"),value:i.endFrameFilename,candidates:l,disabled:t||!i.startFrameFilename,title:u,help:u,t:n,onChange:p=>d({...i,endFrameFilename:p||null})}):null,e.includes("image_references")?s.jsx(Qx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?s.jsx(Po,{id:"mcp-video-reference",label:n("mcp.videoReferenceLabel"),value:i.referenceVideoFilename,candidates:c,disabled:t,t:n,help:n("mcp.videoReferenceCostNote"),onChange:p=>d({...i,referenceVideoFilename:p||null})}):null]})}function tI(e){return Array.isArray(e)&&e.includes("image_references")}function nI(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function Ww(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 Jw(e){return e.length>3}function rI({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(!tI(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=nI({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 gi=new Set(["duration","resolution","quality","mode"]);function yi(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ra(e){return e.options&&e.options.length>0?yi(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):yi([e.min,...e.default!==void 0?[e.default]:[],e.max])}function vi(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 oI(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function sI(e){return[...ra(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function aI({parameter:e,value:t,disabled:n,onChange:r}){const{t:o}=V();if(e.name==="duration"&&e.type==="number"){const l=sI(e);if(l.length>1){const c=vi(e.name,o);return s.jsxs("div",{className:"mcp-preset-row",children:[s.jsx("div",{className:"section-title",children:c}),s.jsx(bd,{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=ra(e);if(a.length===0)return null;const i=vi(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:oI(l,o)},`${typeof l}:${String(l)}`))]})]})}function bi({entries:e,parameters:t,disabled:n,onParameter:r}){return s.jsx(s.Fragment,{children:e.map(o=>s.jsx(aI,{parameter:o,value:t[o.name],disabled:n,onChange:a=>r(o.name,a)},o.name))})}function iI({entry:e,ratio:t,parameters:n,disabled:r,onRatio:o,onParameter:a}){const{t:i}=V(),l=e.capabilities.aspectRatios.filter(m=>m!=="auto"),c=e.capabilities.parameters.filter(m=>ra(m).length>0),d=c.filter(m=>gi.has(m.name)),u=c.filter(m=>!gi.has(m.name)),p=e.capabilities.inputRoles.some(m=>m==="start_image"||m==="end_image"||m==="image_references"||m==="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(m=>s.jsx("button",{type:"button",className:`option-btn${t===m?" active":""}`,"aria-pressed":t===m,disabled:r,onClick:()=>o(m),children:m},m))]})]}):null,s.jsx(bi,{entries:d,parameters:n,disabled:r,onParameter:a}),p?s.jsxs("div",{className:"mcp-tool-inputs",children:[s.jsx("div",{className:"section-title",children:i("mcp.toolInputsLabel")}),s.jsx(eI,{inputRoles:e.capabilities.inputRoles,disabled:r}),s.jsx(rI,{inputRoles:e.capabilities.inputRoles,disabled:r})]}):null,u.length>0?s.jsxs("details",{className:"mcp-advanced-presets",children:[s.jsx("summary",{children:i("mcp.advancedPresetsLabel")}),s.jsx(bi,{entries:u,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:[]},lI={};function cI(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function dI({record:e}){const{t}=V(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),o=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??lI,[c,d]=v.useState(lr),[u,p]=v.useState("idle"),[m,h]=v.useState(0),b=e?.executable===!1,I=e?.status.state==="connected";if(v.useEffect(()=>{if(!n||!I){d(lr),p("idle");return}const _=new AbortController;return d(lr),p("loading"),Vc(n,_.signal).then(w=>{_.signal.aborted||(d(w),p("ready"))}).catch(w=>{w.name!=="AbortError"&&(_.signal.aborted||(d(lr),p("error")))}),()=>_.abort()},[n,I,m]),!n)return null;const x=o==="video"?c.video:c.image,y=x.find(_=>_.id===r)??null,g=_=>ag(_,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:[cI(n)," · MCP"]}),s.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>oo(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),I?null:s.jsx("p",{className:"option-help",children:t("mcp.disconnectedSelection")}),b?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")}),u==="loading"?s.jsx("p",{className:"option-help",role:"status",children:t("mcp.loadingModels")}):u==="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")})]}):u==="ready"&&x.length===0?s.jsx("p",{className:"option-help",children:t("mcp.noModels")}):y?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mcp-selected-model",children:[s.jsx("strong",{children:y.label}),y.description?s.jsx("span",{children:y.description}):null]}),s.jsx(iI,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>ig(_,f.setState),onParameter:(_,w)=>lg(_,w,f.setState,f.getState)})]}):s.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function uI(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"?`${Vt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!$t(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 mI(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(Vt),o=r?e.slice(Vt.length):e;kt(ea(),r?{comfyVideoWorkflow:o}:{comfyWorkflow:o}).selectedAvailable&&(r?n.setComfyVideoWorkflow(o):n.setComfyWorkflow(o))}function pI(){const{t:e}=V(),t=v.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(),u=kt(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${Vt}${l}`:i??"",m=uI(d,u,p,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(Bt(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),s.jsx(Oe,{id:r,groups:m,value:p,onChange:h=>mI(h,{provider:o,mcpProvider:a}),ariaLabel:e("comfy.display.chooseWorkflow"),ariaDescribedBy:n,placeholder:e("comfy.display.chooseWorkflow"),portal:!0}),u.selected?s.jsxs("p",{className:"option-help",children:[e(u.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage"),": ",u.selected.label,s.jsx("br",{}),s.jsx("code",{children:u.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 fI=[{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"}],hI=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Or={"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 gI(e){for(const[t,n]of Object.entries(Or))for(const[r,o]of Object.entries(n))if(o===e)return{ratio:t,res:r};return null}function yI(e,t){const n=e/t;let r="1:1",o=1/0;const a=[...Object.keys(Or),"1:8","8:1","1:4","4:1"];for(const c of a){const[d,u]=c.split(":").map(Number),p=Math.abs(n-d/u);p<o&&(o=p,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 Sd(){const{t:e}=V(),t=f(D=>D.provider),n=f(D=>D.imageToolModel),r=f(D=>D.setImageToolModel),o=f(D=>D.quality),a=f(D=>D.setQuality),i=f(D=>D.format),l=f(D=>D.setFormat),c=f(D=>D.moderation),d=f(D=>D.setModeration),u=f(D=>D.multimode),p=f(D=>D.setMultimode),m=f(D=>D.imageModel),h=f(D=>D.setImageModel),b=f(D=>D.selectVideoModel),I=f(D=>D.sizePreset),x=f(D=>D.customW),y=f(D=>D.customH),g=f(D=>D.setSizePreset),_=f(D=>D.setCustomSize),w=f(D=>D.uiMode),S=f(D=>D.videoModelSelected),N=f(D=>D.mcpProvider??null),{providers:A}=Kc(),L=w==="classic",U=t==="grok"||t==="grok-api",j=t==="agy",z=t==="gemini-api",q=j||z,C=t==="nai",k=t==="comfy",P=U||q||C,B=I==="custom"?`${x}x${y}`:"1024x1024",se=z&&I==="auto",oe=z&&!se?gI(B):null,ae=oe??{ratio:"",res:""},he=z&&!se&&I==="custom"&&!oe,F=m==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[O,ee]=v.useState(!1),[J,me]=v.useState(String(x)),[ge,ie]=v.useState(String(y)),Ee=(D,ye)=>{const T=Or[D||"1:1"]?.[ye||"1K"]||"1024x1024",[ne,de]=T.split("x").map(Number);ee(!1),g("custom"),_(ne,de)},le=()=>{const D=Number(J),ye=Number(ge);!Number.isFinite(D)||!Number.isFinite(ye)||D<=0||ye<=0||(g("custom"),_(D,ye),ee(!1))},Ie=[{value:"low",label:e("quality.lowLabel"),sub:e("quality.lowSub")},{value:"medium",label:e("quality.mediumLabel"),sub:e("quality.mediumSub")},{value:"high",label:e("quality.highLabel"),sub:e("quality.highSub")},...t==="api"&&n?[{value:"xhigh",label:e("quality.xhighLabel")},{value:"max",label:e("quality.maxLabel")}]:[]],Ce=[{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")}:j?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:z?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:C?{title:e("nai.compatTitle"),body:e("nai.compatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},be=D=>{D==="video"?b("grok-imagine-video"):h(m)};return N?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ao,{mcpProviders:A}),s.jsx(dI,{record:A.find(D=>D.id===N)??null})]}):k?s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ao,{mcpProviders:A}),s.jsx(pI,{})]}):s.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[s.jsx(Ao,{mcpProviders:A}),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${S?"":" active"}`,onClick:()=>be("image"),children:e("grokMode.image")}),s.jsx("button",{type:"button",className:`option-btn${S?" active":""}`,onClick:()=>be("video"),children:e("grokMode.video")})]})}),S?s.jsx(Ux,{}):s.jsxs(s.Fragment,{children:[j?null:U?s.jsxs(s.Fragment,{children:[s.jsx(Dx,{}),s.jsx(Ox,{})]}):C?s.jsx(Wx,{}):z?s.jsxs(s.Fragment,{children:[s.jsx(Fe,{title:e("quality.grokModelTitle"),items:Re,value:F,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((D,ye)=>s.jsx("div",{className:"option-row",children:D.map(T=>s.jsx("button",{type:"button",className:`option-btn${ae.ratio===T.value?" active":""}`,onClick:()=>Ee(T.value,ae.res),children:T.label},T.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:hI.map(D=>s.jsxs("button",{type:"button",className:`option-btn${ae.res===D.value?" active":""}`,onClick:()=>Ee(ae.ratio,D.value),children:[s.jsx("span",{children:D.label}),s.jsx("br",{}),s.jsx("small",{children:Or[ae.ratio]?.[D.value]?.replace("x","×")||""})]},D.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(D=>!D),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:D=>me(D.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:D=>ie(D.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 D=yI(Number(J),Number(ge));return`${D.ratio} · ${D.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(Oe,{ariaLabel:e("imageToolModel.title"),items:[{value:"",label:e("imageToolModel.default")},...Ki],value:n??"",onChange:D=>r(D||null),portal:!0})]}),s.jsx(Fe,{className:Ie.length>3?"quality-options-expanded":"",title:e("quality.title"),items:Ie,value:o,onChange:a}),s.jsx(xx,{})]}),P?null:s.jsxs(s.Fragment,{children:[s.jsx(Fe,{title:e("format.title"),items:fI,value:i,onChange:l}),s.jsx(Fe,{title:e("moderation.title"),items:Ce,value:c,onChange:d}),s.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),L&&!q&&!C&&s.jsx("div",{className:"option-group multimode-toggle",children:s.jsxs("button",{type:"button",className:`multimode-toggle__button${u?" active":""}`,"aria-pressed":u,title:e("multimode.tooltip"),onClick:()=>p(!u),children:[s.jsx("span",{children:e("multimode.label")}),s.jsx("span",{children:e("multimode.shortHint")})]})}),q||C?null:s.jsx(Ix,{}),C?null:s.jsx(Cx,{})]})]})}const vI=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Ct98TJ61.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),bI=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-CL34Jpso.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),xI=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-EYEiHIr9.js"),__vite__mapDeps([6,1,2,7])).then(e=>({default:e.GenerationRequestLogPanel})));function II(){const e=f(y=>y.rightPanelOpen),t=f(y=>y.toggleRightPanel),n=f(y=>y.promptLibraryOpen),r=f(y=>y.setPromptLibraryOpen),o=f(y=>y.promptBuilderOpen),a=f(y=>y.togglePromptBuilder),i=f(y=>y.workspaceProfile),{t:l}=V(),[c,d]=v.useState(typeof window<"u"?window.matchMedia("(max-width: 800px)").matches:!1);v.useEffect(()=>{if(typeof window>"u")return;const y=window.matchMedia("(max-width: 800px)"),g=()=>d(y.matches);return y.addEventListener("change",g),()=>y.removeEventListener("change",g)},[]);const[u,p]=v.useState(!1),m=sh(i)&&!c,h=c?e:!0,b=Ve(c&&e,t),I=u?"log":o&&m?"builder":n?"library":"settings",x=y=>{p(y==="log"),y==="builder"?(o||a(),n&&r(!1)):y==="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:b,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:[m?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:()=>x("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${m?"":" right-panel-tabs__button--full"}${I==="log"?" active":""}`,onClick:()=>x("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:()=>x("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:()=>x("settings"),children:l("panel.detailSettings")})]}),I==="builder"&&m?s.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(bI,{variant:"sidebar"})})}):I==="library"?s.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(vI,{variant:"embedded"})})}):I==="log"?s.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:s.jsx(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:s.jsx(xI,{})})}):s.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:s.jsx(Sd,{})})]})]})]})}function SI(e){const t=e.currentTarget;if(t.scrollWidth<=t.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const r=t.scrollLeft<=0,o=t.scrollLeft+t.clientWidth>=t.scrollWidth-1,a=e.deltaY<0,i=e.deltaY>0;a&&r||i&&o||(e.preventDefault(),t.scrollLeft+=e.deltaY)}function wI({id:e}){const{t}=V();return s.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function _I({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 EI({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&&(Ze(l.url)||Ze(l.image))?s.jsx(Wt,{className:"collection-mini"},c):s.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function NI(e){const t=v.useRef(null),n=v.useRef(new Map),[r,o]=v.useState(()=>new Set);v.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 u=new Set(d);for(const p of c){const m=p.target.dataset.historyLazyKey;m&&u.add(m)}return u})},{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=v.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 kI(){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=v.useRef({}),[c,d]=v.useState(null),u=NI(c),{t:p}=V(),m=t?Ae(t):null,h=v.useMemo(()=>Ir(e.filter(vn)),[e]),b=v.useMemo(()=>{const g=[];for(const _ of a){const w=i[_.id];if(_.kind==="multimode"&&w){g.push({type:"collection-skeleton",id:_.id,count:w.requested});for(let S=0;S<w.requested;S++)w.images[S]||g.push({type:"skeleton",id:`${_.id}_${S}`,count:1})}else g.push({type:"skeleton",id:_.id,count:1})}return g},[a,i]),{completedSequences:I,sequenceFirstKeys:x}=v.useMemo(()=>{const g=new Map,_=new Set;for(const w of h)if(w.sequenceId&&(w.sequenceTotalRequested??0)>1){g.has(w.sequenceId)||_.add(Ae(w));const S=g.get(w.sequenceId)||[];S.push(w),g.set(w.sequenceId,S)}return{completedSequences:g,sequenceFirstKeys:_}},[h]);v.useEffect(()=>{m&&l.current[m]?.scrollIntoView({block:"nearest",inline:"nearest"})},[m,h]);const y=(g,_)=>{const w=u.supported?u.visibleKeys.has(g):!0;return s.jsx("div",{ref:S=>{l.current[g]=S,u.register(g,S)},className:"history-thumb","data-history-lazy-key":g,"aria-hidden":w?void 0:!0,style:{padding:0,overflow:"hidden"},children:w?_:null},g)};return s.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:SI,"data-layout":n,children:[s.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:o,"aria-label":p("history.openGalleryAria"),title:p("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"})]})}),b.map(g=>g.type==="collection-skeleton"?s.jsx(_I,{id:g.id,count:g.count},`coll-${g.id}`):s.jsx(wI,{id:g.id},g.id)),h.map(g=>{const _=Ae(g),w=m===_;if(g.sequenceId&&I.has(g.sequenceId)&&x.has(_)){const S=I.get(g.sequenceId);return[y(`coll-${g.sequenceId}`,s.jsx(EI,{sequenceId:g.sequenceId,images:S})),...S.map(N=>{const A=Ae(N),L=m===A;return xe(N)?y(A,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(_n(N))),U.dataTransfer.effectAllowed="copy"},children:[N.thumb?s.jsx("img",{src:N.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Wt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(A,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)&&!x.has(_)?null:xe(g)?y(_,s.jsxs("div",{className:`history-thumb history-thumb--video${w?" active":""}`,onClick:()=>r(g),draggable:!0,onDragStart:S=>{S.dataTransfer.setData("application/ima2-ref",JSON.stringify(_n(g))),S.dataTransfer.effectAllowed="copy"},children:[g.thumb?s.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):s.jsx(Wt,{}),s.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(_,s.jsx("img",{src:g.thumb||g.url||g.image,alt:"",className:`history-thumb${w?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(g),draggable:!0,onDragStart:S=>{S.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:g.url||g.image,filename:g.filename})),S.dataTransfer.effectAllowed="copy"}}))})]})}const xi=3e3;function CI(){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]=v.useState(()=>typeof document>"u"?!0:document.visibilityState==="visible"),l=v.useRef(new Map);v.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)}},[]),v.useEffect(()=>{const d=l.current,u=new Set([...t.map(p=>`toast-${p.id}`),...n.map(p=>`error-card-${p.id}`)]);for(const[p,m]of d)(!u.has(p)||!a)&&(clearTimeout(m),d.delete(p));if(a){for(const p of t){const m=`toast-${p.id}`;if(d.has(m))continue;const h=setTimeout(()=>{d.delete(m),r(p.id)},xi);d.set(m,h)}for(const p of n){const m=`error-card-${p.id}`;if(d.has(m))continue;const h=setTimeout(()=>{d.delete(m),o(p.id)},xi);d.set(m,h)}}},[o,r,n,a,t]),v.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 u=We[d.code],p=d.cardKey??u?.cardKey??"errorCard.unknown",m=e(`${p}.title`),h=e(`${p}.body`),b=d.cta??u?.cta;return{kind:"error-card",id:d.id,key:`error-card-${d.id}`,message:d.fallbackMessage?`${m}: ${h} ${d.fallbackMessage}`:`${m}: ${h}`,error:!0,createdAt:d.createdAt,cta:b,cardKey:p}})].sort((d,u)=>d.createdAt-u.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 u=["toast","visible",d.error?"error":"",d.error?"toast--card":""].filter(Boolean).join(" ");return s.jsxs("div",{className:u,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 jI(){return null}function TI(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 AI(e,t,n){async function r(i){if(i.setId)try{await _e.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(lb(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:o,handleDownloadCardNewsManifest:a}}const PI=["ArrowLeft","ArrowRight","Home","End"];function RI(){return v.useCallback(e=>{if(!PI.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 Ro({className:e,ariaLabel:t,tabs:n,value:r,onChange:o}){const a=RI(),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 MI({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 LI=[{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 OI(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 Ne(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 Me(async()=>{const{continueFromItem:c}=await Promise.resolve().then(()=>gv);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 FI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function DI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function GI(e){return{modelLabel:Wi(e.model,e.provider),derivation:FI(e),sourceLabel:DI(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 $I({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 UI({item:e,active:t,itemRef:n,onSelect:r,onDelete:o,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>LI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await OI(p,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]),u=p=>{p.dataTransfer.setData("application/ima2-ref",JSON.stringify(xe(e)?_n(e):{image:e.url||e.image,filename:e.filename})),p.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:u,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(Wt,{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(p=>s.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:m=>{d(p.id,m)},title:l(p.labelKey),"aria-label":l(p.labelKey),children:s.jsx($I,{id:p.id})},p.id))}):null,e.filename&&a&&s.jsx(td,{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:p=>o(e,p),title:l("gallery.deleteTitle"),"aria-label":l("gallery.deleteAria"),children:"×"}),s.jsx(qI,{view:GI(e)})]})}function HI(e,t,n){const r=new Array(e);return new Proxy(r,{get(o,a,i){if(typeof a=="string"){const l=a.charCodeAt(0);if(l>=48&&l<=57){const c=+a;if(Number.isInteger(c)&&c>=0&&c<e){let d=o[c];if(!d){const u=t[c*2];d=o[c]={index:c,key:n(c),start:u,size:t[c*2+1],end:u+t[c*2+1],lane:0}}return d}}if(a==="length")return e}return Reflect.get(o,a,i)}})}function Gt(e,t,n){let r=n.initialDeps??[],o,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==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 Ii(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const VI=(e,t)=>Math.abs(e-t)<1.01,KI=(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 mn;const Mo=()=>{if(mn!==void 0)return mn;if(typeof navigator>"u")return mn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return mn=!0;const e=navigator.maxTouchPoints;return mn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},Si=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},BI=e=>e,WI=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},JI=(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(Si(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(Si(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Fr={passive:!0},YI=typeof window>"u"?!0:"onscrollend"in window,XI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const o=e.targetWindow;if(!o)return;const a=e.options.useScrollendEvent&&YI;let i=0;const l=a?null:KI(o,()=>t(i,!1),e.options.isScrollingResetDelay),c=p=>()=>{i=n(r),l?.(),t(i,p)},d=c(!0),u=c(!1);return r.addEventListener("scroll",d,Fr),a&&r.addEventListener("scrollend",u,Fr),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u),l?.cancel()}},ZI=(e,t)=>XI(e,t,n=>{const{horizontal:r,isRtl:o}=e.options;return r?n.scrollLeft*(o&&-1||1):n.scrollTop}),QI=(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"]},eS=(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})},tS=eS;class nS{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this._flatMeasurements=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.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,u]of this.elementsCache)if(u===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,o;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:BI,rangeExtractor:WI,onChange:()=>{},measureElement:QI,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 m in n){const h=n[m];h!==void 0&&(a[m]=h)}const i=this.options;let l=null,c=null,d=!1;if(i!==void 0&&i.enabled&&a.enabled&&a.anchorTo==="end"&&this.scrollElement!==null){const m=i.count,h=a.count,b=this.getMeasurements(),I=m>0?((r=b[0])==null?void 0:r.key)??i.getItemKey(0):null,x=m>0?((o=b[m-1])==null?void 0:o.key)??i.getItemKey(m-1):null;if(h!==m||m>0&&h>0&&(a.getItemKey(0)!==I||a.getItemKey(h-1)!==x)){d=!0;const _=m>0?this.getVirtualItemForOffset(this.getScrollOffset())??b[0]:null;_&&(l=[_.key,this.getScrollOffset()-_.start]);const w=a.followOnAppend===!0?"auto":a.followOnAppend||null;w&&h>m&&this.isAtEnd(i.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==x)&&(c=w)}}this.options=a,d&&(this.pendingMin=0,this.itemSizeCacheVersion++);let u=!1,p=0;if(l&&this.scrollOffset!==null){const[m,h]=l,b=this.getMeasurements(),{count:I,getItemKey:x}=this.options;let y=0;for(;y<I&&x(y)!==m;)y++;if(y<I){const g=b[y];if(g){const _=Math.max(0,g.start+h);_!==this.scrollOffset&&(p=_-this.scrollOffset,this.scrollOffset=_,u=!0)}}}(u||c)&&(this.pendingScrollAnchor=[u?l[0]:null,u?l[1]:0,c,p])},this.notify=n=>{var r,o;(o=(r=this.options).onChange)==null||o.call(r,this,n)},this.maybeNotify=Gt(()=>(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.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}if(this.scrollElement=r,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(a=>{this.observer.observe(a)}),this.unsubs.push(this.options.observeElementRect(this,a=>{this.scrollRect=a,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(a,i)=>{if(i&&this._intendedScrollOffset===null&&a===this.scrollOffset)return;this._intendedScrollOffset!==null&&Math.abs(a-this._intendedScrollOffset)<1.5&&(a=this._intendedScrollOffset),this._intendedScrollOffset=null,this.scrollAdjustments=0;const l=this.getScrollOffset();this.scrollDirection=i?l===a?this.scrollDirection:l<a?"forward":"backward":null,this.scrollOffset=a,this.isScrolling=i,this._flushIosDeferredIfReady(),this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),"addEventListener"in this.scrollElement){const a=this.scrollElement,i=()=>{this._iosTouching=!0,this._iosJustTouchEnded=!1,this._iosTouchEndTimerId!==null&&this.targetWindow!=null&&(this.targetWindow.clearTimeout(this._iosTouchEndTimerId),this._iosTouchEndTimerId=null)},l=()=>{this._iosTouching=!1,!(!Mo()||this.targetWindow==null)&&(this._iosJustTouchEnded=!0,this._iosTouchEndTimerId=this.targetWindow.setTimeout(()=>{this._iosJustTouchEnded=!1,this._iosTouchEndTimerId=null,this._flushIosDeferredIfReady()},150))};a.addEventListener("touchstart",i,Fr),a.addEventListener("touchend",l,Fr),this.unsubs.push(()=>{a.removeEventListener("touchstart",i),a.removeEventListener("touchend",l),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 o=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,o&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=o;a!==null&&!l&&(Mo()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?c!==0&&(this._iosDeferredAdjustment+=c):this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})),l&&this.scrollToEnd({behavior:l})}},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=Gt(()=>[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=Gt(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:o,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d},u)=>{const p=this.itemSizeCache;if(!i)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const y of this.laneAssignments.keys())y>=n&&this.laneAssignments.delete(y);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMin=null),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(y=>{this.itemSizeCache.set(y.key,y.size)}));const m=this.lanesSettling?0:this.pendingMin??0;if(this.pendingMin=null,this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1),l===1){const y=n*2;let g=this._flatMeasurements;if(!g||g.length<y){const S=new Float64Array(y);g&&m>0&&S.set(g.subarray(0,m*2)),g=S,this._flatMeasurements=g}let _;if(m===0)_=r+o;else{const S=m-1;_=g[S*2]+g[S*2+1]+d}for(let S=m;S<n;S++){const N=a(S),A=p.get(N),L=typeof A=="number"?A:this.options.estimateSize(S);g[S*2]=_,g[S*2+1]=L,_+=L+d}const w=HI(n,g,a);return this.measurementsCache=w,w}const h=this.measurementsCache.slice(0,m),b=new Array(l).fill(void 0),I=new Float64Array(l);let x=0;for(let y=0;y<m;y++){const g=h[y];g&&(b[g.lane]===void 0&&x++,b[g.lane]=y,I[g.lane]=g.end)}for(let y=m;y<n;y++){const g=a(y),_=this.laneAssignments.get(y);let w,S;const N=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){w=_;const j=b[w],z=j!==void 0?h[j]:void 0;S=z?z.end+d:r+o}else if(x===l){let j=0,z=I[0],q=b[0];for(let C=1;C<l;C++){const k=I[C];(k<z||k===z&&b[C]<q)&&(j=C,z=k,q=b[C])}w=j,S=z+d,N&&this.laneAssignments.set(y,w)}else w=y%this.options.lanes,S=r+o,N&&this.laneAssignments.set(y,w);const A=p.get(g),L=typeof A=="number"?A:this.options.estimateSize(y),U=S+L;h[y]={index:y,start:S,size:L,end:U,key:g,lane:w},b[w]===void 0&&x++,b[w]=y,I[w]=U}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Gt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,o,a)=>n.length===0||r===0?(this.range=null,null):(this.range=oS(n,r,o,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Gt(()=>{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;if(!this.isIndexInRange(n))return;let i,l,c;const d=this._flatMeasurements;if(this.options.lanes===1&&d!==null)c=this.options.getItemKey(n),l=d[n*2],i=d[n*2+1];else{const m=this.measurementsCache[n];if(!m)return;c=m.key,l=m.start,i=m.size}const u=this.itemSizeCache.get(c)??i,p=r-u;if(p!==0){const m=this.options.anchorTo==="end"&&((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&this.getVirtualDistanceFromEnd()<=this.options.scrollEndThreshold,h=m?this.getTotalSize():0,b=this.getScrollOffset()+this.scrollAdjustments,x=!this.itemSizeCache.has(c)?l<b:l+u<=b&&this.scrollDirection!=="backward",y=((a=this.scrollState)==null?void 0:a.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(this.measurementsCache[n]??{index:n,key:c,start:l,size:i,end:l+i,lane:0},p,this):x);(this.pendingMin===null||n<this.pendingMin)&&(this.pendingMin=n),this.itemSizeCache.set(c,r),this.itemSizeCacheVersion++;let g=!1;m?g=this.applyScrollAdjustment(this.getTotalSize()-h):y&&(g=this.applyScrollAdjustment(p)),this.notify(g)}},this.getVirtualItems=Gt(()=>[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=>{const r=this.getMeasurements();if(r.length===0)return;const o=this._flatMeasurements,a=this.options.lanes===1&&o!=null,i=wd(0,r.length-1,a?l=>o[l*2]:l=>Ii(r[l]).start,n);return Ii(r[i])},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;const r=this.getMeasurements();let o;if(r.length===0)o=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?o=i[a*2]+i[a*2+1]:o=((n=r[a])==null?void 0:n.end)??0}else{const a=Array(this.options.lanes).fill(null);let i=r.length-1;for(;i>=0&&a.some(l=>l===null);){const l=r[i];a[l.lane]===null&&(a[l.lane]=l.end),i--}o=Math.max(...a.filter(l=>l!==null))}return Math.max(o-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){return t===0?!1:Mo()&&(this.isScrolling||this._iosTouching||this._iosJustTouchEnded)?(this._iosDeferredAdjustment+=t,!1):(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&&VI(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==o&&this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(o-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=o,d||(this.scrollState.behavior="auto"),this._scrollToOffset(o,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const wd=(e,t,n,r)=>{for(;e<=t;){const o=(e+t)/2|0,a=n(o);if(a<r)e=o+1;else if(a>r)t=o-1;else return o}return e>0?e-1:0};function rS(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 oS(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=rS(o,a,n);let u=d;const p=n+t;for(;u<a&&o[u*2]+o[u*2+1]<p;)u++;return{startIndex:d,endIndex:u}}let l=wd(0,a,d=>e[d].start,n),c=l;if(r===1)for(;c<a&&e[c].end<n+t;)c++;else if(r>1){const d=Array(r).fill(0);for(;c<a&&d.some(p=>p<n+t);){const p=e[c];d[p.lane]=p.end,c++}const u=Array(r).fill(n+t);for(;l>=0&&u.some(p=>p>=n);){const p=e[l];u[p.lane]=p.start,l--}l=Math.max(0,l-l%r),c=Math.min(a,c+(r-1-c%r))}return{startIndex:l,endIndex:c}}const Lo=typeof document<"u"?v.useLayoutEffect:v.useEffect;function sS({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const o=v.useReducer(u=>u+1,0)[1],a=v.useRef({enabled:t,mode:n,container:null,lastSize:null,lastPositions:new WeakMap,prevRange:null});a.current.enabled=t,a.current.mode=n;const i=u=>{const p=a.current;if(!p.enabled||!p.container)return;const m=u.getTotalSize();if(m!==p.lastSize){p.lastSize=m;const h=u.options.horizontal?"width":"height";p.container.style[h]=`${m}px`}},l=u=>{const p=a.current;if(!p.enabled||!p.container)return;i(u);const m=!!u.options.horizontal,h=p.mode==="transform",b=m?"left":"top",I=u.options.scrollMargin,x=u.getVirtualItems();for(const y of x){const g=y.start-I,_=u.elementsCache.get(y.key);_&&p.lastPositions.get(_)!==g&&(p.lastPositions.set(_,g),h?_.style.transform=m?`translate3d(${g}px, 0, 0)`:`translate3d(0, ${g}px, 0)`:_.style[b]=`${g}px`)}},c={...r,onChange:(u,p)=>{var m;const h=a.current;let b=!0;if(h.enabled){l(u);const I=u.range,x=h.prevRange;b=!x||x.isScrolling!==u.isScrolling||x.startIndex!==I?.startIndex||x.endIndex!==I?.endIndex,b&&(h.prevRange=I?{startIndex:I.startIndex,endIndex:I.endIndex,isScrolling:u.isScrolling}:null)}b&&(e&&p?so.flushSync(o):o()),(m=r.onChange)==null||m.call(r,u,p)}},[d]=v.useState(()=>{const u=new nS(c);return Object.assign(u,{containerRef:p=>{const m=a.current;if(m.container=p,m.lastSize=null,p&&m.enabled){const h=u.getTotalSize();m.lastSize=h;const b=u.options.horizontal?"width":"height";p.style[b]=`${h}px`}}})});return d.setOptions(c),Lo(()=>d._didMount(),[]),Lo(()=>(i(d),d._willUpdate())),Lo(()=>{l(d)}),d}function aS(e){return sS({observeElementRect:JI,observeElementOffset:ZI,scrollToFn:tS,...e})}const Dr=170,Gr=10,_d=36,iS=44;function lS(e){const t=Math.max(Dr,e-_d);return Math.max(1,Math.floor((t+Gr)/(Dr+Gr)))}function cS(e,t){const n=Math.max(Dr,e-_d);return Math.max(Dr,Math.floor((n-Gr*Math.max(0,t-1))/t))+Gr}function dS(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 uS({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:o}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>lS(i||960),[i]),d=v.useMemo(()=>cS(i||960,c),[i,c]),u=v.useMemo(()=>dS(e,c),[e,c]);v.useEffect(()=>{const m=a.current;if(!m)return;const h=()=>l(m.clientWidth);h();const b=new ResizeObserver(h);return b.observe(m),()=>b.disconnect()},[]);const p=aS({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?iS:d,overscan:6});return v.useEffect(()=>{if(!t)return;const m=u.findIndex(h=>h.type==="items"&&h.items.some(b=>Ae(b)===t));m>=0&&p.scrollToIndex(m,{align:"center"})},[u,t,p]),s.jsx("div",{ref:a,className:"gallery__virtual",style:{height:p.getTotalSize()},children:p.getVirtualItems().map(m=>{const h=u[m.index];return h?s.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${m.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((b,I)=>o(b,h.id,I))})},h.id):null})})}function wi({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 mS({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 pS({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 _i="ima2.storageNoticeDismissed.0.09.23";function fS(e){const t=v.useRef(null),n=v.useRef(new Map),[r,o]=v.useState(()=>new Set);v.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 u=new Set(d);for(const p of c){const m=p.target.dataset.galleryLazyKey;m&&u.add(m)}return u})},{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=v.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 hS(){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),u=f(R=>R.galleryScope),p=f(R=>R.setGalleryScope),m=f(R=>R.historyNextCursor),h=f(R=>R.historyLoadingOlder),b=f(R=>R.favoriteHistoryNextCursor),I=f(R=>R.favoriteHistoryLoadingOlder),x=f(R=>R.loadOlderHistory),y=f(R=>R.loadFavoriteHistory),g=f(R=>R.loadOlderFavoriteHistory),_=f(gp),[w,S]=v.useState(""),[N,A]=v.useState("date"),[L,U]=v.useState(!1),[j,z]=v.useState(()=>new Set),q=v.useRef(new Set),[C,k]=v.useState([]),[P,B]=v.useState([]),[se,oe]=v.useState(!1),[ae,he]=v.useState(!1),[F,O]=v.useState(!1),[ee,J]=v.useState(0),[me,ge]=v.useState(null),[ie,Ee]=v.useState(()=>{try{return localStorage.getItem(_i)==="1"}catch{return!1}}),le=v.useRef(null),Ie=v.useRef({}),[Ce,Re]=v.useState(null),ce=v.useRef(0),be=v.useRef({open:!1,selectedKey:null}),D=v.useMemo(()=>Ir(o.filter(vn)),[o]),ye=v.useCallback(R=>{le.current=R,Re(R)},[]),T=fS(Ce),ne=Ve(n,r);v.useEffect(()=>{n||S("")},[n]),v.useEffect(()=>{if(!n)return;let R=!1;return(async()=>{try{const Y=await cu();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]),v.useEffect(()=>{if(!n||N!=="session")return;let R=!1;return k([]),B([]),oe(!0),he(!1),O(!1),(async()=>{try{const Y=await iu({limit:500,sessionId:u==="current-session"?_:void 0});if(R)return;O(Y.nextCursor!==null||Y.total>=500);const we=H=>{const pe=H.kind,at=pe==="classic"||pe==="edit"||pe==="generate"||pe==="card-news-card"||pe==="card-news-set"?pe:null,aa=H.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(H.filename??"");return{image:H.url,url:H.url,filename:H.filename,thumb:H.thumb??(aa?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:Ir(H.items.filter(vn).map(we))})).filter(H=>H.items.length>0)),B(Ir(Y.loose.filter(vn).map(we)))}catch{R||he(!0)}finally{R||oe(!1)}})(),()=>{R=!0}},[n,N,u,_,ee]),v.useEffect(()=>{!n||N==="session"||!L||y()},[n,N,L,y]);const de=v.useMemo(()=>{const R=w.trim().toLowerCase().normalize("NFC");return D.filter(Y=>L&&!Y.isFavorite?!1:R?(Y.prompt??"").toLowerCase().normalize("NFC").includes(R)||(Y.filename??"").toLowerCase().normalize("NFC").includes(R):!0)},[D,w,L]),K=v.useMemo(()=>L?C.map(R=>({...R,items:R.items.filter(Y=>Y.isFavorite)})).filter(R=>R.items.length>0):C,[C,L]),G=v.useMemo(()=>L?P.filter(R=>R.isFavorite):P,[P,L]),X=v.useMemo(()=>{const R=new Map;for(const Y of de){const we=TI(Y.createdAt,t);R.has(we)||R.set(we,[]),R.get(we).push(Y)}return Array.from(R.entries())},[de,t]),re=N==="session"?K.reduce((R,Y)=>R+Y.items.length,0)+G.length:de.length;v.useLayoutEffect(()=>{const R=i?Ae(i):null;if(!n){be.current={open:!1,selectedKey:R};return}const Y=be.current,we=!Y.open||Y.selectedKey!==R;be.current={open:!0,selectedKey:R};const H=R?Ie.current[R]:null;if(we&&H){H.scrollIntoView({block:"center"});return}le.current&&(le.current.scrollTop=ce.current)},[n,i?.filename,i?.image,N,re,X.length,K.length,G.length]);async function Le(R,Y){Y.stopPropagation();const we=Ae(R);await l(R),delete Ie.current[we],window.requestAnimationFrame(()=>le.current?.focus())}async function Ge(R){const Y=R.filename;if(!(!Y||q.current.has(Y))){q.current.add(Y),z(new Set(q.current));try{const we=await d(R);if(we===null)return;k(H=>H.map(pe=>({...pe,items:pe.items.map(at=>at.filename===Y?{...at,isFavorite:we}:at)}))),B(H=>H.map(pe=>pe.filename===Y?{...pe,isFavorite:we}:pe))}finally{q.current.delete(Y),z(new Set(q.current))}}}async function Ot(){try{await du(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ke,handleCopyCardNewsSetPath:dt,handleDownloadCardNewsManifest:ut}=AI(r,c,e);function vt(){Ee(!0);try{localStorage.setItem(_i,"1")}catch{}}if(!n)return null;const E=R=>R==="earlier"||R==="today"||R==="yesterday"||R==="thisWeek"?e(`gallery.${R}`):R,W=(R,Y,we)=>{const H=i?.image===R.image,pe=Ae(R),at=Ft=>{Ie.current[pe]=Ft,T.register(pe,Ft)};return(T.supported?T.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(MI,{item:R,onOpen:Ft=>{Ke(Ft)},onCopyPath:dt,onDownloadManifest:ut})},`${Y}-${pe}`):s.jsx(UI,{item:R,active:H,itemRef:at,onSelect:Ft=>{a(Ft),r()},onDelete:Le,onToggleFavorite:Ge,favoriteBusy:!!(R.filename&&j.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",Se=i?Ae(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}),w||L?e("gallery.totalFiltered",{n:D.length}):""]}),s.jsx(Ro,{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(Ro,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:N,onChange:A,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),s.jsx(Ro,{className:"gallery__scope",ariaLabel:e("gallery.scopeAria"),value:u,onChange:p,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:w,onChange:R=>S(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(pS,{status:me,dismissed:ie,onOpenFolder:Ot,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:[F?s.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,s.jsx(mS,{groups:K,loose:G,favoritesOnly:L,galleryScope:u,setGalleryScope:p,renderTile:W,t:e}),s.jsx(wi,{showSessions:Q,favoritesOnly:L,query:w,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):de.length===0?s.jsx("div",{className:"gallery__empty",children:D.length===0?e("gallery.emptyAll"):e(L?"gallery.emptyFavorites":"gallery.noResults")}):s.jsxs(s.Fragment,{children:[s.jsx(uS,{dateGroups:X,selectedKey:Se,scrollElement:Ce,localizeBucket:E,renderTile:W}),s.jsx(wi,{showSessions:Q,favoritesOnly:L,query:w,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function gS(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 yS(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=V(),o=Ve(!!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(gS(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 vS(){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=Ve(!!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 bS=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Ct(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Ht(e){return!e||typeof e!="object"||Array.isArray(e)?Ct():e}function Qo(e){return typeof e!="string"||!e.trim()?Ct():e}function Ed(e){return e===void 0?{}:typeof e!="boolean"?Ct():{executable:e}}function xS(e){const t=Ht(e),n=Ht(t.status);return typeof t.enabled!="boolean"||!bS.has(n.state)?Ct():{id:Qo(t.id),enabled:t.enabled,...Ed(t.executable),status:{state:n.state}}}function Ei(e){return Array.isArray(e)?e.map(t=>{const n=Ht(t);return{id:Qo(n.id),label:Qo(n.label),...Ed(n.executable)}}):Ct()}function Ni(e,t){const n=Ht(e);if(n.ok!==!0||!Array.isArray(n.providers))return Ct();const r=n.providers.map(xS);if(t===null)return{providers:r,catalog:null};const o=Ht(t),a=Ht(o.models);return o.ok!==!0?Ct():{providers:r,catalog:{image:Ei(a.image),video:Ei(a.video)}}}function IS(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 SS(){const{t:e}=V(),t=f(u=>u.mcpProvider??""),n=f(u=>u.mcpModel??null),r=f(u=>u.mcpMediaKind??"image"),[o,a]=v.useState(0),[i,l]=v.useState({selection:{provider:t,model:n,kind:r},phase:"loading",observedAt:null,providers:[],catalog:null});if(v.useEffect(()=>{const u=new AbortController,p={provider:t,model:n,kind:r};return l({selection:p,phase:"loading",observedAt:null,providers:[],catalog:null}),t&&(async()=>{try{const h=await Wh(u.signal),I=Ni(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Jh(t,u.signal):null,y=Ni(h,x);u.signal.aborted||l({...y,selection:p,phase:"ready",observedAt:Date.now()})}catch{u.signal.aborted||l({selection:p,phase:"error",observedAt:null,providers:[],catalog:null})}})(),()=>u.abort()},[t,n,r,o]),!t)return null;const c=IS(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(u=>u+1),children:e("readiness.mcp.refresh")})]})}const ki={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 wS(){const{t:e}=V(),t=f(S=>S.readinessPopupOpen),n=f(S=>S.closeReadinessPopup),r=f(S=>S.openSettings),o=f(S=>S.provider),a=f(S=>S.mcpProvider??null),i=f(S=>S.imageModel),l=f(S=>S.reasoningEffort),c=f(S=>S.webSearchEnabled),d=f(S=>S.comfyWorkflow),u=f(S=>S.comfyVideoWorkflow),p=vd(),m=Vn(),h=o==="grok",b=et.find(S=>S.value===i),I=Ve(t,n);if(!t)return null;const x=p[o],y=kt(m,{comfyWorkflow:d,comfyVideoWorkflow:u}),g=o==="comfy"&&!a,_=g?y.selectedAvailable:x.ok,w=()=>{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:S=>S.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(SS,{}):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?Bt(y,m):_?"readiness.ready":"readiness.blocked")}),s.jsx("small",{children:g?e("comfy.display.controlsHelp"):_?e("readiness.readyBody"):x.reason})]}),!g&&x.hint?s.jsx("p",{className:"modal__hint",children:x.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:ki.comfy})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.workflowsTitle")}),s.jsx("dd",{children:y.selected?.label??e("comfy.display.chooseWorkflow")})]}),y.selected?s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colId")}),s.jsx("dd",{children:y.selected.id})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colKind")}),s.jsx("dd",{children:e(y.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage")})]})]}):null,m.observedAt!==null?s.jsxs("div",{children:[s.jsx("dt",{children:e("comfy.colStatus")}),s.jsx("dd",{children:e("comfy.display.lastChecked",{time:new Date(m.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:ki[o]??"GPT API"})]}),s.jsxs("div",{children:[s.jsx("dt",{children:e("readiness.model")}),s.jsx("dd",{children:b?e(b.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:w,children:e(g?"comfy.display.manage":"readiness.openAccount")})]})]})})}const Ci="ima2.onboardingDismissed";function _S(){const{t:e}=V(),t=f(x=>x.openSettings),n=hd(),r=gd(),{data:o}=yd(),[a,i]=v.useState(()=>{try{return localStorage.getItem(Ci)==="1"}catch{return!1}}),l=n!==null&&r!==null&&o!=null,c=n?.status==="auth_required"||n?.status==="offline",d=r?.status==="offline"||r?.status==="error",u=o?!o.gemini?.configured&&!o.vertex?.configured:!1,m=!a&&(l&&c&&d&&u),h=()=>{try{localStorage.setItem(Ci,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=Ve(m,h);return m?s.jsx("div",{className:"modal-backdrop",role:"presentation",children:s.jsxs("div",{ref:I,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[s.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),s.jsx("div",{className:"modal__body",children:s.jsx("p",{children:e("onboarding.body")})}),s.jsxs("div",{className:"modal__actions",children:[s.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:h,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),s.jsx("button",{type:"button",className:"modal__btn",onClick:b,children:e("onboarding.login")})]})]})}):null}function ES(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=V(),[o,a]=v.useState(Date.now());return v.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 NS(){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 kS(){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(NS,{})})}let zr=null;function CS(e){zr=e}function jS(){const e=zr;zr=null,e?.isConnected&&e.focus()}function ji(){zr=null}function TS(){const{t:e}=V(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),o=r==="agent"&&Qt?"agent":r==="node"&&Zt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=yt(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&CS(p.current),t(u==="library"?"library":u==="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("div",{className:"logo-mark","aria-hidden":"true"}),s.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[s.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),s.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),s.jsxs("div",{className:"mobile-app-bar__actions",children:[s.jsx("button",{ref:i,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>d("library",i),"aria-label":e("promptLibrary.title"),title:e("promptLibrary.title"),children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),s.jsx("button",{ref:l,type:"button",className:"mobile-app-bar__icon-button",onClick:()=>d("controls",l),"aria-label":e("appBar.controls"),title:e("appBar.controls"),children:s.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),s.jsx("button",{ref:c,type:"button",className:"mobile-app-bar__generate",onClick:()=>d("prompt",c),"aria-label":e("appBar.generateAria"),title:e("appBar.generate"),style:{width:44,padding:0},children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),s.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]}),s.jsx("div",{className:"mobile-app-bar__selection",children:s.jsx(cd,{compact:!0})})]})}const AS={"#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 PS(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=AS[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function RS(){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 MS(){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 LS(){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 OS(){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 FS(){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 DS(){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 GS(){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 zS=[{id:"home",mode:"home",icon:MS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:RS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:LS,labelKey:"nav.node",enabled:Zt},{id:"agent",mode:"agent",icon:OS,labelKey:"nav.agent",enabled:Qt},{id:"assets",mode:"assets",icon:DS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:GS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:FS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function qS(){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=v.useRef(null),c=v.useCallback(I=>{const x=l.current;if(!x||!I)return;const y=x.getBoundingClientRect(),g=I.getBoundingClientRect();g.left<y.left?x.scrollLeft-=y.left-g.left:g.right>y.right&&(x.scrollLeft+=g.right-y.right)},[]);v.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=v.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]);v.useEffect(()=>{const I=()=>{const x=PS();x&&(x.settings?o():(r&&a(),n(x.mode)))};return I(),window.addEventListener("popstate",I),window.addEventListener("hashchange",I),()=>{window.removeEventListener("popstate",I),window.removeEventListener("hashchange",I)}},[]);const u=zS.filter(I=>I.enabled),p=u.filter(I=>!I.bottom),m=u.filter(I=>I.bottom),h=I=>I.settingsAction?r:!r&&I.mode===t,b=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:u.map(b)}):s.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[s.jsx("div",{className:"nav-rail__top",children:p.map(b)}),s.jsx("div",{className:"nav-rail__bottom",children:m.map(b)})]})}const $S=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Ct98TJ61.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Be=["prompt","controls","library"],ur="mobile-inflight-panel",mr=e=>`mobile-sheet-tab-${e}`,pr=e=>`mobile-sheet-panel-${e}`;function US(){const{t:e}=V(),t=f(S=>S.composeSheetOpen),n=f(S=>S.composeSheetTab),r=f(S=>S.setComposeSheetTab),o=f(S=>S.closeComposeSheet),a=f(S=>S.inFlight.length),i=f(S=>S.settingsOpen),l=f(S=>S.uiMode),c=l==="agent"&&Qt?"agent":l==="node"&&Zt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=yt(),[u,p]=v.useState(!1),m=v.useRef(a),h=v.useRef(!1),b=v.useRef(null),I=v.useRef({}),x=v.useRef(!1),y=S=>{r(S),requestAnimationFrame(()=>I.current[S]?.focus())},g=(S,N)=>{const A=Be.indexOf(N),L=S.key==="ArrowRight"?Be[(A+1)%Be.length]:S.key==="ArrowLeft"?Be[(A-1+Be.length)%Be.length]:S.key==="Home"?Be[0]:S.key==="End"?Be[Be.length-1]:null;L&&(S.preventDefault(),y(L))},_=Ve(t,o,{autoFocus:!1});v.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&p(!1)},[t,n,o,d,i,c]),v.useLayoutEffect(()=>{const S=m.current>0&&a===0;m.current=a,S&&(p(!1),h.current&&b.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),v.useLayoutEffect(()=>{if(t){x.current=!0;const S=requestAnimationFrame(()=>I.current[n]?.focus());return()=>cancelAnimationFrame(S)}x.current&&(x.current=!1,jS())},[t,n]);const w=d&&!i&&c==="classic";return v.useEffect(()=>{w||(x.current=!1,f.getState().composeSheetOpen&&o(),ji())},[w]),v.useEffect(()=>()=>ji(),[]),w?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:Be.map(S=>s.jsx("button",{ref:N=>{I.current[S]=N},id:mr(S),type:"button",role:"tab","aria-selected":n===S,"aria-controls":pr(S),tabIndex:n===S?0:-1,className:`mobile-sheet-tabs__button${n===S?" active":""}`,onClick:()=>r(S),onKeyDown:N=>g(N,S),children:e(`sheet.tabs.${S}`)},S))}),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:S=>{const N=document.getElementById(ur);h.current=N?.contains(S.target)??!1},children:n==="prompt"?s.jsxs(s.Fragment,{children:[s.jsx(Xs,{}),a>0?s.jsxs("section",{className:"compose-sheet__inflight",hidden:!u,children:[s.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{b.current?.querySelector(".inflight-badge")?.focus(),p(!1)},"aria-expanded":u,"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(Qs,{variant:"inline",panelId:ur}),s.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,s.jsxs("div",{ref:b,className:"compose-sheet__actions",children:[s.jsx(Zs,{}),s.jsx(ad,{variant:"inline",panelId:ur,expanded:u,onToggle:p})]})]}):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(Sd,{}):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(v.Suspense,{fallback:s.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:s.jsx($S,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const HS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function VS(){const e=f(r=>r.uiMode),t=f(r=>!!r.currentImage||!!r.multimodePreviewFlightId),n=f(r=>r.selectHistoryShortcutTarget);v.useEffect(()=>{if(e!=="classic")return;const r=o=>{const a=HS[o.key];a&&(o.defaultPrevented||Sr(o.target)||t&&(o.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const fr=64,Nd="Image Gen";let oa=Nd,es=!1,ht=null,sa="",ts=!1;function kd(){return navigator}function Cd(){if(typeof document>"u")return null;if(ht)return ht;const e=document.querySelector('link[rel~="icon"]');if(e)return ht=e,sa=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),ht=t,ts=!0,t}function KS(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="#0a0a0a",BS(n,6,6,52,52,12),n.fill(),n.strokeStyle="#ffffff",n.lineWidth=5,n.beginPath(),n.arc(30,32,14,0,Math.PI*2),n.stroke(),n.fillStyle="#ffffff",n.beginPath(),n.arc(30,32,5,0,Math.PI*2),n.fill(),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")):sa}function BS(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 WS(e){const t=kd();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function JS(){const e=kd();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function YS(e){document.title=`(${e}) ${oa}`;const t=Cd();t&&(t.href=KS(e)),WS(e)}function Ai(){document.title=oa,ht&&(ts?(ht.remove(),ht=null,ts=!1):ht.href=sa),JS()}function Pi(){es||typeof document>"u"||(es=!0,oa=document.title||Nd,Cd())}function XS(e){v.useEffect(()=>(Pi(),()=>{es&&Ai()}),[]),v.useEffect(()=>{Pi(),e>0?YS(e):Ai()},[e])}function ZS(){v.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 QS=v.lazy(()=>Me(()=>import("./NodeCanvas-DmjbNcTa.js"),__vite__mapDeps([8,1,2,7,9,10,11])).then(e=>({default:e.NodeCanvas}))),ew=v.lazy(()=>Me(()=>import("./SettingsWorkspace-DL9Tm90P.js"),__vite__mapDeps([12,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),tw=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-DsjqhaYO.js"),__vite__mapDeps([13,1,2])).then(e=>({default:e.CardNewsWorkspace}))),nw=v.lazy(()=>Me(()=>import("./AgentWorkspace-C6ke6Eo4.js"),__vite__mapDeps([14,1,2,10])).then(e=>({default:e.AgentWorkspace}))),rw=v.lazy(()=>Me(()=>import("./AssetsWorkspace-CHw1u9VC.js"),__vite__mapDeps([15,1,2,9,10,16,17])).then(e=>({default:e.AssetsWorkspace}))),ow=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-DzEfpUy_.js").then(e=>e.A),__vite__mapDeps([18,1,2,9,10,16,19])).then(e=>({default:e.AssetGenWorkspace}))),sw=v.lazy(()=>Me(()=>import("./HomeWorkspace-DbnY1YF2.js"),__vite__mapDeps([20,1,2])).then(e=>({default:e.HomeWorkspace}))),aw=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Ct98TJ61.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function iw(){return s.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function lw(){VS(),ZS();const{locale:e}=V(),t=f(S=>S.hydrateHistory),n=f(S=>S.loadSessions),r=f(S=>S.syncCapabilities),o=f(S=>S.startInFlightPolling),a=f(S=>S.reconcileInflight),i=f(S=>S.syncFromStorage),l=f(S=>S.settingsOpen),c=f(S=>S.unseenGeneratedCount),d=f(S=>S.historyStripLayout),u=f(S=>S.workspaceProfile),p=f(S=>S.uiMode),m=p==="agent"&&Qt?"agent":p==="node"&&Zt?"node":p==="home"?"home":p==="assets"?"assets":p==="asset-gen"?"asset-gen":"classic",h=m==="agent",b=m==="assets",I=m==="asset-gen",x=m==="home",y=yt(),g=Gn(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",w=!_&&!h&&!b&&!I&&!x;return XS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!ue())return r(),t(),n(),a(),o(),Tt(),pa(()=>a()),fa(S=>{S==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{kn(),pa(()=>{}),fa(()=>{})}},[t,n,a,o,r]),v.useEffect(()=>{const S=N=>{const A=N.detail?.assetId;A&&f.getState().openAssetDetail(A)};return window.addEventListener("ima2:open-assets-detail",S),()=>window.removeEventListener("ima2:open-assets-detail",S)},[]),v.useEffect(()=>{const S=N=>{N.key&&(N.key==="ima2.inFlight"||N.key==="ima2.selectedFilename"||N.key===ys||N.key===gs||N.key===bs)&&i()};return window.addEventListener("storage",S),()=>window.removeEventListener("storage",S)},[i]),v.useEffect(()=>{const S=()=>{hp(f.getState)};return window.addEventListener("beforeunload",S),()=>{window.removeEventListener("beforeunload",S)}},[]),s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`app${u==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${w&&d==="horizontal"?" app--history-horizontal":""}${w&&d==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":d,"data-mobile":y?"1":void 0,"data-ui-mode":m,children:[s.jsx(qS,{}),x?null:s.jsx(Sb,{}),s.jsx(TS,{}),w?s.jsx(kI,{}):null,s.jsx(v.Suspense,{fallback:s.jsx(iw,{}),children:l?s.jsx(ew,{}):m==="classic"?_?s.jsx(hx,{}):s.jsx(Zo,{}):m==="node"?s.jsx(QS,{}):m==="card-news"?s.jsx(tw,{}):m==="agent"?s.jsx(nw,{}):m==="assets"?s.jsx(rw,{}):m==="asset-gen"?s.jsx(ow,{}):m==="home"?s.jsx(sw,{}):s.jsx(Zo,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:s.jsx(II,{})]}),s.jsx(yS,{}),s.jsx(ES,{}),s.jsx(CI,{}),s.jsx(jI,{}),s.jsx(hS,{}),s.jsx(vS,{}),s.jsx(wS,{}),s.jsx(_S,{}),s.jsx(US,{}),s.jsx(kS,{}),m==="card-news"?s.jsx(v.Suspense,{fallback:null,children:s.jsx(aw,{})}):null]})}const Yw=Object.freeze(Object.defineProperty({__proto__:null,default:lw},Symbol.toStringTag,{value:"Module"}));export{Fw as $,zu as A,Ru as B,Lu as C,Fe as D,Kc as E,Gw as F,Mu as G,zw as H,et as I,qw as J,$w as K,Kw as L,ta as M,Uw as N,li as O,Hw as P,Vw as Q,zo as R,yv as S,_e as T,Lw as U,Hu as V,vv as W,SI as X,nm as Y,ot as Z,Zy as _,f as a,ku as a0,Aw as a1,Op as a2,aS as a3,td as a4,Bw as a5,Jw as a6,Ww as a7,Mw as a8,Dw as a9,yw as aA,Sr as aB,bw as aC,gw as aD,dw as aE,xw as aF,hw as aG,jb as aH,fw as aI,ax as aJ,Mi as aK,M as aL,uw as aM,pw as aN,mw as aO,ww as aP,Iw as aQ,_w as aR,Ew as aS,Sw as aT,Nw as aU,kw as aV,Cw as aW,jw as aX,Tw as aY,Yw as aZ,ox as aa,as as ab,dc as ac,RI as ad,Qs as ae,Rw as af,jt as ag,Pw as ah,to as ai,Ys as aj,ed as ak,Cv as al,Ae as am,vd as an,RS as ao,LS as ap,Zt as aq,OS as ar,Qt as as,DS as at,Ti as au,Xy as av,ex as aw,sx as ax,Jo as ay,vw as az,GI as b,_p as c,De as d,Nt as e,Qu as f,Wi as g,Ow as h,Ze as i,cc as j,Ve as k,Fp as l,Eu as m,Sp as n,$ as o,yt as p,Kl as q,so as r,Ne as s,Oe as t,V as u,hd as v,ap as w,gd as x,Ax as y,yd as z};