ima2-gen 3.14.0 → 3.15.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 (546) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/docs/API.md +2 -2
  3. package/docs/CLI.md +1 -1
  4. package/docs/CLI.zh-CN.md +1 -1
  5. package/docs/CLI.zh-TW.md +1 -1
  6. package/docs/migration/runtime-test-inventory.md +2 -1
  7. package/lib/agyArtifactRead.js +0 -3
  8. package/lib/assetLifecycle.js +1 -6
  9. package/lib/errors/providerMap.js +1 -0
  10. package/lib/mcp/downloadMediaResult.js +1 -6
  11. package/lib/naiImageAdapter.js +4 -9
  12. package/lib/naiSubscription.js +95 -0
  13. package/lib/pinnedHttpGet.js +15 -23
  14. package/lib/providers/adapters/api.js +55 -0
  15. package/lib/providers/adapters/atlascloud.js +66 -0
  16. package/lib/providers/adapters/comfy.js +76 -19
  17. package/lib/providers/adapters/gemini-api.js +55 -0
  18. package/lib/providers/adapters/googleExecution.js +26 -51
  19. package/lib/providers/adapters/grok-api.js +55 -0
  20. package/lib/providers/adapters/grokExecution.js +67 -112
  21. package/lib/providers/adapters/index.js +6 -0
  22. package/lib/providers/adapters/minimax.js +63 -0
  23. package/lib/providers/adapters/nai.js +55 -0
  24. package/lib/providers/adapters/openaiExecution.js +12 -37
  25. package/lib/providers/execution/index.js +10 -16
  26. package/lib/providers/execution/legacyClassic.js +5 -65
  27. package/lib/providers/execution/legacyEdit.js +2 -27
  28. package/lib/providers/execution/legacyMultimode.js +2 -31
  29. package/lib/providers/execution/legacyNode.js +2 -38
  30. package/lib/spriteAnchor.js +14 -24
  31. package/lib/spriteAtlasExport.js +8 -13
  32. package/lib/spriteCurationStore.js +4 -9
  33. package/lib/spriteRecipeStore.js +13 -76
  34. package/lib/spriteRowPipeline.js +5 -22
  35. package/node_modules/zod/README.md +27 -0
  36. package/node_modules/zod/compile.cjs +77 -0
  37. package/node_modules/zod/compile.d.cts +1 -0
  38. package/node_modules/zod/compile.d.ts +1 -0
  39. package/node_modules/zod/compile.js +52 -0
  40. package/node_modules/zod/index.cjs +2 -2
  41. package/node_modules/zod/index.d.cts +1 -2
  42. package/node_modules/zod/index.d.ts +1 -2
  43. package/node_modules/zod/index.js +5 -2
  44. package/node_modules/zod/package.json +13 -2
  45. package/node_modules/zod/src/compile.ts +56 -0
  46. package/node_modules/zod/src/index.ts +5 -2
  47. package/node_modules/zod/src/v3/ZodError.ts +22 -12
  48. package/node_modules/zod/src/v3/tests/error.test.ts +35 -0
  49. package/node_modules/zod/src/v3/tests/intersection.test.ts +18 -0
  50. package/node_modules/zod/src/v3/tests/language-server.test.ts +1 -2
  51. package/node_modules/zod/src/v3/tests/object.test.ts +3 -6
  52. package/node_modules/zod/src/v3/tests/readonly.test.ts +0 -80
  53. package/node_modules/zod/src/v3/tests/string.test.ts +6 -0
  54. package/node_modules/zod/src/v3/types.ts +5 -5
  55. package/node_modules/zod/src/v4/classic/checks.ts +1 -0
  56. package/node_modules/zod/src/v4/classic/compat.ts +26 -18
  57. package/node_modules/zod/src/v4/classic/deep-partial.ts +76 -0
  58. package/node_modules/zod/src/v4/classic/errors.ts +59 -44
  59. package/node_modules/zod/src/v4/classic/external.ts +12 -9
  60. package/node_modules/zod/src/v4/classic/from-json-schema.ts +140 -78
  61. package/node_modules/zod/src/v4/classic/in-out.ts +45 -0
  62. package/node_modules/zod/src/v4/classic/index.ts +2 -2
  63. package/node_modules/zod/src/v4/classic/iso.ts +2 -72
  64. package/node_modules/zod/src/v4/classic/parse.ts +10 -4
  65. package/node_modules/zod/src/v4/classic/schemas.ts +452 -262
  66. package/node_modules/zod/src/v4/classic/tests/apply.test.ts +27 -0
  67. package/node_modules/zod/src/v4/classic/tests/array.test.ts +2 -2
  68. package/node_modules/zod/src/v4/classic/tests/assignability.test.ts +135 -0
  69. package/node_modules/zod/src/v4/classic/tests/bigint.test.ts +30 -1
  70. package/node_modules/zod/src/v4/classic/tests/catch.test.ts +278 -0
  71. package/node_modules/zod/src/v4/classic/tests/codec-examples.test.ts +1 -2
  72. package/node_modules/zod/src/v4/classic/tests/codec.test.ts +2 -1
  73. package/node_modules/zod/src/v4/classic/tests/continuability.test.ts +2 -2
  74. package/node_modules/zod/src/v4/classic/tests/credit-card.test.ts +76 -0
  75. package/node_modules/zod/src/v4/classic/tests/cyclic-data.test.ts +720 -0
  76. package/node_modules/zod/src/v4/classic/tests/date.test.ts +30 -0
  77. package/node_modules/zod/src/v4/classic/tests/datetime.test.ts +32 -18
  78. package/node_modules/zod/src/v4/classic/tests/deep-partial.test.ts +380 -0
  79. package/node_modules/zod/src/v4/classic/tests/default-locale.test.ts +32 -0
  80. package/node_modules/zod/src/v4/classic/tests/default.test.ts +46 -0
  81. package/node_modules/zod/src/v4/classic/tests/detached-methods.test.ts +31 -7
  82. package/node_modules/zod/src/v4/classic/tests/discriminated-unions.test.ts +155 -13
  83. package/node_modules/zod/src/v4/classic/tests/enum.test.ts +11 -0
  84. package/node_modules/zod/src/v4/classic/tests/error-utils.test.ts +112 -2
  85. package/node_modules/zod/src/v4/classic/tests/error.test.ts +274 -6
  86. package/node_modules/zod/src/v4/classic/tests/from-json-schema.test.ts +425 -10
  87. package/node_modules/zod/src/v4/classic/tests/function.test.ts +31 -0
  88. package/node_modules/zod/src/v4/classic/tests/global-config.test.ts +2 -9
  89. package/node_modules/zod/src/v4/classic/tests/hash.test.ts +1 -2
  90. package/node_modules/zod/src/v4/classic/tests/in-out.test.ts +159 -0
  91. package/node_modules/zod/src/v4/classic/tests/index.test.ts +21 -2
  92. package/node_modules/zod/src/v4/classic/tests/instance-footprint.test.ts +281 -0
  93. package/node_modules/zod/src/v4/classic/tests/instanceof.test.ts +47 -0
  94. package/node_modules/zod/src/v4/classic/tests/intersection.test.ts +136 -0
  95. package/node_modules/zod/src/v4/classic/tests/issue-schema.test.ts +183 -0
  96. package/node_modules/zod/src/v4/classic/tests/jitless-allows-eval.test.ts +3 -10
  97. package/node_modules/zod/src/v4/classic/tests/lazy.test.ts +36 -1
  98. package/node_modules/zod/src/v4/classic/tests/literal.test.ts +12 -1
  99. package/node_modules/zod/src/v4/classic/tests/map.test.ts +12 -0
  100. package/node_modules/zod/src/v4/classic/tests/number.test.ts +46 -9
  101. package/node_modules/zod/src/v4/classic/tests/object.test.ts +245 -12
  102. package/node_modules/zod/src/v4/classic/tests/optin-ladder.test.ts +234 -0
  103. package/node_modules/zod/src/v4/classic/tests/optional.test.ts +49 -16
  104. package/node_modules/zod/src/v4/classic/tests/partial.test.ts +51 -4
  105. package/node_modules/zod/src/v4/classic/tests/preprocess-types.test.ts +20 -2
  106. package/node_modules/zod/src/v4/classic/tests/readonly.test.ts +0 -68
  107. package/node_modules/zod/src/v4/classic/tests/record.test.ts +186 -18
  108. package/node_modules/zod/src/v4/classic/tests/recursive-types.test.ts +33 -2
  109. package/node_modules/zod/src/v4/classic/tests/redos.test.ts +68 -0
  110. package/node_modules/zod/src/v4/classic/tests/refine.test.ts +60 -0
  111. package/node_modules/zod/src/v4/classic/tests/set.test.ts +9 -0
  112. package/node_modules/zod/src/v4/classic/tests/string.test.ts +127 -5
  113. package/node_modules/zod/src/v4/classic/tests/stringbool.test.ts +18 -0
  114. package/node_modules/zod/src/v4/classic/tests/template-literal.test.ts +11 -2
  115. package/node_modules/zod/src/v4/classic/tests/to-json-schema.test.ts +1585 -173
  116. package/node_modules/zod/src/v4/classic/tests/tuple.test.ts +45 -30
  117. package/node_modules/zod/src/v4/classic/tests/union.test.ts +39 -2
  118. package/node_modules/zod/src/v4/classic/tests/validate.test.ts +76 -0
  119. package/node_modules/zod/src/v4/classic/tests/validations.test.ts +2 -2
  120. package/node_modules/zod/src/v4/core/api.ts +48 -12
  121. package/node_modules/zod/src/v4/core/checks.ts +57 -44
  122. package/node_modules/zod/src/v4/core/compile.ts +2188 -0
  123. package/node_modules/zod/src/v4/core/core.ts +98 -19
  124. package/node_modules/zod/src/v4/core/doc.ts +11 -7
  125. package/node_modules/zod/src/v4/core/errors.ts +115 -24
  126. package/node_modules/zod/src/v4/core/index.ts +3 -0
  127. package/node_modules/zod/src/v4/core/json-schema-generator.ts +6 -1
  128. package/node_modules/zod/src/v4/core/json-schema-processors.ts +257 -93
  129. package/node_modules/zod/src/v4/core/json-schema.ts +2 -1
  130. package/node_modules/zod/src/v4/core/memoizer.ts +284 -0
  131. package/node_modules/zod/src/v4/core/parse.ts +131 -38
  132. package/node_modules/zod/src/v4/core/regexes.ts +30 -13
  133. package/node_modules/zod/src/v4/core/registries.ts +2 -2
  134. package/node_modules/zod/src/v4/core/schemas.ts +759 -461
  135. package/node_modules/zod/src/v4/core/tests/compile-differential.test.ts +969 -0
  136. package/node_modules/zod/src/v4/core/tests/compile-global.test.ts +89 -0
  137. package/node_modules/zod/src/v4/core/tests/compile-off-by-default.test.ts +26 -0
  138. package/node_modules/zod/src/v4/core/tests/compile-stats.test.ts +34 -0
  139. package/node_modules/zod/src/v4/core/tests/compile.test.ts +1639 -0
  140. package/node_modules/zod/src/v4/core/tests/locales/el.test.ts +1 -2
  141. package/node_modules/zod/src/v4/core/tests/locales/es.test.ts +1 -2
  142. package/node_modules/zod/src/v4/core/tests/locales/fr.test.ts +3 -3
  143. package/node_modules/zod/src/v4/core/tests/locales/parity.test.ts +42 -0
  144. package/node_modules/zod/src/v4/core/tests/locales/tk.test.ts +69 -0
  145. package/node_modules/zod/src/v4/core/tests/treeshake.test.ts +51 -0
  146. package/node_modules/zod/src/v4/core/tests/url-no-canparse.test.ts +31 -0
  147. package/node_modules/zod/src/v4/core/to-json-schema.ts +275 -42
  148. package/node_modules/zod/src/v4/core/util.ts +268 -42
  149. package/node_modules/zod/src/v4/core/versions.ts +2 -2
  150. package/node_modules/zod/src/v4/core/visit.ts +193 -0
  151. package/node_modules/zod/src/v4/index.ts +3 -3
  152. package/node_modules/zod/src/v4/locales/ar.ts +3 -0
  153. package/node_modules/zod/src/v4/locales/az.ts +3 -0
  154. package/node_modules/zod/src/v4/locales/be.ts +10 -0
  155. package/node_modules/zod/src/v4/locales/bg.ts +3 -0
  156. package/node_modules/zod/src/v4/locales/bn.ts +121 -0
  157. package/node_modules/zod/src/v4/locales/ca.ts +3 -0
  158. package/node_modules/zod/src/v4/locales/ckb.ts +138 -0
  159. package/node_modules/zod/src/v4/locales/cs.ts +3 -0
  160. package/node_modules/zod/src/v4/locales/da.ts +5 -2
  161. package/node_modules/zod/src/v4/locales/de.ts +3 -0
  162. package/node_modules/zod/src/v4/locales/el.ts +1 -0
  163. package/node_modules/zod/src/v4/locales/en.ts +15 -4
  164. package/node_modules/zod/src/v4/locales/eo.ts +3 -0
  165. package/node_modules/zod/src/v4/locales/es.ts +2 -0
  166. package/node_modules/zod/src/v4/locales/fa.ts +3 -0
  167. package/node_modules/zod/src/v4/locales/fi.ts +3 -0
  168. package/node_modules/zod/src/v4/locales/fr-CA.ts +3 -0
  169. package/node_modules/zod/src/v4/locales/fr.ts +19 -14
  170. package/node_modules/zod/src/v4/locales/gu.ts +121 -0
  171. package/node_modules/zod/src/v4/locales/he.ts +6 -1
  172. package/node_modules/zod/src/v4/locales/hi.ts +124 -0
  173. package/node_modules/zod/src/v4/locales/hr.ts +2 -0
  174. package/node_modules/zod/src/v4/locales/hu.ts +3 -0
  175. package/node_modules/zod/src/v4/locales/hy.ts +9 -0
  176. package/node_modules/zod/src/v4/locales/id.ts +3 -0
  177. package/node_modules/zod/src/v4/locales/index.ts +10 -0
  178. package/node_modules/zod/src/v4/locales/is.ts +3 -0
  179. package/node_modules/zod/src/v4/locales/it.ts +3 -0
  180. package/node_modules/zod/src/v4/locales/ja.ts +3 -0
  181. package/node_modules/zod/src/v4/locales/ka.ts +3 -0
  182. package/node_modules/zod/src/v4/locales/km.ts +3 -0
  183. package/node_modules/zod/src/v4/locales/kn.ts +124 -0
  184. package/node_modules/zod/src/v4/locales/ko.ts +3 -0
  185. package/node_modules/zod/src/v4/locales/lt.ts +2 -0
  186. package/node_modules/zod/src/v4/locales/mk.ts +3 -0
  187. package/node_modules/zod/src/v4/locales/ms.ts +3 -0
  188. package/node_modules/zod/src/v4/locales/ne.ts +126 -0
  189. package/node_modules/zod/src/v4/locales/nl.ts +3 -0
  190. package/node_modules/zod/src/v4/locales/nn.ts +119 -0
  191. package/node_modules/zod/src/v4/locales/no.ts +5 -2
  192. package/node_modules/zod/src/v4/locales/ota.ts +3 -0
  193. package/node_modules/zod/src/v4/locales/pl.ts +3 -0
  194. package/node_modules/zod/src/v4/locales/ps.ts +3 -0
  195. package/node_modules/zod/src/v4/locales/pt-BR.ts +159 -0
  196. package/node_modules/zod/src/v4/locales/pt.ts +99 -58
  197. package/node_modules/zod/src/v4/locales/ro.ts +1 -0
  198. package/node_modules/zod/src/v4/locales/ru.ts +10 -0
  199. package/node_modules/zod/src/v4/locales/sk.ts +121 -0
  200. package/node_modules/zod/src/v4/locales/sl.ts +3 -0
  201. package/node_modules/zod/src/v4/locales/sv.ts +5 -2
  202. package/node_modules/zod/src/v4/locales/ta.ts +3 -0
  203. package/node_modules/zod/src/v4/locales/th.ts +3 -0
  204. package/node_modules/zod/src/v4/locales/tk.ts +111 -0
  205. package/node_modules/zod/src/v4/locales/tr.ts +3 -0
  206. package/node_modules/zod/src/v4/locales/uk.ts +3 -0
  207. package/node_modules/zod/src/v4/locales/ur.ts +3 -0
  208. package/node_modules/zod/src/v4/locales/uz.ts +1 -0
  209. package/node_modules/zod/src/v4/locales/vi.ts +3 -0
  210. package/node_modules/zod/src/v4/locales/yo.ts +3 -0
  211. package/node_modules/zod/src/v4/locales/zh-CN.ts +3 -0
  212. package/node_modules/zod/src/v4/locales/zh-TW.ts +3 -0
  213. package/node_modules/zod/src/v4/mini/checks.ts +1 -0
  214. package/node_modules/zod/src/v4/mini/deep-partial.ts +73 -0
  215. package/node_modules/zod/src/v4/mini/external.ts +10 -1
  216. package/node_modules/zod/src/v4/mini/in-out.ts +45 -0
  217. package/node_modules/zod/src/v4/mini/parse.ts +2 -0
  218. package/node_modules/zod/src/v4/mini/schemas.ts +135 -56
  219. package/node_modules/zod/src/v4/mini/tests/apply.test.ts +33 -0
  220. package/node_modules/zod/src/v4/mini/tests/assignability.test.ts +62 -1
  221. package/node_modules/zod/src/v4/mini/tests/checks.test.ts +14 -0
  222. package/node_modules/zod/src/v4/mini/tests/codec.test.ts +35 -1
  223. package/node_modules/zod/src/v4/mini/tests/cyclic-data.test.ts +84 -0
  224. package/node_modules/zod/src/v4/mini/tests/deep-partial.test.ts +54 -0
  225. package/node_modules/zod/src/v4/mini/tests/error.test.ts +23 -4
  226. package/node_modules/zod/src/v4/mini/tests/functions.test.ts +9 -0
  227. package/node_modules/zod/src/v4/mini/tests/index.test.ts +72 -5
  228. package/node_modules/zod/src/v4/mini/tests/number.test.ts +14 -0
  229. package/node_modules/zod/src/v4/mini/tests/object.test.ts +65 -0
  230. package/node_modules/zod/src/v4/mini/tests/string.test.ts +21 -0
  231. package/node_modules/zod/v3/ZodError.cjs +22 -12
  232. package/node_modules/zod/v3/ZodError.d.cts +1 -1
  233. package/node_modules/zod/v3/ZodError.d.ts +1 -1
  234. package/node_modules/zod/v3/ZodError.js +22 -12
  235. package/node_modules/zod/v3/types.cjs +7 -5
  236. package/node_modules/zod/v3/types.js +7 -5
  237. package/node_modules/zod/v4/classic/checks.cjs +2 -1
  238. package/node_modules/zod/v4/classic/checks.d.cts +1 -1
  239. package/node_modules/zod/v4/classic/checks.d.ts +1 -1
  240. package/node_modules/zod/v4/classic/checks.js +1 -1
  241. package/node_modules/zod/v4/classic/compat.d.cts +9 -11
  242. package/node_modules/zod/v4/classic/compat.d.ts +9 -11
  243. package/node_modules/zod/v4/classic/deep-partial.cjs +39 -0
  244. package/node_modules/zod/v4/classic/deep-partial.d.cts +14 -0
  245. package/node_modules/zod/v4/classic/deep-partial.d.ts +14 -0
  246. package/node_modules/zod/v4/classic/deep-partial.js +13 -0
  247. package/node_modules/zod/v4/classic/errors.cjs +43 -34
  248. package/node_modules/zod/v4/classic/errors.d.cts +3 -4
  249. package/node_modules/zod/v4/classic/errors.d.ts +3 -4
  250. package/node_modules/zod/v4/classic/errors.js +43 -34
  251. package/node_modules/zod/v4/classic/external.cjs +30 -27
  252. package/node_modules/zod/v4/classic/external.d.cts +5 -2
  253. package/node_modules/zod/v4/classic/external.d.ts +5 -2
  254. package/node_modules/zod/v4/classic/external.js +5 -8
  255. package/node_modules/zod/v4/classic/from-json-schema.cjs +136 -75
  256. package/node_modules/zod/v4/classic/from-json-schema.js +136 -75
  257. package/node_modules/zod/v4/classic/in-out.cjs +63 -0
  258. package/node_modules/zod/v4/classic/in-out.d.cts +8 -0
  259. package/node_modules/zod/v4/classic/in-out.d.ts +8 -0
  260. package/node_modules/zod/v4/classic/in-out.js +36 -0
  261. package/node_modules/zod/v4/classic/index.cjs +2 -2
  262. package/node_modules/zod/v4/classic/index.d.cts +1 -2
  263. package/node_modules/zod/v4/classic/index.d.ts +1 -2
  264. package/node_modules/zod/v4/classic/index.js +2 -2
  265. package/node_modules/zod/v4/classic/iso.cjs +11 -22
  266. package/node_modules/zod/v4/classic/iso.d.cts +2 -17
  267. package/node_modules/zod/v4/classic/iso.d.ts +2 -17
  268. package/node_modules/zod/v4/classic/iso.js +2 -17
  269. package/node_modules/zod/v4/classic/parse.cjs +4 -1
  270. package/node_modules/zod/v4/classic/parse.d.cts +17 -4
  271. package/node_modules/zod/v4/classic/parse.d.ts +17 -4
  272. package/node_modules/zod/v4/classic/parse.js +1 -0
  273. package/node_modules/zod/v4/classic/schemas.cjs +498 -398
  274. package/node_modules/zod/v4/classic/schemas.d.cts +53 -18
  275. package/node_modules/zod/v4/classic/schemas.d.ts +53 -18
  276. package/node_modules/zod/v4/classic/schemas.js +492 -396
  277. package/node_modules/zod/v4/core/api.cjs +23 -4
  278. package/node_modules/zod/v4/core/api.d.cts +13 -9
  279. package/node_modules/zod/v4/core/api.d.ts +13 -9
  280. package/node_modules/zod/v4/core/api.js +21 -4
  281. package/node_modules/zod/v4/core/checks.cjs +37 -31
  282. package/node_modules/zod/v4/core/checks.d.cts +13 -13
  283. package/node_modules/zod/v4/core/checks.d.ts +13 -13
  284. package/node_modules/zod/v4/core/checks.js +37 -31
  285. package/node_modules/zod/v4/core/compile.cjs +1813 -0
  286. package/node_modules/zod/v4/core/compile.d.cts +51 -0
  287. package/node_modules/zod/v4/core/compile.d.ts +51 -0
  288. package/node_modules/zod/v4/core/compile.js +1783 -0
  289. package/node_modules/zod/v4/core/core.cjs +81 -18
  290. package/node_modules/zod/v4/core/core.d.cts +16 -4
  291. package/node_modules/zod/v4/core/core.d.ts +16 -4
  292. package/node_modules/zod/v4/core/core.js +82 -19
  293. package/node_modules/zod/v4/core/doc.cjs +5 -7
  294. package/node_modules/zod/v4/core/doc.d.cts +3 -1
  295. package/node_modules/zod/v4/core/doc.d.ts +3 -1
  296. package/node_modules/zod/v4/core/doc.js +5 -7
  297. package/node_modules/zod/v4/core/errors.cjs +110 -25
  298. package/node_modules/zod/v4/core/errors.d.cts +4 -0
  299. package/node_modules/zod/v4/core/errors.d.ts +4 -0
  300. package/node_modules/zod/v4/core/errors.js +110 -25
  301. package/node_modules/zod/v4/core/index.cjs +5 -1
  302. package/node_modules/zod/v4/core/index.d.cts +3 -0
  303. package/node_modules/zod/v4/core/index.d.ts +3 -0
  304. package/node_modules/zod/v4/core/index.js +3 -0
  305. package/node_modules/zod/v4/core/json-schema-generator.cjs +4 -0
  306. package/node_modules/zod/v4/core/json-schema-generator.d.cts +2 -2
  307. package/node_modules/zod/v4/core/json-schema-generator.d.ts +2 -2
  308. package/node_modules/zod/v4/core/json-schema-generator.js +4 -0
  309. package/node_modules/zod/v4/core/json-schema-processors.cjs +264 -95
  310. package/node_modules/zod/v4/core/json-schema-processors.js +243 -97
  311. package/node_modules/zod/v4/core/json-schema.d.cts +2 -1
  312. package/node_modules/zod/v4/core/json-schema.d.ts +2 -1
  313. package/node_modules/zod/v4/core/memoizer.cjs +272 -0
  314. package/node_modules/zod/v4/core/memoizer.d.cts +15 -0
  315. package/node_modules/zod/v4/core/memoizer.d.ts +15 -0
  316. package/node_modules/zod/v4/core/memoizer.js +265 -0
  317. package/node_modules/zod/v4/core/parse.cjs +96 -34
  318. package/node_modules/zod/v4/core/parse.d.cts +14 -11
  319. package/node_modules/zod/v4/core/parse.d.ts +14 -11
  320. package/node_modules/zod/v4/core/parse.js +94 -33
  321. package/node_modules/zod/v4/core/regexes.cjs +27 -15
  322. package/node_modules/zod/v4/core/regexes.d.cts +2 -0
  323. package/node_modules/zod/v4/core/regexes.d.ts +2 -0
  324. package/node_modules/zod/v4/core/regexes.js +24 -13
  325. package/node_modules/zod/v4/core/registries.js +2 -2
  326. package/node_modules/zod/v4/core/schemas.cjs +537 -326
  327. package/node_modules/zod/v4/core/schemas.d.cts +100 -31
  328. package/node_modules/zod/v4/core/schemas.d.ts +100 -31
  329. package/node_modules/zod/v4/core/schemas.js +526 -325
  330. package/node_modules/zod/v4/core/to-json-schema.cjs +242 -39
  331. package/node_modules/zod/v4/core/to-json-schema.d.cts +42 -3
  332. package/node_modules/zod/v4/core/to-json-schema.d.ts +42 -3
  333. package/node_modules/zod/v4/core/to-json-schema.js +241 -39
  334. package/node_modules/zod/v4/core/util.cjs +212 -31
  335. package/node_modules/zod/v4/core/util.d.cts +58 -1
  336. package/node_modules/zod/v4/core/util.d.ts +58 -1
  337. package/node_modules/zod/v4/core/util.js +202 -30
  338. package/node_modules/zod/v4/core/versions.cjs +2 -2
  339. package/node_modules/zod/v4/core/versions.d.cts +1 -1
  340. package/node_modules/zod/v4/core/versions.d.ts +1 -1
  341. package/node_modules/zod/v4/core/versions.js +2 -2
  342. package/node_modules/zod/v4/core/visit.cjs +195 -0
  343. package/node_modules/zod/v4/core/visit.d.cts +30 -0
  344. package/node_modules/zod/v4/core/visit.d.ts +30 -0
  345. package/node_modules/zod/v4/core/visit.js +169 -0
  346. package/node_modules/zod/v4/index.cjs +15 -5
  347. package/node_modules/zod/v4/index.d.cts +2 -2
  348. package/node_modules/zod/v4/index.d.ts +2 -2
  349. package/node_modules/zod/v4/index.js +3 -2
  350. package/node_modules/zod/v4/locales/ar.cjs +3 -0
  351. package/node_modules/zod/v4/locales/ar.js +3 -0
  352. package/node_modules/zod/v4/locales/az.cjs +3 -0
  353. package/node_modules/zod/v4/locales/az.js +3 -0
  354. package/node_modules/zod/v4/locales/be.cjs +10 -0
  355. package/node_modules/zod/v4/locales/be.js +10 -0
  356. package/node_modules/zod/v4/locales/bg.cjs +3 -0
  357. package/node_modules/zod/v4/locales/bg.js +3 -0
  358. package/node_modules/zod/v4/locales/bn.cjs +138 -0
  359. package/node_modules/zod/v4/locales/bn.d.cts +5 -0
  360. package/node_modules/zod/v4/locales/bn.d.ts +4 -0
  361. package/node_modules/zod/v4/locales/bn.js +111 -0
  362. package/node_modules/zod/v4/locales/ca.cjs +3 -0
  363. package/node_modules/zod/v4/locales/ca.js +3 -0
  364. package/node_modules/zod/v4/locales/ckb.cjs +158 -0
  365. package/node_modules/zod/v4/locales/ckb.d.cts +5 -0
  366. package/node_modules/zod/v4/locales/ckb.d.ts +4 -0
  367. package/node_modules/zod/v4/locales/ckb.js +131 -0
  368. package/node_modules/zod/v4/locales/cs.cjs +3 -0
  369. package/node_modules/zod/v4/locales/cs.js +3 -0
  370. package/node_modules/zod/v4/locales/da.cjs +5 -2
  371. package/node_modules/zod/v4/locales/da.js +5 -2
  372. package/node_modules/zod/v4/locales/de.cjs +3 -0
  373. package/node_modules/zod/v4/locales/de.js +3 -0
  374. package/node_modules/zod/v4/locales/el.cjs +1 -0
  375. package/node_modules/zod/v4/locales/el.js +1 -0
  376. package/node_modules/zod/v4/locales/en.cjs +14 -4
  377. package/node_modules/zod/v4/locales/en.js +14 -4
  378. package/node_modules/zod/v4/locales/eo.cjs +3 -0
  379. package/node_modules/zod/v4/locales/eo.js +3 -0
  380. package/node_modules/zod/v4/locales/es.cjs +2 -0
  381. package/node_modules/zod/v4/locales/es.js +2 -0
  382. package/node_modules/zod/v4/locales/fa.cjs +3 -0
  383. package/node_modules/zod/v4/locales/fa.js +3 -0
  384. package/node_modules/zod/v4/locales/fi.cjs +3 -0
  385. package/node_modules/zod/v4/locales/fi.js +3 -0
  386. package/node_modules/zod/v4/locales/fr-CA.cjs +3 -0
  387. package/node_modules/zod/v4/locales/fr-CA.js +3 -0
  388. package/node_modules/zod/v4/locales/fr.cjs +16 -14
  389. package/node_modules/zod/v4/locales/fr.js +16 -14
  390. package/node_modules/zod/v4/locales/gu.cjs +138 -0
  391. package/node_modules/zod/v4/locales/gu.d.cts +5 -0
  392. package/node_modules/zod/v4/locales/gu.d.ts +4 -0
  393. package/node_modules/zod/v4/locales/gu.js +111 -0
  394. package/node_modules/zod/v4/locales/he.cjs +5 -0
  395. package/node_modules/zod/v4/locales/he.js +5 -0
  396. package/node_modules/zod/v4/locales/hi.cjs +136 -0
  397. package/node_modules/zod/v4/locales/hi.d.cts +5 -0
  398. package/node_modules/zod/v4/locales/hi.d.ts +4 -0
  399. package/node_modules/zod/v4/locales/hi.js +109 -0
  400. package/node_modules/zod/v4/locales/hr.cjs +2 -0
  401. package/node_modules/zod/v4/locales/hr.js +2 -0
  402. package/node_modules/zod/v4/locales/hu.cjs +3 -0
  403. package/node_modules/zod/v4/locales/hu.js +3 -0
  404. package/node_modules/zod/v4/locales/hy.cjs +9 -0
  405. package/node_modules/zod/v4/locales/hy.js +9 -0
  406. package/node_modules/zod/v4/locales/id.cjs +3 -0
  407. package/node_modules/zod/v4/locales/id.js +3 -0
  408. package/node_modules/zod/v4/locales/index.cjs +22 -2
  409. package/node_modules/zod/v4/locales/index.d.cts +10 -0
  410. package/node_modules/zod/v4/locales/index.d.ts +10 -0
  411. package/node_modules/zod/v4/locales/index.js +10 -0
  412. package/node_modules/zod/v4/locales/is.cjs +3 -0
  413. package/node_modules/zod/v4/locales/is.js +3 -0
  414. package/node_modules/zod/v4/locales/it.cjs +3 -0
  415. package/node_modules/zod/v4/locales/it.js +3 -0
  416. package/node_modules/zod/v4/locales/ja.cjs +3 -0
  417. package/node_modules/zod/v4/locales/ja.js +3 -0
  418. package/node_modules/zod/v4/locales/ka.cjs +3 -0
  419. package/node_modules/zod/v4/locales/ka.js +3 -0
  420. package/node_modules/zod/v4/locales/km.cjs +3 -0
  421. package/node_modules/zod/v4/locales/km.js +3 -0
  422. package/node_modules/zod/v4/locales/kn.cjs +141 -0
  423. package/node_modules/zod/v4/locales/kn.d.cts +5 -0
  424. package/node_modules/zod/v4/locales/kn.d.ts +4 -0
  425. package/node_modules/zod/v4/locales/kn.js +114 -0
  426. package/node_modules/zod/v4/locales/ko.cjs +3 -0
  427. package/node_modules/zod/v4/locales/ko.js +3 -0
  428. package/node_modules/zod/v4/locales/lt.cjs +2 -0
  429. package/node_modules/zod/v4/locales/lt.js +2 -0
  430. package/node_modules/zod/v4/locales/mk.cjs +3 -0
  431. package/node_modules/zod/v4/locales/mk.js +3 -0
  432. package/node_modules/zod/v4/locales/ms.cjs +3 -0
  433. package/node_modules/zod/v4/locales/ms.js +3 -0
  434. package/node_modules/zod/v4/locales/ne.cjs +136 -0
  435. package/node_modules/zod/v4/locales/ne.d.cts +5 -0
  436. package/node_modules/zod/v4/locales/ne.d.ts +4 -0
  437. package/node_modules/zod/v4/locales/ne.js +109 -0
  438. package/node_modules/zod/v4/locales/nl.cjs +3 -0
  439. package/node_modules/zod/v4/locales/nl.js +3 -0
  440. package/node_modules/zod/v4/locales/nn.cjs +138 -0
  441. package/node_modules/zod/v4/locales/nn.d.cts +5 -0
  442. package/node_modules/zod/v4/locales/nn.d.ts +4 -0
  443. package/node_modules/zod/v4/locales/nn.js +111 -0
  444. package/node_modules/zod/v4/locales/no.cjs +5 -2
  445. package/node_modules/zod/v4/locales/no.js +5 -2
  446. package/node_modules/zod/v4/locales/ota.cjs +3 -0
  447. package/node_modules/zod/v4/locales/ota.js +3 -0
  448. package/node_modules/zod/v4/locales/pl.cjs +3 -0
  449. package/node_modules/zod/v4/locales/pl.js +3 -0
  450. package/node_modules/zod/v4/locales/ps.cjs +3 -0
  451. package/node_modules/zod/v4/locales/ps.js +3 -0
  452. package/node_modules/zod/v4/locales/pt-BR.cjs +168 -0
  453. package/node_modules/zod/v4/locales/pt-BR.d.cts +5 -0
  454. package/node_modules/zod/v4/locales/pt-BR.d.ts +4 -0
  455. package/node_modules/zod/v4/locales/pt-BR.js +141 -0
  456. package/node_modules/zod/v4/locales/pt.cjs +87 -55
  457. package/node_modules/zod/v4/locales/pt.js +87 -55
  458. package/node_modules/zod/v4/locales/ro.cjs +1 -0
  459. package/node_modules/zod/v4/locales/ro.js +1 -0
  460. package/node_modules/zod/v4/locales/ru.cjs +10 -0
  461. package/node_modules/zod/v4/locales/ru.js +10 -0
  462. package/node_modules/zod/v4/locales/sk.cjs +141 -0
  463. package/node_modules/zod/v4/locales/sk.d.cts +5 -0
  464. package/node_modules/zod/v4/locales/sk.d.ts +4 -0
  465. package/node_modules/zod/v4/locales/sk.js +114 -0
  466. package/node_modules/zod/v4/locales/sl.cjs +3 -0
  467. package/node_modules/zod/v4/locales/sl.js +3 -0
  468. package/node_modules/zod/v4/locales/sv.cjs +5 -2
  469. package/node_modules/zod/v4/locales/sv.js +5 -2
  470. package/node_modules/zod/v4/locales/ta.cjs +3 -0
  471. package/node_modules/zod/v4/locales/ta.js +3 -0
  472. package/node_modules/zod/v4/locales/th.cjs +3 -0
  473. package/node_modules/zod/v4/locales/th.js +3 -0
  474. package/node_modules/zod/v4/locales/tk.cjs +132 -0
  475. package/node_modules/zod/v4/locales/tk.d.cts +5 -0
  476. package/node_modules/zod/v4/locales/tk.d.ts +4 -0
  477. package/node_modules/zod/v4/locales/tk.js +105 -0
  478. package/node_modules/zod/v4/locales/tr.cjs +3 -0
  479. package/node_modules/zod/v4/locales/tr.js +3 -0
  480. package/node_modules/zod/v4/locales/uk.cjs +3 -0
  481. package/node_modules/zod/v4/locales/uk.js +3 -0
  482. package/node_modules/zod/v4/locales/ur.cjs +3 -0
  483. package/node_modules/zod/v4/locales/ur.js +3 -0
  484. package/node_modules/zod/v4/locales/uz.cjs +1 -0
  485. package/node_modules/zod/v4/locales/uz.js +1 -0
  486. package/node_modules/zod/v4/locales/vi.cjs +3 -0
  487. package/node_modules/zod/v4/locales/vi.js +3 -0
  488. package/node_modules/zod/v4/locales/yo.cjs +3 -0
  489. package/node_modules/zod/v4/locales/yo.js +3 -0
  490. package/node_modules/zod/v4/locales/zh-CN.cjs +3 -0
  491. package/node_modules/zod/v4/locales/zh-CN.js +3 -0
  492. package/node_modules/zod/v4/locales/zh-TW.cjs +3 -0
  493. package/node_modules/zod/v4/locales/zh-TW.js +3 -0
  494. package/node_modules/zod/v4/mini/checks.cjs +2 -1
  495. package/node_modules/zod/v4/mini/checks.d.cts +1 -1
  496. package/node_modules/zod/v4/mini/checks.d.ts +1 -1
  497. package/node_modules/zod/v4/mini/checks.js +1 -1
  498. package/node_modules/zod/v4/mini/deep-partial.cjs +39 -0
  499. package/node_modules/zod/v4/mini/deep-partial.d.cts +14 -0
  500. package/node_modules/zod/v4/mini/deep-partial.d.ts +14 -0
  501. package/node_modules/zod/v4/mini/deep-partial.js +13 -0
  502. package/node_modules/zod/v4/mini/external.cjs +12 -1
  503. package/node_modules/zod/v4/mini/external.d.cts +5 -2
  504. package/node_modules/zod/v4/mini/external.d.ts +5 -2
  505. package/node_modules/zod/v4/mini/external.js +3 -1
  506. package/node_modules/zod/v4/mini/in-out.cjs +63 -0
  507. package/node_modules/zod/v4/mini/in-out.d.cts +8 -0
  508. package/node_modules/zod/v4/mini/in-out.d.ts +8 -0
  509. package/node_modules/zod/v4/mini/in-out.js +36 -0
  510. package/node_modules/zod/v4/mini/parse.cjs +3 -1
  511. package/node_modules/zod/v4/mini/parse.d.cts +1 -1
  512. package/node_modules/zod/v4/mini/parse.d.ts +1 -1
  513. package/node_modules/zod/v4/mini/parse.js +1 -1
  514. package/node_modules/zod/v4/mini/schemas.cjs +75 -47
  515. package/node_modules/zod/v4/mini/schemas.d.cts +43 -13
  516. package/node_modules/zod/v4/mini/schemas.d.ts +43 -13
  517. package/node_modules/zod/v4/mini/schemas.js +71 -45
  518. package/package.json +5 -5
  519. package/routes/quota.js +29 -3
  520. package/ui/dist/.vite/manifest.json +61 -61
  521. package/ui/dist/assets/{AgentWorkspace-CL3MLv3l.js → AgentWorkspace-BulKz33A.js} +1 -1
  522. package/ui/dist/assets/{App-B9cEM6dJ.js → App-juOjrIgh.js} +3 -3
  523. package/ui/dist/assets/{AssetGenWorkspace-swWPvXrx.js → AssetGenWorkspace-8SYhS2Y2.js} +2 -2
  524. package/ui/dist/assets/{AssetsWorkspace-CRVeYU2F.js → AssetsWorkspace-Dxz-Xksp.js} +1 -1
  525. package/ui/dist/assets/{CardNewsWorkspace-BAOxWLKf.js → CardNewsWorkspace-DV4hpvKf.js} +1 -1
  526. package/ui/dist/assets/{GenerationRequestLogPanel-DZtYZm-D.js → GenerationRequestLogPanel-VFu4cAdd.js} +1 -1
  527. package/ui/dist/assets/{HomeWorkspace-BeZ1s0Jm.js → HomeWorkspace-D1UBgwRZ.js} +1 -1
  528. package/ui/dist/assets/{KeyingPanel-ZyBSXioh.js → KeyingPanel-GdUcaaJR.js} +1 -1
  529. package/ui/dist/assets/{NodeCanvas-BvvcCErf.js → NodeCanvas-B6zoJhHr.js} +3 -3
  530. package/ui/dist/assets/{PromptBuilderPanel-DBycmShA.js → PromptBuilderPanel-CJ56MEk2.js} +1 -1
  531. package/ui/dist/assets/{PromptImportDialog-ChvMv7ek.js → PromptImportDialog-DMFnggIT.js} +2 -2
  532. package/ui/dist/assets/{PromptImportDiscoverySection-60py7whH.js → PromptImportDiscoverySection-4KCIWmZ8.js} +1 -1
  533. package/ui/dist/assets/{PromptImportFolderSection-CCRh_-_7.js → PromptImportFolderSection-BjqopFX5.js} +1 -1
  534. package/ui/dist/assets/{PromptLibraryPanel-BFWQO8OT.js → PromptLibraryPanel-DwFK4ALC.js} +2 -2
  535. package/ui/dist/assets/SettingsWorkspace-BWcNnQ56.js +1 -0
  536. package/ui/dist/assets/{SpriteRecipeWorkspace-DRWdkmwU.js → SpriteRecipeWorkspace-Bsl_NZ3A.js} +1 -1
  537. package/ui/dist/assets/{index-7ngEOVxt.js → index-BWzT2RyM.js} +3 -3
  538. package/ui/dist/assets/{index-B5jy7ePg.css → index-C5zSMtGM.css} +1 -1
  539. package/ui/dist/assets/{index-gxh_02DQ.js → index-Cl5SnWLL.js} +7 -7
  540. package/ui/dist/assets/{pptxgen.es-OUNhQLEV.js → pptxgen.es-BslswdiL.js} +1 -1
  541. package/ui/dist/assets/{promptBuilderStore-BTUUzbBT.js → promptBuilderStore-Cl2q0Oe6.js} +1 -1
  542. package/ui/dist/assets/useAgentDialogFocus-B8niAv4W.js +1 -0
  543. package/ui/dist/index.html +2 -2
  544. package/node_modules/zod/src/v4/core/config.ts +0 -15
  545. package/ui/dist/assets/SettingsWorkspace-B5Ghsgdj.js +0 -1
  546. package/ui/dist/assets/useAgentDialogFocus-DSc2qY8p.js +0 -1
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-7ngEOVxt.js","assets/index-gxh_02DQ.js","assets/index-B5jy7ePg.css","assets/PromptLibraryPanel-BFWQO8OT.js","assets/PromptBuilderPanel-DBycmShA.js","assets/promptBuilderStore-BTUUzbBT.js","assets/GenerationRequestLogPanel-DZtYZm-D.js","assets/NodeCanvas-BvvcCErf.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-B5Ghsgdj.js","assets/CardNewsWorkspace-BAOxWLKf.js","assets/AgentWorkspace-CL3MLv3l.js","assets/useAgentDialogFocus-DSc2qY8p.js","assets/AssetsWorkspace-CRVeYU2F.js","assets/KeyingPanel-ZyBSXioh.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-swWPvXrx.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-BeZ1s0Jm.js"])))=>i.map(i=>d[i]);
2
- import{R as an,i as ce,c as Je,r as ki,g as pe,a as gd,b as yd,L as St,z as vd,d as bd,e as xd,k as Id,f as v,s as Sd,l as wd,j as o,h as _d,_ as Me}from"./index-gxh_02DQ.js";const oa=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))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,s,l);return l},Ed=(e=>e?oa(e):oa),Nd=e=>e;function kd(e,t=Nd){const n=an.useSyncExternalStore(e.subscribe,an.useCallback(()=>t(e.getState()),[e,t]),an.useCallback(()=>t(e.getInitialState()),[e,t]));return an.useDebugValue(n),n}const aa=e=>{const t=Ed(e),n=r=>kd(t,r);return Object.assign(n,t),n},Ci=(e=>e?aa(e):aa);async function we(e,t){const n=pe();let r=!1;try{if(typeof window<"u"){const s=new URL(e,window.location.href);r=s.origin===window.location.origin&&/^\/(api|generated)(?:\/|$)/i.test(s.pathname)}}catch{}try{if(r&&t?.signal?.throwIfAborted(),r&&ce())throw Je(n-1);const s=await fetch(e,t);if(r&&s.status===401){const i=await s.clone().json().catch(()=>null);if(i?.error?.code==="LAN_TOKEN_REQUIRED"||i?.code==="LAN_TOKEN_REQUIRED"){ki(n);try{await s.body?.cancel()}catch{}throw Je(n)}}return s}catch(s){throw s}}async function z(e,t){const n=await we(e,t),r=await n.json().catch(()=>({}));if(!n.ok){const s=r.error,a=r.code,i=typeof s=="string"?s:s?.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 ji(e,t){t?.throwIfAborted();const n=await we(e,{method:"GET",signal:t});if(!n.ok){try{await n.body?.cancel()}catch{}const s=new Error(`Request failed: ${n.status}`);throw s.status=n.status,s}t?.throwIfAborted();const r=await n.json();return t?.throwIfAborted(),r}let en=null;function Pi(){if(!en){const e=localStorage.getItem("ima2.browserId");e?en=e:(en=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",en))}return en}function Ht(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Pi()};return z(e,{...t,headers:n})}function Cd(){return z("/api/capabilities")}function Ai(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 z(`/api/inflight${n}`)}function Ce(e){return z(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function jd(){return z("/api/oauth/status")}function Pd(){return z("/api/billing")}const Ad=5400*1e3,Rd=2e3,ia=3e4;let ge=null,Sr="";const Ms=new Set;let Ls=null,Be=null,la=!1,fr=0,wr=0,ca=!1;const Td=3;let eo=null;const Md=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function Ld(){return Sr?`/api/events?lastEventId=${encodeURIComponent(Sr)}`:"/api/events"}function Fd(){wr+=1;const e=ge;ge=null,e?.close(),Be&&(clearTimeout(Be),Be=null)}function Od(){ca||typeof window>"u"||(window.addEventListener(St,Fd),ca=!0)}function da(e,t){if(e!==wr||t!==pe()||ce()||ge)return;const n=Math.min(Rd*Math.pow(1.5,fr),ia),r=Math.min(n*(.8+Math.random()*.4),ia);fr+=1,Be=setTimeout(to,r),eo?.(fr>=Td?"failed":"reconnecting")}function to(){if(Od(),ce()||ge&&ge.readyState!==EventSource.CLOSED)return;wr+=1;const e=new EventSource(Ld());ge=e,Be&&(clearTimeout(Be),Be=null),e.onopen=()=>{if(ge!==e)return;Be&&(clearTimeout(Be),Be=null),fr=0;const t=la;la=!0,t&&Ls?.(),ge===e&&eo?.("connected")};for(const t of Md)e.addEventListener(t,n=>{ge!==e||typeof n.data!="string"||Dd(t,n)});e.addEventListener("replay-gap",()=>{ge===e&&(Sr="",Ls?.())}),e.onerror=t=>{if(ge!==e||typeof t.data=="string")return;ge=null,e.close();const n=++wr,r=pe();if(gd()?.mode==="lan"){const s=()=>da(n,r);yd().then(s,s)}else da(n,r)}}function Dd(e,t){t.lastEventId&&(Sr=t.lastEventId);let n;try{n=JSON.parse(t.data)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;const r=n,s=r.jobId??r.requestId;if(!(typeof s!="string"||!s))for(const a of Ms)a.jobId===s&&(a.event!==null&&a.event!==e||a.handler(e,r))}function kt(e,t,n){const r={jobId:e,event:t,handler:n};return Ms.add(r),(!ge||ge.readyState===EventSource.CLOSED)&&to(),()=>{Ms.delete(r)}}function Kt(e,t=Ad){const n=setTimeout(e,t);return()=>clearTimeout(n)}function ua(e){Ls=e}function ma(e){eo=e}function Ct(){(!ge||ge.readyState===EventSource.CLOSED)&&to()}function no(e=1e4){const t=pe();return ce()?Promise.reject(Je(t-1)):(Ct(),ge&&ge.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const s=Date.now(),a=()=>{if(t!==pe()||ce()){r(Je(t));return}if(ge&&ge.readyState===EventSource.OPEN){n();return}if(Date.now()-s>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const Gd=["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"&&Gd.includes(e)}function pa(e){if(typeof e=="string")return zd[e]}const Ri="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Ve={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_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 fa(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 $d=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED"];function Ud(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 tt(e){const t=e,n=t&&typeof t=="object"?t:{},r=typeof n.message=="string"?n.message:String(e??""),s=typeof n.code=="string"?n.code:"";if(s==="LAN_TOKEN_REQUIRED")return{code:"LAN_TOKEN_REQUIRED",spec:Ve.LAN_TOKEN_REQUIRED,message:Je().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=s&&s in Ve?s:a&&a in Ve?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Ve.JOB_TRACKING_TIMEOUT,message:Ri};const c=qd(i)?pa(i):void 0,d=l?$d.includes(l):!1,u=pa(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=Ve[l]):u?(p=fa(r),m=u):(p=fa(r),m=Ve[p]??Ve.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||Ud(r):void 0;return{code:p,spec:m,message:r,...a?{rawCode:a}:s&&!l?{rawCode:s}:{},...i&&(c||u)?{errorClass:i}:{},...h?{moderationStage:h}:{}}}function Hd(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function at(e,t="Generation failed"){const n=e.error;let r=t,s,a,i,l;const c=Hd(e);if(c&&c.terminal===!0&&(typeof c.phase=="string"&&(l=c.phase),c.error&&typeof c.error=="object"&&(typeof c.error.code=="string"&&(s=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"&&(s=s??m.code),typeof m.rawCode=="string"&&(a=m.rawCode),typeof m.errorClass=="string"&&(i=m.errorClass)}typeof e.code=="string"&&(s=s??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=tt({code:s,rawCode:a,message:r,errorClass:i});u.code==="JOB_TRACKING_TIMEOUT"&&(s=u.code,r=u.message,d=504,l="timed_out",a=void 0,i=void 0);const p=new Error(r);return p.code=s,p.status=d,a&&(p.rawCode=a),i&&(p.errorClass=i),l&&(p.phase=l),p}const ha=5e3,ga=3e4;function Kd(e){if(!e)return ha;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(ga,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(ga,Math.max(1e3,n-Date.now())):ha}function Vd(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function as(){return new DOMException("Aborted","AbortError")}function zr(...e){const t=e.filter(s=>!!s);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 s of t)s.removeEventListener("abort",r);n.abort()};return t.some(s=>s.aborted)?r():t.forEach(s=>s.addEventListener("abort",r,{once:!0})),n.signal}async function qr({url:e,payload:t,requestId:n,signal:r,parseError:s}){const a=pe();let i=null;const l=c=>new Promise((d,u)=>{if(r?.aborted){u(as());return}const p=()=>{i&&(clearTimeout(i),i=null),u(as())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",p),d()},c),r?.addEventListener("abort",p,{once:!0})});for(;;){if(r?.aborted)throw as();if(a!==pe())throw Je(a);if(ce())throw Je(a-1);const c=await we(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(Vd(c,d)){await l(Kd(c.headers.get("Retry-After")));continue}throw s(c,d)}}async function Ti(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return Ct(),new Promise((r,s)=>{let a=!1;const i=new AbortController,l=zr(t.signal,i.signal),c=p=>{a||(a=!0,u(),d(),p())},d=kt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>s(at(m,"Generation failed"))))}),u=Kt(()=>{c(()=>{i.abort(),Ce(n),s(new Error("Generation stream timed out"))})});if(t.signal){if(t.signal.aborted){c(()=>{i.abort(),Ce(n),s(new DOMException("Aborted","AbortError"))});return}t.signal.addEventListener("abort",()=>{c(()=>{i.abort(),Ce(n),s(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(p,m)=>{const h=at(m,`Request failed: ${p.status}`);return h.status=h.status??p.status,h}}).then(()=>{}).catch(p=>{c(()=>s(p instanceof Error?p:new Error(String(p))))})})}async function Bd(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="image"?t.onImage?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Multimode generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Multimode generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 zS(e){return z("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Wd(e){const t=await e.arrayBuffer(),n=await we("/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 s={};try{s=await n.json()}catch{}const a=new Error(s.error||`Import failed (${n.status})`);throw a.code=s.code||"IMPORT_FAILED",a}return(await n.json()).item}function qS(e){return z("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function $S(){return z("/api/prompt-builder/config")}function US(e){return z("/api/prompt-builder/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ro(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="planning"?t.onPlanning?.():m==="submitted"?t.onSubmitted?.(h):m==="progress"?t.onProgress?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Video generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Video generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 Vt(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"),Ht(`/api/history?${t.toString()}`)}function Jd(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),Ht(`/api/history?${t.toString()}`)}function Yd(e){return Ht("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function Xd(){return(await z("/api/storage/status")).data}function Zd(){return z("/api/storage/open-generated-dir",{method:"POST"})}function Mi(e){return z(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function Qd(e){return z(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function eu(e,t){return z(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function tu(e){return z("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function nu(){return z("/api/sessions")}function ru(e){return z("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function Li(e){return z(`/api/sessions/${encodeURIComponent(e)}`)}function su(e,t){return z(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function ou(e){return z(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function au(e,t,n,r,s={}){const a={"Content-Type":"application/json","If-Match":String(t)};return s.saveId&&(a["X-Ima2-Graph-Save-Id"]=s.saveId),s.saveReason&&(a["X-Ima2-Graph-Save-Reason"]=s.saveReason),s.tabId&&(a["X-Ima2-Tab-Id"]=s.tabId),z(`/api/sessions/${encodeURIComponent(e)}/graph`,{method:"PUT",headers:a,body:JSON.stringify({nodes:n,edges:r})})}function iu(e){return z("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function HS(e){return Ht(`/api/annotations/${encodeURIComponent(e)}`)}async function KS(e,t){await Ht(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function VS(e){await Ht(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function BS(e){const t=new URLSearchParams({sourceFilename:e.sourceFilename});return z(`/api/canvas-versions?${t.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e.image})}function WS(e,t){const n=new URLSearchParams;t.sourceFilename&&n.set("sourceFilename",t.sourceFilename);const r=n.size>0?`?${n.toString()}`:"";return z(`/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 JS(e,t,n){return z(`/api/canvas-versions/${encodeURIComponent(e)}/annotation-bake`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshot:t,annotationOnly:n})})}function YS(e){return z(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function lu(e){const t=new URLSearchParams;return z(`/api/prompts?${t.toString()}`)}function cu(e){return z("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function du(e){return z(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function uu(e){return z(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function mu(e){return z("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function XS(e){return z("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ZS(e){return z("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function QS(){return z("/api/prompts/import/curated-sources")}function ew(e){return z("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function tw(e){return z("/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 z(`/api/prompts/import/discovery${n}`)}function rw(e){return z("/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 sw(e){return z("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ow(e){return z("/api/prompts/import/folder-files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input}})})}function aw(e){return z("/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 so(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 z(`/api/assets${n?`?${n}`:""}`)}function pu(e){return z(`/api/assets/${encodeURIComponent(e)}`)}function $r(e){return z("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function iw(e){return z("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Fi(e,t){return z(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function lw(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 we(`/api/assets/derived?${n.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e});if(!r.ok){const s=await r.json().catch(()=>({}));throw new Error(s.error||`derived upload failed (${r.status})`)}return r.json()}async function fu(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 we(`/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 cw(e){return z("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function hu(e){return z(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function oo(){return z("/api/assets/folders")}function gu(e){return z("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Oi(e,t){return z(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function yu(e){return z(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ao(){return z("/api/assets/tags")}function dw(){return z("/api/assets/all",{method:"DELETE"})}async function vu(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Node generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Node generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 io=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],bu=new Set(io);function jt(e){return typeof e=="string"&&bu.has(e)}const Nn={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-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"],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-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"]},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:[]}},xu=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality","nano-banana-2","nano-banana-pro","openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit","image-01","image-01-live","nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],Di={oauth:{},api:{},grok:{image:3,edit:3,video:7},"grok-api":{image:3,edit:3,video:7},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}},lo={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"}}},hr="gpt-5.6-luna",Xe=[{value:"gpt-5.6-luna",shortLabel:"5.6l",fullLabelKey:"settings.imageModel.gpt56Luna"},{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"}],Ur=new Set(Nn["gemini-api"].image),co=new Set(Nn.atlascloud.image),uo=new Set(Nn.minimax.image),mo=new Set(Nn.nai.image),Iu=Xe.filter(e=>!e.value.startsWith("grok-")&&!Ur.has(e.value)&&!co.has(e.value)&&!uo.has(e.value)&&!mo.has(e.value)),Su=Xe.filter(e=>e.value.startsWith("grok-")),wu=Xe.filter(e=>Ur.has(e.value)),_u=Xe.filter(e=>co.has(e.value)),Eu=Xe.filter(e=>uo.has(e.value)),Gi=Xe.filter(e=>mo.has(e.value)),uw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Nu(e){return Xe.some(t=>t.value===e)}function ku(e){return typeof e=="string"&&e.startsWith("grok-")}function Cu(e){return typeof e=="string"&&Ur.has(e)}function ju(e){return e==="grok"||e==="grok-api"?Su:e==="agy"||e==="gemini-api"?wu:e==="atlascloud"?_u:e==="minimax"?Eu:e==="nai"?Gi:e==="comfy"?[]:Iu}function zi(e,t){return e?Ur.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:co.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:uo.has(e)?t==="minimax"?`${e} minimax`:e:mo.has(e)?Xe.find(n=>n.value===e)?.shortLabel??e:Xe.find(n=>n.value===e)?.shortLabel??e:null}const po="grok-imagine-video",pt="grok-imagine-video-1.5",qi="grok-imagine-video-1.5-preview",Pu=[{value:po,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:pt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Au(e){return e===po||e===pt||e===qi}function kn(e){return Au(e)?e===qi?pt:e:!1}function Ru(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function is(e,t,n){return t!=="1080p"?!0:e===pt&&(n==="text-to-video"||n==="image-to-video")}const zt="comfy-video:",$i="video:";function Tu(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${zt}${a}`:s??"":(t==="grok"||t==="grok-api")&&r?`${$i}${r}`:n}const Fs=new Set(xu),Mu={oauth:hr,api:hr,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:hr};function Hr(e,t){return typeof t=="string"&&Fs.has(t)&&Nn[e].image.includes(t)}function un(e){return typeof e=="string"&&e.trim().length>0?e:null}function Ui(e,t){if(kn(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Hr(n,e))return n;return"oauth"}function ot(e){const t=jt(e.provider)?e.provider:Ui(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=un(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Fs.has(e.imageModel)?e.imageModel:hr,videoModelSelected:!1,comfyWorkflow:un(e.comfyWorkflow)??(n&&!Fs.has(n)?n:null),comfyVideoWorkflow:un(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Hr(t,e.imageModel)?e.imageModel:Mu[t],videoModelSelected:t==="grok"||t==="grok-api"?kn(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Lu(e,t){return jt(e)&&Hr(e,t)?e:Ui(t,!1)}function Fu(e,t,n){return e.provider===t?e:ot(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 ya(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 Hi(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Os(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of io){if(!Object.hasOwn(e,n))continue;const r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;const s=r;if(s.kind!=="image"&&s.kind!=="video")continue;const a=n==="comfy"?un(s.image):Hr(n,s.image)?s.image:null,i=n==="comfy"?un(s.video):n==="grok"||n==="grok-api"?kn(s.video):!1;t[n]={kind:s.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Ou="none",Ds=[{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 Ki(e){return Ds.some(t=>t.value===e)}const Du={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Gu(e){return!Ki(e)||e==="none"?null:`R:${Du[e]}`}const _e=["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"],Vi=_e[0],Bi=_e[1],Wi=_e[2],Ji=_e[3],fo=_e[4],Yi=_e[5],Xi=_e[6],ho=_e[7],Zi=_e[8],Gs=_e[9],zs=_e[10],va=_e[11],go=_e[12],Qi=_e[13],yo=_e[17],el=_e[19],tl=_e[20],zu=!0,qu=!1,Bt=!0,nl=qu,Wt=!0,$u=24;function qs(e){return Math.min($u,Math.max(1,Math.trunc(e||1)))}const ba={ko:Id,en:xd,"zh-Hant":bd,"zh-Hans":vd};function xa(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function Uu(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function A(e,t){const n=f.getState().locale;return rl(n,e,t)}function rl(e,t,n){const r=xa(ba[e],t),s=typeof r=="string"?r:xa(ba.en,t),a=typeof s=="string"?s:t;return n?Uu(a,n):a}function H(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>rl(e,t,n)}}function Hu(e){return Math.round(e/16)*16}const xt=16,vo=3840,ls=655360,gr=8294400,Ku=3,Lt=3,Ia=Math.floor(Math.sqrt(gr)/xt)*xt,sl=xt,Vu=vo,Kn=Ku;function Sa(e){return Math.floor(e/16)*16}function _r(e){return Math.ceil(e/16)*16}function De(e){return Math.min(Vu,Math.max(sl,e))}function Ze(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function wt(e,t){e.includes(t)||e.push(t)}function wa(e,t){const n=Hu(e);return n!==e&&wt(t,"snap"),n}function _a(e,t){return e<sl&&wt(t,"min"),e>vo&&wt(t,"maxEdge"),De(e)}function Ea(e,t,n){return e>t*Kn?(wt(n,"ratio"),{w:e,h:De(_r(e/Kn))}):t>e*Kn?(wt(n,"ratio"),{w:De(_r(t/Kn)),h:t}):{w:e,h:t}}function Bu(e,t,n){if(e*t<ls){wt(n,"minPixels");const i=Math.sqrt(ls/(e*t));let l=De(_r(e*i)),c=De(_r(t*i));for(;l*c<ls;)l<=c?l=De(l+xt):c=De(c+xt);return{w:l,h:c}}if(e*t<=gr)return{w:e,h:t};wt(n,"maxPixels");const r=Math.sqrt(gr/(e*t));let s=De(Sa(e*r)),a=De(Sa(t*r));for(;s*a>gr;)s>=a?s=De(s-xt):a=De(a-xt);return{w:s,h:a}}function bo(e,t,n,r){const s=[],a=Ze(e,n),i=Ze(t,r);let l=_a(wa(a,s),s),c=_a(wa(i,s),s);return{w:l,h:c}=Ea(l,c,s),{w:l,h:c}=Bu(l,c,s),{w:l,h:c}=Ea(l,c,s),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:s}}function ol(e,t,n,r){const s=bo(e,t,n,r);return{w:s.w,h:s.h}}const Wu=[{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 Ju(e,t){return`${e}x${t}`}function Yu(e,t=1024){if(e.id==="free")return null;const n=t,r=e.w>=e.h,s=r?Math.round(n*e.w/e.h):n,a=r?n:Math.round(n*e.h/e.w);return ol(s,a,s,a)}function Kr(e){const t=ol(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function Ft(e){return e.slice(0,Lt).map(Kr)}function Xu(e,t){const n=Kr(t),r=e.findIndex(s=>s.id===n.id);return r>=0?Ft(e.map((s,a)=>a===r?n:s)):e.length>=Lt?Ft(e):Ft([...e,n])}function Zu(e,t,n){const r=Kr({...n,id:t});return Ft(e.map(s=>s.id===t?r:s))}const Qu=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],em=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],tm=[{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"}],nm=[{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 rm(){return[{value:"auto",label:A("size.autoLabel"),sub:A("size.autoSub")},{value:"custom",label:A("size.customLabel"),sub:A("size.customSub")}]}const al=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],il=["native","karras","exponential","polyexponential"],ll=["heavy","light","furryFocus","humanFocus","none"],cl=["standard","light","none"],sm={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},Er={min:1,max:50},Nr={min:1,max:10},kr={min:0,max:1},dl=2**32-1;function om(e,t){return{...sm,...e??{},...t}}function $s(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Vn(e,t){return typeof e=="string"&&t.includes(e)?e:void 0}function cs(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function ul(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Vn(t.sampler,al);r!==void 0&&(n.sampler=r);const s=Vn(t.noiseSchedule,il);s!==void 0&&(n.noiseSchedule=s);const a=Vn(t.ucPresetId,ll);a!==void 0&&(n.ucPresetId=a);const i=Vn(t.qualityPresetId,cl);i!==void 0&&(n.qualityPresetId=i);const l=cs(t.steps,Er.min,Er.max);l!==void 0&&(n.steps=l);const c=cs(t.scale,Nr.min,Nr.max);c!==void 0&&(n.scale=c);const d=cs(t.cfgRescale,kr.min,kr.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<=dl&&(n.seed=t.seed),n}function qe(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Us="vid:",Hs="img:",am=/^[\p{L}\p{N}_-]{1,32}$/u;function xo(e){return am.test(e)}function im(e){return e.references.some(t=>t.tag!==void 0&&!xo(t.tag))}function ml(e){return e==="video"?"video":"image"}function Vr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function lm(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function Br(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)&&lm(r)))}function Na(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 pl(e,t,n){const r=Vr(t),s=Br(n),a={};for(const i of e.parameters){const l=s[i.name];l!==void 0&&Na(i,l)?a[i.name]=l:i.default!==void 0&&Na(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function cm(e){return e?pl(e,null,{}):{ratio:null,parameters:{}}}function dm(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function fl(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,s=typeof t.displayName=="string"&&t.displayName?t.displayName.slice(0,180):null;return{filename:t.filename,...n?{tag:n}:{},...r?{dataUrl:r}:{},...s?{displayName:s}:{}}}function Io(e){if(!e||typeof e!="object")return qe();const t=e,n=Array.isArray(t.references)?t.references.map(fl).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,s)=>n.findIndex(a=>a.filename===r.filename)===s).slice(0,3),referenceVideoFilename:typeof t.referenceVideoFilename=="string"&&t.referenceVideoFilename?t.referenceVideoFilename:null}}function So(e,t){const n=Io(t),r=e.includes("start_image")?n.startFrameFilename:null;return{startFrameFilename:r,endFrameFilename:e.includes("end_image")&&r?n.endFrameFilename:null,references:e.includes("image_references")?n.references:[],referenceVideoFilename:e.includes("video_references")?n.referenceVideoFilename:null}}function hl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function um(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:ml(e.mcpMediaKind),ratio:Vr(e.mcpRatio),parameters:Br(e.mcpParameters)}}function Bn(e,t){return`${e==="video"?Us:Hs}${t}`}function mm(e){if(e.startsWith(Us)){const t=e.slice(Us.length);return t?{kind:"video",model:t}:null}if(e.startsWith(Hs)){const t=e.slice(Hs.length);return t?{kind:"image",model:t}:null}return null}function gl(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 pm(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const s=ml(e.mcpMediaKind),a=Vr(e.mcpRatio),i=Br(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=y=>c===void 0||c.includes(y),u=Io(e.mcpReferenceSelection),p=l?d("start_image")?u.startFrameFilename:null:s==="video"?e.currentImageFilename??null:null,m=l&&d("image_references")?u.references:[],h=d("image_references")?e.elementReferences??[]:[],b=[...m,...h].map(fl).filter(y=>!!y).filter((y,g,_)=>_.findIndex(S=>S.filename===y.filename)===g).slice(0,3);if(b.some(y=>y.dataUrl||y.tag!==void 0&&!xo(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:s,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 Cn(e,t){const n=t.filter(s=>s.placement!=="after"),r=t.filter(s=>s.placement==="after");return[...n.map(s=>s.text.trim()).filter(Boolean),e.trim(),...r.map(s=>s.text.trim()).filter(Boolean)].filter(Boolean).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BWzT2RyM.js","assets/index-Cl5SnWLL.js","assets/index-C5zSMtGM.css","assets/PromptLibraryPanel-DwFK4ALC.js","assets/PromptBuilderPanel-CJ56MEk2.js","assets/promptBuilderStore-Cl2q0Oe6.js","assets/GenerationRequestLogPanel-VFu4cAdd.js","assets/NodeCanvas-B6zoJhHr.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-BWcNnQ56.js","assets/CardNewsWorkspace-DV4hpvKf.js","assets/AgentWorkspace-BulKz33A.js","assets/useAgentDialogFocus-B8niAv4W.js","assets/AssetsWorkspace-Dxz-Xksp.js","assets/KeyingPanel-GdUcaaJR.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-8SYhS2Y2.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-D1UBgwRZ.js"])))=>i.map(i=>d[i]);
2
+ import{R as an,i as ce,c as Je,r as ki,g as pe,a as gd,b as yd,L as St,z as vd,d as bd,e as xd,k as Id,f as v,s as Sd,l as wd,j as o,h as _d,_ as Me}from"./index-Cl5SnWLL.js";const oa=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))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=e(r,s,l);return l},Ed=(e=>e?oa(e):oa),Nd=e=>e;function kd(e,t=Nd){const n=an.useSyncExternalStore(e.subscribe,an.useCallback(()=>t(e.getState()),[e,t]),an.useCallback(()=>t(e.getInitialState()),[e,t]));return an.useDebugValue(n),n}const aa=e=>{const t=Ed(e),n=r=>kd(t,r);return Object.assign(n,t),n},Ci=(e=>e?aa(e):aa);async function we(e,t){const n=pe();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&&ce())throw Je(n-1);const s=await fetch(e,t);if(r&&s.status===401){const i=await s.clone().json().catch(()=>null);if(i?.error?.code==="LAN_TOKEN_REQUIRED"||i?.code==="LAN_TOKEN_REQUIRED"){ki(n);try{await s.body?.cancel()}catch{}throw Je(n)}}return s}async function z(e,t){const n=await we(e,t),r=await n.json().catch(()=>({}));if(!n.ok){const s=r.error,a=r.code,i=typeof s=="string"?s:s?.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 ji(e,t){t?.throwIfAborted();const n=await we(e,{method:"GET",signal:t});if(!n.ok){try{await n.body?.cancel()}catch{}const s=new Error(`Request failed: ${n.status}`);throw s.status=n.status,s}t?.throwIfAborted();const r=await n.json();return t?.throwIfAborted(),r}let en=null;function Pi(){if(!en){const e=localStorage.getItem("ima2.browserId");e?en=e:(en=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",en))}return en}function Ht(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Pi()};return z(e,{...t,headers:n})}function Cd(){return z("/api/capabilities")}function Ai(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 z(`/api/inflight${n}`)}function Ce(e){return z(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function jd(){return z("/api/oauth/status")}function Pd(){return z("/api/billing")}const Ad=5400*1e3,Rd=2e3,ia=3e4;let ge=null,Sr="";const Ms=new Set;let Ls=null,Be=null,la=!1,fr=0,wr=0,ca=!1;const Td=3;let eo=null;const Md=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function Ld(){return Sr?`/api/events?lastEventId=${encodeURIComponent(Sr)}`:"/api/events"}function Fd(){wr+=1;const e=ge;ge=null,e?.close(),Be&&(clearTimeout(Be),Be=null)}function Od(){ca||typeof window>"u"||(window.addEventListener(St,Fd),ca=!0)}function da(e,t){if(e!==wr||t!==pe()||ce()||ge)return;const n=Math.min(Rd*Math.pow(1.5,fr),ia),r=Math.min(n*(.8+Math.random()*.4),ia);fr+=1,Be=setTimeout(to,r),eo?.(fr>=Td?"failed":"reconnecting")}function to(){if(Od(),ce()||ge&&ge.readyState!==EventSource.CLOSED)return;wr+=1;const e=new EventSource(Ld());ge=e,Be&&(clearTimeout(Be),Be=null),e.onopen=()=>{if(ge!==e)return;Be&&(clearTimeout(Be),Be=null),fr=0;const t=la;la=!0,t&&Ls?.(),ge===e&&eo?.("connected")};for(const t of Md)e.addEventListener(t,n=>{ge!==e||typeof n.data!="string"||Dd(t,n)});e.addEventListener("replay-gap",()=>{ge===e&&(Sr="",Ls?.())}),e.onerror=t=>{if(ge!==e||typeof t.data=="string")return;ge=null,e.close();const n=++wr,r=pe();if(gd()?.mode==="lan"){const s=()=>da(n,r);yd().then(s,s)}else da(n,r)}}function Dd(e,t){t.lastEventId&&(Sr=t.lastEventId);let n;try{n=JSON.parse(t.data)}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;const r=n,s=r.jobId??r.requestId;if(!(typeof s!="string"||!s))for(const a of Ms)a.jobId===s&&(a.event!==null&&a.event!==e||a.handler(e,r))}function kt(e,t,n){const r={jobId:e,event:t,handler:n};return Ms.add(r),(!ge||ge.readyState===EventSource.CLOSED)&&to(),()=>{Ms.delete(r)}}function Kt(e,t=Ad){const n=setTimeout(e,t);return()=>clearTimeout(n)}function ua(e){Ls=e}function ma(e){eo=e}function Ct(){(!ge||ge.readyState===EventSource.CLOSED)&&to()}function no(e=1e4){const t=pe();return ce()?Promise.reject(Je(t-1)):(Ct(),ge&&ge.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const s=Date.now(),a=()=>{if(t!==pe()||ce()){r(Je(t));return}if(ge&&ge.readyState===EventSource.OPEN){n();return}if(Date.now()-s>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const Gd=["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"&&Gd.includes(e)}function pa(e){if(typeof e=="string")return zd[e]}const Ri="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Ve={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 fa(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 $d=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function Ud(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 tt(e){const t=e,n=t&&typeof t=="object"?t:{},r=typeof n.message=="string"?n.message:String(e??""),s=typeof n.code=="string"?n.code:"";if(s==="LAN_TOKEN_REQUIRED")return{code:"LAN_TOKEN_REQUIRED",spec:Ve.LAN_TOKEN_REQUIRED,message:Je().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=s&&s in Ve?s:a&&a in Ve?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Ve.JOB_TRACKING_TIMEOUT,message:Ri};const c=qd(i)?pa(i):void 0,d=l?$d.includes(l):!1,u=pa(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=Ve[l]):u?(p=fa(r),m=u):(p=fa(r),m=Ve[p]??Ve.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||Ud(r):void 0;return{code:p,spec:m,message:r,...a?{rawCode:a}:s&&!l?{rawCode:s}:{},...i&&(c||u)?{errorClass:i}:{},...h?{moderationStage:h}:{}}}function Hd(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function at(e,t="Generation failed"){const n=e.error;let r=t,s,a,i,l;const c=Hd(e);if(c&&c.terminal===!0&&(typeof c.phase=="string"&&(l=c.phase),c.error&&typeof c.error=="object"&&(typeof c.error.code=="string"&&(s=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"&&(s=s??m.code),typeof m.rawCode=="string"&&(a=m.rawCode),typeof m.errorClass=="string"&&(i=m.errorClass)}typeof e.code=="string"&&(s=s??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=tt({code:s,rawCode:a,message:r,errorClass:i});u.code==="JOB_TRACKING_TIMEOUT"&&(s=u.code,r=u.message,d=504,l="timed_out",a=void 0,i=void 0);const p=new Error(r);return p.code=s,p.status=d,a&&(p.rawCode=a),i&&(p.errorClass=i),l&&(p.phase=l),p}const ha=5e3,ga=3e4;function Kd(e){if(!e)return ha;const t=Number.parseFloat(e);if(Number.isFinite(t)&&t>0)return Math.min(ga,Math.max(1e3,Math.round(t*1e3)));const n=Date.parse(e);return Number.isFinite(n)?Math.min(ga,Math.max(1e3,n-Date.now())):ha}function Vd(e,t){return e.status===429&&t.code==="TOO_MANY_JOBS"}function as(){return new DOMException("Aborted","AbortError")}function zr(...e){const t=e.filter(s=>!!s);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 s of t)s.removeEventListener("abort",r);n.abort()};return t.some(s=>s.aborted)?r():t.forEach(s=>s.addEventListener("abort",r,{once:!0})),n.signal}async function qr({url:e,payload:t,requestId:n,signal:r,parseError:s}){const a=pe();let i=null;const l=c=>new Promise((d,u)=>{if(r?.aborted){u(as());return}const p=()=>{i&&(clearTimeout(i),i=null),u(as())};i=setTimeout(()=>{i=null,r?.removeEventListener("abort",p),d()},c),r?.addEventListener("abort",p,{once:!0})});for(;;){if(r?.aborted)throw as();if(a!==pe())throw Je(a);if(ce())throw Je(a-1);const c=await we(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(Vd(c,d)){await l(Kd(c.headers.get("Retry-After")));continue}throw s(c,d)}}async function Ti(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return Ct(),new Promise((r,s)=>{let a=!1;const i=new AbortController,l=zr(t.signal,i.signal),c=p=>{a||(a=!0,u(),d(),p())},d=kt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>s(at(m,"Generation failed"))))}),u=Kt(()=>{c(()=>{i.abort(),Ce(n),s(new Error("Generation stream timed out"))})});if(t.signal){if(t.signal.aborted){c(()=>{i.abort(),Ce(n),s(new DOMException("Aborted","AbortError"))});return}t.signal.addEventListener("abort",()=>{c(()=>{i.abort(),Ce(n),s(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({url:"/api/generate",payload:e,requestId:n,signal:l,parseError:(p,m)=>{const h=at(m,`Request failed: ${p.status}`);return h.status=h.status??p.status,h}}).then(()=>{}).catch(p=>{c(()=>s(p instanceof Error?p:new Error(String(p))))})})}async function Bd(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="image"?t.onImage?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Multimode generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Multimode generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 zS(e){return z("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function Wd(e){const t=await e.arrayBuffer(),n=await we("/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 s={};try{s=await n.json()}catch{}const a=new Error(s.error||`Import failed (${n.status})`);throw a.code=s.code||"IMPORT_FAILED",a}return(await n.json()).item}function qS(e){return z("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function $S(){return z("/api/prompt-builder/config")}function US(e){return z("/api/prompt-builder/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function ro(e,t={},n={}){const r=e.requestId??`vreq_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="planning"?t.onPlanning?.():m==="submitted"?t.onSubmitted?.(h):m==="progress"?t.onProgress?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Video generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Video generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 Vt(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"),Ht(`/api/history?${t.toString()}`)}function Jd(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),Ht(`/api/history?${t.toString()}`)}function Yd(e){return Ht("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function Xd(){return(await z("/api/storage/status")).data}function Zd(){return z("/api/storage/open-generated-dir",{method:"POST"})}function Mi(e){return z(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function Qd(e){return z(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function eu(e,t){return z(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function tu(e){return z("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function nu(){return z("/api/sessions")}function ru(e){return z("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function Li(e){return z(`/api/sessions/${encodeURIComponent(e)}`)}function su(e,t){return z(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function ou(e){return z(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function au(e,t,n,r,s={}){const a={"Content-Type":"application/json","If-Match":String(t)};return s.saveId&&(a["X-Ima2-Graph-Save-Id"]=s.saveId),s.saveReason&&(a["X-Ima2-Graph-Save-Reason"]=s.saveReason),s.tabId&&(a["X-Ima2-Tab-Id"]=s.tabId),z(`/api/sessions/${encodeURIComponent(e)}/graph`,{method:"PUT",headers:a,body:JSON.stringify({nodes:n,edges:r})})}function iu(e){return z("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function HS(e){return Ht(`/api/annotations/${encodeURIComponent(e)}`)}async function KS(e,t){await Ht(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function VS(e){await Ht(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function BS(e){const t=new URLSearchParams({sourceFilename:e.sourceFilename});return z(`/api/canvas-versions?${t.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e.image})}function WS(e,t){const n=new URLSearchParams;t.sourceFilename&&n.set("sourceFilename",t.sourceFilename);const r=n.size>0?`?${n.toString()}`:"";return z(`/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 JS(e,t,n){return z(`/api/canvas-versions/${encodeURIComponent(e)}/annotation-bake`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshot:t,annotationOnly:n})})}function YS(e){return z(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function lu(e){const t=new URLSearchParams;return z(`/api/prompts?${t.toString()}`)}function cu(e){return z("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function du(e){return z(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function uu(e){return z(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function mu(e){return z("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function XS(e){return z("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ZS(e){return z("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function QS(){return z("/api/prompts/import/curated-sources")}function ew(e){return z("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function tw(e){return z("/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 z(`/api/prompts/import/discovery${n}`)}function rw(e){return z("/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 sw(e){return z("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ow(e){return z("/api/prompts/import/folder-files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input}})})}function aw(e){return z("/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 so(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 z(`/api/assets${n?`?${n}`:""}`)}function pu(e){return z(`/api/assets/${encodeURIComponent(e)}`)}function $r(e){return z("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function iw(e){return z("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Fi(e,t){return z(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function lw(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 we(`/api/assets/derived?${n.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e});if(!r.ok){const s=await r.json().catch(()=>({}));throw new Error(s.error||`derived upload failed (${r.status})`)}return r.json()}async function fu(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 we(`/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 cw(e){return z("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function hu(e){return z(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function oo(){return z("/api/assets/folders")}function gu(e){return z("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Oi(e,t){return z(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function yu(e){return z(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ao(){return z("/api/assets/tags")}function dw(){return z("/api/assets/all",{method:"DELETE"})}async function vu(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return Ct(),new Promise((s,a)=>{let i=!1;const l=new AbortController,c=zr(n.signal,l.signal),d=m=>{i||(i=!0,p(),u(),m())},u=kt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(at(h,"Node generation failed"))))}),p=Kt(()=>{d(()=>{l.abort(),Ce(r),a(new Error("Node generation stream timed out"))})});if(n.signal){if(n.signal.aborted){d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))});return}n.signal.addEventListener("abort",()=>{d(()=>{l.abort(),Ce(r),a(new DOMException("Aborted","AbortError"))})},{once:!0})}qr({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 io=["oauth","api","grok","grok-api","agy","gemini-api","atlascloud","minimax","nai","comfy"],bu=new Set(io);function jt(e){return typeof e=="string"&&bu.has(e)}const Nn={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-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"],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-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"]},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:[]}},xu=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality","nano-banana-2","nano-banana-pro","openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit","image-01","image-01-live","nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],Di={oauth:{},api:{},grok:{image:3,edit:3,video:7},"grok-api":{image:3,edit:3,video:7},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}},lo={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"}}},hr="gpt-5.6-luna",Xe=[{value:"gpt-5.6-luna",shortLabel:"5.6l",fullLabelKey:"settings.imageModel.gpt56Luna"},{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"}],Ur=new Set(Nn["gemini-api"].image),co=new Set(Nn.atlascloud.image),uo=new Set(Nn.minimax.image),mo=new Set(Nn.nai.image),Iu=Xe.filter(e=>!e.value.startsWith("grok-")&&!Ur.has(e.value)&&!co.has(e.value)&&!uo.has(e.value)&&!mo.has(e.value)),Su=Xe.filter(e=>e.value.startsWith("grok-")),wu=Xe.filter(e=>Ur.has(e.value)),_u=Xe.filter(e=>co.has(e.value)),Eu=Xe.filter(e=>uo.has(e.value)),Gi=Xe.filter(e=>mo.has(e.value)),uw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Nu(e){return Xe.some(t=>t.value===e)}function ku(e){return typeof e=="string"&&e.startsWith("grok-")}function Cu(e){return typeof e=="string"&&Ur.has(e)}function ju(e){return e==="grok"||e==="grok-api"?Su:e==="agy"||e==="gemini-api"?wu:e==="atlascloud"?_u:e==="minimax"?Eu:e==="nai"?Gi:e==="comfy"?[]:Iu}function zi(e,t){return e?Ur.has(e)?`${e} ${t==="gemini-api"?"gemini-api":t==="agy"?"agy":t||"agy"}`:co.has(e)?t==="atlascloud"?"gpt-image-2 atlas":e:uo.has(e)?t==="minimax"?`${e} minimax`:e:mo.has(e)?Xe.find(n=>n.value===e)?.shortLabel??e:Xe.find(n=>n.value===e)?.shortLabel??e:null}const po="grok-imagine-video",pt="grok-imagine-video-1.5",qi="grok-imagine-video-1.5-preview",Pu=[{value:po,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:pt,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Au(e){return e===po||e===pt||e===qi}function kn(e){return Au(e)?e===qi?pt:e:!1}function Ru(e,t="image-to-video"){return e>=2?"reference-to-video":e===1?t:"text-to-video"}function is(e,t,n){return t!=="1080p"?!0:e===pt&&(n==="text-to-video"||n==="image-to-video")}const zt="comfy-video:",$i="video:";function Tu(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${zt}${a}`:s??"":(t==="grok"||t==="grok-api")&&r?`${$i}${r}`:n}const Fs=new Set(xu),Mu={oauth:hr,api:hr,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:hr};function Hr(e,t){return typeof t=="string"&&Fs.has(t)&&Nn[e].image.includes(t)}function un(e){return typeof e=="string"&&e.trim().length>0?e:null}function Ui(e,t){if(kn(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Hr(n,e))return n;return"oauth"}function ot(e){const t=jt(e.provider)?e.provider:Ui(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=un(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Fs.has(e.imageModel)?e.imageModel:hr,videoModelSelected:!1,comfyWorkflow:un(e.comfyWorkflow)??(n&&!Fs.has(n)?n:null),comfyVideoWorkflow:un(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Hr(t,e.imageModel)?e.imageModel:Mu[t],videoModelSelected:t==="grok"||t==="grok-api"?kn(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Lu(e,t){return jt(e)&&Hr(e,t)?e:Ui(t,!1)}function Fu(e,t,n){return e.provider===t?e:ot(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 ya(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 Hi(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Os(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t={};for(const n of io){if(!Object.hasOwn(e,n))continue;const r=e[n];if(!r||typeof r!="object"||Array.isArray(r))continue;const s=r;if(s.kind!=="image"&&s.kind!=="video")continue;const a=n==="comfy"?un(s.image):Hr(n,s.image)?s.image:null,i=n==="comfy"?un(s.video):n==="grok"||n==="grok-api"?kn(s.video):!1;t[n]={kind:s.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Ou="none",Ds=[{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 Ki(e){return Ds.some(t=>t.value===e)}const Du={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Gu(e){return!Ki(e)||e==="none"?null:`R:${Du[e]}`}const _e=["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"],Vi=_e[0],Bi=_e[1],Wi=_e[2],Ji=_e[3],fo=_e[4],Yi=_e[5],Xi=_e[6],ho=_e[7],Zi=_e[8],Gs=_e[9],zs=_e[10],va=_e[11],go=_e[12],Qi=_e[13],yo=_e[17],el=_e[19],tl=_e[20],zu=!0,qu=!1,Bt=!0,nl=qu,Wt=!0,$u=24;function qs(e){return Math.min($u,Math.max(1,Math.trunc(e||1)))}const ba={ko:Id,en:xd,"zh-Hant":bd,"zh-Hans":vd};function xa(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function Uu(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function A(e,t){const n=f.getState().locale;return rl(n,e,t)}function rl(e,t,n){const r=xa(ba[e],t),s=typeof r=="string"?r:xa(ba.en,t),a=typeof s=="string"?s:t;return n?Uu(a,n):a}function H(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>rl(e,t,n)}}function Hu(e){return Math.round(e/16)*16}const xt=16,vo=3840,ls=655360,gr=8294400,Ku=3,Lt=3,Ia=Math.floor(Math.sqrt(gr)/xt)*xt,sl=xt,Vu=vo,Kn=Ku;function Sa(e){return Math.floor(e/16)*16}function _r(e){return Math.ceil(e/16)*16}function De(e){return Math.min(Vu,Math.max(sl,e))}function Ze(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function wt(e,t){e.includes(t)||e.push(t)}function wa(e,t){const n=Hu(e);return n!==e&&wt(t,"snap"),n}function _a(e,t){return e<sl&&wt(t,"min"),e>vo&&wt(t,"maxEdge"),De(e)}function Ea(e,t,n){return e>t*Kn?(wt(n,"ratio"),{w:e,h:De(_r(e/Kn))}):t>e*Kn?(wt(n,"ratio"),{w:De(_r(t/Kn)),h:t}):{w:e,h:t}}function Bu(e,t,n){if(e*t<ls){wt(n,"minPixels");const i=Math.sqrt(ls/(e*t));let l=De(_r(e*i)),c=De(_r(t*i));for(;l*c<ls;)l<=c?l=De(l+xt):c=De(c+xt);return{w:l,h:c}}if(e*t<=gr)return{w:e,h:t};wt(n,"maxPixels");const r=Math.sqrt(gr/(e*t));let s=De(Sa(e*r)),a=De(Sa(t*r));for(;s*a>gr;)s>=a?s=De(s-xt):a=De(a-xt);return{w:s,h:a}}function bo(e,t,n,r){const s=[],a=Ze(e,n),i=Ze(t,r);let l=_a(wa(a,s),s),c=_a(wa(i,s),s);return{w:l,h:c}=Ea(l,c,s),{w:l,h:c}=Bu(l,c,s),{w:l,h:c}=Ea(l,c,s),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:s}}function ol(e,t,n,r){const s=bo(e,t,n,r);return{w:s.w,h:s.h}}const Wu=[{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 Ju(e,t){return`${e}x${t}`}function Yu(e,t=1024){if(e.id==="free")return null;const n=t,r=e.w>=e.h,s=r?Math.round(n*e.w/e.h):n,a=r?n:Math.round(n*e.h/e.w);return ol(s,a,s,a)}function Kr(e){const t=ol(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function Ft(e){return e.slice(0,Lt).map(Kr)}function Xu(e,t){const n=Kr(t),r=e.findIndex(s=>s.id===n.id);return r>=0?Ft(e.map((s,a)=>a===r?n:s)):e.length>=Lt?Ft(e):Ft([...e,n])}function Zu(e,t,n){const r=Kr({...n,id:t});return Ft(e.map(s=>s.id===t?r:s))}const Qu=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],em=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],tm=[{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"}],nm=[{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 rm(){return[{value:"auto",label:A("size.autoLabel"),sub:A("size.autoSub")},{value:"custom",label:A("size.customLabel"),sub:A("size.customSub")}]}const al=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],il=["native","karras","exponential","polyexponential"],ll=["heavy","light","furryFocus","humanFocus","none"],cl=["standard","light","none"],sm={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},Er={min:1,max:50},Nr={min:1,max:10},kr={min:0,max:1},dl=2**32-1;function om(e,t){return{...sm,...e??{},...t}}function $s(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Vn(e,t){return typeof e=="string"&&t.includes(e)?e:void 0}function cs(e,t,n){if(!(typeof e!="number"||!Number.isFinite(e)))return e<t||e>n?void 0:e}function ul(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Vn(t.sampler,al);r!==void 0&&(n.sampler=r);const s=Vn(t.noiseSchedule,il);s!==void 0&&(n.noiseSchedule=s);const a=Vn(t.ucPresetId,ll);a!==void 0&&(n.ucPresetId=a);const i=Vn(t.qualityPresetId,cl);i!==void 0&&(n.qualityPresetId=i);const l=cs(t.steps,Er.min,Er.max);l!==void 0&&(n.steps=l);const c=cs(t.scale,Nr.min,Nr.max);c!==void 0&&(n.scale=c);const d=cs(t.cfgRescale,kr.min,kr.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<=dl&&(n.seed=t.seed),n}function qe(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Us="vid:",Hs="img:",am=/^[\p{L}\p{N}_-]{1,32}$/u;function xo(e){return am.test(e)}function im(e){return e.references.some(t=>t.tag!==void 0&&!xo(t.tag))}function ml(e){return e==="video"?"video":"image"}function Vr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function lm(e){return typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.length<=128}function Br(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)&&lm(r)))}function Na(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 pl(e,t,n){const r=Vr(t),s=Br(n),a={};for(const i of e.parameters){const l=s[i.name];l!==void 0&&Na(i,l)?a[i.name]=l:i.default!==void 0&&Na(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function cm(e){return e?pl(e,null,{}):{ratio:null,parameters:{}}}function dm(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function fl(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,s=typeof t.displayName=="string"&&t.displayName?t.displayName.slice(0,180):null;return{filename:t.filename,...n?{tag:n}:{},...r?{dataUrl:r}:{},...s?{displayName:s}:{}}}function Io(e){if(!e||typeof e!="object")return qe();const t=e,n=Array.isArray(t.references)?t.references.map(fl).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,s)=>n.findIndex(a=>a.filename===r.filename)===s).slice(0,3),referenceVideoFilename:typeof t.referenceVideoFilename=="string"&&t.referenceVideoFilename?t.referenceVideoFilename:null}}function So(e,t){const n=Io(t),r=e.includes("start_image")?n.startFrameFilename:null;return{startFrameFilename:r,endFrameFilename:e.includes("end_image")&&r?n.endFrameFilename:null,references:e.includes("image_references")?n.references:[],referenceVideoFilename:e.includes("video_references")?n.referenceVideoFilename:null}}function hl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function um(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:ml(e.mcpMediaKind),ratio:Vr(e.mcpRatio),parameters:Br(e.mcpParameters)}}function Bn(e,t){return`${e==="video"?Us:Hs}${t}`}function mm(e){if(e.startsWith(Us)){const t=e.slice(Us.length);return t?{kind:"video",model:t}:null}if(e.startsWith(Hs)){const t=e.slice(Hs.length);return t?{kind:"image",model:t}:null}return null}function gl(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 pm(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const s=ml(e.mcpMediaKind),a=Vr(e.mcpRatio),i=Br(e.mcpParameters),l=e.mcpReferenceSelection!==void 0,c=e.mcpInputRoles,d=y=>c===void 0||c.includes(y),u=Io(e.mcpReferenceSelection),p=l?d("start_image")?u.startFrameFilename:null:s==="video"?e.currentImageFilename??null:null,m=l&&d("image_references")?u.references:[],h=d("image_references")?e.elementReferences??[]:[],b=[...m,...h].map(fl).filter(y=>!!y).filter((y,g,_)=>_.findIndex(S=>S.filename===y.filename)===g).slice(0,3);if(b.some(y=>y.dataUrl||y.tag!==void 0&&!xo(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:s,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 Cn(e,t){const n=t.filter(s=>s.placement!=="after"),r=t.filter(s=>s.placement==="after");return[...n.map(s=>s.text.trim()).filter(Boolean),e.trim(),...r.map(s=>s.text.trim()).filter(Boolean)].filter(Boolean).join(`
3
3
 
4
4
  `)}function fm(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 jn(e){if(!Array.isArray(e))return null;const t=e.map(fm);return t.every(n=>n!==null)?t:null}function wo(e){return e.map(t=>({id:t.id,name:t.name,text:t.text,placement:t.placement==="after"?"after":"before"}))}function hm(e){const t=jn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function gm(){try{const e=localStorage.getItem(Vi);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function ym(){try{const e=localStorage.getItem(Bi);if(e==="agent")return Wt?e:"classic";if(e==="card-news")return nl?e:"classic";if(e==="node")return Bt?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function vm(){try{const e=localStorage.getItem(Wi);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function ka(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function Ca(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(Ji);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 yl(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(Ji,JSON.stringify({mode:e,matteColor:t}))}catch{}}function vl(e){try{localStorage.setItem(fo,e)}catch{}}function bm(){try{const e=localStorage.getItem(Yi);if(Ki(e))return e}catch{}return Ou}function xm(e){try{localStorage.setItem(Yi,e)}catch{}}function Im(){try{const e=localStorage.getItem(el);return e?ul(JSON.parse(e)):{}}catch{return{}}}function bl(e){try{localStorage.setItem(el,JSON.stringify(e))}catch{}}function Sm(){try{const e=localStorage.getItem(Xi);if(e==="false")return!1;if(e==="true")return!0}catch{}return zu}function wm(e){try{localStorage.setItem(Xi,String(e))}catch{}}const ja={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function Wr(){try{const e=localStorage.getItem(yo);if(!e)return ja;const t=JSON.parse(e);return{model:kn(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 ja}}function ln(e){try{const t=Wr();localStorage.setItem(yo,JSON.stringify({...t,...e}))}catch{}}function xl(){try{const e=localStorage.getItem(Gs);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function nt(e){try{e?localStorage.setItem(Gs,e):localStorage.removeItem(Gs)}catch{}}function _m(){try{const e=localStorage.getItem(zs);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function _o(e){try{e?localStorage.setItem(zs,e):localStorage.removeItem(zs)}catch{}}function Em(e,t){return`${e}x${t}`}function hn(e){return qs(e)}const Il=new Set(["1024x1024","1536x1024","1024x1536","1360x1024","1024x1360","1824x1024","1024x1824","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840","auto","custom"]);function Nm(e){if(typeof e!="string")return{};if(Il.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 Sl(e){return e==="low"||e==="medium"||e==="high"}function wl(e){return e==="png"||e==="jpeg"||e==="webp"}function _l(e){return e==="low"||e==="auto"}function km(e){return jt(e)}function Cm(e){return e==="auto"||e==="direct"}function jm(e){return typeof e=="string"&&Il.has(e)}function Pn(){try{const e=localStorage.getItem(ho);if(!e)return{};const t=JSON.parse(e),n={};km(t.provider)&&(n.provider=t.provider);const r=t.mcpProvider,s=t.mcpModel;(typeof r=="string"||r===null)&&(n.mcpProvider=r),(typeof s=="string"||s===null)&&(n.mcpModel=s),(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=Vr(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=Br(t.mcpParameters)),Sl(t.quality)&&(n.quality=t.quality),jm(t.sizePreset)&&(n.sizePreset=t.sizePreset),typeof t.customW=="number"&&Number.isFinite(t.customW)&&(n.customW=Ze(t.customW,1920)),typeof t.customH=="number"&&Number.isFinite(t.customH)&&(n.customH=Ze(t.customH,1088)),wl(t.format)&&(n.format=t.format),_l(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=hn(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=hn(t.multimodeMaxImages)),Cm(t.promptMode)&&(n.promptMode=t.promptMode),typeof t.prompt=="string"&&(n.prompt=t.prompt),typeof t.negativePrompt=="string"&&(n.negativePrompt=t.negativePrompt);const a=jn(t.insertedPrompts);return a&&(n.insertedPrompts=a),n}catch{return{}}}function Pm(){return um(Pn())}function An(e,t,n="image"){ne({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function ne(e){try{const t=Pn();localStorage.setItem(ho,JSON.stringify({...t,...e}))}catch{}}function El(){const e=localStorage.getItem(tl);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Nl(){try{const e=El();return e?.version===1?Os(e.lanes):{}}catch{return{}}}function Am(e){try{let t=null;try{t=El()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Os(t.lanes):{},...Os(e)};localStorage.setItem(tl,JSON.stringify({version:1,lanes:r}))}catch{}}function kl(){const e=Pn(),t=Wr();let n=null;try{n=localStorage.getItem(fo)}catch{}return ot({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Rm(e){vl(e.imageModel),ln({model:e.videoModelSelected}),ne({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function Tm(e,t,n){const r=new Set(e.map(l=>l.id));if(!r.has(n))return[];const s=new Map;for(const l of r)s.set(l,new Set);for(const l of t)!r.has(l.source)||!r.has(l.target)||(s.get(l.source)?.add(l.target),s.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 s.get(c)??[])a.has(d)||i.push(d)}}return e.filter(l=>a.has(l.id)).map(l=>l.id)}function Cl(e){return e.filter(t=>t.selected).map(t=>t.id)}function gn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function Mm(e,t,n,r){const s=new Set(Tm(e,t,n));if(!s.size)return e;if(!r)return gn(e,s);const a=e.find(c=>c.id===n),i=e.some(c=>s.has(c.id)&&c.selected),l=new Set(Cl(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of s)l.add(c);return gn(e,l)}const Lm={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Pa=16777216;function Aa(e,t,n){let r=e,s=t;if(r<=0||s<=0)return{w:1,h:1};const a=Math.max(r,s);if(a>n){const i=n/a;r=Math.round(r*i),s=Math.round(s*i)}if(r*s>Pa){const i=Math.sqrt(Pa/(r*s));r=Math.max(1,Math.floor(r*i)),s=Math.max(1,Math.floor(s*i))}return{w:r,h:s}}function Wn(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 ds(e,t,n){return new Promise((r,s)=>{e.toBlob(a=>a?r(a):s(new Error("canvas.toBlob returned null")),t,n)})}function Jn(e){const t=e.indexOf(",");return t<0?e.length:e.length-t-1}async function Eo(e,t={}){const n={...Lm,...t},r=await Wn(e);if(Jn(r)<=n.maxB64Bytes)return r;let s;try{s=await createImageBitmap(e)}catch(a){throw new Error("이미지 디코드 실패. JPEG/PNG로 변환 후 다시 시도해 주세요.",{cause:a})}try{const{w:a,h:i}=Aa(s.width,s.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(s,0,0,a,i),n.preserveTransparency){const u=await ds(l,"image/png"),p=await Wn(u);if(Jn(p)>n.maxB64Bytes)throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.");return p}for(const u of n.qualityLadder){const p=await ds(l,"image/jpeg",u),m=await Wn(p);if(Jn(m)<=n.maxB64Bytes)return m}const d=Aa(a,i,2048);l.width=d.w,l.height=d.h,c.drawImage(s,0,0,d.w,d.h);for(const u of[.7,.5,.35]){const p=await ds(l,"image/jpeg",u),m=await Wn(p);if(Jn(m)<=n.maxB64Bytes)return m}throw new Error("이미지 압축 실패. JPEG/PNG로 미리 변환 후 다시 시도해 주세요.")}finally{s.close?.()}}function Cr(e){const t=(e.type||"").toLowerCase();if(t.includes("heic")||t.includes("heif"))return!0;const n=(e.name||"").toLowerCase();return n.endsWith(".heic")||n.endsWith(".heif")}function jl(e){return(e.type||"").toLowerCase()==="image/png"}const Pl=18e4;function Fm(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)yn(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function yn(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 Al(e){const t=await Promise.all(e.map(n=>Ai({kind:n.kind,sessionId:n.sessionId,includeTerminal:!0})));return{jobs:t.flatMap(n=>n.jobs),terminalJobs:t.flatMap(n=>n.terminalJobs??[])}}function jr(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:Ks(e.kind)??Ks(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:jn(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 Om(e){const t=typeof e.errorCode=="string"&&e.errorCode?e.errorCode:"UNKNOWN",n=new Error(t==="JOB_TRACKING_TIMEOUT"?Ri: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 Jt(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Ra(e){return e.filename||e.image}function Ta(e,t){const n=new Map(e.map(r=>[Ra(r),r]));for(const r of t)n.set(Ra(r),r);return[...n.values()].sort((r,s)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(s.sequenceIndex??Number.MAX_SAFE_INTEGER))}function Rl({includeExpired:e=!1}={}){try{const t=localStorage.getItem(Zi);if(!t)return[];const n=JSON.parse(t);if(!Array.isArray(n))return[];const r=Date.now();return n.filter(s=>s&&typeof s.id=="string"&&typeof s.prompt=="string"&&typeof s.startedAt=="number"&&(e||r-s.startedAt<Pl)).map(s=>({id:s.id,prompt:s.prompt,startedAt:s.startedAt,composerPrompt:typeof s.composerPrompt=="string"?s.composerPrompt:void 0,composerInsertedPrompts:jn(s.composerInsertedPrompts)??void 0,phase:typeof s.phase=="string"?s.phase:void 0,sessionId:typeof s.sessionId=="string"?s.sessionId:null,parentNodeId:typeof s.parentNodeId=="string"?s.parentNodeId:null,clientNodeId:typeof s.clientNodeId=="string"?s.clientNodeId:null,kind:s.kind==="classic"||s.kind==="node"||s.kind==="multimode"||s.kind==="video"?s.kind:Ks(s.kind)}))}catch{return[]}}function Ks(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 ze=500,No=5;function Dm(e){return e==="classic"||e==="edit"||e==="generate"||e==="card-news-card"||e==="card-news-set"?e:null}function Rn(e){const t=jn(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?wo(t):null,size:e.size??void 0,quality:e.quality??void 0,format:e.format,model:e.model??void 0,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:Dm(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 Ge(e){return e.filename??e.image}function Tl(e,t){const n=Ge(t);return e.filter(r=>Ge(r)!==n)}function Ml(e,t){const n=Ge(t);return e.find(r=>Ge(r)===n)}function Ll(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 Fl(e,t){const n=new Map(e.map(r=>[Ge(r),r]));for(const r of t)n.set(Ge(r),r);return[...e.map(r=>n.get(Ge(r))??r),...t.filter(r=>!e.some(s=>Ge(s)===Ge(r)))]}function Jr(e,t){return e.slice(0,Math.max(ze,t))}function ko(e){return e.replace(/^data:[^;]+;base64,/,"")}async function Tn(e,t="reference.png"){const n=await we(e);if(!n.ok)throw new Error(`reference fetch failed: ${n.status}`);const r=await n.blob(),s=new File([r],t,{type:r.type||"image/png"});return Eo(s,{preserveTransparency:!1})}function Gm(e,t){let n=!1;const r={};for(const[s,a]of Object.entries(e)){const i=a.images.filter(l=>l.filename!==t);if(i.length===a.images.length){r[s]=a;continue}n=!0,i.length!==0&&(r[s]={...a,images:i,returned:i.length,status:a.status==="complete"&&i.length<a.requested?"partial":a.status})}return n?r:e}function Re(e){try{localStorage.setItem(Zi,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function zm(e){return om(e.naiServerDefaults,e.naiOptionOverrides)}function Yr(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=bo(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 qm(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):No}async function $m(e){try{const t=await Cd();e({referenceLimit:qm(t.limits?.maxRefCount),naiServerDefaults:ul(t.defaults?.nai??null)})}catch{e({referenceLimit:No})}}function Co(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 Um(e){const t=await we(e);if(!t.ok)throw new Error(`reference fetch failed: ${t.status}`);const n=await t.blob();return Co(new File([n],"reference.png",{type:n.type||"image/png"}))}function Hm(e,t=256){return new Promise(n=>{const r=new Image;r.onload=()=>{const s=Math.min(1,t/Math.max(r.width,r.height)),a=document.createElement("canvas");a.width=r.width*s,a.height=r.height*s;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 Km(e,t){return e.find(n=>n.target===t)??null}function Vm(e,t,n){return e.some(r=>r.target===n&&r.source!==t)}function Bm(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 s=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;s.has(l)||(s.add(l),a.push(l))}return!1}function mw(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 s=e.filter(i=>(n.get(i.id)??0)===0).map(i=>i.id);let a=0;for(let i=0;i<s.length;i++){a+=1;for(const l of r.get(s[i])??[]){const c=(n.get(l)??0)-1;n.set(l,c),c===0&&s.push(l)}}return a<e.length}function Qe(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const s=Km(t,r.id),i=(s?n.get(s.source):null)?.data.serverNodeId??null;return r.data.parentServerNodeId===i?r:{...r,data:{...r.data,parentServerNodeId:i}}})}const Ol="ima2.nodeRefs.v1";function jo(){try{const e=localStorage.getItem(Ol);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Dl(e){try{localStorage.setItem(Ol,JSON.stringify(e))}catch{}}function Wm(e,t){if(!e)return[];const n=jo()[e]?.[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function Xr(e,t,n){if(!e)return;const r=jo(),s={...r[e]??{}};n.length===0?delete s[t]:s[t]=n,r[e]=s,Dl(r)}function Po(e,t){Xr(e,t,[])}function Jm(e,t){if(!e)return;const n=jo(),r=n[e];if(!r)return;const s=new Set(t);for(const a of Object.keys(r))s.has(a)||delete r[a];n[e]=r,Dl(n)}const Ym=/\.(mp4|webm|mov)$/i;function Ye(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return Ym.test(t)||e.startsWith("data:video/")}function xe(e){return e?e.mediaType==="video"?!0:Ye(e.filename)||Ye(e.url)||Ye(e.image):!1}const Xm=15e3;function Ao(e,t,n={}){return new Promise((r,s)=>{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(()=>s(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(()=>s(new Error("frame extraction timed out")))},Xm),a.onloadedmetadata=()=>{const p=a.duration;if(!Number.isFinite(p)||p<=0){d(()=>s(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(()=>s(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(()=>s(p))}},a.onerror=()=>{d(()=>s(new Error("Failed to load video for frame extraction")))},a.src=e})}function Yt(e,t){return Ao(e,n=>n-.1,t)}function Gl(e,t){return Ao(e,n=>Math.min(n*.3,.4),t)}function zl(e,t){return Ao(e,n=>n/2,t)}function ql(e){const t=e.nodes.map(r=>{const s=r.data??{},a=typeof s.imageUrl=="string"&&s.imageUrl.length>0?s.imageUrl:null,i=typeof s.serverNodeId=="string"&&s.serverNodeId.length>0?`/generated/${s.serverNodeId}.png`:null,l=a??i,c={...s,clientId:r.id,serverNodeId:s.serverNodeId??null,parentServerNodeId:s.parentServerNodeId??null,prompt:typeof s.prompt=="string"?s.prompt:"",imageUrl:l,status:s.status??(l?"ready":"empty"),pendingRequestId:s.pendingRequestId??null,recoveryRequestId:s.recoveryRequestId??null,pendingPhase:s.pendingPhase??null,pendingStartedAt:typeof s.pendingStartedAt=="number"?s.pendingStartedAt:null,partialImageUrl:null,error:s.error,elapsed:s.elapsed,reasoningEffort:s.reasoningEffort,webSearchCalls:s.webSearchCalls,model:s.model??null,size:s.size??null,referenceImages:Wm(e.id,r.id),video:s.video??null};return{id:r.id,type:s.nodeType==="element-reference"?"elementReferenceNode":"imageNode",position:{x:r.x,y:r.y},data:c}}),n=e.edges.map(r=>{const s=r.data??{};return{id:r.id,source:r.source,target:r.target,sourceHandle:typeof s.sourceHandle=="string"?s.sourceHandle:null,targetHandle:typeof s.targetHandle=="string"?s.targetHandle:null}});return{graphNodes:Qe(t,n),graphEdges:n,graphVersion:e.graphVersion}}const Zm=800;let We=null,yr=!1,vr=!1,bt=null,$l=0;function Ul(){try{const e=sessionStorage.getItem(va);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(va,t),t}catch{return"tab_unavailable"}}function Hl(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 Kl(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 Vl(e,t){const n=e().activeSessionId;if(!n||e().graphNodes.filter(l=>!l.data.imageUrl&&!l.data.serverNodeId).length===0)return;let s=[];try{s=(await Vt({sessionId:n,limit:ze})).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?s.find(m=>(m.sessionId??null)===n&&(m.requestId??null)===d):null)??s.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}),Wl(e,t,"recovery"))}async function Qm(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await Li(n),{graphNodes:s,graphEdges:a,graphVersion:i}=ql(r);t({graphNodes:s,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(A("toast.sessionReloadedElsewhere"),!0),await Vl(e,t).catch(()=>{})}async function ep(e,t,n){const r=e().activeSessionId,s=e().activeSessionGraphVersion;if(!r||s==null)return"skipped";const{graphNodes:a,graphEdges:i,sessionLoading:l}=e();if(l||a.length===0&&s>0)return"skipped";const c=a.map(p=>({id:p.id,x:p.position.x,y:p.position.y,data:Hl(p.data)})),d=Kl(i),u=`gs_${Date.now().toString(36)}_${++$l}`;try{const p=await au(r,s,c,d,{saveId:u,saveReason:n,tabId:Ul()});return e().activeSessionId!==r?"skipped":(Jm(r,e().graphNodes.map(m=>m.id)),t({activeSessionGraphVersion:p.graphVersion}),"saved")}catch(p){return p.status===409?(await Qm(e,t),"conflict"):(console.warn("[sessions] save failed:",p),"failed")}}async function Bl(e,t,n){return yr?(vr=!0,bt||"skipped"):(yr=!0,bt=(async()=>{let r=n,s="skipped";do{if(vr=!1,s=await ep(e,t,r),s==="conflict"||s==="failed")break;r="queued"}while(vr);return s})().finally(()=>{yr=!1,bt=null}),bt)}function Wl(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(We&&clearTimeout(We),We=setTimeout(()=>{We=null,Bl(e,t,n)},Zm)))}async function tp(e,t,n="manual"){let r=!1;if(We&&(clearTimeout(We),We=null,r=!0),yr){if(vr=!0,(bt?await bt:"skipped")==="failed")throw new Error(A("modal.graphSaveFailed"));return}if(r&&await Bl(e,t,n)==="failed")throw new Error(A("modal.graphSaveFailed"))}function np(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;We&&(clearTimeout(We),We=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:Hl(i.data)})),r=Kl(t.graphEdges),s=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{we(s,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++$l}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":Ul()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function ft(e,t,n,r={}){const s=xe(e)?void 0:await Hm(e.image).catch(()=>e.image),a=e.filename?`/generated/${e.filename}`:e.image,i={...e,thumb:s,url:a,createdAt:e.createdAt||Date.now()},l=n(),c=Ml(l.history,i),d=Ll(i,c),u=Tl(l.history,d),p=Jr([d,...u],l.loadedHistoryRetainLimit+1),h=!(r.autoSelectStartedAt!=null&&l.lastHistorySelectedAt>r.autoSelectStartedAt)&&(!l.currentImage||r.autoSelectStartedAt==null||l.lastHistorySelectedAt<=r.autoSelectStartedAt);h&&nt(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 rp(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const sp=30;function us(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function op(e,t,n=sp){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function ap(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 ip(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 lp=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function Ma(e,t){const n=new Map(t.map(s=>[s.id,s]));return{nodes:e.nodes.map(s=>{const a=n.get(s.id);if(!a||!(a.data.status==="pending"||a.data.status==="reconciling"))return s;const l={...s.data};for(const c of lp)l[c]=a.data[c];return{...s,data:l}}),edges:e.edges}}function cp(e){return e.data.status==="ready"&&!!e.data.imageUrl}function dp(e,t,n){const r=new Set(n),s=new Set(e.map(p=>p.id)),a=new Map,i=new Map;for(const p of r)s.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 up(e,t){const n=new Set(t),r=new Set,s=new Map;for(const i of e){const l=s.get(i.source)??[];l.push(i.target),s.set(i.source,l)}const a=[...n];for(let i=0;i<a.length;i++)for(const l of s.get(a[i])??[])n.has(l)||r.has(l)||(r.add(l),a.push(l));return[...r]}function mp(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,s=[t];for(let a=0;a<s.length;a++)for(const i of n.get(s[a])??[])r.has(i)||(r.add(i),s.push(i));return[...r]}function pp(e,t,n){const r=new Set(n);return e.filter(s=>s.source===t&&!r.has(s.target)).map(s=>s.target)}function fp(e,t,n){const r=new Set(n),s=new Map(e.map(i=>[i.id,i])),a=[];for(const i of t){if(!r.has(i.target)||r.has(i.source))continue;s.get(i.source)?.data.serverNodeId||a.push(i.target)}return a}function hp(e,t,n){const r=new Set(n),s=new Set(e.map(d=>d.id)),a=new Map,i=new Map;for(const d of r)s.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 $e(e,t){const{code:n,spec:r,message:s}=tt(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return ki(typeof a=="number"?a:void 0),{code:n,message:s}}if(r.surface==="card")t.showErrorCard(n,{fallbackMessage:s,cardKey:r.cardKey,cta:r.cta});else{const a=r.toastKey?A(r.toastKey):s||A("toast.generateFailed");if(t.showToast(a,!0),n==="JOB_TRACKING_TIMEOUT")return{code:n,message:a}}return{code:n,message:s}}const gp=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],yp=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function vp(e){if(gp.includes(e))return"auth";const t=Ve[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||yp.includes(e)?"retry":"fix-input"}function Jl(e){const{code:t,message:n}=tt(e),r=vp(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const bp=Di.grok.video,xp=3;function Ip(e,t){return Di[e]?.[t]}function Yl(e){if(e.mcpProvider)return xp;if(e.videoModelSelected)return Math.min(e.serverLimit,bp);if(jt(e.provider)&&!lo[e.provider].generate.references)return 0;const t=Ip(e.provider,"image");return t===void 0?e.serverLimit:Math.min(e.serverLimit,t)}function Ro(e,t={}){const n=t.provider??e.provider,r=t.imageModel??e.imageModel;if(n!=="nai")return{};const s={...e.naiOptionOverrides};$s(r)||(delete s.straightAlpha,delete s.qualityPresetId),s.seed===null&&delete s.seed;const a=e.negativePrompt.trim();return{...s,...a?{negativePrompt:a}:{}}}const Pr=new Map;function Xt(e,t){Pr.set(e,t)}function Zt(e){Pr.delete(e)}function Xl(e){Pr.get(e)?.abort(),Pr.delete(e)}const Sp="element-source:",wp=500;function _p(e){return`${Sp}${e}`}function pw(e,t){const n=_p(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function Zl(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function Ep(e=so){const t=[],n=new Set,r=new Set;let s=null;try{do{const a=await e({kind:"element",folderId:null,tag:null,q:"",cursor:s,limit:wp});for(const i of a.assets)n.has(i.id)||(n.add(i.id),t.push(i));if(s=a.nextCursor,s&&r.has(s))throw new Error("element pagination returned a repeated cursor");s&&r.add(s)}while(s);return t}catch(a){throw a instanceof Error?a:new Error(String(a))}}function Ql(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function fw(e){const t=e.filePath??(e.kind==="element"?Zl(e)??"":""),n=Ql(t),r=e.metadata?.derivedKind,s=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}`,...s==="transparent"?{backgroundPreset:"transparent"}:{},kind:typeof r=="string"&&(r.startsWith("keyed-")||r==="vector-svg")?"edit":"imported"}}const La=32,Fa="Image_",Np=/@([\p{L}\p{N}_-]+)/gu,kp=new Set([" "," ",`
5
5
  `,"(","["]);function ec(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${Fa}${r}`);)r+=1;return{tag:`${Fa}${r}`,nextAttachmentOrdinal:r+1}}function Cp(e,t){const n=new Set(t),r=e.slice(0,La)||"Element";if(!n.has(r))return r;let s=2;for(;;){const a=`_${s}`,i=`${r.slice(0,La-a.length)}${a}`;if(!n.has(i))return i;s+=1}}function Mn(e){return e.trayItems.filter(t=>t.kind==="attachment")}function tc(e){return e.trayItems.filter(t=>t.kind==="element")}function jp(e){return Mn(e).map(t=>t.source.dataUrl)}function Pp(e){return tc(e).map(t=>t.source.elementId)}function Ap(e){const t={trayItems:e};return{referenceImages:jp(t),selectedElementIds:Pp(t)}}function To(e,t){return e.length<t}function Zr(e,t,n=Date.now()){const r={...e};for(const s of t)Object.defineProperty(r,s.tag,{value:n,enumerable:!0,configurable:!0,writable:!0});return r}function Rp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Mo(e,t){if(!Rp(e,t))return e;const n={...e};return delete n[t],n}function Tp(e){const t=[];for(const n of e.matchAll(Np)){const r=n.index,s=r>0?e[r-1]:void 0;s!==void 0&&!kp.has(s)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function Mp(e){return e.reduce((t,n)=>t+(n.kind==="attachment"?1:n.source.referenceFilenames.length),0)}function Lo(e,t){let n;return e(r=>{const s=t(r,r.activeReferenceLimit());if(n=s.result,!s.patch)return{};const a=s.patch.trayItems??r.trayItems,i=r.elementCatalog,l=s.patch.elementCatalog??i??null;return{...s.patch,trayItems:a,elementCatalog:l,missingElementIds:sc(a,l),...Ap(a)}}),n}function Lp(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function nc(e,t){const n=e??[],r=n.findIndex(s=>s.id===t.id);return r<0?[...n,t]:n.map((s,a)=>a===r?t:s)}function Fp(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function rc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function br(e,t,n,r){return r&&(r.id!==e||r.kind!=="element")?null:Lo(t,(s,a)=>{if(!To(s.trayItems,a))return{result:null};if(s.trayItems.some(p=>p.kind==="element"&&p.source.elementId===e))return{result:null};const i=s,l=Fp(i,e,r),c=l?gl(l.name):null;if(!l||!c)return{result:null};const d=Cp(c,s.trayItems.map(p=>p.tag)),u={kind:"element",tokenId:crypto.randomUUID(),tag:d,insertedAt:Date.now(),source:{elementId:e,nameAtInsertion:l.name,referenceFilenames:rc(l)}};return{result:u,patch:{trayItems:[...s.trayItems,u],retiredTags:Mo(s.retiredTags,d),elementCatalog:nc(i.elementCatalog,l)}}})}function sc(e,t){if(t==null)return[];const n=new Set(t.map(s=>s.id)),r=new Set;return e.reduce((s,a)=>{if(a.kind!=="element")return s;const i=a.source.elementId;return!n.has(i)&&!r.has(i)&&s.push(i),r.add(i),s},[])}function Vs(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function Op(e,t,n){Lo(t,r=>{const s=Vs(r.trayItems,e);return s?{result:void 0,patch:{trayItems:r.trayItems.filter(a=>a.tokenId!==s.tokenId),retiredTags:Zr(r.retiredTags,[s])}}:{result:void 0}})}function oc(e,t,n){const r=Lp(e);t(s=>({elementCatalog:r,missingElementIds:sc(s.trayItems,r)}))}function ac(e,t,n){const r=new Map(e.map(l=>[l.id,l])),s=new Set,a=new Map,i=[...n];for(;i.length>0;){const l=i.shift();if(!s.has(l)){s.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 yt=new Set;async function Dp(e,t,n){const r=[],s=[],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 pu(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=nc(n().elementCatalog,c),u=c.updatedAt??c.createdAt;a.push(c.id),i[c.id]=u,typeof c.notes=="string"&&c.notes.trim()&&s.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 rc(c))try{const m=await Um(Ql(p));r.includes(m)||r.push(m)}catch{}}return{ok:!0,referenceDataUrls:r,notes:s,elementIds:a,revisions:i}}function Gp(e,t,n){const r=[];for(const s of[...e,...t])if(r.includes(s)||r.push(s),r.length>=n)break;return r}async function zp(e,t,n,r,s){if(yt.has(e))return null;yt.add(e);const a=r().graphNodes,i=Qe(a,r().graphEdges);i.some((R,$)=>R.data.parentServerNodeId!==a[$]?.data.parentServerNodeId)&&n({graphNodes:i});const l=i.find(R=>R.id===e);if(!l)return yt.delete(e),null;const c=ac(r().graphNodes,r().graphEdges,[e]),d=await Dp(c,n,r);if(d.ok===!1)return r().showToast(A("node.elementMissing",{name:d.name}),!0),yt.delete(e),null;const{prompt:u,parentServerNodeId:p}=l.data;if(!u.trim())return r().showToast(A("toast.promptRequired"),!0),yt.delete(e),null;const m=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:m.provider,b=Yl({provider:h,serverLimit:m.referenceLimit,videoModelSelected:!!m.videoModelSelected,mcpProvider:m.mcpProvider??null}),I=Gp(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;if(r().graphEdges.find(R=>R.target===e)&&!g)return r().showToast(A("node.parentImageRequired"),!0),yt.delete(e),null;const S=m.activeSessionId,w=Date.now(),j=Math.random().toString(36).slice(2,6),P=`fn_${e}_${w}_${j}`,M=new AbortController;Xt(P,M);const q=[...m.inFlight,{id:P,prompt:u,startedAt:w,kind:"node",sessionId:S,clientNodeId:e}];s(q),n({graphNodes:r().graphNodes.map(R=>R.id===e?{...R,data:{...R.data,status:"pending",pendingRequestId:P,recoveryRequestId:P,pendingPhase:"queued",pendingStartedAt:w,partialImageUrl:null,error:void 0,errorInfo:null,size:y}}:R),activeGenerations:m.activeGenerations+1,inFlight:q}),r().startInFlightPolling();let N=!0;try{const R=await vu({parentNodeId:g,prompt:u,quality:m.quality,size:y,format:m.format,moderation:m.moderation,provider:h,model:x,reasoningEffort:m.reasoningEffort,storyboard:m.storyboardActive||void 0,requestId:P,sessionId:S,clientNodeId:e,contextMode:"parent-plus-refs",searchMode:m.webSearchEnabled?"on":"off",webSearchEnabled:m.webSearchEnabled,...Ro(m,{provider:h,imageModel:x}),...I.length?{references:I.map(ko)}:{},...d.elementIds.length?{elementIds:d.elementIds,elementRevisions:d.revisions,elementNotes:d.notes}:{}},{onPartial:$=>{r().activeSessionId===S&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,status:"pending",partialImageUrl:$.image,pendingPhase:"partial"}}:k)})},onPhase:$=>{r().activeSessionId===S&&$.phase&&n({graphNodes:r().graphNodes.map(k=>k.id===e?{...k,data:{...k.data,pendingPhase:$.phase??k.data.pendingPhase}}:k)})}},{signal:M.signal});return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map($=>{if($.id!==e)return $;const k={...$.data};return delete k.partialImageUrl,{...$,data:{...k,serverNodeId:R.nodeId,imageUrl:R.url,status:"ready",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:R.elapsed,reasoningEffort:R.reasoningEffort,webSearchCalls:R.webSearchCalls,model:R.model??null,size:R.size??null,errorInfo:null}}})}),N=!0,t.suppressToast||r().showToast(A("toast.nodeCreated",{id:R.nodeId.slice(0,8),elapsed:R.elapsed}))),R.nodeId}catch(R){if(Jt(R))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)}),N=!0),null;const $=R instanceof Error?R.message:A("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:$,errorInfo:Jl(R)}}:k)}),N=!0,$e(R,r())),null}finally{yt.delete(e);const R=r().inFlight.filter($=>$.id!==P);s(R),Zt(P),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:R}),r().activeSessionId===S&&N&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function qp(e,t,n){if(n().nodeBatchRunning)return;const r=Cl(n().graphNodes).filter(x=>n().graphNodes.find(y=>y.id===x)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(A("nodeBatch.noneSelected"),!0);return}const s=fp(n().graphNodes,n().graphEdges,r);if(s.length>0){n().showToast(A("nodeBatch.parentRequired",{count:s.length}),!0);return}const a=hp(n().graphNodes,n().graphEdges,r);if(a.length>0){n().showToast(A("nodeBatch.cycleBlocked",{count:a.length}),!0);return}const i=dp(n().graphNodes,n().graphEdges,r),l=new Set(r),c=i.filter(x=>{if(e==="regenerate-all")return!0;const y=n().graphNodes.find(g=>g.id===x);return y?!cp(y):!1});if(c.length===0){n().showToast(A("nodeBatch.nothingToRun"));return}const u=ac(n().graphNodes,n().graphEdges,c).find(x=>x.missing);if(u){n().showToast(A("node.elementMissing",{name:u.name}),!0);return}t({nodeBatchRunning:!0,nodeBatchStopping:!1});const p=new Map;let m=0,h=0,b=0;const I=new Set;try{for(const x of c){if(n().nodeBatchStopping)break;if(I.has(x)){b+=1;continue}const y=n().graphEdges.find(P=>P.target===x),g=y?p.get(y.source)??n().graphNodes.find(P=>P.id===x)?.data.parentServerNodeId??null:null,_=n().videoModelSelected?await n().runVideoGenerate(x).then(()=>n().graphNodes.find(M=>M.id===x)?.data.serverNodeId??null):await n().runGenerateNodeInPlace(x,{parentServerNodeIdOverride:g,suppressToast:!0});if(!_){h+=1;for(const P of mp(n().graphEdges,x))I.add(P);continue}m+=1,p.set(x,_);const S=pp(n().graphEdges,x,l),w=n().graphEdges.filter(P=>P.source===x&&l.has(P.target)).map(P=>P.target),j=new Set(up(n().graphEdges,l));t({graphNodes:n().graphNodes.map(P=>w.includes(P.id)?{...P,data:{...P.data,parentServerNodeId:_}}:j.has(P.id)?{...P,data:{...P.data,status:"stale",parentServerNodeId:S.includes(P.id)?_:P.data.parentServerNodeId,error:A("nodeBatch.staleBecauseParentChanged")}}:P)})}h>0?n().showToast(A("nodeBatch.partialFinished",{done:m,failed:h,skipped:b,total:c.length}),!0):n().showToast(A("nodeBatch.finished",{done:m,total:c.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function Bs(e){return Array.isArray(e.images)}function $p(e,t){return e.modes.includes("both")||e.modes.includes(t)}function Qr(e){const t=new Map(e.catalog.map(i=>[i.id,i])),n=[],r={},s=[],a=[];for(const i of e.presetIds){const l=t.get(i);if(!l||!$p(l,e.mode)){a.push(i);continue}const c=l.perProvider?.[e.provider];n.push(c?.fragment??l.promptFragment),Object.assign(r,c?.params),s.push(i)}return{promptFragment:n.join(" "),params:r,appliedPresetIds:s,skipped:a}}const Up=[{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"]}],Hp=[{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"]}],Kp=[{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"]}],ic=[...Up,...Hp,...Kp];function lc(e){return ic.find(t=>t.id===e)}function es(){return[...ic]}function cc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function dc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function Vp(e,t,n){const r=n();if(r.uiMode!=="classic")return;const s=Cn(r.prompt,r.insertedPrompts);if(!s)return;const a=Qr({catalog:es(),presetIds:r.selectedPresetIds,provider:dc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${s}`:s,l=r.prompt,c=wo(r.insertedPrompts),d=e??r.getResolvedSize(),u=`mm_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;Xt(u,p);const m=Date.now(),h=m,b=hn(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"};Re(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:Hi(r),reasoningEffort:r.reasoningEffort,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:cc(r),...Ro(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(ko)}:{}},g=await Bd(y,{onPartial:w=>{t(j=>{const P=j.multimodeSequences[u];return P?{multimodeSequences:{...j.multimodeSequences,[u]:{...P,partials:[...P.partials,{image:w.image,index:w.index??null}].slice(-b)}}}:{}})},onImage:w=>{t(j=>{const P=j.multimodeSequences[u];if(!P)return{};const M=Ta(P.images,[w]);return M.length===P.images.length?{}:{multimodeSequences:{...j.multimodeSequences,[u]:{...P,sequenceId:w.sequenceId??P.sequenceId,returned:M.length,images:M,status:"partial"}}}})}},{signal:p.signal}),_=g.images.map(w=>({...w,prompt:i,elapsed:Number.parseFloat(g.elapsed),provider:g.provider,usage:g.usage,requestId:w.requestId??g.requestId??u,composerPrompt:l,composerInsertedPrompts:c,quality:g.quality,size:g.size,model:g.model??null}));for(const w of _)await ft(w,t,n,{autoSelectStartedAt:h});t(w=>({multimodeSequences:{...w.multimodeSequences,[u]:(()=>{const j=w.multimodeSequences[u],P=Ta(j?.images??[],_);return{sequenceId:g.sequenceId,requestId:u,requested:g.requested,returned:P.length,images:P,partials:[],status:g.status,elapsed:g.elapsed}})()}}));const S=g.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(A(S,{returned:g.returned,requested:g.requested,elapsed:g.elapsed}))}catch(y){y.name==="AbortError"||Jt(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}}}:{}}),$e(y,n()))}finally{const y=n().inFlight.filter(g=>g.id!==u);Re(y),Zt(u),t(g=>{const _=new Set(g.activeFlightIds);_.delete(u);let S=g.multimodePreviewFlightId;const w=g.multimodeSequences[u]?.status,j=w==="complete"||w==="partial";if(S===u&&!j){const M=[..._];S=M.length>0?M[M.length-1]:null}const P={...g.multimodeSequences};return j&&S!==u&&delete P[u],{activeGenerations:Math.max(0,g.activeGenerations-1),inFlight:y,activeFlightIds:_,multimodePreviewFlightId:S,multimodeSequences:P}})}}async function Bp(e,t,n){const r=n(),s=Cn(r.prompt,r.insertedPrompts);if(!s)return;const a=Qr({catalog:es(),presetIds:r.selectedPresetIds,provider:dc(r.provider),mode:"image"}),i=a.promptFragment?`${a.promptFragment} ${s}`:s,l=r.prompt,c=wo(r.insertedPrompts),d=e??r.getResolvedSize(),u=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,p=new AbortController;Xt(u,p);const m=Date.now(),h=m,b=[...r.inFlight,{id:u,prompt:i,startedAt:m,composerPrompt:l,composerInsertedPrompts:c}];Re(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:Hi(r),reasoningEffort:r.reasoningEffort,storyboard:r.storyboardActive||void 0,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:cc(r),...Ro(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(ko)}:{}},x=await Ti(I,{signal:p.signal});if(Bs(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,createdAt:y.createdAt??Date.now()};await ft(g,t,n,{autoSelectStartedAt:h})}n().showToast(A("toast.generatedBatch",{count:x.images.length,elapsed:x.elapsed}))}else{let y;if(Bs(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,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,createdAt:x.createdAt??Date.now()};await ft(y,t,n,{autoSelectStartedAt:h}),n().showToast(A("toast.generatedSingle",{elapsed:x.elapsed}))}}catch(I){!(I instanceof Error&&I.name==="AbortError")&&!Jt(I)&&$e(I,n())}finally{const I=n().inFlight.filter(x=>x.id!==u);Re(I),Zt(u),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:I})}}function Wp(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 Jp(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,s=await we(r,{signal:n.signal});if(!s.ok)throw Object.assign(new Error(`frame extraction failed (${s.status})`),{status:s.status});const a=await s.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 Yp(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(!Wp(a))throw a}const s=t.kind==="url"?t.url:`/generated/${encodeURIComponent(t.filename)}`;return{dataUrl:await e.extractFromElement(s,n,r),via:"browser-canvas"}}}}const Xp=Yp({fetchGeneratedFrame:Jp,extractFromElement:(e,t,n)=>t==="last"?Yt(e,n):t==="first"?Gl(e,n):zl(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 Zp(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 Yn(e){return typeof e=="string"&&e.trim()?e.trim():null}function uc(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:Zp(e.videoContinuity.entries)};const t=Yn(e.revisedPrompt)??Yn(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:Yn(e.userPrompt)??Yn(e.prompt),revisedPrompt:t,createdAt:e.createdAt??Date.now()}]}}function vn(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 Qp(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
6
  `)}}function mc(e){if(!e?.entries?.length)return null;const t=e.entries[e.entries.length-1];return`${e.entries.length}/4 clips · last frame · ${t?.filename??"unsaved source"}`}function pc(e){return e.provider==="comfy"&&e.comfyVideoWorkflow||(e.provider==="grok"||e.provider==="grok-api")&&e.videoModelSelected?"video":e.uiMode==="classic"&&e.multimode&&e.provider!=="nai"&&jt(e.provider)&&lo[e.provider].multimode.supported?"multimode":"image"}function ef(e){return e.mcpProvider?e.multimode:pc(e)==="multimode"}async function tf(e,t){const n=t();if(!Cn(n.prompt,n.insertedPrompts)||Fo(t))return;const s=pc(n);if(s==="video")return t().runVideoGenerate();const a=s==="multimode",i=Yr(n,{kind:a?"multimode":"classic"});if(i){e({customSizeConfirm:i});return}if(a){await t().generateMultimode();return}await t().runGenerate()}function nf(e,t){const n=t().multimodePreviewFlightId;n&&(Xl(n),t().cancelInFlightJob(n),e(r=>{const s=r.multimodeSequences[n];return s?{multimodeSequences:{...r.multimodeSequences,[n]:{...s,status:"canceled"}}}:{}}))}function Fo(e){return(e().missingElementIds??[]).length>0?(e().showToast(A("toast.missingElements"),!0),!0):!1}async function rf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Fo(t))return;const r=Em(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 sf(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return;const{prompt:s}=r.data;if(!s.trim()){n().showToast(A("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const a=Yr(n(),{kind:"node",clientId:e});if(a){t({customSizeConfirm:a});return}await n().runGenerateNode(e)}async function of(e,t,n){const r=n().graphNodes.find(a=>a.id===e);if(!r)return;if(!r.data.prompt.trim()){n().showToast(A("toast.promptRequired"),!0);return}if(n().videoModelSelected)return n().runVideoGenerate(e);const s=Yr(n(),{kind:"node-in-place",clientId:e});if(s){t({customSizeConfirm:s});return}await n().runGenerateNodeInPlace(e)}async function af(e,t,n,r){const s=r().graphNodes.find(i=>i.id===e);if(!s)return;if(!s.data.prompt.trim()){r().showToast(A("toast.promptRequired"),!0);return}if(r().videoModelSelected){const i=r().addSiblingNode(e);return r().runVideoGenerate(i)}if(!t){const i=Yr(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 lf(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 fc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function hc(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 gc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function cf(e,t,n){const r=e?n().graphNodes.find(S=>S.id===e):null,s=r?r.data.referenceImages??[]:n().referenceImages,a=s.length===1&&n().videoSingleRefMode==="image-to-video",i=r?r.data.prompt.trim():Cn(n().prompt,n().insertedPrompts);if(!i.trim()){n().showToast(Ar,!0);return}const l=n(),c=Qr({catalog:es(),presetIds:l.selectedPresetIds,provider:gc(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&&s.length===0&&r.data.parentServerNodeId){const S=n().graphNodes.find(w=>w.data.serverNodeId===r.data.parentServerNodeId);if(S?.data.imageUrl)if(Ye(S.data.imageUrl))try{const w=S.data.imageUrl.replace(/^\/generated\//,"");p=(await Xp.extractFrame({kind:"generated",filename:w},"last")).dataUrl,m=S.data.videoContinuity??uc({filename:w,prompt:S.data.prompt,userPrompt:S.data.prompt,revisedPrompt:S.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=w}catch{n().showToast(A("video.continuationFallbackT2V"),!0)}else u=S.data.imageUrl.replace(/^\/generated\//,"")}const b=Date.now(),I=b,x=`vid_${b}_${Math.random().toString(36).slice(2,6)}`,y=new AbortController;Xt(x,y);const g=n().activeSessionId,_=[...n().inFlight,{id:x,prompt:d,startedAt:b,kind:"video",sessionId:g,clientNodeId:e??null}];Re(_),r&&t({graphNodes:n().graphNodes.map(S=>S.id===e?{...S,data:{...S.data,status:"pending",pendingRequestId:x,pendingPhase:"queued",pendingStartedAt:b,partialImageUrl:null,error:void 0,errorInfo:null}}:S)}),t({inFlight:_,activeGenerations:_.length,videoProgress:0}),n().startInFlightPolling();try{const S=n().providerUrlReference,w={prompt:d,requestId:x,...hc(n()),referenceImages:s.length>0&&!a?s:void 0,sourceImage:a?s[0]:s.length>0?void 0:p,sourceFilename:s.length===0&&!p?u:void 0,continueFromVideo:h,continuityLineage:m,duration:n().videoDuration,resolution:n().videoResolution,aspectRatio:n().videoAspectRatio,topic:n().videoTopic||void 0,storyboard:n().storyboardActive||void 0,presetIds:c.appliedPresetIds,elementIds:fc(n()),sessionId:g,clientNodeId:e??null,...S?{providerUrl:S}:{}},j=await ro(w,{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&&j&&n().activeSessionId===g&&(t({graphNodes:n().graphNodes.map(P=>P.id===e?{...P,data:{...P.data,serverNodeId:j.filename.replace(/\.[^.]+$/,""),imageUrl:j.url,status:"ready",error:void 0,errorInfo:null,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:j.elapsed??void 0,model:j.effectiveModel??j.requestedModel??r.data.model??null,videoContinuity:j.videoContinuity??m,video:{...j.video??{},...j.videoSeries?.topic?{topic:j.videoSeries.topic}:{}}}}:P)}),n().scheduleGraphSave(),n().flushGraphSave("video-node-complete")),j){const P={image:j.url,filename:j.filename,url:j.url,mediaType:"video",prompt:d,elapsed:j.elapsed,video:j.video??{},videoSeries:j.videoSeries??null,videoContinuity:j.videoContinuity??null,revisedPrompt:j.revisedPrompt??null,requestId:j.requestId??x,createdAt:Date.now(),sessionId:g};await ft(P,t,n,{autoSelectStartedAt:I})}}catch(S){if(Jt(S))r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(w=>w.id===e?{...w,data:{...w.data,status:w.data.imageUrl?"ready":"empty",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:void 0,errorInfo:null}}:w)});else{const w=tt(S).code==="JOB_TRACKING_TIMEOUT",j=w?$e(S,n()).message:S instanceof Error?S.message:"Video generation failed",P=w?{...Jl(S),message:j}:null;r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(M=>M.id===e?{...M,data:{...M.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:j,errorInfo:P}}:M)}),w||n().showToast(j,!0)}}finally{const S=n().inFlight.filter(w=>w.id!==x);Re(S),Zt(x),t({inFlight:S,activeGenerations:S.length,videoProgress:null}),n().startInFlightPolling()}}async function df(e,t,n,r){const s=t?.trim();if(!s)throw r().showToast(Ar,!0),new Error(Ar);if(Fo(r))return!1;const a=r(),i=Qr({catalog:es(),presetIds:a.selectedPresetIds,provider:gc(a.provider),mode:"video"}),l=i.promptFragment?`${i.promptFragment} ${s}`:s,c=Date.now(),d=c,u=`vid_${c}_${Math.random().toString(36).slice(2,6)}`,p=new AbortController;Xt(u,p);const m=[...r().inFlight,{id:u,prompt:l,startedAt:c,kind:"video",sessionId:r().activeSessionId,clientNodeId:null}];Re(m),n({inFlight:m,activeGenerations:m.length,videoProgress:0}),r().startInFlightPolling();try{const h={prompt:l,presetIds:i.appliedPresetIds,elementIds:fc(r()),requestId:u,...hc(r()),mode:"image-to-video",sourceFilename:e,duration:5,resolution:"480p",aspectRatio:"auto"},b=await ro(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 ft(I,n,r,{autoSelectStartedAt:d})}catch(h){return Jt(h)||(tt(h).code==="JOB_TRACKING_TIMEOUT"?$e(h,r()):r().showToast(h instanceof Error?h.message:"Video generation failed",!0)),!1}finally{const h=r().inFlight.filter(b=>b.id!==u);Re(h),Zt(u),n({inFlight:h,activeGenerations:h.length,videoProgress:null}),r().startInFlightPolling()}return!0}function Ws(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 bn(e){const t=new Map([...Rl({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,Ws(r)])),memory:new Map(e.inFlight.map(n=>[n.id,n])),scopes:Fm({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function Oo(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function yc(e,t){return new Set([...t.local].filter(([n,r])=>{const s=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)&&!s&&yn(r,e.scopes)}).map(([n])=>n))}function uf(e,t,n){const r=jr(t),s=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 Ws(s)===Ws(e)?e:s}function mf(e,t,n,r,s){if(t&&(s.mode==="reconcile"||!n))return[yn(jr(t),r.scopes)?uf(e,t,s.mode):e];if(n)return yn(jr(n),r.scopes)?(n.status==="error"&&s.terminalErrors.push(Om(n)),[]):[e];const a=s.now-e.startedAt;return(s.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function vc(e,t,n,r){if(!Oo(e,t))return null;const s=bn(t),a=yc(e,s),i=new Map(n.jobs.map(p=>[p.requestId,p])),l=new Map(n.terminalJobs.map(p=>[p.requestId,p])),c=[],d=[...s.local.values()].flatMap(p=>a.has(p.id)?mf(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=jr(m);yn(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)&&!s.local.has(p)&&d.push(h)))}return{inFlight:d,terminalErrors:c,eligibleIds:a,serverActiveIds:u}}let xn=0;function In(){if(xn+=1,typeof window>"u")return;const e=window;e.__ima2InflightTimer!==void 0&&clearInterval(e.__ima2InflightTimer),e.__ima2InflightTimer=void 0,e.__ima2StopTicks=0,window.removeEventListener(St,In)}function pf(e,t,n){const r=n();Re(e.inFlight),(e.inFlight.length!==r.inFlight.length||r.activeGenerations!==e.inFlight.length||e.inFlight.some((s,a)=>s!==r.inFlight[a]))&&t({inFlight:e.inFlight,activeGenerations:e.inFlight.length});for(const s of e.terminalErrors)$e(s,n())}function ff(e,t){e.length&&t(n=>{const r=new Set(n.history.map(Ge)),s=e.filter(a=>{const i=Ge(a);return r.has(i)?!1:(r.add(i),!0)});return s.length?(!n.currentImage&&s[0]?.filename&&nt(s[0].filename),{history:Jr([...s,...n.history],Math.max(ze,n.history.length+s.length)),currentImage:n.currentImage??s[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+s.length)}):{}})}function hf(e,t,n){const r=bn(n()),s=yc(e.snapshot,r),a=Date.now(),i=[...r.local.values()].filter(l=>!e.eligibleIds.has(l.id)||!s.has(l.id)||e.serverActiveIds.has(l.id)||a-l.startedAt<Pl);i.length!==r.local.size&&(Re(i),t({inFlight:i,activeGenerations:i.length}))}async function gf(e,t,n,r,s){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await Vt({limit:ze,since:a});if(!s()||!Oo(e,r()))return;ff(i.map(Rn),n),t&&hf(t,n,r)}catch{}}function yf(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function vf(e,t,n){if(ce()){In();return}const r=pe(),s=xn,a=()=>!ce()&&r===pe()&&s===xn,i=bn(t());let l=null;if(!yf(t(),n))try{const c=await Al(i.scopes);if(!a())return;const d=vc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;pf(d,e,t),l={snapshot:bn(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&Oo(i,t())&&await gf(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&In()}function bf(e,t){if(typeof window>"u"||ce())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(St,In),n.__ima2InflightTimer=window.setInterval(()=>vf(e,t,n),1500))}async function xf(e,t){if(ce())return;const n=pe(),r=xn;try{const s=bn(t()),a=await Al(s.scopes);if(ce()||n!==pe()||r!==xn)return;const i=vc(s,t(),a,{mode:"reconcile",now:Date.now()});if(!i)return;Re(i.inFlight),e({inFlight:i.inFlight,activeGenerations:i.inFlight.length});for(const l of i.terminalErrors)$e(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const _t=()=>"nc_"+Math.random().toString(36).slice(2,10);function Oa(e,t){return{x:e*360,y:t*320}}const If=360,bc=320;function Sf(e,t,n){const r=new Set(n.filter(s=>s.source===e).map(s=>s.target));return t.filter(s=>r.has(s.id))}function Do(e){const t=e.filter(r=>!r.data.parentServerNodeId);if(t.length===0)return Oa(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:Oa(0,0).x,y:n+bc}}function xc(e,t,n){const r=Sf(e.id,t,n),s=e.position.x+If;if(r.length===0)return{x:s,y:e.position.y};const a=Math.max(...r.map(i=>i.position.y));return{x:s,y:a+bc}}const Sn="source-right",wn="target-left";function ts(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function wf(e,t){return e&&e.startsWith(`${t}-`)?e:null}function _f(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 Ef(e,t){const n=_t();t().recordGraphHistory("add-root");const r={id:n,type:"imageNode",position:Do(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 Nf(e,t,n){const r=_t();n().recordGraphHistory("add-root-from-history");const s={id:r,type:"imageNode",position:Do(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,s]}),n().scheduleGraphSave(),r}function kf(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return e;n().recordGraphHistory("add-child");const s=_t(),a={id:s,type:"imageNode",position:xc(r,n().graphNodes,n().graphEdges),data:{clientId:s,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:Ye(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:ts(e,s,Sn,wn),source:e,target:s,sourceHandle:Sn,targetHandle:wn};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&Ye(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 Yt(l);t({graphNodes:n().graphNodes.map(d=>d.id===s?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return s}function Cf(e,t,n){const r=n().graphNodes.find(u=>u.id===e);if(!r)return e;n().recordGraphHistory("add-sibling");const s=n().graphEdges.find(u=>u.target===e);if(!s){const u=_t(),p={id:u,type:"imageNode",position:Do(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=s.source,i=n().graphNodes.find(u=>u.id===a);if(!i)return e;const l=_t(),c={id:l,type:"imageNode",position:xc(i,n().graphNodes,n().graphEdges),data:{clientId:l,serverNodeId:null,parentServerNodeId:r.data.parentServerNodeId,prompt:r.data.prompt,imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},d={id:ts(a,l,Sn,wn),source:a,target:l,sourceHandle:Sn,targetHandle:wn};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function jf(e,t,n,r,s){const a=s().graphNodes.find(p=>p.id===e);if(!a)return e;s().recordGraphHistory("add-child-at");const i=_t(),l=wf(n,"source")??Sn,c=_f(l)??wn,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:ts(e,i,l,c),source:e,target:i,sourceHandle:l,targetHandle:c};return r({graphNodes:[...s().graphNodes,d],graphEdges:[...s().graphEdges,u]}),s().scheduleGraphSave(),i}function Pf(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return e;n().recordGraphHistory("duplicate-branch");const s=_t(),a={id:s,type:"imageNode",position:{x:r.position.x+420,y:r.position.y+40},data:{clientId:s,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 Tn(i,"node-reference.png");t({graphNodes:n().graphNodes.map(c=>c.id===s?{...c,data:{...c.data,referenceImages:[l]}}:c)})}catch{}})()}return s}function Af(e,t,n,r){n({graphNodes:r().graphNodes.map(s=>s.id===e?{...s,data:{...s.data,prompt:t}}:s)}),r().scheduleGraphSave()}function Rf(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return;n().recordGraphHistory("delete-node");const s=r?.data?.pendingRequestId;s&&Ce(s),Po(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:Qe(a,i),graphEdges:i}),n().scheduleGraphSave()}function Tf(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)Po(n().activeSessionId,i);for(const i of n().graphNodes)r.has(i.id)&&i.data?.pendingRequestId&&Ce(i.data.pendingRequestId);const s=n().graphNodes.filter(i=>!r.has(i.id)),a=n().graphEdges.filter(i=>!r.has(i.source)&&!r.has(i.target));t({graphNodes:Qe(s,a),graphEdges:a}),n().scheduleGraphSave()}function Mf(e,t,n){const r=new Set(e);if(r.size===0)return;const s=n().graphEdges.filter(c=>r.has(c.id));if(s.length===0)return;n().recordGraphHistory("disconnect-edges");const a=n().graphEdges.filter(c=>!r.has(c.id)),i=new Set(s.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:Qe(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(A("edge.disconnected"))}function Lf(e,t,n,r,s,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(Vm(a().graphEdges,e,t)){a().showToast(A("edge.parentConflict"),!0);return}if(Bm(a().graphEdges,e,t)){a().showToast(A("edge.cycleBlocked"),!0);return}if(!a().graphNodes.find(d=>d.id===e))return;a().recordGraphHistory("connect-nodes");const c=[...a().graphEdges,{id:ts(e,t,n,r),source:e,target:t,sourceHandle:n,targetHandle:r}];s({graphNodes:Qe(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function Ff(e,t,n,r){const s=r().graphNodes.find(h=>h.id===e);if(!s)return;const a=s.data.referenceImages??[],l=r().referenceLimit-a.length;if(l<=0){r().showToast(A("toast.refLimitExceeded"),!0);return}const c=t.slice(0,Math.max(0,l)),d=c.filter(Cr),u=c.filter(h=>!Cr(h)),m=(await Promise.all(u.map(async h=>{try{return await Eo(h,{preserveTransparency:jl(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 Xr(h,e,I),{...b,data:{...b.data,referenceImages:I}}})}),r().scheduleGraphSave()}d.length>0&&r().showToast(A("toast.refHeicUnsupported"),!0),u.length-m.length>0&&r().showToast(A("toast.refTooLarge"),!0),t.length>l&&r().showToast(A("toast.refLimitExceeded"),!0)}function Ic(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 Xr(r().activeSessionId,e,l),{...a,data:{...a.data,referenceImages:l}}})}),r().scheduleGraphSave())}async function Of(e,t,n,r,s){const a=s().graphNodes.find(l=>l.id===e);if(!a)return;if((a.data.referenceImages??[]).length>=s().referenceLimit){s().showToast(A("toast.refLimitExceeded"),!0);return}let i;try{i=Ye(t)||Ye(n)?await Yt(t):await Tn(t,n||"node-reference.png")}catch{s().showToast(A("toast.currentImageLoadFailed"),!0);return}Ic(e,i,r,s)}function Df(e,t,n,r){n({graphNodes:r().graphNodes.map(s=>{if(s.id!==e)return s;const a=(s.data.referenceImages??[]).filter((i,l)=>l!==t);return Xr(r().activeSessionId,e,a),{...s,data:{...s.data,referenceImages:a}}})}),r().scheduleGraphSave()}function Gf(e,t,n){Po(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const Da=10;function Sc(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 Pt(e){return e.filter(t=>!t.canvasVersion)}function et(e,t){if(!t)return null;const n=Pt(e);if(!t.canvasVersion)return n.find(a=>Sc(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=Pt(e),r=et(e,t);return n.findIndex(s=>Sc(s,r))}function $f(e,t,n){const r=Pt(e);if(r.length===0)return null;if(n==="first")return r[0]??null;if(n==="last")return r[r.length-1]??null;const s=qf(e,t);if(s<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-Da:Da,l=Math.max(0,Math.min(r.length-1,s+i));return r[l]??null}const a=n==="previous"?s-1:s+1;return r[a]??null}function wc(e,t){const n=Pt(e),r=n.findIndex(s=>s.filename===t);return r<0?null:n[r+1]??n[r-1]??null}function Ae(e){return e.filename||e.image}function mn(e){return!e.canvasVersion}function xr(e){const t=new Set;return e.filter(n=>{const r=Ae(n);return t.has(r)?!1:(t.add(r),!0)})}const _c=72,Ga=10;function Ec(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 Uf(e){return e<=1?1:e===2?2:4}function Nc(e){const t=new Set,n=new Map,r=[];for(const s of e){if(!mn(s))continue;if(s.sequenceId){const i=`sequence:${s.sequenceId}`;let l=n.get(s.sequenceId);l||(l={type:"sequence",key:i,sequenceId:s.sequenceId,items:[]},n.set(s.sequenceId,l),r.push(l)),l.items.push(s);continue}const a=Ae(s);t.has(a)||(t.add(a),r.push({type:"image",key:a,item:s}))}for(const s of n.values())s.items.sort(Ec);return r}function kc(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Ae(e):null}function ms(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function Hf(e,t,n,r,s=_c){const a=Nc(e).slice(0,s);if(a.length===0)return null;const i=a[0],l=a[a.length-1];if(!i||!l)return null;if(n==="first")return ms(i);if(n==="last")return ms(l);const c=kc(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const u=n==="pagePrevious"?-Ga:n==="pageNext"?Ga: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?ms(m):null}const Cc={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},Kf={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},Vf={default:Cc,"prompt-studio":Kf};function Ln(e,t){return Vf[e]??Cc}function Bf(e,t){return Ln(e).promptBuilderSurface!=="off"}const Wf="history:";function jc(e,t,n){if(!t||n||!t.startsWith(Wf)||!(t in e))return e;const r={...e};return delete r[t],r}function Jf(e){const t=e.multimodePreviewFlightId;return t?t.startsWith("history:")?t.slice(8):e.multimodeSequences[t]?.sequenceId??null:null}async function Yf(e,t){const n=t().historyNextCursor;if(!(!n||t().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const r=await Vt({limit:ze,cursor:n}),s=r.items.map(Rn);e(a=>{const i=new Set(a.history.map(c=>c.filename??c.image)),l=s.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(A("gallery.loadOlderFailed"),!0)}}}async function Xf(e,t){try{const n=await Vt({limit:ze,favoritesOnly:!0}),r=n.items.map(Rn);e(s=>{const a=Fl(s.history,r);return{history:a,favoriteHistoryNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(s.loadedHistoryRetainLimit,a.length),galleryFavorites:new Set([...Array.from(s.galleryFavorites),...r.filter(i=>i.filename).map(i=>i.filename)])}})}catch{t().showToast(A("gallery.loadOlderFailed"),!0)}}async function Zf(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await Vt({limit:ze,cursor:n,favoritesOnly:!0}),s=r.items.map(Rn);e(a=>{const i=Fl(a.history,s);return{history:i,favoriteHistoryNextCursor:r.nextCursor,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:Math.max(a.loadedHistoryRetainLimit,i.length),galleryFavorites:new Set([...Array.from(a.galleryFavorites),...s.filter(l=>l.filename).map(l=>l.filename)])}})}catch{e({favoriteHistoryLoadingOlder:!1}),t().showToast(A("gallery.loadOlderFailed"),!0)}}}function Qf(e,t,n){const r=Date.now(),s=n().history,a=e.canvasVersion?et(s,e)??Pt(s)[0]??null:et(s,e)??e;nt(a?.filename??null);const i=Ln(n().workspaceProfile).restoreComposerFromHistory,l=n().prompt,c=n().insertedPrompts,d=l.trim()!==""||c.length>0,u=i&&a&&!d?hm(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:jc(b.multimodeSequences,p,!!h),...u}))}function eh(e,t,n){const r=Date.now(),s=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(Ec);if(s.length===0)return;const a=`history:${e}`,i=Math.max(s.length,...s.map(d=>d.sequenceTotalRequested??0)),l=s.length,c=s[0]?.sequenceStatus==="empty"?"empty":l>=i?"complete":"partial";nt(null),t(d=>({currentImage:null,lastHistorySelectedAt:r,unseenGeneratedCount:0,canvasOpen:!1,multimodePreviewFlightId:a,multimodeSequences:{...jc(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:s,partials:[],status:c}}}))}function th(e,t,n){const r=n(),s=Ln(r.workspaceProfile);if(r.uiMode==="classic"&&s.multimodeHistoryGrouping==="sequence"){const i=Hf(r.history,r.currentImage,e,Jf(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=$f(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function nh(e,t,n){const r=e.canvasVersion?et(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(A("gallery.deleteFailed"),!0);return}const s=r.filename,a=n().currentImage,l=(a?et(n().history,a)??a:null)?.filename===s,c=l?wc(n().history,s):a;try{await Mi(s),t(d=>{const u=Gm(d.multimodeSequences,s),p=d.multimodePreviewFlightId&&!u[d.multimodePreviewFlightId]?null:d.multimodePreviewFlightId;return{history:d.history.filter(m=>m.filename!==s),currentImage:c,multimodePreviewFlightId:p,multimodeSequences:u,trashPending:null}}),l&&nt(c?.filename??null),n().showToast(A("gallery.movedToSystemTrash",{filename:s}))}catch(d){console.error("[history] trash failed",d),n().showToast(A("gallery.deleteFailed"),!0)}}async function rh(e,t,n){const r=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion&&!!d.filename);if(r.length===0){n().showToast(A("gallery.deleteFailed"),!0);return}if(!window.confirm(A("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 Mi(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&&nt(null),n().showToast(A("history.sequenceDeleted",{count:a.size}))}catch(d){console.error("[history] sequence trash failed",d),n().showToast(A("gallery.deleteFailed"),!0)}}async function sh(e,t){const n=t().trashPending;if(n)try{await eu(n.filename,n.trashId),t().addHistoryItem(n.item),e({trashPending:null})}catch(r){console.error("[history] restore failed",r),t().showToast(A("gallery.restoreFailed"),!0)}}async function oh(e,t,n){const r=e.canvasVersion?et(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(A("gallery.deleteFailed"),!0);return}const s=r.filename;if(!window.confirm(A("result.permanentDeleteConfirm",{filename:s})))return;const i=n().currentImage,c=(i?et(n().history,i)??i:null)?.filename===s,d=c?wc(n().history,s):i;try{await Qd(s),t(u=>({history:u.history.filter(p=>p.filename!==s),currentImage:d,trashPending:u.trashPending?.filename===s?null:u.trashPending})),c&&nt(d?.filename??null),n().showToast(A("gallery.permanentDeleted",{filename:s}))}catch(u){console.error("[history] permanent delete failed",u),n().showToast(A("gallery.deleteFailed"),!0)}}function ah(e,t,n){const r=n(),s=r.history.filter(i=>i.filename!==e),a=r.currentImage&&r.currentImage.filename===e?null:r.currentImage;t({history:s,currentImage:a}),a===null&&nt(null)}function ih(e,t,n){const r=n(),s={...e,createdAt:e.createdAt||Date.now()},a=Ml(r.history,s),i=Ll(s,a),l=Tl(r.history,i);t({history:Jr([i,...l],r.loadedHistoryRetainLimit+1),loadedHistoryRetainLimit:Math.max(r.loadedHistoryRetainLimit,Math.min(r.history.length+1,r.loadedHistoryRetainLimit+1))})}async function lh(e,t,n){if(!e.type||!/^image\/(png|jpeg|webp)$/.test(e.type))return n().showToast(A("toast.localImportInvalid"),!0),null;try{const r=await Wd(e);return n().addHistoryItem(r),t({currentImage:r,unseenGeneratedCount:0}),r.filename&&nt(r.filename),n().showToast(A("toast.localImportSuccess")),r}catch{return n().showToast(A("toast.localImportFailed"),!0),null}}function ch(e,t){(async()=>{try{const n=await Vt({limit:ze}),r=n.items.map(Rn);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:ze}),r.length>0){const s=xl(),a=s?r.find(c=>c.filename===s):null,i=Pt(r),l=(a?et(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(ze,r.length)}),l?.filename!==s&&nt(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function Pc(e,t){try{const{sessions:n}=await nu();if(e({sessions:n}),!t().activeSessionId){const s=_m(),a=s?n.some(i=>i.id===s):!1;s&&a?await t().switchSession(s):await t().createAndSwitchSession(A("session.firstGraph"))}}catch(n){console.warn("[sessions] load failed:",n),t().showToast(A("modal.sessionInitialLoadFailed"),!0),window.confirm(A("modal.sessionInitialLoadRetry"))&&await Pc(e,t)}}async function dh(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(A("modal.sessionSwitchSaveFailed"),!0);return}t({sessionLoading:!0});try{const{session:r}=await Li(e),{graphNodes:s,graphEdges:a,graphVersion:i}=ql(r);t({activeSessionId:e,activeSessionGraphVersion:i,graphNodes:s,graphEdges:a,graphHistoryPast:[],graphHistoryFuture:[],sessionLoading:!1}),_o(e),await n().reconcileGraphPending().catch(()=>{})}catch(r){console.warn("[sessions] switch failed:",r),t({sessionLoading:!1}),n().showToast(A("toast.sessionLoadFailed"),!0)}}}async function uh(e,t){const n=t().activeSessionId;if(!n)return;if(t().graphNodes.filter(s=>s.data?.pendingRequestId&&(s.data.status==="pending"||s.data.status==="reconciling")).length>0){let s=[];try{s=(await Ai({kind:"node",sessionId:n})).jobs}catch{s=[]}const a=new Map(s.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:A("session.assetAbortedError")}}});e({graphNodes:c})}await Vl(t,e).catch(()=>{})}async function mh(e,t,n){e==null&&(e=A("session.untitled"));try{const{session:r}=await ru(e);t({sessions:[r,...n().sessions],activeSessionId:r.id,activeSessionGraphVersion:r.graphVersion,graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[]}),_o(r.id)}catch(r){console.warn("[sessions] create failed:",r),n().showToast(A("toast.sessionCreateFailed"),!0)}}async function ph(e,t,n){const r=n().activeSessionId;if(r)try{await su(r,e),t({sessions:n().sessions.map(s=>s.id===r?{...s,title:e,updatedAt:Date.now()}:s)})}catch{n().showToast(A("toast.sessionRenameFailed"),!0)}}async function fh(e,t,n){try{await ou(e);const r=n().sessions.filter(s=>s.id!==e);t({sessions:r}),n().activeSessionId===e&&(t({activeSessionId:null,activeSessionGraphVersion:null,graphNodes:[],graphEdges:[]}),_o(null),r.length>0?await n().switchSession(r[0].id):await n().createAndSwitchSession(A("session.firstGraph")))}catch{n().showToast(A("toast.sessionDeleteFailed"),!0)}}function hh(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),Sl(t.quality)&&(n.quality=t.quality),wl(t.format)&&(n.format=t.format),_l(t.moderation)&&(n.moderation=t.moderation),(t.promptMode==="auto"||t.promptMode==="direct")&&(n.promptMode=t.promptMode),t.model&&Nu(t.model)&&(n.imageModel=t.model);const s=Nm(t.size);return s.preset&&(n.sizePreset=s.preset),s.preset==="custom"&&s.w&&s.h&&(n.customW=Ze(s.w,e.customW),n.customH=Ze(s.h,e.customH)),n}function Fn(e,t){return Lo(e,t)}function Go(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 Ac(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function zo(e,t){return Fn(t,(n,r)=>{const s=[...n.trayItems];let a=n.retiredTags;const i=new Set(s.map(d=>d.tag)),l=[];let c=n.nextAttachmentOrdinal;for(const d of e){if(!To(s,r))break;const u=ec(c,i),p=Ac(d,u.tag);s.push(p),l.push(p),i.add(p.tag),a=Mo(a,p.tag),c=u.nextAttachmentOrdinal}return l.length===0?{result:l}:{result:l,patch:{trayItems:s,nextAttachmentOrdinal:c,retiredTags:a,providerUrlReference:null}}})}function gh(e,t,n){return zo(e,t)}function ns(e,t,n,r){const s=Go(e);return s?zo([{dataUrl:e,mimeType:s,origin:t}],n)[0]??null:null}function yh(e,t,n){ns(e,"gallery",t)}async function vh(e,t,n){const r=n().activeReferenceLimit(),s=Math.max(0,r-n().trayItems.length),a=e.slice(0,s),i=a.filter(Cr),l=a.filter(p=>!Cr(p)),d=(await Promise.all(l.map(async p=>{try{const m=await Eo(p,{preserveTransparency:jl(p)}),h=Go(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=zo(d,t);i.length>0&&n().showToast(A("toast.refHeicUnsupported"),!0),l.length-d.length>0&&n().showToast(A("toast.refTooLarge"),!0),(e.length>s||d.length>u.length)&&n().showToast(A("toast.refLimitExceeded"),!0)}async function bh(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let s="";try{s=await Co(e);const a=await iu({filename:e.name,dataUrl:s});return a.metadata?(n({metadataRestore:{filename:e.name,image:s,metadata:a.metadata,source:a.source??"xmp",targetNodeId:t}}),!0):!1}catch{return r().showToast(A("metadata.readFailed"),!0),!1}}function xh(e,t){const n=t().metadataRestore;if(!n)return;const r=hh(t(),n.metadata);if(r.imageModel&&vl(r.imageModel),n.targetNodeId&&typeof r.prompt=="string"){const s=r.prompt;e({...r,metadataRestore:null,graphNodes:t().graphNodes.map(a=>a.id===n.targetNodeId?{...a,data:{...a.data,prompt:s}}:a)}),t().scheduleGraphSave()}else e({...r,metadataRestore:null});t().showToast(A("metadata.applied"))}function qo(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function $o(e,t){t.length!==e.length&&ne({insertedPrompts:t})}function Rc(e,t,n){const r=n().insertedPrompts;Fn(t,s=>{const a=s.trayItems.find(c=>c.tokenId===e);if(!a)return{result:void 0};const i=s.trayItems.filter(c=>c.tokenId!==e),l={trayItems:i,retiredTags:Zr(s.retiredTags,[a])};if(a.kind==="attachment"){const c=Mn({trayItems:i}).length===0;l.canvasReferenceImage=a.source.dataUrl===s.canvasReferenceImage?null:s.canvasReferenceImage,c&&(l.insertedPrompts=qo(s),l.videoContinuityLineage=null)}return{result:void 0,patch:l}}),$o(r,n().insertedPrompts)}function Ih(e,t,n){const r=Mn(n())[e];r&&Rc(r.tokenId,t,n)}function Sh(e,t){const n=t().insertedPrompts;Fn(e,r=>{const s=Mn(r);return{result:void 0,patch:{trayItems:r.trayItems.filter(i=>i.kind!=="attachment"),retiredTags:Zr(r.retiredTags,s),canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:qo(r),providerUrlReference:null}}}),$o(n,t().insertedPrompts)}function wh(e,t){const n=t().insertedPrompts;Fn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:qo(r),providerUrlReference:null}})),$o(n,t().insertedPrompts)}function _h(e,t,n){const r=Mn(e).filter(d=>d.source.dataUrl===n.dataUrl||d.source.dataUrl===e.canvasReferenceImage),s=new Set(r.map(d=>d.tokenId)),a=e.trayItems.filter(d=>!s.has(d.tokenId));if(!To(a,t))return{result:!1};const i=ec(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=Ac(n,i.tag),c=Mo(Zr(e.retiredTags,r),l.tag);return{result:!0,patch:{trayItems:[l,...a],nextAttachmentOrdinal:i.nextAttachmentOrdinal,retiredTags:c,canvasReferenceImage:n.dataUrl,providerUrlReference:null}}}async function Eh(e,t,n,r){let s;try{s=await Tn(r??e.image,e.filename||"canvas-version-reference.png")}catch{throw n().showToast(A("toast.currentImageLoadFailed"),!0),new Error("canvas_reference_attach_failed")}const a=Go(s);if(!a){n().showToast(A("toast.currentImageLoadFailed"),!0);return}if(!Fn(t,(l,c)=>_h(l,c,{dataUrl:s,mimeType:a,originalName:e.filename||"canvas-version-reference.png",origin:"canvas"}))){n().showToast(A("toast.refSlotFull"),!0);return}n().showToast(A("canvas.version.usingAsReference"))}function Tc(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Nh(e,t){const n=t().currentImage;if(!n){t().showToast(A("toast.noCurrentImageForRef"),!0);return}if(t().trayItems.length>=t().activeReferenceLimit()){t().showToast(A("toast.refSlotFull"),!0);return}let r;try{r=await Tn(Tc(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(A("toast.currentImageLoadFailed"),!0);return}if(!ns(r,"gallery",e)){t().showToast(A("toast.refSlotFull"),!0);return}t().showToast(A("toast.addedCurrentAsRef"))}async function kh(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(A("toast.refSlotFull"),!0);return}let r;try{r=await Tn(Tc(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(A("toast.currentImageLoadFailed"),!0);return}if(!ns(r,"gallery",t)){n().showToast(A("toast.refSlotFull"),!0);return}n().showToast(A("toast.addedCurrentAsRef"))}function On(e){const{provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e();return ot({provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:s,comfyVideoWorkflow:a})}function Dn(e,t,n,r){const s=Nl();s[e.provider]={...s[e.provider],...ya(e)};const a={...s[t.provider],...ya(t)};r&&delete a[r],s[t.provider]=a,Am(s),Rm(t),n(t)}function Ch(e,t,n){const r=On(n);if(e===r.provider)return;const s=jt(e)?Nl()[e]:void 0,a=Fu(r,e,s);Dn(r,a,t)}function jh(e,t,n){const r=On(n),s=ot({provider:Lu(r.provider,e),imageModel:e,videoModelSelected:!1});Dn(r,s,t)}function Ph(e,t,n){const r=On(n),s=ot({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:kn(e)||pt});Dn(r,s,t)}function Ah(e,t,n){const r=On(n),s=ot({...r,provider:"comfy",comfyWorkflow:e,comfyVideoWorkflow:null});Dn(r,s,t,e===null?"image":void 0)}function Rh(e,t,n){const r=On(n),s=ot({...r,provider:"comfy",comfyVideoWorkflow:e,videoModelSelected:!1});Dn(r,s,t,e===null?"video":void 0)}function Th(e,t,n){const r=n.data?.parentServerNodeId;if(r){const a=e.find(i=>i.data?.serverNodeId===r);if(a)return a}const s=t.find(a=>a.target===n.id);return s?e.find(a=>a.id===s.source):void 0}function Mh(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&&Th(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const Lh=1e4;let _n=[];async function Uo(e){const t=await z("/api/mcp/providers",{signal:e});return _n=Array.isArray(t.providers)?t.providers:[],_n}function Fh(e){return ji("/api/mcp/providers",e)}function Oh(e,t){return ji(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function Dh(){return _n}async function hw(e){const t=window.open("about:blank",`ima2_mcp_${e}`);try{const n=await z(`/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 gw(e){return(await z(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function yw(e){return(await z(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function Mc(e,t){const r=(await z(`/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 Gh(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,s(),a(),!0),s=kt(e,null,(i,l)=>{if(i==="done"){const c=Gh(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?.(at(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Kt(()=>{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 Uo()).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 z("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(s){throw r(),s}}function Lc(){const[e,t]=v.useState(()=>[..._n]),[n,r]=v.useState(_n.length===0),[s,a]=v.useState(null),i=v.useCallback(async()=>{try{const l=await Uo();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()},Lh);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:s,refresh:i}}let Rr=null;function Fc(e){if(tt(e).code==="JOB_TRACKING_TIMEOUT")return A("toast.jobTrackingTimeout");const t=e,n=t.code??t.message??"";return n.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")||t.message?.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")?A("mcp.errorUnsupportedInput"):n==="MCP_END_FRAME_REQUIRES_START"?A("mcp.errorEndRequiresStart"):n==="INVALID_MCP_REFERENCES"?A("mcp.errorInvalidReferences"):n==="INVALID_START_FRAME"?A("mcp.errorInvalidFrame"):n.startsWith("INVALID_MCP_TEMP_REFERENCE")||n==="MCP_TEMP_REFERENCES_FAILED"?A("mcp.errorTempReferences"):A(n==="MCP_NOT_CONNECTED"||n==="MCP_PROVIDER_UNKNOWN"?"mcp.selectionUnavailable":"mcp.generateFailed")}async function $h(e){const t=e.references.filter(a=>a.dataUrl);if(t.length===0)return{selection:e,batchId:null};const n=await z("/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 s=e.references.map(a=>a.dataUrl?{filename:n.files[r++].filename,...a.tag?{tag:a.tag}:{}}:a);return{selection:{...e,references:s},batchId:n.batchId}}async function Uh(e){try{await z(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function Hh(e,t,n){let r=()=>{};const s=new Promise(i=>{r=i});if(await qh(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(Fc(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 s,a)throw a}async function Kh(e){const t=e();if((t.mcpProvider?Dh().find(c=>c.id===t.mcpProvider):void 0)?.executable===!1){e().showToast(A("mcp.higgsfieldLocked"),!0);return}const r=Cn(t.prompt,t.insertedPrompts);if(!r)return;const s=t.mcpReferenceSelection??qe();if(im(s)){e().showToast(A("mcp.referenceTagInvalid"),!0);return}const a=t.selectedElementIds??[];if(t.mcpCharacterElementId&&a.length>0){e().showToast(A("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?gl(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 $h(s);l=c.batchId;const d=pm({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 Hh(d,e,!!l)}catch(c){e().showToast(Fc(c),!0)}finally{l&&await Uh(l)}}function Qt(e){An(null,null,"image"),ne({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:qe(),mcpCharacterElementId:null,...Rr?{generate:Rr}:{}})}function rs(e,t,n,r=null,s){if(!e){Qt(t);return}Rr||(Rr=n().generate);const a=n().mcpProvider===e?n().mcpModel??r:r,i=s??n().mcpMediaKind??"image",l=n().mcpProvider!==e;An(e,a,i),ne({count:1,multimode:!1,...l?{mcpRatio:null,mcpParameters:{}}:{}}),t({mcpProvider:e,mcpModel:a,mcpMediaKind:i,...l?{mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:qe()}:{},count:1,multimode:!1,generate:()=>Kh(n)})}function Vh(e,t,n){An(n().mcpProvider??null,e,n().mcpMediaKind??"image"),ne({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:qe()})}function Bh(e,t,n,r,s){const a=cm(s);let i=s?So(s.inputRoles,r().mcpReferenceSelection):qe();const l=r().currentImage;s?.inputRoles.includes("start_image")&&!i.startFrameFilename&&l?.filename&&!xe(l)&&(i={...i,startFrameFilename:l.filename}),An(r().mcpProvider??null,e,t),ne({mcpRatio:a.ratio,mcpParameters:a.parameters}),n({mcpModel:e,mcpMediaKind:t,mcpRatio:a.ratio,mcpParameters:a.parameters,mcpInputRoles:s?[...s.inputRoles]:[],mcpReferenceSelection:i})}function Wh(e,t,n){(n().mcpMediaKind??"image")!==e&&(An(n().mcpProvider??null,null,e),ne({mcpRatio:null,mcpParameters:{}}),t({mcpMediaKind:e,mcpModel:null,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:qe()}))}function Jh(e,t){ne({mcpRatio:e}),t({mcpRatio:e})}function Yh(e,t,n,r){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))return;const s={...r().mcpParameters??{}};t===null?delete s[e]:s[e]=t,ne({mcpParameters:s}),n({mcpParameters:s})}function Xh(e,t,n){const r=So(n().mcpInputRoles??[],Io(e)),s=n().mcpReferenceSelection??qe();hl(s,r)||t({mcpReferenceSelection:r})}function Zh(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},s=pl(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??qe(),i=So(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!dm(r,s),d=!hl(a,i);!c&&!d&&!l||(c&&ne({mcpRatio:s.ratio,mcpParameters:s.parameters}),t({...c?{mcpRatio:s.ratio,mcpParameters:s.parameters}:{},mcpInputRoles:[...e.inputRoles],mcpReferenceSelection:i}))}function Qh(e,t){const n=Pm();n.provider&&(rs(n.provider,e,t,n.model,n.kind),ne({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function eg(e,t,n){Qt(t),Ch(e,t,n)}function tg(e,t){ne({quality:e}),t({quality:e})}function ng(e,t){ne({sizePreset:e}),t({sizePreset:e})}function rg(e,t,n,r){const s=Ze(e,r().customW),a=Ze(t,r().customH);ne({customW:s,customH:a}),n({customW:s,customH:a})}function sg(e,t){ne({grokAspectRatio:e}),t({grokAspectRatio:e})}function og(e,t){ne({grokResolution:e}),t({grokResolution:e})}function ag(e,t){ne({format:e}),t({format:e})}function ig(e,t){ne({moderation:e}),t({moderation:e})}function lg(e,t,n){Qt(t),jh(e,t,n)}function cg(e,t,n){Qt(t),Ph(e,t,n)}function dg(e,t,n){Qt(t),Ah(e,t,n)}function ug(e,t,n){Qt(t),Rh(e,t,n)}function mg(e){return Mh(e())}function pg(e,t){xm(e),t({reasoningEffort:e})}function fg(e,t){wm(e),t({webSearchEnabled:e})}function hg(e,t){const n=hn(e);ne({count:n}),t({count:n})}function gg(e,t,n){if(e&&n().uiMode!=="classic")return;ne({multimode:e});const r=n();t({multimode:e,multimodeSequences:e?r.multimodeSequences:{},multimodePreviewFlightId:e?r.multimodePreviewFlightId:null})}function yg(e,t){const n=hn(e);ne({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function vg(e,t){ne({promptMode:e}),t({promptMode:e})}function bg(e,t){ne({prompt:e}),t({prompt:e})}function xg(e,t){ne({negativePrompt:e}),t({negativePrompt:e})}function Ig(e,t,n,r){const s={...r().naiOptionOverrides,[e]:t};bl(s),n({naiOptionOverrides:s})}function Sg(e){bl({}),e({naiOptionOverrides:{}})}function wg(e){const{provider:t,sizePreset:n,customW:r,customH:s,grokAspectRatio:a,grokResolution:i}=e();return t==="grok"||t==="grok-api"?`grok:${a}:${i}`:n==="custom"?`${r}x${s}`:n}const ps="starred";async function _g(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(ps))return"noop";if(r)return await t.updateAsset(r.id,{tags:[...new Set([...r.tags,ps])]}),"tagged";const s=xe({...e,image:e.image??""})?"video":"image";return await t.createAsset({filePath:e.filename,kind:s,name:e.prompt?.trim().slice(0,80)||e.filename,tags:[ps],metadata:{origin:"star",mediaType:s}}),"created"}function Eg(e,t){t(n=>{const r=n.insertedPrompts.some(i=>i.id===e.id),s={...e,placement:e.placement==="after"?"after":"before"},a=r?n.insertedPrompts:[...n.insertedPrompts,s];return ne({insertedPrompts:a}),{insertedPrompts:a}})}function Ng(e,t){t(n=>{const r=n.insertedPrompts.filter(s=>s.id!==e);return ne({insertedPrompts:r}),{insertedPrompts:r,videoContinuityLineage:e.startsWith("video-continuity:")?null:n.videoContinuityLineage}})}function kg(e,t,n){n(r=>{const s=r.insertedPrompts.filter(m=>m.placement!=="after"),a=r.insertedPrompts.filter(m=>m.placement==="after"),i=[...s.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 ne({insertedPrompts:p}),{insertedPrompts:p}})}function Cg(e){ne({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function jg(e){e({promptLibraryLoading:!0});try{const t=await lu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function Pg(e,t,n){try{await cu(e),await n().loadPromptLibrary(),n().showToast(A("promptLibrary.saved"))}catch(r){console.error("[PromptLibrary] save failed",r),n().showToast(A("promptLibrary.saveFailed"),!0)}}async function Ag(e,t,n){try{await du(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function Rg(e,t,n){try{await uu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function Tg(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()||A("promptLibrary.untitled"),text:i.trim(),tags:[]})}if(r.length===0){n().showToast(A("promptLibrary.importNoValidFiles"),!0);return}const s=await mu({prompts:r});await n().loadPromptLibrary(),n().showToast(A("promptLibrary.imported",{count:s.promptsImported}))}catch(r){console.error("[PromptLibrary] import failed",r),n().showToast(A("promptLibrary.importFailed"),!0)}}async function Mg(e,t,n){const r=e.filename;if(!r)return null;let s;try{s=(await Yd(r)).isFavorite,t(i=>{const l=new Set(i.galleryFavorites);return s?l.add(r):l.delete(r),{galleryFavorites:l}}),t(i=>({history:i.history.map(l=>l.filename===r?{...l,isFavorite:s}:l),currentImage:i.currentImage?.filename===r?{...i.currentImage,isFavorite:s}:i.currentImage}))}catch(a){return console.error("[GalleryFavorite] toggle failed",a),n().showToast(A("gallery.favoriteFailed"),!0),null}if(!s)return s;try{await _g({...e,filename:r},{getAssets:so,createAsset:$r,updateAsset:Fi})!=="noop"&&n().showToast(A("assets.starSaved"))}catch(a){console.error("[GalleryFavorite] asset sync failed",a),n().showToast(A("assets.starSaveFailed"),!0)}return s}async function Lg(e,t,n){if(e){Xl(e),t(r=>{const s=r.inFlight.map(a=>a.id===e?{...a,phase:"canceling"}:a);return Re(s),{inFlight:s}});try{await Ce(e),n().startInFlightPolling()}catch{n().showToast(A("toast.cancelFailed"),!0)}}}function Fg(e,t){const n=Rl(),r=xl(),s=kl(),a=Wr();e(i=>{const l=r?i.history.find(p=>p.filename===r)??null:null,c=l?et(i.history,l):null,d=Pt(i.history)[0]??null,u=i.currentImage?.canvasVersion?et(i.history,i.currentImage)??d:i.currentImage;return{inFlight:n,activeGenerations:n.length,...s,videoDuration:a.duration,videoResolution:a.resolution,videoAspectRatio:a.aspectRatio,currentImage:r&&u?.filename!==r?c??u:u}}),n.length>0&&t().startInFlightPolling()}function Og(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):Jr([e,...n.history],n.loadedHistoryRetainLimit+1):n.history,loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,Math.min(n.history.length+1,n.loadedHistoryRetainLimit+1))}))}function Dg(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function Gg(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(Vi,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function zg(e,t){try{localStorage.setItem(go,e)}catch{}t({galleryScope:e})}function qg(e,t){try{localStorage.setItem(Qi,e),localStorage.setItem(go,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function $g(e,t){const n=e==="card-news"&&!nl?"classic":e;try{localStorage.setItem(Bi,n)}catch{}t({uiMode:n})}function Ug(e,t){try{localStorage.setItem(Wi,e)}catch{}t({historyStripLayout:e})}function Hg(e,t,n){const r=Date.now(),s={message:e,error:t,id:r+Math.random(),createdAt:r};n(a=>({toast:s,toastLog:[...a.toastLog,s].slice(-50)}))}function Kg(e,t){t(n=>{const r=n.toastLog.filter(s=>s.id!==e);return{toastLog:r,toast:n.toast?.id===e?r[r.length-1]??null:n.toast}})}function Vg(e,t,n){const r=Date.now(),s={code:e,cardKey:t?.cardKey,cta:t?.cta,fallbackMessage:t?.fallbackMessage,id:r+Math.random(),createdAt:r};n(a=>({errorCard:s,errorCardLog:[...a.errorCardLog,s]}))}function Bg(e,t){t(n=>{if(e==null)return{errorCard:null,errorCardLog:[]};const r=n.errorCardLog.filter(s=>s.id!==e);return{errorCardLog:r,errorCard:n.errorCard?.id===e?r[r.length-1]??null:n.errorCard}})}function Wg(e,t,n){t({graphNodes:Qe(e,n().graphEdges)}),n().scheduleGraphSave()}function Jg(e,t,n){t({graphEdges:e,graphNodes:Qe(n().graphNodes,e)}),n().scheduleGraphSave()}function Yg(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:gn(t().graphNodes,[])}})}function Xg(e,t,n,r){n({graphNodes:Mm(r().graphNodes,r().graphEdges,e,t)})}function Zg(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(A("nodeBatch.stopQueued")))}function Qg(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function ey(e,t,n){t({canvasExportBackground:e}),yl(e,n().canvasExportMatteColor)}function ty(e,t,n){t({canvasExportMatteColor:e}),yl(n().canvasExportBackground,e)}const it=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let fs=0;async function Oc(e){const{folders:t}=await oo();e({assetsFolders:t})}const Ho=Oc;async function Ko(e,t,n){const r=e!==!1;if(!r&&n().assetsLoading)return;const s=++fs;t({assetsLoading:!0,...r?{assetsLoadError:!1}:{}});try{const a=n().assetsFilters,i=await so({...a,cursor:r?null:n().assetsCursor}),l=r?await Promise.all([oo(),ao()]):null;if(s!==fs)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){it(a),s===fs&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function ny(e,t){!t().assetsCursor||t().assetsLoading||await Ko(!1,e,t)}function za(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),Ko(!0,t,n)}async function ry(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(([,s])=>s!==void 0));try{const s=n().selectedProjectId??void 0,{asset:a}=await $r({filePath:e.filename,kind:xe(e)?"video":"image",name:(e.prompt||"").trim().slice(0,80)||e.filename,folderId:s,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(s){return it(s),!1}}async function sy(e,t,n){try{const{asset:r}=await Fi(e,t);let s=null;try{s=(await ao()).tags}catch(a){it(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),...s?{assetsTags:s}:{}}}),!0}catch(r){return it(r),!1}}async function oy(e,t){try{return await hu(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return it(n),!1}}async function ay(e,t,n){try{return await gu({name:e,parentId:t}),await Ho(n),!0}catch(r){return it(r),!1}}async function iy(e,t,n){try{return await Oi(e,{name:t}),await Ho(n),!0}catch(r){return it(r),!1}}async function ly(e,t,n){try{return await Oi(e,{parentId:t}),await Ho(n),!0}catch(r){return it(r),!1}}async function cy(e,t){try{await yu(e);const[{folders:n},{tags:r}]=await Promise.all([oo(),ao()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return it(n),!1}}function dy(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(ku(e.imageModel)||Cu(e.imageModel)))return e.imageModel}async function Dc(e,t,n){if(!e.filename)return;const r=n();try{await $r({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(s=>({assetGenSaveFailures:s.assetGenSaveFailures.filter(a=>a!==e.requestId)}))}catch{t(s=>({assetGenSaveFailures:s.assetGenSaveFailures.includes(e.requestId??"")?s.assetGenSaveFailures:[...s.assetGenSaveFailures,e.requestId??""]}))}}async function uy(e,t,n){const r=n().assetGenItems.find(s=>s.requestId===e);r&&(r.mediaType==="video"?await Gc(r,t,n):await Dc(r,t,n))}async function my(e,t,n,r){const s=n(),a=s.assetGenPrompt.trim(),i=await ro({prompt:a,provider:"grok",duration:s.assetGenVideoDuration,resolution:s.assetGenVideoResolution,aspectRatio:s.assetGenVideoAspect,requestId:e,backgroundPreset:s.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:s.assetGenBackground,createdAt:Date.now()};await ft(l,t,n,{autoSelectStartedAt:Date.now()}),t(c=>({assetGenItems:[l,...c.assetGenItems]})),await Gc(l,t,n),n().showToast(A("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function Gc(e,t,n){if(!e.filename)return;const r=n();try{await $r({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(s=>({assetGenSaveFailures:s.assetGenSaveFailures.filter(a=>a!==e.requestId)}))}catch{t(s=>({assetGenSaveFailures:s.assetGenSaveFailures.includes(e.requestId??"")?s.assetGenSaveFailures:[...s.assetGenSaveFailures,e.requestId??""]}))}}async function py(e,t){const n=t(),r=n.assetGenPrompt.trim();if(!r)return;const s=`f_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,a=new AbortController;Xt(s,a);const i=Date.now(),l=[...n.inFlight,{id:s,prompt:r,startedAt:i}];Re(l),e({assetGenLastError:null,activeGenerations:n.activeGenerations+1,inFlight:l}),t().startInFlightPolling();try{if(n.assetGenKind==="video"){await my(s,e,t,a);return}const c={prompt:r,quality:n.quality,size:"1024x1024",format:"png",moderation:n.moderation,provider:n.assetGenProvider,n:1,model:dy(n),requestId:s,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await Ti(c,{signal:a.signal}),u=Bs(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??s,quality:d.quality,size:d.size,model:d.model??null,backgroundPreset:n.assetGenBackground,createdAt:(u?u.createdAt:d.createdAt)??Date.now()};await ft(p,e,t,{autoSelectStartedAt:i}),e(m=>({assetGenItems:[p,...m.assetGenItems]})),await Dc(p,e,t),t().showToast(A("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!Jt(c)){const d=$e(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!==s);Re(c),Zt(s),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function fy(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function tn(e){ne({presetIds:e})}const hy=e=>({selectedPresetIds:Pn().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return tn(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(s=>s!==t);return tn(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(s=>s!==t):[...n.selectedPresetIds,t];return tn(r),{selectedPresetIds:r}}),clearPresets:()=>{tn([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=fy(t);tn(n),e({selectedPresetIds:n})}});function gy(){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 Gn=(e,t="POST",n)=>({method:t,signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),yy=e=>z("/api/sprite-recipes",{signal:e}),vy=(e,t)=>z(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),by=(e,t)=>z("/api/sprite-recipes",Gn(e,"POST",t)),xy=(e,t,n)=>z(`/api/sprite-recipes/${encodeURIComponent(e)}`,Gn(t,"PATCH",n)),Iy=(e,t={},n)=>z(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Gn({...t,async:!0},"POST",n)),Sy=(e,t,n)=>z(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,Gn({assetId:t},"POST",n)),wy=(e,t={},n)=>z(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,Gn({...t,async:!0},"POST",n)),qt=new Map,zn=e=>e instanceof Error?e.message:String(e),zc=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function _y(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await yy();e({spriteRecipes:n.map(zc)}),t().activeSpriteRecipeId&&await Vo(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:zn(n)})}finally{e({spriteRecipeLoading:!1})}}async function Vo(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await vy(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:zn(r)})}finally{t({spriteRecipeLoading:!1})}}async function Ey(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await xy(n.activeSpriteRecipeId,n.spriteRecipeDraft):await by(n.spriteRecipeDraft);return e(s=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[zc(r.recipe),...s.spriteRecipes.filter(a=>a.id!==r.recipe.id)]})),r.recipe.id}catch(n){return e({spriteRecipeError:zn(n)}),null}finally{e({spriteRecipeSaving:!1})}}function qc(e,t,n){qt.get(e)?.(),qt.set(e,kt(e,null,(r,s)=>Py({event:r,data:{...s,requestId:e}},t,n)))}function Bo(e){qt.get(e)?.(),qt.delete(e)}function $c(e,t){return tt(e).code==="JOB_TRACKING_TIMEOUT"?$e(e,t()).message:zn(e)}async function Ny(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{qc(r,e,t),await no(),await Iy(n,{requestId:r,async:!0})}catch(s){Bo(r),e({spriteRecipeError:$c(s,t),spriteRecipeGenerating:!1})}}async function ky(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:s}=await Sy(r,e);t({activeSpriteRecipe:s,spriteRecipeDraft:s,spriteRecipeDirty:!1})}catch(s){t({spriteRecipeError:zn(s)})}finally{t({spriteRecipeGenerating:!1})}}}async function Cy(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const s=crypto.randomUUID();try{qc(s,t,n),await no(),await wy(r,{requestId:s,stateKeys:e,async:!0})}catch(a){Bo(s),t({spriteRecipeError:$c(a,n),spriteRecipeGenerating:!1})}}async function jy(e,t,n){qt.get(e)?.(),qt.delete(e),t({spriteRecipeGenerating:!1})}function Py(e,t,n){const r=e.data.stateKey,s=e.data.url??e.data.image??e.data.previewUrl;if(r&&s&&t(a=>({spritePartialPreviews:{...a.spritePartialPreviews,[r]:s}})),(e.event==="error"||e.event==="done")&&Bo(String(e.data.requestId??"")),e.event==="error"){const a=String(e.data.message??"Generation failed"),i=at(e.data,a),l=tt(i).code==="JOB_TRACKING_TIMEOUT"?$e(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&Vo(a,t)}}function Ay(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const Pe=Pn(),Xn=Wr(),Zn=kl(),f=Ci((e,t,n)=>({...hy(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:gy(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>_y(e,t),selectSpriteRecipe:r=>Vo(r,e),updateSpriteRecipeDraft:r=>Ay(r,e),saveSpriteRecipe:()=>Ey(e,t),generateSpriteAnchor:()=>Ny(e,t),approveSpriteAnchor:r=>ky(r,e,t),generateSpriteRows:r=>Cy(r,e,t),cancelSpriteJob:r=>jy(r,e),assetsFolders:[],assetsTags:[],assetsLoading:!1,assetsLoadError:!1,assetsCursor:null,assetsFilters:{kind:null,folderId:null,tag:null,q:""},assetGenPrompt:"",assetGenBackground:"chroma-green",assetGenProvider:Zn.provider==="grok"||Zn.provider==="grok-api"?Zn.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(s=>r.filename&&s.assetGenItems.some(a=>a.filename===r.filename)?{}:{assetGenItems:[r,...s.assetGenItems]}),selectedProjectId:null,setSelectedProject:r=>{e({selectedProjectId:r}),za({folderId:r},e,t)},loadAssetFolders:()=>Oc(e),retryAssetGenSave:r=>uy(r,e,t),setAssetGenPrompt:r=>e({assetGenPrompt:r}),setAssetGenBackground:r=>e({assetGenBackground:r}),setAssetGenProvider:r=>e(s=>({assetGenProvider:r,...(r==="grok"||r==="grok-api")&&s.assetGenBackground==="transparent"?{assetGenBackground:"chroma-green"}:{}})),setAssetGenKind:r=>e({assetGenKind:r}),generateAssetGen:()=>py(e,t),loadAssets:r=>Ko(r,e,t),loadMoreAssets:()=>ny(e,t),setAssetsFilters:r=>za(r,e,t),saveToAssets:r=>ry(r,e,t),updateAssetItem:(r,s)=>sy(r,s,e),deleteAssetItem:r=>oy(r,e),createAssetFolder:(r,s)=>ay(r,s,e),renameAssetFolder:(r,s)=>iy(r,s,e),moveAssetFolder:(r,s)=>ly(r,s,e),deleteAssetFolder:r=>cy(r,e),...Zn,quality:Pe.quality??"medium",sizePreset:Pe.sizePreset??"1024x1024",customW:Pe.customW??1920,customH:Pe.customH??1088,grokAspectRatio:Pe.grokAspectRatio??"1:1",grokResolution:Pe.grokResolution??"1k",format:Pe.format??"png",moderation:Pe.moderation??"low",count:Pe.count??1,multimode:Pe.multimode??!1,multimodeMaxImages:Pe.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:Pe.promptMode??"auto",prompt:Pe.prompt??"",negativePrompt:Pe.negativePrompt??"",naiOptionOverrides:Im(),naiServerDefaults:null,insertedPrompts:Pe.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:qe(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:No,activeReferenceLimit:()=>Yl({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>Mp(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:Pi(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:Ca().mode,canvasExportMatteColor:Ca().matteColor,syncCapabilities:()=>$m(e),addTrayAttachments:async r=>gh(r,e),addTrayAttachmentDataUrl:(r,s)=>ns(r,s,e),addTrayElement:r=>br(r,e),addElementFromMention:r=>br(r.id,e,t,r),syncElementCatalog:r=>oc(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>Rc(r,e,t),clearTray:()=>wh(e,t),addElementId:r=>{br(r,e)},removeElementId:r=>Op(r,e),addReferences:r=>vh(r,e,t),addReferenceDataUrl:r=>yh(r,e),metadataRestore:null,readDroppedImageMetadata:(r,s=null)=>bh(r,s,e,t),applyMetadataRestore:()=>xh(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>Dg(e,t),removeReference:r=>Ih(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>Sh(e,t),attachCanvasVersionReference:(r,s)=>Eh(r,e,t,s),useCurrentAsReference:()=>Nh(e,t),useImageAsReference:r=>kh(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>Lg(r,e,t),startInFlightPolling:()=>{bf(e,t)},reconcileInflight:async()=>{await xf(e,t)},syncFromStorage:()=>Fg(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>Og(r,e),addGeneratedHistoryItem:async r=>{await ft(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:ze,loadOlderHistory:async()=>Yf(e,t),loadFavoriteHistory:async()=>Xf(e,t),loadOlderFavoriteHistory:async()=>Zf(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:gm(),toggleRightPanel:()=>Gg(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:ka(go),galleryDefaultScope:ka(Qi),setGalleryScope:r=>zg(r,e),setGalleryDefaultScope:r=>qg(r,e),reasoningEffort:bm(),webSearchEnabled:Sm(),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:ym(),setUIMode:r=>$g(r,e),historyStripLayout:vm(),setHistoryStripLayout:r=>Ug(r,e),locale:wd(),setLocale:r=>{Sd(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const s=t();e({graphHistoryPast:op(s.graphHistoryPast,us(s.graphNodes,s.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),s=ap(r.graphHistoryPast,us(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!s)return!1;const a=Ma(s.restored,r.graphNodes);return e({graphNodes:Qe(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),s=ip(r.graphHistoryPast,us(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!s)return!1;const a=Ma(s.restored,r.graphNodes);return e({graphNodes:Qe(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>Wg(r,e,t),setGraphEdges:r=>Jg(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>Mf(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>Yg(e,t),selectAllGraphNodes:()=>{e({graphNodes:gn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,s)=>Xg(r,s,e,t),clearNodeSelection:()=>{e({graphNodes:gn(t().graphNodes,[])})},cancelNodeBatch:()=>Zg(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await Pc(e,t)},async switchSession(r){await dh(r,e,t)},async reconcileGraphPending(){await uh(e,t)},async createAndSwitchSession(r){await mh(r,e,t)},async renameCurrentSession(r){await ph(r,e,t)},async deleteSessionById(r){await fh(r,e,t)},scheduleGraphSave(){Wl(t,e)},async flushGraphSave(r="manual"){await tp(t,e,r)},addRootNode:()=>Ef(e,t),createRootNodeFromHistoryItem:r=>Nf(r,e,t),addChildNode:r=>kf(r,e,t),addSiblingNode:r=>Cf(r,e,t),updateNodePrompt:(r,s)=>Af(r,s,e,t),addNodeReferences:async(r,s)=>Ff(r,s,e,t),addNodeReferenceDataUrl:(r,s)=>Ic(r,s,e,t),addNodeReferenceFromUrl:async(r,s,a)=>Of(r,s,a,e,t),removeNodeReference:(r,s)=>Df(r,s,e,t),clearNodeReferences:r=>Gf(r,e,t),duplicateBranchRoot:r=>Pf(r,e,t),generateNode:r=>sf(r,e,t),generateNodeInPlace:r=>of(r,e,t),generateNodeVariation:(r,s)=>af(r,s,e,t),runGenerateNode:(r,s)=>lf(r,s,e,t),async runGenerateNodeInPlace(r,s={}){return zp(r,s,e,t,Re)},async runNodeBatch(r){await qp(r,e,t)},deleteNode:r=>Rf(r,e,t),deleteNodes:r=>Tf(r,e,t),addChildNodeAt:(r,s,a)=>jf(r,s,a,e,t),connectNodes:(r,s,a,i)=>Lf(r,s,a,i,e,t),setProvider:r=>eg(r,e,t),setQuality:r=>tg(r,e),setSizePreset:r=>ng(r,e),setCustomSize:(r,s)=>rg(r,s,e,t),setGrokAspectRatio:r=>sg(r,e),setGrokResolution:r=>og(r,e),setFormat:r=>ag(r,e),setModeration:r=>ig(r,e),setImageModel:r=>lg(r,e,t),videoDuration:Xn.duration,videoResolution:Xn.resolution,videoSingleRefMode:Xn.singleRefMode,videoAspectRatio:Xn.aspectRatio,videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>cg(r,e,t),setComfyWorkflow:r=>dg(r,e,t),setComfyVideoWorkflow:r=>ug(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),ln({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),ln({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),ln({aspectRatio:r})},setVideoSingleRefMode:r=>{e({videoSingleRefMode:r}),ln({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>mg(t),runVideoGenerate:async r=>{await cf(r,e,t)},animateImage:async(r,s)=>df(r,s,e,t),setReasoningEffort:r=>pg(r,e),setWebSearchEnabled:r=>fg(r,e),setCount:r=>hg(r,e),setMultimode:r=>gg(r,e,t),setMultimodeMaxImages:r=>yg(r,e),setPromptMode:r=>vg(r,e),setPrompt:r=>bg(r,e),setNegativePrompt:r=>xg(r,e),setNaiOption:(r,s)=>Ig(r,s,e,t),resetNaiOptions:()=>Sg(e),insertPromptToComposer:r=>Eg(r,e),removeInsertedPromptFromComposer:r=>Ng(r,e),moveInsertedPromptInComposer:(r,s)=>kg(r,s,e),clearInsertedPrompts:()=>Cg(e),selectHistory:r=>Qf(r,e,t),showHistorySequence:r=>eh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>th(r,e,t),trashHistoryItem:async r=>nh(r,e,t),trashHistorySequence:async r=>rh(r,e,t),restorePendingTrash:async()=>sh(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>oh(r,e,t),removeFromHistory:r=>ah(r,e,t),addHistoryItem:r=>ih(r,e,t),importLocalImageToHistory:async r=>lh(r,e,t),getResolvedSize:()=>wg(t),generate:()=>tf(e,t),async generateMultimode(r){await Vp(r,e,t)},cancelMultimode:()=>nf(e,t),async runGenerate(r){await Bp(r,e,t)},confirmCustomSizeAdjustment:()=>rf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){ch(e)},showToast:(r,s=!1)=>Hg(r,s,e),dismissToast:r=>Kg(r,e),showErrorCard:(r,s)=>Vg(r,s,e),dismissErrorCard:r=>Bg(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:()=>jg(e),savePromptToLibrary:r=>Pg(r,e,t),deletePromptFromLibrary:r=>Ag(r,e,t),togglePromptFavorite:r=>Rg(r,e,t),importPromptsToLibrary:r=>Tg(r,e,t),toggleGalleryFavorite:r=>Mg(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,s)=>Qg(r,s,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>ey(r,e,t),setCanvasExportMatteColor:r=>ty(r,e,t)})),Ry=/^[\p{L}\p{N}_-]$/u,Ty=new Set([" "," ","(","["]);function My(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
7
  `;){if(!Ry.test(e[r-1]))return null;r-=1}if(r===0||e[r-1]!=="@")return null;const s=r-1,a=e[s-1];return a!==void 0&&!Ty.has(a)&&a!==`
8
8
  `?null:{start:s,end:n,query:e.slice(r,n)}}function Oe({title:e,help:t,items:n,value:r,onChange:s,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(),s(m.value),i.current?.querySelector(`[data-value="${m.value}"]`)?.focus()};return o.jsxs("div",{className:`option-group${a?` ${a}`:""}`,children:[e?o.jsx("div",{className:"section-title",children:e}):null,o.jsx("div",{className:"option-row",role:"group",ref:i,onKeyDown:l,children:n.map(c=>o.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:()=>s(c.value),children:[c.label,c.sub?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:c.sub})]}):null]},c.value))}),t?o.jsx("p",{className:"option-help",children:t}):null]})}var ss=_d();function Ly(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Fy=(e,t)=>{if(e&&e.length>0){const r=e.filter(s=>s.items.length>0);return{flat:r.flatMap(s=>[...s.items]),rendered:r}}const n=t??[];return{flat:[...n],rendered:[{items:n}]}},qa=(e,t,n)=>{if(t==="first"){const r=e.findIndex(s=>!s.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 Fe({items:e,groups:t,value:n,onChange:r,ariaLabel:s,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),[S,w]=v.useState({top:0,left:0,width:200,maxHeight:260}),{flat:j,rendered:P}=Fy(t,e),M=j.length===0,[q,N]=v.useState(()=>Math.max(0,j.findIndex(O=>O.value===n))),R=v.useRef({buffer:"",at:0}),$=j.find(O=>O.value===n),k=O=>`${b}-opt-${O}`,J=O=>O.searchText?O.searchText:typeof O.label=="string"?O.label:O.value,T=O=>{const Q=Date.now(),V=R.current;V.buffer=Q-V.at>1e3?O:V.buffer+O,V.at=Q;const ae=V.buffer.toLowerCase(),fe=V.buffer.length===1?q+1:q;for(let ie=0;ie<j.length;ie+=1){const Ee=(fe+ie+j.length)%j.length,he=j[Ee];if(!(!he||he.disabled)&&J(he).toLowerCase().startsWith(ae)){N(Ee);return}}};v.useEffect(()=>{if(!g)return;const O=Q=>{const V=Q.target;V instanceof Node&&(I.current?.contains(V)||y.current?.contains(V)||_(!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 fe=Math.max(0,window.innerWidth-24),ie=Math.min(300,fe,Math.max(190,O.width)),Ee=Math.max(12,window.innerWidth-ie-12),he=Math.min(Math.max(12,O.left),Ee),Se=window.innerHeight-O.bottom-12,Ne=O.top-12,ke=Se>=160||Se>=Ne?"down":"up",D=Math.max(0,ke==="down"?Se:Ne),le=Math.min(420,D),se=8+j.length*44,G=y.current?.scrollHeight??se,C=Math.min(G,le);w({top:ke==="down"?O.bottom+4:Math.max(12,O.top-C-4),left:he,width:ie,maxHeight:le})}const Q=()=>_(!1),V=ae=>{Ly(ae,y.current)&&_(!1)};return window.addEventListener("resize",Q),window.addEventListener("scroll",V,!0),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",V,!0)}},[d,g]),v.useEffect(()=>{g&&y.current?.querySelector(`[data-index="${q}"]`)?.scrollIntoView({block:"nearest"})},[g,q]);const Z=()=>{M||(N(Math.max(0,j.findIndex(O=>O.value===n))),_(!0))};v.useEffect(()=>{M&&(_(!1),N(0))},[M]);const te=O=>{let Q=q;for(let V=0;V<j.length&&(Q=(Q+O+j.length)%j.length,!!j[Q]?.disabled);V+=1);N(Q)},de=O=>{const Q=j[O];!Q||Q.disabled||(r(Q.value),_(!1),x.current?.focus())},ye=O=>{if(!g){["Enter"," ","ArrowDown","ArrowUp"].includes(O.key)&&(O.preventDefault(),Z());return}if(O.key==="Escape")O.preventDefault(),_(!1);else if(O.key==="ArrowDown")O.preventDefault(),te(1);else if(O.key==="ArrowUp")O.preventDefault(),te(-1);else if(O.key==="Home")O.preventDefault(),N(qa(j,"first",q));else if(O.key==="End")O.preventDefault(),N(qa(j,"last",q));else if(O.key==="Enter"||O.key===" "){if(O.key===" "&&Date.now()-R.current.at<=1e3&&R.current.buffer){O.preventDefault(),T(" ");return}O.preventDefault(),de(q)}else O.key==="Tab"?_(!1):O.key.length===1&&!O.metaKey&&!O.ctrlKey&&!O.altKey&&(O.preventDefault(),T(O.key))};let ve=-1;const F=g&&!M?o.jsx("ul",{className:`ctl-select__list${d?" ctl-select__list--portal":""}`,role:"listbox",id:b,ref:y,style:d?{position:"fixed",top:S.top,left:S.left,width:S.width,maxHeight:S.maxHeight}:void 0,children:P.map((O,Q)=>o.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[O.label?o.jsx("div",{className:"ctl-select__group-label",children:O.label}):null,o.jsx("ul",{role:"group","aria-label":typeof O.label=="string"?O.label:void 0,className:"ctl-select__group-items",children:O.items.map(V=>{ve+=1;const ae=ve;return o.jsxs("li",{role:"option",id:k(ae),"data-index":ae,"aria-selected":V.value===n,"aria-disabled":V.disabled||void 0,title:V.title,className:`ctl-select__item${V.value===n?" is-selected":""}${ae===q?" is-active":""}${V.disabled?" is-disabled":""}${V.stacked?" is-stacked":""}`,onPointerEnter:()=>N(ae),onClick:()=>de(ae),children:[o.jsx("span",{className:"ctl-select__item-label",children:V.label}),V.sub?o.jsx("span",{className:"ctl-select__item-sub",children:V.sub}):null]},V.value)})})]},`g-${Q}`))}):null;return o.jsxs("div",{className:`ctl-select${i?` ${i}`:""}`,ref:I,children:[o.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&&j[q]?k(q):void 0,"aria-label":s,"aria-describedby":a,disabled:c||M,title:h,onClick:()=>g?_(!1):Z(),onKeyDown:ye,children:[o.jsx("span",{className:"ctl-select__value",children:u??$?.label??m??""}),p??$?.sub?o.jsx("span",{className:"ctl-select__value-sub",children:p??$?.sub}):null,o.jsx("svg",{className:"ctl-select__caret",width:"10",height:"10",viewBox:"0 0 10 10","aria-hidden":"true",children:o.jsx("path",{d:"M2 3.5 5 6.5 8 3.5",fill:"none",stroke:"currentColor",strokeWidth:"1.4"})})]}),F?d?ss.createPortal(F,document.body):F:null]})}function Oy({checked:e,onChange:t,label:n,ariaLabel:r,className:s,disabled:a,id:i}){return o.jsxs("button",{type:"button",id:i,role:"switch","aria-checked":e,"aria-label":r,disabled:a,className:`ctl-toggle${e?" is-on":""}${s?` ${s}`:""}`,onClick:()=>t(!e),children:[o.jsx("span",{className:"ctl-toggle__track","aria-hidden":"true",children:o.jsx("span",{className:"ctl-toggle__thumb"})}),n?o.jsx("span",{className:"ctl-toggle__label",children:n}):null]})}function Uc({selected:e,onSelect:t,onRemove:n,removeLabel:r,disabled:s,className:a,children:i,title:l}){return o.jsxs("span",{className:`ctl-chip${e?" is-selected":""}${s?" is-disabled":""}${a?` ${a}`:""}`,children:[o.jsx("button",{type:"button",className:"ctl-chip__body","aria-pressed":t?e:void 0,disabled:s,title:l,onClick:t,children:i}),n?o.jsx("button",{type:"button",className:"ctl-chip__remove","aria-label":r,disabled:s,onClick:n,children:o.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8","aria-hidden":"true",children:o.jsx("path",{d:"M1 1l6 6M7 1L1 7",stroke:"currentColor",strokeWidth:"1.3"})})}):null]})}function Wo({className:e,children:t,ariaLabel:n}){return o.jsx("div",{className:`ctl-chip-row${e?` ${e}`:""}`,role:"group","aria-label":n,children:t})}function Dy(){return o.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",children:o.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 Hc({active:e,label:t,variant:n,busy:r=!1,onToggle:s}){const a=c=>{c.stopPropagation()},i=c=>{c.stopPropagation()},l=c=>{(c.key==="Enter"||c.key===" ")&&c.stopPropagation()};return o.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(),s()},children:o.jsx(Dy,{})})}function Gy(){return o.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:o.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 $a=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 $y(e,t){const n=qy(e,t),r=window.innerHeight-n.bottom,s=r<zy?"top":"bottom",a=s==="bottom"?r:n.top;return{left:Math.max($a,Math.min(n.left,window.innerWidth-332)),top:s==="bottom"?n.bottom+6:Math.max($a,n.top-Math.min(320,a-8)),placement:s,maxHeight:Math.max(120,Math.min(320,a-12))}}function Uy(){return window.matchMedia("(max-width: 640px)").matches}function Hy({open:e,textareaRef:t,composingRef:n,caret:r,query:s,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),S=v.useMemo(()=>{const M=s.trim().toLocaleLowerCase();return M?a.filter(q=>[q.name,...q.tags??[]].some(N=>N.toLocaleLowerCase().includes(M))):a},[a,s]),w=M=>{b(M),p?.(M)},j=()=>{const M=S[h];M&&d(M)};if(v.useLayoutEffect(()=>{if(!e||!t.current)return;const M=()=>{if(!t.current){u();return}g(Uy()),x($y(t.current,r))},q=()=>requestAnimationFrame(M);return M(),window.addEventListener("resize",q),t.current.addEventListener("scroll",q),()=>{window.removeEventListener("resize",q),t.current?.removeEventListener("scroll",q)}},[e,t,r,u]),v.useEffect(()=>{w(0)},[s,S.length]),v.useEffect(()=>{if(!e)return;const M=t.current;if(!M)return;M.setAttribute("aria-controls",m),M.setAttribute("aria-expanded","true");const q=N=>{if(document.activeElement===M&&!(n?.current||N.isComposing||N.keyCode===229)&&!(N.key==="Enter"&&(N.ctrlKey||N.metaKey))){if(N.key==="Escape"){N.preventDefault(),u("escape");return}N.key==="ArrowDown"||N.key==="ArrowUp"?(N.preventDefault(),w((h+(N.key==="ArrowDown"?1:-1)+S.length)%Math.max(1,S.length))):N.key==="Home"?(N.preventDefault(),w(0)):N.key==="End"?(N.preventDefault(),w(Math.max(0,S.length-1))):N.key==="Enter"?S.length&&(N.preventDefault(),j()):N.key==="Tab"&&S.length&&j()}};return M.addEventListener("keydown",q),()=>{M.removeAttribute("aria-controls"),M.removeAttribute("aria-expanded"),M.removeAttribute("aria-activedescendant"),M.removeEventListener("keydown",q)}},[e,t,n,m,h,S,u]),v.useEffect(()=>{const M=t.current,q=S[h];M&&q&&M.setAttribute("aria-activedescendant",`${m}-${q.id}`)},[h,S,m,t]),v.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const P=o.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:o.jsx("ul",{id:m,className:"element-mention-menu__list",role:"listbox",ref:_,children:S.length?S.map((M,q)=>o.jsxs("li",{id:`${m}-${M.id}`,role:"option","aria-selected":q===h,className:`element-mention-menu__option${q===h?" is-active":""}`,onPointerEnter:()=>w(q),onMouseDown:N=>{N.preventDefault(),d(M)},children:[M.thumbnail?o.jsx("img",{src:M.thumbnail,alt:"",className:"element-mention-menu__thumbnail"}):o.jsx("span",{className:"element-mention-menu__thumbnail is-empty","aria-hidden":"true"}),o.jsxs("span",{className:"element-mention-menu__copy",children:[o.jsx("strong",{children:M.name}),o.jsx("small",{children:c(M.kind)})]})]},M.id)):o.jsx("li",{className:"element-mention-menu__empty",role:"presentation",children:l})})});return ss.createPortal(P,document.body)}function Ky(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function Vy(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??Ky(e.source.referenceFilenames[0])}function By({items:e,limit:t,onRemove:n,onAdd:r}){const{t:s}=H(),a=e.length>t,i=e.length>=t;return o.jsxs("div",{className:"composer__tray-wrap",children:[o.jsxs("div",{className:"composer__tray",role:"list","aria-label":s("prompt.trayAria",{count:e.length,max:t}),children:[e.map((l,c)=>{const d=Vy(l);return o.jsxs("div",{className:"composer__tray-slot",role:"listitem","aria-label":`@${l.tag}, ${c+1}/${t}`,children:[o.jsxs("span",{className:"composer__tray-thumbnail",children:[d?o.jsx("img",{src:d,alt:"",loading:"lazy",decoding:"async"}):o.jsx("span",{className:"composer__tray-thumbnail-empty","aria-hidden":"true",children:"@"}),o.jsx("button",{type:"button",className:"composer__tray-remove",onClick:()=>n(l.tokenId),"aria-label":`${s("prompt.refRemoveAria",{n:c+1})}: @${l.tag}`,children:"×"})]}),o.jsxs("span",{className:"composer__tray-tag",title:`@${l.tag}`,children:["@",l.tag]})]},l.tokenId)}),o.jsx("button",{type:"button",className:"composer__tray-slot composer__tray-slot--add",onClick:r,disabled:i,"aria-label":s("prompt.attachTitle"),title:s("prompt.attachTitle"),children:o.jsx("span",{"aria-hidden":"true",children:"+"})})]}),a?o.jsx("p",{className:"composer__ref-warning",role:"alert",children:s("prompt.refOverProviderLimit",{max:t,excess:e.length-t})}):null]})}function Wy({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 o.jsx("svg",{className:"element-mention-chip__kind",viewBox:"0 0 16 16","aria-hidden":"true",children:o.jsx("path",{d:t[e]})})}function Jy({elementId:e,name:t,kind:n,thumbnail:r,missing:s,ariaLabel:a,unavailableLabel:i,removeLabel:l,onRemove:c,onOpen:d}){return o.jsxs("span",{className:`element-mention-chip${s?" is-missing":""}`,"data-element-id":e,children:[o.jsxs("button",{type:"button",className:"element-mention-chip__body",onClick:()=>d?.(e),"aria-label":a,children:[r?o.jsx("img",{className:"element-mention-chip__thumbnail",src:r,alt:""}):o.jsx("span",{className:"element-mention-chip__thumbnail is-empty","aria-hidden":"true"}),s?o.jsx("span",{className:"element-mention-chip__warning","aria-label":i,children:"!"}):o.jsx(Wy,{kind:n}),o.jsx("span",{className:"element-mention-chip__name",children:t})]}),o.jsx("button",{type:"button",className:"element-mention-chip__remove",onClick:()=>c(e),"aria-label":l,children:o.jsx("svg",{viewBox:"0 0 16 16","aria-hidden":"true",children:o.jsx("path",{d:"m4 4 8 8m0-8-8 8"})})})]})}const Yy=new Set(["character","product","style","scene"]);function Xy(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&Yy.has(t)?t:"character"}function Zy(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 Qy(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),s=new Set(n);return tc({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:Xy(i),thumbnail:Zy(i)??a.source.thumbnailUrl,missing:s.has(a.source.elementId)||t!==null&&!i}})}function ev(e){const t=Qy(e.items,e.assets,e.missingElementIds);return t.length===0?null:o.jsx(Wo,{ariaLabel:e.selectedLabel,children:t.map(n=>{const r=e.kindLabel(n.kind);return o.jsx(Jy,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const tv=["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 nv({prompt:e,retiredTags:t,textareaRef:n}){const{t:r}=H(),s=v.useRef(null),a=v.useRef(null),[i,l]=v.useState([]),c=v.useMemo(()=>Tp(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=s.current,m=a.current?.firstChild;if(!u||!p||!(m instanceof Text)){l([]);return}const h=()=>{const I=getComputedStyle(u);tv.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((S,w)=>{y.push({key:`${g.start}-${g.end}-${w}`,left:S.left-x.left+p.scrollLeft,top:S.top-x.top+p.scrollTop,width:S.width,height:S.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]),o.jsxs(o.Fragment,{children:[o.jsxs("div",{ref:s,className:"composer__prompt-mirror","aria-hidden":"true",children:[o.jsx("span",{ref:a,children:e}),i.map(u=>o.jsx("span",{className:"dead-tag",style:u},u.key))]}),o.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 os(e){const t=f.getState(),n=xe(e),r=!!e.prompt;if(t.clearReferences(),t.setPrompt(r&&!n?e.prompt:""),n){const s=e.url||e.image,a=await Yt(s);t.addReferenceDataUrl(a);const i=uc(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(Qp(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 Kc(e){const t=await os(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const rv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:os,continueFromItemAsUrl:Kc},Symbol.toStringTag,{value:"Module"}));function sv({text:e,mode:t,onClose:n}){const{t:r}=H(),s=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 s({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 o.jsxs("div",{className:"save-prompt-popover",onClick:b=>b.stopPropagation(),children:[o.jsxs("div",{className:"save-prompt-popover__header",children:[o.jsx("span",{children:r("promptLibrary.saveTitle")}),o.jsx("button",{className:"save-prompt-popover__close",onClick:n,"aria-label":r("common.close"),children:"×"})]}),o.jsxs("div",{className:"save-prompt-popover__body",children:[o.jsxs("label",{children:[r("promptLibrary.name"),o.jsx("input",{type:"text",value:a,onChange:b=>i(b.target.value),placeholder:l.slice(0,30)})]}),o.jsxs("label",{children:[r("promptLibrary.content"),o.jsx("textarea",{value:l,onChange:b=>c(b.target.value),placeholder:r("common.enterPrompt"),rows:4,autoFocus:!0})]}),o.jsxs("label",{children:[r("promptLibrary.tags"),o.jsx("input",{type:"text",value:d,onChange:b=>u(b.target.value),placeholder:"cta, product, summer"})]})]}),o.jsx("div",{className:"save-prompt-popover__footer",children:o.jsx("button",{onClick:h,disabled:p||!l.trim(),className:"save-prompt-popover__save",children:r(p?"common.saving":"promptLibrary.save")})})]})}function ov({variant:e="label"}){const{t}=H(),n=f(a=>a.webSearchEnabled),r=f(a=>a.setWebSearchEnabled),s=t(n?"settings.webSearch.on":"settings.webSearch.off");return e==="label"?o.jsx(Oy,{checked:n,onChange:r,label:s,className:"web-search-toggle web-search-toggle--label"}):o.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":s,title:s,children:e==="compact"?o.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:[o.jsx("circle",{cx:"12",cy:"12",r:"10"}),o.jsx("path",{d:"M2 12h20"}),o.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 0 20"}),o.jsx("path",{d:"M12 2a15.3 15.3 0 0 0 0 20"})]}):o.jsx("span",{children:s})})}function av({canAddMore:e,onAttach:t}){const{t:n}=H(),r=f(I=>I.prompt),s=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 o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"composer__hint-row",children:o.jsx("span",{className:"composer__hint",children:n("prompt.hint")})}),o.jsxs("div",{className:"composer__toolbar",children:[o.jsx("button",{type:"button",className:"composer__tool",onClick:t,disabled:!e,title:n("prompt.attachTitle"),"aria-label":n("prompt.attachTitle"),children:o.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:o.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"})})}),o.jsx("button",{type:"button",className:"composer__tool",onClick:()=>s&&void os(s).catch(()=>{}),disabled:!s||!e,title:n("prompt.continueTitle"),children:n("prompt.continue")}),o.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:o.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:[o.jsx("polygon",{points:"23 7 16 12 23 17 23 7"}),o.jsx("rect",{x:"1",y:"5",width:"15",height:"14",rx:"2",ry:"2"})]})}),o.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:o.jsx("span",{"aria-hidden":"true",style:{fontWeight:700,fontSize:11},children:"1:1"})}),o.jsx(ov,{variant:"compact"}),o.jsxs("div",{className:"composer__tool-wrap",children:[o.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&&o.jsx(sv,{text:r,mode:c,onClose:()=>h(!1)})]})]}),o.jsx("div",{className:"composer__storyboard-row",children:o.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 Ua(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 iv(e){const{maxRefs:t,trayItemCount:n,captureAttachmentCaret:r,addFilesAtCaret:s}=e,{t:a}=H(),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 s(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=Ua(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=Ua(d.clipboardData?.items??null);p.length!==0&&(d.preventDefault(),i(p,f.getState().prompt.length))};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[s,t,a,n]),l}function lv({variant:e,onSubmit:t}){const n=f(d=>d.provider),r=f(d=>d.negativePrompt),s=f(d=>d.setNegativePrompt),a=v.useRef(!1),{t:i}=H();if(v.useLayoutEffect(()=>{n!=="nai"&&(a.current=!1)},[n]),n!=="nai")return null;const l=`negative-prompt-${e}`,c=`${l}-hint`;return o.jsxs("div",{className:`negative-prompt negative-prompt--${e}`,children:[o.jsx("label",{className:"negative-prompt__label",htmlFor:l,children:i("nai.negativePrompt.label")}),o.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=>s(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())}}),o.jsx("p",{id:c,className:"negative-prompt__hint",children:i("nai.negativePrompt.hint",{count:r.length})})]})}const hs="tray:";function gs(e){return`${e.start}:${e.end}:${e.query}`}function cv(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):br(e.id,f.setState,f.getState,e)}function dv(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):oc(e,f.setState,f.getState)}function uv(e){const t=Number.parseFloat(e);return Number.isFinite(t)&&t>0?t:null}function Jo({variant:e="sidebar"}){const t=f(E=>E.prompt),n=f(E=>E.setPrompt),r=f(E=>E.provider),s=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 B=b.find(ee=>ee.id===E);return B?cv(B):(p?.(E),null)};v.useEffect(()=>{let E=!1;return Ep().then(B=>{E||(I(B),dv(B))}).catch(B=>console.error("[ElementMention] load failed",B)),()=>{E=!0}},[]);const{t:y}=H(),g=f(E=>E.trayItems),_=f(E=>E.retiredTags),S=f(E=>E.removeTrayItem),w=f(E=>E.activeReferenceLimit()),j=f(E=>E.providerUrlReference),P=f(E=>E.setProviderUrlReference),M=f(E=>E.addReferences),q=f(E=>E.addReferenceDataUrl),N=f(E=>E.useImageAsReference),R=f(E=>E.readDroppedImageMetadata),$=v.useRef(null),k=v.useRef(null),J=v.useRef(null),[T,Z]=v.useState(!1),[te,de]=v.useState(null),ye=v.useRef(!1),ve=v.useRef(null),F=v.useRef(null),O=f(E=>E.promptMode),Q=f(ef),V=f(E=>E.multimodeMaxImages),ae=O==="direct",fe=r==="nai",ie=s.filter(E=>E.placement!=="after"),Ee=s.filter(E=>E.placement==="after"),he=[...ie.map(E=>E.id),"__main_prompt__",...Ee.map(E=>E.id)],Se=g.length<w,Ne=Q?g.length>0?y("multimode.promptPlaceholderWithRefs"):y("multimode.promptPlaceholder"):g.length>0?y("prompt.placeholderWithRefs"):y("prompt.placeholder"),ke=()=>{h.length>0||l()},D=()=>k.current?.selectionStart??f.getState().prompt.length,le=(E,B)=>{const ee=f.getState().trayItems.filter(Y=>Y.kind==="attachment"&&!E.has(Y.tokenId));if(ee.length===0)return 0;const oe=f.getState().prompt,ue=Math.max(0,Math.min(B,oe.length)),Le=ee.map(Y=>`@${Y.tag} `).join("");n(`${oe.slice(0,ue)}${Le}${oe.slice(ue)}`);const L=ue+Le.length;return requestAnimationFrame(()=>k.current?.setSelectionRange(L,L)),ee.length},se=(E,B)=>{const ee=`@${E} `,oe=f.getState().prompt,ue=`${oe.slice(0,B.start)}${ee}${oe.slice(B.end)}`,Le=B.start+ee.length;n(ue),requestAnimationFrame(()=>k.current?.setSelectionRange(Le,Le))},G=(E,B)=>{if(ye.current)return;const ee=My(E,B);de(ee&&gs(ee)!==F.current?ee:null)},C=async(E,B,ee)=>{if(E.length===0)return 0;const oe=new Set(f.getState().trayItems.map(ue=>ue.tokenId));try{return ee&&E.length===1&&await R(E[0])?0:(await M(E),le(oe,B))}catch{return 0}},X=async E=>{const B=J.current??D();J.current=null,await C(E,B,!0)},re=()=>{Se&&(J.current=D(),$.current?.click())},K=async(E,B)=>{const ee=new Set(f.getState().trayItems.map(oe=>oe.tokenId));try{const oe=E.url||E.image;if(!oe)return;const ue={image:oe,url:E.url,filename:E.filename};if(xe(ue)){const Le=await Yt(oe);Le&&q(Le)}else await N(ue);le(ee,B)}catch{}},be=E=>{E.preventDefault(),Z(!1);const B=E.dataTransfer.getData("application/ima2-ref");if(B){try{const oe=JSON.parse(B);K(oe,D())}catch{}return}const ee=Array.from(E.dataTransfer.files).filter(oe=>oe.type.startsWith("image/"));ee.length>0&&X(ee)},Te=E=>{E.preventDefault(),T||Z(!0)},He=E=>{E.currentTarget.contains(E.relatedTarget)||Z(!1)},gt=iv({maxRefs:w,trayItemCount:g.length,captureAttachmentCaret:D,addFilesAtCaret:C}),lt=v.useRef(null),$n=v.useRef(e);v.useLayoutEffect(()=>{const E=k.current;if(!E)return;(lt.current===null||$n.current!==e)&&(lt.current=uv(window.getComputedStyle(E).maxHeight)??0,$n.current=e),E.style.height="auto";const B=lt.current,ee=B?Math.min(E.scrollHeight,B):E.scrollHeight;E.style.height=`${ee}px`},[t,e]);const Un=(E,B)=>{const ee=he.indexOf(E);return ee<0?!1:B==="up"?ee>0:ee<he.length-1},Hn=E=>o.jsxs("div",{className:"composer__prompt-chip",title:E.name,children:[o.jsx("span",{className:"composer__prompt-chip-plus","aria-hidden":"true",children:"+"}),o.jsx("span",{className:"composer__prompt-chip-title",children:E.name}),o.jsxs("div",{className:"composer__prompt-chip-actions",children:[o.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>i(E.id,"up"),disabled:!Un(E.id,"up"),"aria-label":y("prompt.moveBlockUp",{name:E.name}),title:y("prompt.moveBlockUp",{name:E.name}),children:"^"}),o.jsx("button",{type:"button",className:"composer__prompt-chip-move",onClick:()=>i(E.id,"down"),disabled:!Un(E.id,"down"),"aria-label":y("prompt.moveBlockDown",{name:E.name}),title:y("prompt.moveBlockDown",{name:E.name}),children:"v"}),o.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 o.jsxs("div",{className:`composer composer--${e}${T?" composer--drag":""}${ae?" composer--direct":""}${Q?" composer--multimode":""}${ae&&Q?" composer--combined-modes":""}`,role:"group","aria-label":Q?y("multimode.composerAriaLabel",{count:V}):y("prompt.label"),onDrop:be,onDragOver:Te,onDragLeave:He,onPaste:gt,children:[o.jsxs("div",{className:"composer__header",children:[o.jsx("span",{className:"section-title composer__label",children:y("prompt.label")}),o.jsxs("div",{className:"composer__header-meta",children:[Q&&o.jsx("span",{className:"composer__mode-badge",children:y("multimode.composerBadge",{count:V})}),ae&&o.jsx("span",{className:"composer__direct-badge",children:y("prompt.directModeActive")}),j&&o.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>P(null),title:y("prompt.urlRefActiveTitle"),"aria-label":y("prompt.urlRefClear"),children:[o.jsx("span",{className:"composer__url-ref-dot","aria-hidden":"true"}),y("prompt.urlRefActive")]}),g.length>0&&o.jsx("span",{className:"composer__count",children:y("prompt.refCount",{count:g.length,max:w})})]})]}),o.jsx(By,{items:g,limit:w,onRemove:S,onAdd:re}),ie.length>0&&o.jsx("div",{className:"composer__prompt-chips",children:ie.map(Hn)}),c.length>0&&o.jsx(Wo,{ariaLabel:y("home.selectedPresets"),children:c.map(E=>{const B=lc(E);return B?o.jsx(Uc,{onRemove:()=>d(E),removeLabel:y("common.removeNamed",{name:B.name}),children:B.name},E):null})}),o.jsx(ev,{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,B,ee)=>ee?y("element.unavailableAria",{name:E}):y("element.mentionAria",{name:E,kind:B}),removeLabel:E=>y("element.removeAria",{name:E}),onRemove:E=>u.removeElementId?.(E)}),o.jsxs("div",{className:`composer__prompt-panes${fe?" composer__prompt-panes--dual":""}`,children:[o.jsxs("div",{className:"composer__prompt-pane",children:[fe?o.jsx("label",{className:"composer__prompt-pane-label",htmlFor:`positive-prompt-${e}`,children:y("nai.positivePrompt.label")}):null,o.jsxs("div",{className:"composer__prompt-stack",children:[o.jsx(nv,{prompt:t,retiredTags:_,textareaRef:k}),o.jsx("textarea",{id:`positive-prompt-${e}`,ref:k,className:"prompt-area composer__textarea",value:t,placeholder:fe?y("nai.positivePrompt.placeholder"):Ne,"aria-describedby":fe?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{ye.current=!0,de(null)},onCompositionEnd:E=>{ye.current=!1,ve.current=E.currentTarget.value,queueMicrotask(()=>{ve.current=null}),G(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{F.current=null,n(E.target.value),ve.current!==E.target.value&&G(E.target.value,E.target.selectionStart)},onClick:E=>G(E.currentTarget.value,E.currentTarget.selectionStart),onKeyDown:E=>{if(!(ye.current||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229)){if(E.key==="Escape"&&te){E.preventDefault(),F.current=gs(te),de(null);return}if(E.key==="Enter"&&(E.metaKey||E.ctrlKey)){if(E.defaultPrevented)return;E.preventDefault(),ke()}}}})]}),fe?o.jsx("p",{id:`positive-prompt-${e}-hint`,className:"composer__prompt-hint",children:y("nai.positivePrompt.hint",{count:t.length})}):null]}),o.jsx(lv,{variant:"classic",onSubmit:ke})]}),o.jsx(Hy,{open:te!==null,textareaRef:k,composingRef:ye,caret:te?.end??0,query:te?.query??"",elements:[...g.filter(E=>E.kind==="attachment").map(E=>({id:`${hs}${E.tokenId}`,name:E.tag,kind:"reference",thumbnail:E.source.dataUrl})),...b.map(E=>{const B=Zl(E);return{id:E.id,name:E.name,kind:typeof E.metadata?.elementKind=="string"?E.metadata.elementKind:"character",thumbnail:B?`/generated/${B.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 B=Vs(f.getState().trayItems,E.id);if(E.id.startsWith(hs)){const oe=E.id.slice(hs.length),ue=f.getState().trayItems.find(Le=>Le.tokenId===oe);ue&&te&&se(ue.tag,te),de(null);return}if(x?.(E.id),B){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),de(null);return}const ee=Vs(f.getState().trayItems,E.id);!ee||!te||(se(ee.tag,te),de(null))},onClose:E=>{E==="escape"&&te&&(F.current=gs(te)),de(null)}}),Ee.length>0&&o.jsxs("div",{className:"composer__prompt-chips composer__prompt-chips--after",children:[o.jsx("span",{className:"composer__prompt-chips-label",children:y("prompt.afterBlocks")}),Ee.map(Hn)]}),o.jsx(av,{canAddMore:Se,onAttach:re}),T&&o.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:y("prompt.dropHere",{max:w})}),o.jsx("input",{ref:$,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:E=>{const B=Array.from(E.target.files??[]);B.length>0?X(B):J.current=null,E.target.value=""}})]})}function Yo(){const e=f(l=>l.activeGenerations),t=f(l=>l.generate),n=f(l=>l.openReadinessPopup),r=f(l=>l.missingElementIds??[]),{t:s}=H(),a=e>0,i=r.length>0;return o.jsxs("div",{className:"generate-row",children:[o.jsxs("button",{type:"button",className:`generate-btn foil-hover${a?" generate-btn--active":""}`,disabled:i,title:i?s("toast.missingElements"):void 0,onClick:()=>{t()},children:[s("generate.button"),a?o.jsx("span",{className:"generate-btn__count","aria-label":s("generate.buttonLoading",{n:e}),children:e}):null]}),o.jsx("button",{type:"button",className:"generate-row__readiness",onClick:n,title:s("readiness.openTitle"),"aria-label":s("readiness.openTitle"),children:"?"})]})}function Vc(e,t=28){const n=e.trim().replace(/\s+/g," ");return n.length>t?`${n.slice(0,t)}...`:n}function Xo(e={}){const t=f(i=>i.inFlight),n=f(i=>i.cancelInFlightJob),r=f(i=>i.videoProgress),{t:s}=H(),a={queued:s("inflight.queued"),planning:s("inflight.planning"),streaming:s("inflight.streaming"),decoding:s("inflight.decoding"),canceling:s("inflight.canceling")};return t.length===0?null:"panelId"in e?o.jsx(fv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s,variant:e.variant,panelId:e.panelId}):o.jsx(mv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s})}function mv(e){return o.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>o.jsx(pv,{f:t,...e},t.id))})}function pv({f:e,phaseLabels:t,videoProgress:n,cancelInFlightJob:r,t:s}){const a=e.phase?t[e.phase]??e.phase:s("inflight.queued"),l=e.prompt.trim().replace(/\s+/g," ")||s("inflight.noPrompt");return o.jsxs("li",{className:"in-flight-item","data-phase":e.phase??"queued",title:l,"aria-label":`${a}: ${l}`,children:[o.jsx("span",{className:"in-flight-prompt",children:Vc(e.prompt)}),o.jsx("span",{className:"in-flight-phase",children:e.kind==="video"&&n!=null&&n>0?`${Math.round(n*100)}%`:a}),o.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{r(e.id)},disabled:e.phase==="canceling","aria-label":s("inflight.cancelAria",{prompt:l}),title:s("common.cancel"),children:"×"}),o.jsx("span",{className:"in-flight-spinner","aria-hidden":"true","data-motion-essential":!0})]})}function fv(e){const t=e.jobs.filter(s=>s.kind==="video"||s.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 o.jsx("ul",{id:e.panelId,className:`in-flight-list in-flight-list--${e.variant}`,children:e.jobs.map(s=>o.jsx(hv,{f:s,determinateVideoId:n,validVideoProgress:r,...e},s.id))})}function hv({f:e,determinateVideoId:t,validVideoProgress:n,phaseLabels:r,cancelInFlightJob:s,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=yv(e)??vv(e.kind,a),p=e.id===t&&n!=null?Math.round(n*100):null;return o.jsxs("li",{className:"in-flight-rich-item","data-phase":e.phase??"queued",title:c,"aria-label":`${u}, ${i}: ${c}`,children:[o.jsx("span",{className:`in-flight-placeholder${d?" in-flight-placeholder--video":""}`,"aria-hidden":"true",children:o.jsx(bv,{video:d})}),o.jsxs("span",{className:"in-flight-rich-copy",children:[o.jsx("span",{className:"in-flight-rich-title",children:u}),o.jsx("span",{className:"in-flight-rich-prompt",title:c,children:Vc(e.prompt,54)}),o.jsxs("span",{className:"in-flight-rich-status",children:[o.jsx("span",{className:"in-flight-phase",children:p==null?i:`${i} · ${p}%`}),o.jsx(gv,{progressPercent:p,phaseLabel:i,t:a})]})]}),o.jsx("button",{type:"button",className:"in-flight-cancel",onClick:()=>{s(e.id)},disabled:e.phase==="canceling","aria-label":a("inflight.cancelAria",{prompt:c}),title:a("common.cancel"),children:"×"})]})}function gv({progressPercent:e,phaseLabel:t,t:n}){return o.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:o.jsx("span",{style:e==null?void 0:{width:`${e}%`}})})}function yv(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function vv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function bv({video:e}){return o.jsxs("svg",{viewBox:"0 0 24 24",focusable:"false",children:[o.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),e?o.jsx("path",{d:"m10 9 5 3-5 3Z"}):o.jsxs(o.Fragment,{children:[o.jsx("circle",{cx:"9",cy:"9",r:"1.5"}),o.jsx("path",{d:"m5.5 17 4.2-4 2.7 2.4 2.2-2 3.9 3.6"})]})]})}const Ha="(max-width: 800px)";function ht(){const[e,t]=v.useState(()=>typeof window<"u"?window.matchMedia(Ha).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Ha),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const xv=10,ct=12;function Iv({anchorRef:e,panelId:t,focusOnOpen:n,onRequestClose:r,onPointerEnter:s,onPointerLeave:a}){const{t:i}=H(),l=v.useRef(null),c=v.useRef(null),d=v.useRef(null),[u,p]=v.useState({left:ct,top:ct,caretTop:24}),[m,h]=v.useState(!1);v.useLayoutEffect(()=>{const x=()=>{const _=e.current,S=l.current;if(!_||!S)return;const w=_.getBoundingClientRect(),j=_.closest(".sidebar")?.getBoundingClientRect(),P=S.getBoundingClientRect(),M=j?j.right:w.right,q=Math.max(ct,window.innerWidth-P.width-ct),N=Math.max(ct,window.innerHeight-P.height-ct),R=Math.min(Math.max(M+xv,ct),q),$=Math.min(Math.max(w.bottom-P.height,ct),N),k=Math.min(Math.max(w.top+w.height/2-$,16),P.height-16);p({left:R,top:$,caretTop:k}),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 ss.createPortal(o.jsxs("div",{ref:l,className:"inflight-popup",role:"dialog","aria-modal":"false","aria-labelledby":b,"data-positioned":m,style:I,onPointerEnter:s,onPointerLeave:a,children:[o.jsxs("header",{className:"inflight-popup__header",children:[o.jsx("h2",{ref:c,id:b,tabIndex:-1,children:i("inflight.title")}),o.jsx("button",{type:"button",className:"inflight-popup__close","aria-label":i("common.close"),title:i("common.close"),onClick:()=>r(!0),children:o.jsx("span",{"aria-hidden":"true",children:"×"})})]}),o.jsx(Xo,{variant:"popup",panelId:t}),o.jsx("footer",{className:"inflight-popup__footer",children:i("inflight.footerHint")})]}),document.body)}const Sv=180,wv=180;function Bc({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const s=f(N=>N.inFlight.length),a=ht(),{t:i}=H(),[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(s!==0)return;const N=document.activeElement;b&&N instanceof HTMLElement&&N.closest(".inflight-popup")&&p.current?.focus(),I(),c("closed"),u(!1),e==="inline"&&n&&r?.(!1)},[s,n,r,b,e]),s===0&&!(s===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"),Sv))},S=()=>{m.current!=null&&window.clearTimeout(m.current),m.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),wv))},w=N=>{I(),c("closed"),u(!1),N&&p.current?.focus()},j=N=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){w(!1);return}u(N.detail===0),c("pinned")},P=N=>{N.pointerType==="mouse"&&_()},M=s>99?"99+":String(s),q=b?"inflight.badgeClose":"inflight.badgeOpen";return o.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:P,onPointerLeave:S,children:[o.jsxs("button",{ref:p,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:j,"aria-live":"polite","aria-expanded":b,"aria-controls":t,"aria-haspopup":e==="popup"?"dialog":void 0,"aria-label":i(q,{n:s}),title:i(q,{n:s}),children:[o.jsx("span",{className:"inflight-badge__spinner","aria-hidden":"true"}),o.jsx("span",{className:"inflight-badge__count","aria-hidden":"true",children:M})]}),e==="popup"&&b?o.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&b?o.jsx(Iv,{anchorRef:p,panelId:t,focusOnOpen:d,onRequestClose:w,onPointerEnter:g,onPointerLeave:S}):null]})}function _v(){const{t:e}=H(),t=f(m=>m.sessions),n=f(m=>m.activeSessionId),r=f(m=>m.switchSession),s=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 o.jsxs("div",{className:"session-picker",children:[o.jsxs("div",{className:"session-picker-row",children:[o.jsxs("button",{type:"button",className:"session-current",onClick:()=>c(m=>!m),title:e("session.switchTitle"),children:[o.jsx("span",{className:"session-title",children:d?.title??e("session.loading")}),o.jsx("span",{className:"session-caret",children:l?"▴":"▾"})]}),o.jsx("button",{type:"button",className:"session-btn",onClick:()=>{s(e("session.newSession"))},title:e("session.newSessionTitle"),children:"+"}),o.jsx("button",{type:"button",className:"session-btn",onClick:u,title:e("session.renameTitle"),disabled:!d,children:o.jsx(Gy,{})})]}),l&&o.jsxs("ul",{className:"session-list",children:[t.map(m=>o.jsxs("li",{className:m.id===n?"is-active":"",children:[o.jsxs("button",{type:"button",className:"session-item",onClick:()=>{c(!1),r(m.id)},children:[o.jsx("span",{className:"session-item-title",children:m.title}),o.jsx("span",{className:"session-item-count",children:m.nodeCount})]}),o.jsx("button",{type:"button",className:"session-del",onClick:()=>p(m.id,m.title),title:e("session.deleteTitle"),children:"×"})]},m.id)),t.length===0&&o.jsx("li",{className:"session-empty",children:e("session.empty")})]})]})}function vw(){return z("/api/comfy/workflows")}function bw(e){return z("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function xw(e){return z("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function Iw(e){return z("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function Sw(e){return z(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Ev(e){return kv(await z("/api/models",e?{signal:e}:{}))}function Nv(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function pn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function cn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ka(e){if(!cn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return pn();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 pn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return pn();t.executable=e.executable}return t}function kv(e){return!cn(e)||e.ok!==!0||!cn(e.lanes)?pn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!cn(n)||!Nv(n.status)||!cn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return pn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Ka),video:n.models.video.map(Ka)}};return[t,r]}))}const Wc={phase:"idle",catalog:null,observedAt:null,error:null},ut=new Set;let En=Wc,Tr=0,dt=null,Qn=null;const Va=()=>{Qo()};function Zo(){return En}function dn(e){En=e;for(const t of[...ut])ut.has(t)&&t()}function ys(e,t){return e===Tr&&dt===t&&!t.signal.aborted&&ut.size>0}function Cv(e){const t=e;return t?.status===401||t?.status===403?"app-auth":t?.code==="MODEL_CATALOG_INVALID"?"invalid":"request"}async function Qo(){const e=++Tr;if(dt?.abort(),dt=null,ut.size===0){dn(Wc);return}const t=new AbortController;if(dt=t,dn({...En,phase:"loading",error:null}),!!ys(e,t))try{const n=await Ev(t.signal);ys(e,t)&&dn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){ys(e,t)&&dn({...En,phase:"error",error:Cv(n)})}finally{e===Tr&&dt===t&&(dt=null)}}function jv(e){const t=ut.size===0;return ut.add(e),t&&(typeof window<"u"&&(Qn=window,Qn.addEventListener("focus",Va)),Qo()),()=>{!ut.delete(e)||ut.size>0||(++Tr,dt?.abort(),dt=null,Qn?.removeEventListener("focus",Va),Qn=null,dn({...En,phase:"idle",error:null}))}}function qn(){return{...v.useSyncExternalStore(jv,Zo),refresh:Qo}}function Ot(e){return e.executable!==!1&&!e.description?.endsWith("(offline)")}function Et(e,t){const n=e.catalog?.comfy,r=n?.models??{image:[],video:[]},s=t?.comfyVideoWorkflow?"video":"image",a=t?.comfyVideoWorkflow||t?.comfyWorkflow||null,i=a?r[s].find(m=>m.id===a):void 0,l=lo.comfy,c=r.image.some(Ot)||r.video.some(Ot),d=e.phase==="ready"&&n?.status==="ready"&&c,u=!!(d&&i&&Ot(i)&&(s==="video"?l.video.supported:l.generate.supported)),p=m=>({code:m,laneAvailable:d,selectedAvailable:u,selected:a?{id:a,kind:s,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 Pv={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 $t(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":Pv[e.code]}const Jc=[{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"}],Ba=new Map(Jc.map(e=>[e.value,e.label])),Av=new Set(["runway","higgsfield"]),er="mcp:",tr="core:",vs="effort:",bs=$i,nn=zt;function Rv(e){rs(e,f.setState,f.getState)}function Tv(e){Vh(e,f.setState,f.getState)}function Mv(e,t,n){Bh(e,t,f.setState,f.getState,n)}const xs={image:[],video:[]};function Is(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Lv(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function Yc({compact:e=!1}={}){const{t}=H(),n=f(C=>C.provider),r=f(C=>C.imageModel),s=f(C=>C.videoModelSelected),a=f(C=>C.mcpProvider??null),i=f(C=>C.mcpModel??null),l=f(C=>C.mcpMediaKind??"image"),c=f(C=>C.setProvider),d=f(C=>C.setImageModel),u=f(C=>C.selectVideoModel),p=f(C=>C.setComfyWorkflow),m=f(C=>C.comfyWorkflow),h=f(C=>C.setComfyVideoWorkflow),b=f(C=>C.comfyVideoWorkflow),I=f(C=>C.setReasoningEffort),x=f(C=>C.reasoningEffort),{providers:y,loading:g,error:_}=Lc(),[S,w]=v.useState(xs),[j,P]=v.useState(!1),[M,q]=v.useState(0),[N,R]=v.useState(!1),$=qn(),k=$.catalog??{},J=k.comfy?.models??{image:[],video:[]};v.useEffect(()=>{Qh(f.setState,f.getState)},[]);const T=a?y.find(C=>C.id===a)??null:null,Z=!!(T?.enabled&&T.status.state==="connected");v.useEffect(()=>{if(!a||!Z){w(xs),P(!1);return}const C=new AbortController;return R(!0),P(!1),Mc(a,C.signal).then(X=>{if(C.signal.aborted)return;w(X);const re=f.getState(),be=(re.mcpMediaKind==="video"?X.video:X.image).find(Te=>Te.id===re.mcpModel);be&&Zh(be.capabilities,f.setState,f.getState)}).catch(X=>{X.name!=="AbortError"&&(C.signal.aborted||(w(xs),P(!0)))}).finally(()=>{C.signal.aborted||R(!1)}),()=>C.abort()},[a,Z,M]);const te=v.useMemo(()=>y.filter(C=>C.enabled&&C.status.state==="connected"),[y]),de=a?`${er}${a}`:`${tr}${n}`,ye=ju(n),ve=n==="comfy"?J.image.map(C=>({id:C.id,label:C.description?.endsWith("(offline)")?`${C.label} — ${t("comfy.statusOffline")}`:C.label,disabled:$.phase!=="ready"||k.comfy?.status!=="ready"||!Ot(C),reason:C.lockReason})):[],F=n==="comfy"?J.video.map(C=>({id:C.id,label:C.description?.endsWith("(offline)")?`${C.label} — ${t("comfy.statusOffline")}`:C.label,reason:C.lockReason,disabled:$.phase!=="ready"||k.comfy?.status!=="ready"||!Ot(C)})):[],O=Tu({provider:n,imageModel:r,videoModel:s,comfyWorkflow:m,comfyVideoWorkflow:b}),Q=a?i?Bn(l,i):"":O,V=!a&&(n==="oauth"||n==="api")&&!s,ae=!!(i&&(S.image.some(C=>C.id===i)||S.video.some(C=>C.id===i))),fe=T?.executable===!1?T.lockReason??t("mcp.higgsfieldLocked"):null,ie=a?T?T.status.state!=="connected"?t("mcp.disconnectedSelection"):T.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,Ee=C=>{if(C.startsWith(tr)){const K=C.slice(tr.length);if(!Ba.has(K))return;c(K);return}const X=C.slice(er.length),re=y.find(K=>K.id===X);!re||re.status.state!=="connected"||Rv(X)},he=C=>{const X=f.getState();if(X.provider!==n||(X.mcpProvider??null)!==a)return;const re=Zo();if(X.mcpProvider){if(C.startsWith(nn))return;const K=mm(C);if(K){const Te=(K.kind==="video"?S.video:S.image).find(He=>He.id===K.model);Mv(K.model,K.kind,Te?.capabilities)}else Tv(C||null);return}if(X.provider==="comfy"){const K=C.startsWith(nn),be=K?C.slice(nn.length):C;if(!Et(re,K?{comfyVideoWorkflow:be}:{comfyWorkflow:be}).selectedAvailable)return;K?h(be):p(be||null);return}if(!C.startsWith(nn)){if(C.startsWith(vs)){I(C.slice(vs.length));return}if(C.startsWith(bs)){u(C.slice(bs.length));return}d(C)}},Se=Object.keys(k).filter(C=>!Av.has(C)),Ne=Se.length>0?Se:Jc.map(C=>C.value);Ne.includes("comfy")||Ne.push("comfy");const ke=[{label:t("mcp.coreProviders"),items:Ne.map(C=>{const X=k[C],re=Ba.get(C),K=X?Lv(X.status,t):null;return{value:`${tr}${C}`,label:re??Is(C),...K?{sub:K}:{},...X?.reason?{title:X.reason}:{},...re?{}:{disabled:!0}}})}];te.length>0&&ke.push({label:t("mcp.connectedProviders"),items:te.map(C=>({value:`${er}${C.id}`,label:Is(C.id),sub:C.executable===!1?t("mcp.locked"):void 0}))}),a&&!te.some(C=>C.id===a)&&ke.push({items:[{value:`${er}${a}`,label:Is(a),sub:t("mcp.unavailable"),disabled:!0}]});const D=[];if(a)i&&!ae&&D.push({items:[{value:Bn(l,i),label:i}]}),D.push({label:t("mcp.imageModels"),items:S.image.map(C=>({value:Bn("image",C.id),label:C.label}))}),D.push({label:t("mcp.videoModels"),items:S.video.map(C=>({value:Bn("video",C.id),label:C.label}))});else{const C=k[n]?.models.video.length??0,X=(n==="grok"||n==="grok-api")&&C>0;D.push({label:t("mcp.imageModels"),items:n==="comfy"?ve.map(K=>({value:K.id,label:K.label,sub:K.reason,...K.disabled?{disabled:!0}:{}})):ye.map(K=>({value:K.value,label:K.shortLabel}))}),n==="comfy"&&F.length>0&&D.push({label:t("mcp.videoModels"),items:F.map(K=>({value:`${nn}${K.id}`,label:K.label,stacked:!0,...K.reason?{sub:t("comfy.videoCatalogShort"),title:K.reason}:{},...K.disabled?{disabled:!0}:{}}))}),(X||s)&&D.push({label:t("mcp.videoModels"),items:Pu.map(K=>({value:`${bs}${K.value}`,label:K.shortLabel}))}),V&&D.push({label:t("sidebar.reasoningLabel"),items:Ds.map(K=>({value:`${vs}${K.value}`,label:K.shortLabel,sub:K.value===x?"●":void 0}))});const re=new Set(D.flatMap(K=>K.items.map(be=>be.value)));O&&!re.has(O)&&D.unshift({items:[{value:O,label:O.includes(":")?O.split(":").slice(1).join(":"):O,title:t("mcp.unavailable"),...n==="comfy"?{disabled:!0}:{}}]})}const le=Ds.find(C=>C.value===x),se=n==="comfy"&&!a?Et($,{comfyWorkflow:m,comfyVideoWorkflow:b}):null,G=se?t($t(se,$)):null;return o.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[o.jsx(Fe,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:ke,value:de,onChange:Ee,ariaLabel:t("mcp.providerLabel"),title:ie??t("mcp.providerLabel"),triggerSub:"",portal:!0}),o.jsx(Fe,{id:"sidebar-generation-model",className:"gen-provider-model__select gen-provider-model__select--model",groups:D,value:Q,onChange:he,ariaLabel:t("mcp.modelLabel"),title:ie??t("mcp.modelLabel"),disabled:!!ie,placeholder:a?t(N?"mcp.loadingModels":"mcp.chooseModel"):n==="comfy"?t("mcp.chooseModel"):void 0,triggerSub:V&&le?le.shortLabel:void 0,portal:!0}),ie||fe||_||j||G?o.jsx("span",{className:se?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:se&&G?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:G}),$.phase==="error"?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{$.refresh()},children:t("comfy.display.refresh")}):null]}):ie??fe??(j?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>q(C=>C+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function Xc(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function fn(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(Xc):[]}}async function At(e,t){const n=await we(e,t),r=await n.json().catch(()=>({}));if(!n.ok){const s=r,a=typeof s.error=="string"?s.error:s.error?.message||`Request failed: ${n.status}`,i=new Error(a);throw typeof s.error!="string"&&(i.code=s.error?.code),i}return r}function Fv(){return At("/api/cardnews/image-templates")}function Ov(){return At("/api/cardnews/role-templates")}async function Dv(e){const t=await At("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:fn(t.plan)}}function Gv(e){return At("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function zv(e){return At(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function qv(e){const n=(await At(`/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 Wa(e){return At(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:fn(t.plan)}))}function $v(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function Uv(e){return e[0]?.id||"academy-lesson-square"}function Hv(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function Kv(e){return Math.round(e/16)*16}function Mr(e){return Math.min(vo,Math.max(1024,Kv(e)))}function Ja(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Mr(e.customW)}x${Mr(e.customH)}`}function Zc(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 Vv(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?Zc(t.error)||A("cardNews.error"):void 0}}function Bv(e){return new Promise(t=>setTimeout(t,e))}function Ss(e,t){const n=new Map(t.cards.map(r=>[r.id,r]));return{...e,cards:e.cards.map(r=>{const s=n.get(r.id);return s?{...r,...s,textFields:Array.isArray(s.textFields)?s.textFields:r.textFields,status:s.status||r.status,error:Zc(s.error)}:r})}}const Ie=Ci((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([Fv(),Ov()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:Uv(n.templates),roleTemplateId:Hv(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:Mr(n),customH:Mr(r)})},async draft(){const n=t();e({loading:!0,error:null,draftError:null});try{const{plan:r,planner:s}=await Dv({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:Ja(n)});e({activePlan:fn(r),selectedCardId:r.cards[0]?.id||null,selectedTextFieldId:null,plannerMeta:s||null,loading:!1})}catch(r){const s=r instanceof Error?r.message:String(r);e({loading:!1,draftError:s,error:s})}},updateCard(n,r){e(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.activePlan.cards.map(a=>a.id===n?{...a,...r}:a)}:null}))},updateTextField(n,r,s){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,...s,source:s.source||"user"}:l)})}:null}))},addTextField(n,r){e(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.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(s=>({activePlan:s.activePlan?{...s.activePlan,cards:s.activePlan.cards.map(a=>a.id===n&&!a.locked?{...a,textFields:a.textFields.filter(i=>i.id!==r)}:a)}:null,selectedTextFieldId:s.selectedTextFieldId===r?null:s.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(s=>s.locked?{...s,status:"skipped"}:{...s,status:"queued",error:void 0})}});try{const s=t().activePlan||n.activePlan;let i=await Gv({...s,size:Ja(n),quality:r.quality,moderation:r.moderation,model:r.imageModel,sessionId:r.activeSessionId});for(e(c=>({activePlan:c.activePlan?Ss(c.activePlan,i):c.activePlan}));["queued","running"].includes(i.status);)await Bv(900),i=await zv(i.jobId),e(c=>({activePlan:c.activePlan?Ss(c.activePlan,i):c.activePlan}));const l=await Wa(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?fn(l.plan):c.activePlan?Ss(c.activePlan,i):c.activePlan,selectedTextFieldId:null})),r.showToast(A("cardNews.generated",{count:i.generated}))}catch(s){const a=s instanceof Error?s.message:String(s);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 s=t().activePlan,a=s?.cards.find(l=>l.id===n);if(!s||!a||a.locked||!["draft","error"].includes(a.status))return;const i=f.getState();e({error:null,activePlan:{...s,cards:s.cards.map(l=>l.id===n?{...l,status:"generating",error:void 0}:l)}});try{const{card:l}=await qv({setId:s.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?Vv(d,Xc(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 Wa(n);e({activePlan:fn(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 Wv(){const{t:e}=H(),t=Ie(S=>S.hydrate),n=Ie(S=>S.topic),r=Ie(S=>S.audience),s=Ie(S=>S.goal),a=Ie(S=>S.contentBrief),i=Ie(S=>S.outputSizePreset),l=Ie(S=>S.customW),c=Ie(S=>S.customH),d=Ie(S=>S.setBriefField),u=Ie(S=>S.setOutputSizePreset),p=Ie(S=>S.setCustomSize),m=Ie(S=>S.draft),h=Ie(S=>S.loading),b=Ie(S=>S.generating),I=Ie(S=>S.draftError),x=Ie(S=>S.generateSet),y=Ie(S=>S.activePlan),g=y?.cards||[],_={total:g.length,done:g.filter(S=>S.status==="generated").length};return v.useEffect(()=>{t()},[t]),o.jsxs("section",{className:"card-news-composer","aria-label":e("cardNews.composer"),children:[o.jsx("div",{className:"card-news-composer__head",children:o.jsxs("div",{children:[o.jsx("div",{className:"section-title",children:e("cardNews.composer")}),o.jsx("p",{children:e("cardNews.composerHint")})]})}),o.jsxs("label",{className:"card-news-field",children:[o.jsx("span",{children:e("cardNews.topic")}),o.jsx("input",{value:n,placeholder:e("cardNews.topicPlaceholder"),onChange:S=>d("topic",S.target.value)})]}),o.jsxs("label",{className:"card-news-field",children:[o.jsx("span",{children:e("cardNews.audience")}),o.jsx("input",{value:r,placeholder:e("cardNews.audiencePlaceholder"),onChange:S=>d("audience",S.target.value)})]}),o.jsxs("label",{className:"card-news-field",children:[o.jsx("span",{children:e("cardNews.goal")}),o.jsx("input",{value:s,placeholder:e("cardNews.goalPlaceholder"),onChange:S=>d("goal",S.target.value)})]}),o.jsxs("label",{className:"card-news-field",children:[o.jsx("span",{children:e("cardNews.brief")}),o.jsx("textarea",{value:a,placeholder:e("cardNews.briefPlaceholder"),onChange:S=>d("contentBrief",S.target.value)})]}),o.jsxs("div",{className:"card-news-field",children:[o.jsx("span",{children:e("cardNews.outputSize")}),o.jsx("div",{className:"card-news-size-row",role:"group","aria-label":e("cardNews.outputSize"),children:["1024x1024","2048x2048","custom"].map(S=>o.jsx("button",{type:"button",className:`option-btn${i===S?" active":""}`,onClick:()=>u(S),children:S==="custom"?e("cardNews.customSize"):S==="1024x1024"?"1024²":"2048²"},S))}),i==="custom"?o.jsxs("div",{className:"card-news-custom-size",children:[o.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:l,onChange:S=>p(Number.parseInt(S.target.value,10)||l,c),"aria-label":e("size.width")}),o.jsx("span",{children:"×"}),o.jsx("input",{className:"custom-size-input",type:"text",inputMode:"numeric",value:c,onChange:S=>p(l,Number.parseInt(S.target.value,10)||c),"aria-label":e("size.height")})]}):null]}),o.jsxs("button",{type:"button",className:"generate-btn card-news-draft-btn",onClick:()=>{m()},disabled:h||!n.trim(),children:[h?o.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,e(h?"cardNews.drafting":"cardNews.draft")]}),I?o.jsx("div",{className:"card-news-error",role:"alert",children:I}):null,h?o.jsxs("div",{className:"card-news-inline-status",role:"status",children:[o.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}),o.jsx("span",{children:e("cardNews.drafting")})]}):null,o.jsxs("button",{type:"button",className:"composer__tool card-news-generate-btn",onClick:()=>{x()},disabled:!y||b||y.cards.every(S=>S.locked),children:[b?o.jsx("span",{className:"card-news-spinner","aria-hidden":"true"}):null,b?e("cardNews.progress.generating",{done:_.done,total:_.total}):e("cardNews.batchGenerate")]})]})}function Ut({className:e}){return o.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function Jv({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Ae(e),c=xe(e),d=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?vn(e):{image:e.url||e.image,filename:e.filename})),u.dataTransfer.effectAllowed="copy"};return o.jsxs("div",{className:"sidebar-history__item",children:[o.jsx("button",{ref:u=>s(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?o.jsxs(o.Fragment,{children:[e.thumb?o.jsx("img",{src:e.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Ut,{}),o.jsx("span",{className:"sidebar-history__play-badge","aria-hidden":"true",children:"▶"})]}):o.jsx("img",{src:e.thumb||e.url||e.image,alt:"",loading:"lazy",decoding:"async"})}),o.jsx("button",{type:"button",className:"sidebar-history__delete",onClick:u=>{u.preventDefault(),u.stopPropagation(),i(e)},"aria-label":r,title:r,children:"x"})]})}function Yv({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Uf(e.items.length);return o.jsxs("div",{className:"sidebar-history__item",children:[o.jsxs("button",{ref:c=>s(e.key,c),type:"button",className:`sidebar-history__sequence${t?" active":""}`,onClick:()=>a(e.sequenceId),"aria-label":n,children:[o.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?o.jsx(Ut,{},Ae(u)):u?o.jsx("img",{src:u.thumb||u.url||u.image,alt:"",loading:"lazy",decoding:"async"},Ae(u)):o.jsx("span",{className:"sidebar-history__sequence-placeholder"},`sequence-placeholder-${e.sequenceId}-${d}`)})}),o.jsx("span",{className:"sidebar-history__sequence-badge",children:e.items.length})]}),o.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 Ya="ima2.sidebarHistoryCollapsed";function Xa(){const{t:e}=H();return o.jsx("div",{className:"sidebar-history__item",children:o.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--skeleton","aria-label":e("common.generating")})})}function Xv({count:e}){const t=Math.min(e,4);return o.jsx("div",{className:"sidebar-history__item",children:o.jsx("div",{className:"sidebar-history__thumb sidebar-history__thumb--collection-skeleton",children:Array.from({length:t},(n,r)=>o.jsx("div",{className:"sidebar-collection-mini sidebar-collection-mini--skeleton"},r))})})}function Zv(){const e=f(y=>y.history),t=f(y=>y.currentImage),n=f(y=>y.selectHistory),r=f(y=>y.showHistorySequence),s=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(Ya)==="1"}catch{return!1}}),{t:h}=H(),b=kc(t,c),I=v.useMemo(()=>Nc(e).slice(0,_c),[e]);v.useEffect(()=>{!b||p||u.current[b]?.scrollIntoView({block:"nearest",inline:"nearest"})},[b,p,I]),v.useEffect(()=>{try{localStorage.setItem(Ya,p?"1":"0")}catch{}},[p]);const x=(y,g)=>{u.current[y]=g};return o.jsxs("section",{className:`sidebar-history${p?" sidebar-history--collapsed":""}`,"aria-label":h("history.recentTitle"),children:[o.jsxs("div",{className:"sidebar-history__header",children:[o.jsx("span",{className:"section-title",children:h("history.recentTitle")}),o.jsxs("div",{className:"sidebar-history__header-actions",children:[o.jsx("button",{type:"button",className:"sidebar-history__gallery-button",onClick:d,"aria-label":h("history.galleryCard"),title:h("history.openGalleryTitle"),children:o.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:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),o.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:o.jsxs("div",{className:"sidebar-history__grid",children:[i.map(y=>{const g=l[y.id];if(y.kind==="multimode"&&g){const _=[o.jsx(Xv,{count:g.requested},`coll-sk-${y.id}`)];for(let S=0;S<g.requested;S++)g.images[S]||_.push(o.jsx(Xa,{},`sk-${y.id}-${S}`));return _}return o.jsx(Xa,{},`sk-${y.id}`)}),I.length===0&&i.length===0?o.jsx("button",{type:"button",className:"sidebar-history__empty",onClick:d,children:h("history.emptyRecent")}):null,I.map(y=>y.type==="sequence"?o.jsx(Yv,{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):o.jsx(Jv,{item:y.item,active:b===y.key,selectLabel:h("history.selectRecent"),deleteLabel:h("history.deleteImageAria"),setRef:x,onSelect:n,onDelete:g=>{s(g)}},y.key))]})]})}const Qv="sidebar-inflight-panel";function eb(){const{t:e}=H(),t=f(d=>d.uiMode),n=f(d=>d.workspaceProfile),r=f(d=>d.referenceImages),s=f(d=>d.clearReferences),a=ht(),i=t==="agent"&&Wt?"agent":t==="node"&&Bt?"node":t==="assets"?"assets":t==="asset-gen"?"asset-gen":"classic",l=Ln(n),c=!a&&i==="classic"&&l.composerPlacement==="bottom"&&l.multimodeHistoryGrouping==="sequence";return o.jsxs(o.Fragment,{children:[o.jsx(tb,{}),i==="classic"?c?o.jsx(o.Fragment,{children:o.jsx(Zv,{})}):o.jsxs(o.Fragment,{children:[o.jsx(Jo,{}),o.jsxs("div",{className:"sidebar-generate-with-inflight",children:[o.jsx(Yo,{}),o.jsx(Bc,{variant:"popup",panelId:Qv})]})]}):i==="card-news"?o.jsx(o.Fragment,{children:o.jsx(Wv,{})}):i==="node"?o.jsxs(o.Fragment,{children:[o.jsx(_v,{}),r.length>0?o.jsxs("div",{className:"node-mode-ref-warning",role:"status",children:[o.jsx("strong",{children:e("node.classicRefsParkedTitle")}),o.jsx("span",{children:e("node.classicRefsParkedBody")}),o.jsx("button",{type:"button",onClick:s,children:e("node.clearParkedRefs")})]}):null,o.jsx("div",{className:"sidebar__node-hint",children:e("sidebar.nodeModeHint")}),o.jsx(Xo,{})]}):null]})}function tb(){const e=ht();return o.jsx(o.Fragment,{children:o.jsxs("div",{className:"logo",children:[o.jsx("div",{className:"logo-mark","aria-hidden":"true"}),o.jsxs("div",{className:"logo-copy",children:[o.jsx("div",{className:"logo-title",children:"ima2"}),o.jsx("div",{className:"logo-title logo-title--gen",children:"gen"})]}),o.jsxs("div",{className:"logo-actions",children:[o.jsx(rb,{}),o.jsx(Yc,{compact:e})]})]})})}function nb(){return o.jsx("aside",{className:"sidebar",children:o.jsx("div",{className:"sidebar__scroll",children:o.jsx(eb,{})})})}function rb(){const{t:e}=H(),t=f(i=>i.togglePromptLibrary),n=f(i=>i.promptLibraryOpen),r=f(i=>i.rightPanelOpen),s=f(i=>i.toggleRightPanel),a=()=>{!n&&!r&&s(),t()};return o.jsx("button",{type:"button",className:"settings-button",onClick:a,title:e("promptLibrary.title"),"aria-label":e("promptLibrary.title"),children:o.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:o.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})})}const sb=1024,ob=1024,ab="blank-canvas.png";function Za(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function ib(e){const t=Za(e?.width,sb),n=Za(e?.height,ob),r=document.createElement("canvas");r.width=t,r.height=n;const s=r.getContext("2d");if(!s)throw new Error("blank_canvas_context_unavailable");s.fillStyle="#ffffff",s.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],ab,{type:"image/png"})}const nr=1024;function lb(e){const t=/^(\d+)x(\d+)$/.exec(e);if(!t)return{width:nr,height:nr};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:nr,height:nr}:{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:s}=H(),[a,i]=v.useState(!1),l=v.useCallback(async()=>{if(!a){i(!0);try{const c=lb(r()),d=await ib(c);await e(d)&&t()}catch{n(s("canvas.blank.failed"),!0)}finally{i(!1)}}},[a,r,e,t,n,s]);return{creatingBlankCanvas:a,createBlankCanvas:l}}function db(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 ub(e,t){try{const n=await we("/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 at(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 mb(e,t){const n=pe();return ce()?Promise.reject(Je(n-1)):(Ct(),new Promise((r,s)=>{let a=!1,i=()=>{},l=()=>{};const c=m=>{a||(a=!0,i(),l(),t.removeEventListener("abort",u),m())},d=()=>{Ce(e.requestId).catch(()=>{})},u=()=>c(()=>{d(),s(new DOMException("Aborted","AbortError"))});if(l=kt(e.requestId,null,(m,h)=>{m==="done"?c(()=>r(h)):m==="error"&&c(()=>s(at(h,"Video extension failed")))}),i=Kt(()=>c(()=>{d(),s(new Error("Video extension stream timed out"))})),t.aborted)return u();t.addEventListener("abort",u,{once:!0}),no().then(()=>{if(n!==pe())throw Je(n);if(ce())throw Je(n-1);return ub(e,t)}).catch(m=>c(()=>s(m)))}))}let vt={source:null,status:"idle"},rn=null,Qa=0;const Js=new Set;function rr(e,t){vt={source:e,status:t};for(const n of Js)n()}const Tt={getSnapshot:()=>vt,subscribe(e){return Js.add(e),()=>{Js.delete(e)}},select(e){vt.status!=="pending"&&vt.source!==e&&rr(e,"idle")},start(e){if(vt.status==="pending"||vt.source===e.sourceVideoId&&vt.status==="tracking-expired")return null;const t=new AbortController;return rn=t,Qa=pe(),rr(e.sourceVideoId,"pending"),mb(e,t.signal).then(n=>(rn=null,rr(e.sourceVideoId,"idle"),n),n=>{rn=null;const r=tt(n).code,s=n instanceof DOMException&&n.name==="AbortError";throw rr(e.sourceVideoId,s||r==="LAN_TOKEN_REQUIRED"?"idle":r==="JOB_TRACKING_TIMEOUT"?"tracking-expired":"error"),n})},cancel(){rn?.abort()},releaseView(){!ce()&&Qa===pe()&&rn?.abort()}},pb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),Dt=[];function fb(e){return Dt.length>0&&Dt[Dt.length-1]===e}function Ue(e,t,n={}){const r=v.useRef(null),s=v.useRef(t);s.current=t;const a=v.useId(),{trap:i=!0,autoFocus:l=!0,restoreFocus:c=!0}=n;return v.useEffect(()=>{if(!e)return;Dt.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=r.current,p=()=>Array.from(u?.querySelectorAll(pb)??[]).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(!fb(a))return;if(x.key==="Escape"){x.preventDefault(),s.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=s.current;return s.current=x=>{b=x??"programmatic",I(x)},()=>{const x=Dt.indexOf(a);x!==-1&&Dt.splice(x,1),document.removeEventListener("keydown",h),m(b)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const hb={oauth:"GPT OAuth / Codex login",api:"GPT API key",grok:"Grok OAuth / progrok","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 gb(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):typeof e=="boolean"}function ea(e){return gb(e)?String(e):null}function yb(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function ei(e){return e?e.replace("x","×"):null}function vb(e){if(e==null)return null;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function W(e,t,n,r={}){const s=ea(n);s&&e.push({label:t,value:s,...r})}function ws(e,t,n,r={}){typeof n!="number"||n<=0||W(e,t,n,r)}function bb(e,t,n){const r=vb(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function xb(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 Ib(e){return e?hb[e]??e:null}function Sb(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const s=ea(r);if(!s)return;const a=Sb(s);!a||t.has(a)||(t.add(a),e.push({label:n,value:s,copyValue:s,pre:!0}))}function ti(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function ni(e,t,n){const r=e?.[t];if(!r||typeof r!="object"||Array.isArray(r))return null;const s=r[n];return typeof s=="number"&&Number.isFinite(s)?s:null}function wb(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 _b({item:e,onClose:t,onCopy:n}){const{t:r,locale:s}=H(),a=Ue(!0,t),i=v.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=Ib(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),ei(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=[];W(p,r("metadata.fields.provider"),c,{compact:!0}),W(p,r("metadata.fields.model"),e.model,{compact:!0}),W(p,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),W(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=[];W(m,r("metadata.fields.quality"),e.quality,{compact:!0}),W(m,r("metadata.fields.size"),ei(e.size),{compact:!0}),W(m,r("metadata.fields.format"),e.format,{compact:!0}),W(m,r("metadata.fields.moderation"),e.moderation,{compact:!0}),W(m,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),W(m,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),W(m,r("metadata.fields.kind"),e.kind,{compact:!0}),W(m,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),m.length&&u.push({title:r("metadata.sections.settings"),fields:m,compact:!0});const h=[];W(h,r("metadata.fields.elapsed"),e.elapsed!=null?`${e.elapsed}s`:null,{compact:!0}),W(h,r("metadata.fields.totalTokens"),e.usage?.total_tokens,{compact:!0}),W(h,r("metadata.fields.inputTokens"),ti(e.usage,"input_tokens"),{compact:!0}),ws(h,r("metadata.fields.cachedTokens"),ni(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),W(h,r("metadata.fields.outputTokens"),ti(e.usage,"output_tokens"),{compact:!0}),ws(h,r("metadata.fields.reasoningTokens"),ni(e.usage,"output_tokens_details","reasoning_tokens"),{compact:!0}),ws(h,r("metadata.fields.webSearchCalls"),e.webSearchCalls,{compact:!0}),e.usage?.grok_cost_usd_ticks!=null&&W(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=[];W(b,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),W(b,r("metadata.fields.createdAt"),yb(e.createdAt,s)),W(b,r("metadata.fields.sessionId"),e.sessionId),W(b,r("metadata.fields.nodeId"),e.nodeId),W(b,r("metadata.fields.parentNodeId"),e.parentNodeId),W(b,r("metadata.fields.clientNodeId"),e.clientNodeId),W(b,r("metadata.fields.refsCount"),e.refsCount),W(b,r("metadata.fields.sequence"),xb(e)),W(b,r("metadata.fields.setId"),e.setId),W(b,r("metadata.fields.cardId"),e.cardId),b.length&&u.push({title:r("metadata.sections.lineage"),fields:b});const I=[];W(I,r("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),W(I,r("metadata.fields.videoResolution"),e.video?.resolution),W(I,r("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),W(I,r("metadata.fields.videoRequestedModel"),e.video?.requestedModel),W(I,r("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),W(I,r("metadata.fields.videoModelFallback"),e.video?.modelFallback),W(I,r("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:ea(e.video?.xaiVideoRequestId)??void 0}),W(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&u.push({title:r("metadata.sections.video"),fields:I});const x=[];W(x,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),W(x,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),W(x,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),W(x,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),W(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),bb(y,r("metadata.fields.insertedPrompts"),e.composerInsertedPrompts),y.length&&u.push({title:r("metadata.sections.prompts"),fields:y}),o.jsx("div",{className:"modal-backdrop metadata-modal-backdrop",onClick:t,children:o.jsxs("section",{ref:a,className:"modal metadata-modal",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-modal-title",onClick:_=>_.stopPropagation(),children:[o.jsxs("header",{className:"metadata-modal__header",children:[o.jsxs("div",{children:[o.jsx("h3",{id:"metadata-modal-title",children:r("metadata.title")}),o.jsx("p",{children:[e.mediaType??r("metadata.asset"),e.filename].filter(Boolean).join(" · ")}),d.length?o.jsx("div",{className:"metadata-modal__summary","aria-label":r("metadata.summary"),children:d.map(_=>o.jsx("span",{children:_},_))}):null]}),o.jsx("button",{type:"button",className:"metadata-modal__close",onClick:t,"aria-label":r("common.close"),children:"×"})]}),o.jsxs("div",{className:"metadata-modal__body",children:[u.map(_=>o.jsxs("section",{className:_.compact?"metadata-modal__section metadata-modal__section--compact":"metadata-modal__section",children:[o.jsx("h4",{children:_.title}),o.jsx("dl",{children:_.fields.map(S=>o.jsxs("div",{className:wb(S),children:[o.jsx("dt",{children:S.label}),o.jsxs("dd",{children:[S.pre?o.jsx("pre",{children:S.value}):o.jsx("span",{children:S.value}),S.copyValue?o.jsx("button",{type:"button",onClick:()=>n(S.copyValue),"aria-label":r("metadata.copyField",{label:S.label}),children:r("metadata.copy")}):null]})]},`${_.title}:${S.label}`))})]},_.title)),o.jsxs("details",{className:"metadata-modal__raw",children:[o.jsx("summary",{children:r("metadata.rawJson")}),o.jsx("div",{className:"metadata-modal__raw-actions",children:o.jsx("button",{type:"button",onClick:()=>n(i),children:r("metadata.copyRaw")})}),o.jsx("pre",{children:i})]})]})]})})}function Eb(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function Qc(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 Nb(e,t){const n=Eb(e);if(!n||Qc(n,t))return null;const r=n==="image"?"upscale-image":"upscale-video",s=Object.fromEntries(Object.entries(t).filter(([,a])=>a!==void 0));return{action:r,files:[e],...Object.keys(s).length>0?{parameters:s}:{}}}const kb=[2,4,8,16],Cb=["sublime","photo","photo_denoiser"];function jb({pending:e,onSubmit:t,onClose:n}){const{t:r}=H(),s=Ue(!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=Qc("image",I);return o.jsxs("div",{ref:s,className:"upscale-popover",role:"dialog","aria-label":r("result.upscaleTitle"),children:[o.jsx("div",{className:"option-row",role:"group","aria-label":"scaleFactor",children:kb.map(y=>o.jsxs("button",{type:"button",className:`option-btn${a===y?" active":""}`,"aria-pressed":a===y,onClick:()=>i(y),children:[y,"x"]},y))}),o.jsxs("label",{className:"upscale-popover__field",children:[o.jsx("span",{children:r("result.upscaleFlavor")}),o.jsxs("select",{value:l,onChange:y=>c(y.target.value),children:[o.jsx("option",{value:"",children:r("result.upscaleFlavorAuto")}),Cb.map(y=>o.jsx("option",{value:y,children:y},y))]})]}),[["sharpen",d,u],["smartGrain",p,m],["ultraDetail",h,b]].map(([y,g,_])=>o.jsxs("label",{className:"upscale-popover__field",children:[o.jsxs("span",{children:[y," ",o.jsx("output",{children:g})]}),o.jsx("input",{type:"range",min:0,max:100,step:5,value:g,onChange:S=>_(Number(S.target.value))})]},y)),x?o.jsx("p",{className:"element-detail__error",role:"alert",children:x}):null,o.jsxs("div",{className:"upscale-popover__actions",children:[o.jsx("button",{type:"button",className:"action-btn action-btn--primary",disabled:e||!!x,onClick:()=>t(I),children:r(e?"inflight.streaming":"result.upscaleStart")}),o.jsx("button",{type:"button",className:"action-btn",onClick:n,children:r("common.cancel")})]})]})}const Pb="canvas-mode-context",Ab="Canvas Mode",ri=36e5,Rb=["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 Tb({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=H(),r=f(G=>G.currentImage),s=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(Tt.subscribe,Tt.getSnapshot),[y,g]=v.useState(!1),[_,S]=v.useState(!1),[w,j]=v.useState(!1),[P,M]=v.useState(!1);v.useEffect(()=>{let G=!0;return Uo().then(C=>{G&&M(C.some(X=>X.id==="runway"&&X.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const q=async G=>{if(!N?.filename||w)return;const C=Nb(N.filename,G);if(!C){s(n("result.upscaleInvalid"),!0);return}j(!0);try{await z("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}),S(!1),s(n("result.upscaleStarted"))}catch{s(n("result.upscaleFailed"),!0)}finally{j(!1)}};v.useEffect(()=>Tt.releaseView,[]);const N=e??r,R=N?.filename??null;v.useEffect(()=>{Tt.select(R)},[R]);const $=x.status==="pending"||x.source===R?x.status:"idle";if(!N)return null;const k=xe(N),J=k?N.url||N.image:"",T=!!N.filename,Z=!!N.filename&&!k,te=k&&!!N.filename,ye=!!((N.provider==="grok"||N.provider==="grok-api")&&!k&&N.providerUrl&&N.createdAt&&Date.now()-N.createdAt<ri),ve=async()=>{if(!(!N.filename||b)){I(!0);try{await f.getState().animateImage(N.filename,N.prompt??void 0)&&s(n("toast.animateDone"))}catch(G){const C=G instanceof Error?G.message:n("toast.animateFailed");s(C,!0)}finally{I(!1)}}},F=async()=>{if(!N.filename||$==="pending"||$==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const C=Tt.start({requestId:G,sourceVideoId:N.filename,prompt:N.prompt?.trim()||void 0,provider:N.provider==="grok-api"?"grok-api":"grok",model:N.model??void 0});if(!C)return;const X=await C;f.getState().addHistoryItem(db(X,N)),s(n("toast.animateDone"))}catch(C){const X=C instanceof DOMException&&C.name==="AbortError",re=tt(C).code;re==="JOB_TRACKING_TIMEOUT"||re==="LAN_TOKEN_REQUIRED"?$e(C,f.getState()):X||s(C instanceof Error?C.message:n("toast.animateFailed"),!0)}},O=()=>Tt.cancel(),Q=()=>{const G=document.createElement("a");G.href=N.image,G.download=N.filename||"generated.png",G.click()},V=async G=>{const X=await(await fetch(G)).blob();let re;if(X.type==="image/png")re=X;else{const K=new Image;K.crossOrigin="anonymous";const be=URL.createObjectURL(X);await new Promise((He,gt)=>{K.onload=()=>He(),K.onerror=gt,K.src=be});const Te=document.createElement("canvas");Te.width=K.naturalWidth,Te.height=K.naturalHeight,Te.getContext("2d").drawImage(K,0,0),URL.revokeObjectURL(be),re=await new Promise((He,gt)=>Te.toBlob(lt=>lt?He(lt):gt(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":re})])},ae=async()=>{try{if(k){const G=await Yt(J);await V(G)}else await V(N.image);s(n(k?"toast.frameCopied":"toast.imageCopied"))}catch{s(n("toast.copyFailed"),!0)}},fe=async()=>{try{const G=await Gl(J);await V(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},ie=async()=>{try{const G=await zl(J);await V(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},Ee=async()=>{if(N.prompt)try{await navigator.clipboard.writeText(N.prompt),s(n("toast.promptCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},he=async G=>{try{await navigator.clipboard.writeText(G),s(n("toast.metadataCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},Se=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await os(N)}catch{}u&&e&&a({id:Pb,name:Ab,text:Rb});const C=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');C&&(C.focus(),C.setSelectionRange(C.value.length,C.value.length)),s(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},Ne=async()=>{if(k||!N.providerUrl||!N.createdAt||Date.now()-N.createdAt>=ri){s(n("toast.continueAsUrlExpired"),!0);return}try{await Kc(N)}catch{}const G=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');G&&(G.focus(),G.setSelectionRange(G.value.length,G.value.length)),s(n("toast.continueAsUrlStarted"))},ke=async()=>{if(!(!N.filename||m)){h(!0);try{const G=await tu({filename:N.filename});s(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const C=G instanceof Error?G.code:void 0;s(n(C==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":C==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":C==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{h(!1)}}},D=()=>{i(N),s(n("toast.nodeRootCreated"))},le=async()=>{try{await l(N)}finally{t?.()}},se=async()=>{try{await d(N)}finally{t?.()}};return o.jsxs("div",{className:"result-actions",children:[o.jsx("button",{type:"button",className:"action-btn",onClick:Q,children:n("result.download")}),o.jsx("button",{type:"button",className:`action-btn${k?" action-btn--frame":""}`,onClick:ae,children:n(k?"result.copyLastFrame":"result.copyImage")}),k&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:fe,children:n("result.copyFirstFrame")}),o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:ie,children:n("result.copyMidFrame")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Ee()},children:n("result.copyPrompt")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const G=await c(N);s(n(G?"chain.savedToAssets":"chain.saveToAssetsFailed"),!G)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),o.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:Se,title:n("result.continueHereTitle"),children:n("result.continueHere")}),ye&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Ne()},title:n("result.continueAsUrlTitle"),children:n("result.continueAsUrl")}),Z&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ve()},disabled:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),P&&N.filename&&(k?o.jsx("button",{type:"button",className:"action-btn",disabled:w,onClick:()=>{q({})},title:n("result.upscaleTitle"),children:n(w?"inflight.streaming":"result.upscale")}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",disabled:w,onClick:()=>S(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),_?o.jsx(jb,{pending:w,onSubmit:G=>{q(G)},onClose:()=>S(!1)}):null]})),te&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",onClick:F,disabled:$==="pending"||$==="tracking-expired","aria-busy":$==="pending",title:n($==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:$==="pending"?n("inflight.streaming"):$==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),$==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:O,children:n("common.cancel")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:D,title:n("result.firstNodeTitle"),children:n("result.firstNode")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>g(!0),title:n("result.infoTitle"),children:n("result.info")}),!u&&o.jsx("button",{type:"button",className:"action-btn",onClick:p,title:n("canvas.open"),"aria-label":n("canvas.openAria"),children:o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:o.jsx("path",{d:"M4 4h8v8M12 4l-8 8"})})}),N.filename&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{le()},title:n("result.deleteTitle"),children:n("result.delete")}),o.jsxs("details",{className:"result-actions__more",children:[o.jsx("summary",{className:"action-btn",children:n("result.more")}),o.jsxs("div",{className:"result-actions__menu",children:[T&&o.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{ke()},title:n("result.sendToComfyUITitle"),disabled:m,children:n("result.sendToComfyUI")}),o.jsx("button",{type:"button",className:"result-actions__menu-item result-actions__danger-item",onClick:()=>{se()},children:n("result.permanentDelete")})]})]})]}),y&&o.jsx(_b,{item:N,onClose:()=>g(!1),onCopy:G=>{he(G)}})]})}const Mb=["auto","flat","detailed","mono"],st={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function Lb(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 Fb(e){return`${Math.round(e/1024)}KB`}function Ob(){const{t:e}=H(),t=f(R=>R.vectorizeTarget),n=f(R=>R.setVectorizeTarget),r=f(R=>R.addAssetGenDerivedItem),s=f(R=>R.selectedProjectId),a=f(R=>R.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=Ue(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(st.colorPrecision),[b,I]=v.useState(st.filterSpeckle),[x,y]=v.useState(st.cornerThreshold),[g,_]=v.useState(!1),[S,w]=v.useState(null),[j,P]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),w(null),P(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const M=v.useCallback(()=>{if(!t?.filename||g)return;const R=t.filename,$=new AbortController;i.current=$,_(!0),w(null),fu({source:R,preset:u,...m!==st.colorPrecision?{colorPrecision:m}:{},...b!==st.filterSpeckle?{filterSpeckle:b}:{},...x!==st.cornerThreshold?{cornerThreshold:x}:{},projectId:s,signal:$.signal}).then(k=>{if(!(i.current!==$||l.current!==R)){if(!k.filePath)throw new Error(e("vectorize.saveError"));P({filePath:k.filePath,pathCount:k.pathCount,bytes:k.bytes}),r(Lb(t,k.filePath)),a(e("vectorize.saved"))}}).catch(k=>{if(k instanceof DOMException&&k.name==="AbortError"||i.current!==$||l.current!==R)return;const J=k instanceof Error?k.message:e("vectorize.saveError");w(J),a(J,!0)}).finally(()=>{i.current!==$||l.current!==R||(i.current=null,_(!1))})},[t,g,u,m,b,x,s,r,a,e]);if(!t)return null;const q=t.url||t.image,N=j?`/generated/${encodeURIComponent(j.filePath)}`:null;return o.jsx("div",{className:"assetgen-popup-backdrop",onClick:c,children:o.jsxs("div",{ref:d,className:"keying-panel vectorize-panel",role:"dialog","aria-modal":"true","aria-label":e("vectorize.title"),onClick:R=>R.stopPropagation(),children:[o.jsxs("header",{className:"keying-panel__head",children:[o.jsx("h2",{children:e("vectorize.title")}),o.jsx("span",{className:"keying-panel__hint",children:e("vectorize.hint")})]}),o.jsxs("div",{className:"keying-panel__compare","aria-busy":g,children:[o.jsxs("figure",{className:"keying-panel__preview",children:[o.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.original")}),o.jsx("div",{className:"keying-panel__stage keying-panel__stage--original",children:o.jsx("img",{src:q??"",alt:e("vectorize.originalAlt")})})]}),o.jsxs("figure",{className:"keying-panel__preview",children:[o.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.result")}),o.jsx("div",{className:"keying-panel__stage",children:N?o.jsx("img",{src:N,alt:e("vectorize.resultAlt")}):o.jsx("span",{className:"keying-panel__loading",role:"status",children:e(g?"vectorize.running":"vectorize.idle")})})]})]}),o.jsx("div",{className:"keying-panel__modes",role:"group","aria-label":e("vectorize.preset"),children:Mb.map(R=>o.jsx("button",{type:"button",className:u===R?"is-active":"","aria-pressed":u===R,onClick:()=>p(R),children:e(`vectorize.preset_${R}`)},R))}),j?o.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(j.pathCount),size:Fb(j.bytes)})}):null,o.jsxs("details",{className:"keying-panel__advanced",children:[o.jsx("summary",{children:e("vectorize.advanced")}),o.jsxs("div",{className:"keying-panel__controls",children:[o.jsxs("label",{children:[e("vectorize.colorPrecision")," ",o.jsx("output",{children:m}),o.jsx("input",{type:"range",min:1,max:8,value:m,onChange:R=>h(Number(R.target.value))})]}),o.jsxs("label",{children:[e("vectorize.filterSpeckle")," ",o.jsx("output",{children:b}),o.jsx("input",{type:"range",min:0,max:32,value:b,onChange:R=>I(Number(R.target.value))})]}),o.jsxs("label",{children:[e("vectorize.cornerThreshold")," ",o.jsx("output",{children:x}),o.jsx("input",{type:"range",min:0,max:180,value:x,onChange:R=>y(Number(R.target.value))})]}),o.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(st.colorPrecision),I(st.filterSpeckle),y(st.cornerThreshold)},children:e("vectorize.reset")})]})]}),o.jsxs("footer",{className:"keying-panel__actions",children:[S?o.jsx("span",{className:"keying-panel__save-error",role:"alert",children:S}):null,o.jsx("button",{type:"button",className:"assetgen-generate",disabled:g||!t.filename,onClick:M,children:e(g?"vectorize.running":"vectorize.run")}),N?o.jsx("a",{className:"assetgen-popup__close",href:N,download:j?.filePath,children:e("vectorize.download")}):null,o.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function Db({prompt:e,onCopy:t}){const{t:n}=H(),r=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())};return o.jsx("div",{className:"result-prompt",onClick:t,onKeyDown:r,role:"button",tabIndex:0,title:n("result.copyPrompt"),"aria-label":n("result.copyPrompt"),children:o.jsx("span",{className:"result-prompt__text",children:e})})}function Gb(){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),s=f(m=>m.currentImage),a=f(m=>m.openCanvas),{t:i}=H(),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 o.jsxs("section",{className:"multimode-sequence","aria-live":"polite",children:[o.jsxs("div",{className:"multimode-sequence__header",children:[o.jsxs("div",{children:[o.jsx("div",{className:"multimode-sequence__title",children:i("multimode.sequenceTitle")}),o.jsx("div",{className:"multimode-sequence__meta",children:i("multimode.sequenceProgress",{returned:e.returned,requested:e.requested})})]}),n?o.jsx("button",{type:"button",className:"secondary-btn",onClick:t,children:i("multimode.cancel")}):null]}),o.jsx("div",{className:`multimode-sequence__grid count-${Math.min(e.requested,4)}`,children:p.map(({index:m,image:h,partial:b})=>{const I=h&&s?.filename&&h.filename===s.filename;return o.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:[o.jsx("div",{className:"multimode-sequence__badge",children:i("multimode.stageLabel",{index:m+1})}),h?o.jsx("img",{src:h.url??h.image,alt:i("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):b?o.jsx("img",{src:b.image,alt:i("multimode.partialAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):e.status==="pending"||e.status==="complete"?o.jsx("div",{className:"multimode-sequence__skeleton"}):o.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 zb({zoom:e,minZoom:t,maxZoom:n,onZoomIn:r,onZoomOut:s,onReset:a,labels:i}){return o.jsxs("div",{className:"viewer-controls","aria-label":i.controls,onPointerDown:l=>l.stopPropagation(),onDoubleClick:l=>l.stopPropagation(),onWheel:l=>l.stopPropagation(),children:[o.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),s()},disabled:e<=t,"aria-label":i.zoomOut,children:"-"}),o.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),"%"]}),o.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),r()},disabled:e>=n,"aria-label":i.zoomIn,children:"+"})]})}function Ir(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function qb(e,t,n,r){if(!e)return!1;const s=t.find(a=>a.filename===e);return s?!!s.isFavorite:r!==void 0?r:n.has(e)}function ww(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const It=1,ed=5,or=.22;function $b(e){return Math.min(ed,Math.max(It,e))}function Ub(e){const[t,n]=v.useState(1),[r,s]=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),s({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=$b(y+x);return g<=It?(s({x:0,y:0}),It):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?or:-or)},[u]),m=v.useCallback(()=>{if(t>It){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=It||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(()=>{s(y),c.current=null})},[a]),I=v.useCallback(x=>{!a||a.pointerId!==x.pointerId||(cancelAnimationFrame(l.current),l.current=0,c.current&&(s(c.current),c.current=null),i(null),x.currentTarget.releasePointerCapture(x.pointerId))},[a]);return{zoom:t,pan:r,reset:d,zoomIn:()=>u(or),zoomOut:()=>u(-or),handleWheel:p,handleDoubleClick:m,handlePointerDown:h,handlePointerMove:b,handlePointerUp:I}}const Hb=v.lazy(()=>Me(()=>import("./index-7ngEOVxt.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function Kb(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Vb(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function Bb(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 Ys(){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),s=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}=H(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:S}=cb(),w=v.useRef(null),j=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,P=Ub(j),M=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},q=F=>{if(F.key==="Delete"||F.key==="Backspace"){if(!e||F.target!==F.currentTarget||Ir(F.target))return;if(F.preventDefault(),F.shiftKey){a(e);return}s(e);return}F.key!=="ArrowLeft"&&F.key!=="ArrowRight"&&F.key!=="Home"&&F.key!=="End"||F.target===F.currentTarget&&(Ir(F.target)||(F.preventDefault(),F.key==="ArrowLeft"?r("previous"):F.key==="ArrowRight"?r("next"):F.key==="Home"?r("first"):F.key==="End"&&r("last")))},N=F=>{Ir(F.target)||(i(),F.currentTarget.focus())},R=v.useCallback(()=>{window.requestAnimationFrame(()=>w.current?.focus())},[]),$=async()=>{const F=e?.filename;if(!(!e||!F||y===F)){g(F);try{await h(e)}finally{g(O=>O===F?null:O)}}},k=v.useCallback(F=>{Array.from(F.dataTransfer.types).includes("Files")&&(F.preventDefault(),x(O=>O||!0))},[]),J=v.useCallback(F=>{F.currentTarget.contains(F.relatedTarget)||x(!1)},[]),T=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(Q=>/^image\/(png|jpeg|webp)$/.test(Q.type));O.length!==0&&await t(O[0])},[t]);if(c&&e)return o.jsxs(o.Fragment,{children:[o.jsx(v.Suspense,{fallback:o.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:o.jsx(Hb,{currentImage:e})}),o.jsx(Ob,{})]});const Z=Kb(e?.quality),te=Vb(e?.size),de=zi(e?.model,e?.provider),ye=e?Bb(e):null,ve=qb(e?.filename,p,m,e?.isFavorite);return o.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:k,onDragLeave:J,onDrop:T,children:[I?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:b("canvas.drop.hint")})}):null,o.jsx("div",{className:`progress-bar${l>0?" active":""}`}),n?o.jsx(Gb,{}):e&&ye?o.jsxs("div",{ref:w,className:"result-container visible",tabIndex:0,onMouseDown:N,onKeyDown:q,"aria-label":b("canvas.imageViewerAria"),children:[o.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${P.zoom>It?" 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?o.jsx(Hc,{variant:"result",active:ve,busy:y===e.filename,label:b(ve?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:$}):null,xe(e)?o.jsxs(o.Fragment,{children:[o.jsx("video",{className:"result-img",src:ye,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${P.pan.x}px, ${P.pan.y}px) scale(${P.zoom})`}},j??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(e))),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}):o.jsxs(o.Fragment,{children:[o.jsx("img",{className:"result-img",src:ye,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()}},j??void 0),o.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")})]}),o.jsx(zb,{zoom:P.zoom,minZoom:It,maxZoom:ed,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")}})]}),o.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,mc(e.videoContinuity),de]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Gu(e.reasoningEffort),Z,te,de]).filter(F=>!!F).join(" · ")}),o.jsx(Tb,{onAfterDeleteFocus:R}),e.prompt?o.jsx(Db,{prompt:e.prompt,onCopy:M}):null]}):e?null:o.jsxs("div",{className:"canvas__blank-entry",children:[o.jsx("div",{className:"canvas__blank-sheet","aria-hidden":!0}),o.jsxs("div",{className:"canvas__blank-copy",children:[o.jsx("strong",{children:b("canvas.blank.title")}),o.jsx("span",{children:b("canvas.blank.subtitle")})]}),o.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{S()},disabled:_,children:b(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function Wb(){return o.jsxs("div",{className:"classic-workspace",children:[o.jsx("div",{className:"classic-workspace__stage",children:o.jsx(Ys,{})}),o.jsxs("div",{className:"classic-workspace__dock",children:[o.jsx(Jo,{variant:"bottom"}),o.jsx(Yo,{})]})]})}const td="ima2.customSizeSlots";function Jb(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 Yb(){try{const e=localStorage.getItem(td);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?Ft(t.filter(Jb)):[]}catch{return[]}}function Xb(e){try{localStorage.setItem(td,JSON.stringify(Ft(e)))}catch{}}function Zb(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 sn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function Qb(){const e=f(T=>T.sizePreset),t=f(T=>T.setSizePreset),n=f(T=>T.customW),r=f(T=>T.customH),s=f(T=>T.setCustomSize),{t:a}=H(),[i,l]=v.useState(String(n)),[c,d]=v.useState(String(r)),[u,p]=v.useState(e==="custom"),[m,h]=v.useState(()=>Yb()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=bo(i,c,n,r),S=rm().filter(T=>T.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function w(T){h(T),Xb(T)}function j(){const T=Ze(i,n),Z=Ze(c,r);s(T,Z),l(String(T)),d(String(Z))}function P(T){T.key==="Enter"&&(T.preventDefault(),j())}function M(){t("custom"),p(!0),I(m.length>=Lt?m[0]?.id??null:null)}function q(T){t(T),T!=="custom"&&(p(!1),I(null))}function N(T){t("custom"),s(T.w,T.h),l(String(T.w)),d(String(T.h)),p(!1),I(T.id)}function R(T){y(T.id);const Z=Yu(T);Z&&(l(String(Z.w)),d(String(Z.h)))}function $(){const T=Zb(_.w,_.h,x),Z=m.length>=Lt&&b?Zu(m,b,T):Xu(m,T);w(Z),t("custom"),s(_.w,_.h),l(String(_.w)),d(String(_.h)),I(T.id),p(!1)}const k=_.reasons.length>0?_.reasons.map(T=>a(`size.adjustedReasons.${T}`)).join(", "):a("size.noAdjustment"),J=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${Ia}×${Ia}`}):null;return o.jsxs("div",{className:"option-group size-picker",children:[o.jsx("div",{className:"section-title",children:a("size.title")}),o.jsx(Oe,{title:"",items:sn(Qu),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(em),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(tm),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(nm),value:e,onChange:q}),o.jsxs("div",{className:"option-row size-picker__quick-row",children:[sn(S).map(T=>o.jsxs("button",{type:"button",className:`option-btn${e===T.value?" active":""}`,onClick:()=>q(T.value),children:[T.label,T.sub?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.sub})]}):null]},T.value)),o.jsxs("button",{type:"button",className:`option-btn${g?" active":""}`,onClick:M,children:[a("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:a("size.customSub")})]})]}),m.length>0?o.jsx("div",{className:"option-row size-picker__slot-row",children:m.map(T=>o.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===T.w&&r===T.h?" active":""}`,onClick:()=>N(T),children:[T.w,"×",T.h,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.ratio||a("size.customSlot")})]},T.id))}):null,u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"size-picker__ratio-row",children:Wu.map(T=>o.jsx("button",{type:"button",className:`size-picker__ratio${x===T.id?" active":""}`,onClick:()=>R(T),children:T.id==="free"?a("size.ratioFree"):T.label},T.id))}),o.jsxs("div",{className:"option-row size-picker__custom-row",children:[o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:i,onChange:T=>l(T.target.value.replace(/\D/g,"")),onBlur:j,onKeyDown:P,placeholder:a("size.width")}),o.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:c,onChange:T=>d(T.target.value.replace(/\D/g,"")),onBlur:j,onKeyDown:P,placeholder:a("size.height")})]}),o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:a("size.normalizedPreview")}),o.jsx("strong",{children:Ju(_.w,_.h)})]}),o.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:k}),J?o.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:J}):null,m.length>=Lt?o.jsxs("div",{className:"size-picker__replace-row",children:[o.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(T=>o.jsxs("button",{type:"button",className:`size-picker__replace${b===T.id?" active":""}`,onClick:()=>I(T.id),children:[T.w,"×",T.h]},T.id))]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:$,children:m.length>=Lt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),o.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const _s=[1,2,4];function ex(){const e=f(g=>g.count),t=f(g=>g.setCount),n=f(g=>g.uiMode),r=f(g=>g.multimode),s=f(g=>g.multimodeMaxImages),a=f(g=>g.setMultimodeMaxImages),{t:i}=H(),l=n==="classic"&&r,c=l?s:e,d=l?a:t,[u,p]=v.useState(!_s.includes(c)),[m,h]=v.useState(String(c));v.useEffect(()=>{p(!_s.includes(c)),h(String(c))},[l,c]);function b(g=m){const _=qs(Number.parseInt(g,10));d(_),h(String(_))}function I(g){p(!1),h(String(g)),d(g)}function x(g){const _=qs(c+g);p(!0),h(String(_)),d(_)}function y(g){g.key==="Enter"&&(g.preventDefault(),b())}return o.jsxs("div",{className:"option-group count-picker",children:[o.jsx("div",{className:"section-title",children:i(l?"multimode.maxStages":"count.title")}),o.jsxs("div",{className:"option-row",children:[_s.map(g=>o.jsx("button",{type:"button",className:`option-btn${c===g&&!u?" active":""}`,onClick:()=>I(g),children:g},g)),o.jsx("button",{type:"button",className:`option-btn${u?" active":""}`,onClick:()=>{p(g=>!g),h(String(c))},children:i("count.customPlus")})]}),u?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"count-picker__custom",children:[o.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(-1),"aria-label":i("count.decrease"),children:"-"}),o.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")}),o.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(1),"aria-label":i("count.increase"),children:"+"})]}),o.jsx("p",{className:"option-help",children:c>=5?i(l?"multimode.highCountHint":"count.highCountHint"):i(l?"multimode.minMaxHint":"count.minMaxHint")})]}):null]})}const tx={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}},nx={512:.045,"1K":.067,"2K":.101,"4K":.151},rx={512:.134,"1K":.134,"2K":.134,"4K":.24};function sx(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function ox(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),s=sx(r),i=t==="nano-banana-pro"?rx:nx;return i[s]??i["1K"]??.003}function ax(e,t,n,r){return n==="gemini-api"?ox(t,r):tx[e]?.[t]??0}function ix(){const{t:e}=H(),t=f(m=>m.provider),n=f(m=>m.quality),r=f(m=>m.multimode),s=f(m=>m.multimodeMaxImages),i=f(m=>m.getResolvedSize)(),l=f(m=>m.imageModel),c=t==="oauth"||t==="grok"||t==="agy",d=ax(n,i,t,l),u=c?e("cost.free"):r?e("cost.multimodeApprox",{amount:(d*s).toFixed(3),count:s}):e("cost.approx",{amount:d.toFixed(3)}),p=c?"var(--green)":void 0;return o.jsxs("div",{className:"cost-estimate",children:[o.jsx("span",{children:e("cost.label")}),o.jsx("span",{className:"price",style:p?{color:p}:void 0,children:u})]})}function nd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const s=async()=>{try{const a=await jd();if(n)return;t(a),a.status==="starting"&&(r=setTimeout(s,3e3))}catch{n||t(null)}};return s(),()=>{n=!0,r&&clearTimeout(r)}},[]),e}function lx(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let s=!1;return Pd().then(a=>{s||t(a)}).catch(()=>{s||r(!0)}),()=>{s=!0}},[]),{data:e,error:n}}function rd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(ce())return;const n=pe();let r=!1,s=null;const a=async()=>{if(!(r||ce()||n!==pe()))try{const l=await we("/api/grok/status");if(r)return;const c=await l.json();if(r||ce()||n!==pe())return;t(c),c.status!=="ready"&&(s=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,s&&clearTimeout(s),window.removeEventListener(St,i)};return window.addEventListener(St,i),a(),i},[]),e}function sd(){const[e,t]=v.useState(null),[n,r]=v.useState(null),s=v.useRef(!1),a=v.useCallback(async()=>{if(!s.current||ce())return;const i=pe();try{const c=await(await we("/api/keys/status")).json();if(!s.current||ce()||i!==pe())return;t(c),r(null)}catch(l){if(!s.current||ce()||i!==pe())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return v.useEffect(()=>{if(ce())return;s.current=!0;let i=!1,l=null;const c=async()=>{await a(),i||(l=setInterval(a,3e4))},d=()=>{s.current=!1,i=!0,l&&clearInterval(l),window.removeEventListener(St,d)};return window.addEventListener(St,d),c(),d},[a]),{data:e,error:n,mutate:a}}function od(){const{t:e}=H(),t=nd(),{data:n}=lx(),r=rd(),{data:s}=sd(),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=s?.xai?.valid===!0,m=s?.gemini?.valid===!0||s?.vertex?.valid===!0,h=s?.atlascloud?.valid===!0,b=s?.minimax?.valid===!0,I=s?.nai?.valid===!0,x=qn(),y=Et(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":$t(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function cx({open:e,providerLabel:t,reason:n,hint:r,onClose:s}){const{t:a}=H(),i=Ue(e,s);if(!e)return null;const l=a("apiDisabled.title",{provider:t});return o.jsx("div",{className:"modal-backdrop",onClick:s,role:"presentation",children:o.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-label":l,tabIndex:-1,onClick:c=>c.stopPropagation(),children:[o.jsx("div",{className:"modal__title",children:l}),o.jsxs("div",{className:"modal__body",children:[o.jsx("p",{children:n}),r?o.jsx("p",{className:"modal__hint",children:r}):null]}),o.jsx("div",{className:"modal__actions",children:o.jsx("button",{type:"button",className:"modal__btn",onClick:s,"data-modal-initial-focus":!0,children:a("common.ok")})})]})})}const ar="core:",Es="mcp:",dx={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"}},Ns=io.map(e=>dx[e]);function ks(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Cs({tone:e}){return o.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function si(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 js({mcpProviders:e}){const{t}=H(),n=f(N=>N.provider),r=f(N=>N.mcpProvider??null),s=f(N=>N.setProvider),a=od(),i=qn(),l=f(N=>N.comfyWorkflow),c=f(N=>N.comfyVideoWorkflow),d=Et(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=N=>{const R=a[N.value];return N.value==="comfy"?u?t($t(d,i)):R.reason:R.ok?t("provider.statusReady"):R.reason},I=N=>N.enabled?N.status.state==="connected"?N.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):N.status.state==="connecting"?t("mcp.connecting"):N.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Ns.map(N=>{const R=a[N.value];return{value:`${ar}${N.value}`,searchText:`${N.provider} ${N.value==="comfy"?t("comfy.display.localMethod"):N.method}`,label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:N.value==="comfy"&&u?p:R.ok?"ok":"bad"}),o.jsxs("span",{children:[N.provider," ",N.value==="comfy"?t("comfy.display.localMethod"):N.method]})]}),sub:b(N)}})}],y=e.filter(N=>N.enabled).map(N=>({value:`${Es}${N.id}`,searchText:ks(N.id),label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:si(N)}),o.jsx("span",{children:ks(N.id)})]}),sub:I(N)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${Es}${r}`:`${ar}${n}`,_=r?null:Ns.find(N=>N.value===n)??null,S=r?e.find(N=>N.id===r)??null:null,w=_?.value==="comfy",j=w?t($t(d,i)):_?b(_):S?I(S):t("provider.statusDisconnected"),P=w?p:_?a[_.value].ok?"ok":"bad":S?si(S):"bad",M=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",q=N=>{if(N.startsWith(ar)){const k=N.slice(ar.length);if(!jt(k))return;const J=Ns.find(Z=>Z.value===k),T=a[k];if(k==="comfy"){s(k);return}if(!T.ok){h({label:J?`${J.provider} ${J.method}`:k,reason:T.reason,hint:T.hint});return}s(k);return}const R=N.slice(Es.length),$=e.find(k=>k.id===R);if(!$||!$.enabled||$.status.state!=="connected"){h({label:ks(R),reason:!$||!$.enabled?t("mcp.disabledProvider"):t("mcp.disconnectedSelection")});return}rs(R,f.setState,f.getState)};return o.jsxs("div",{className:"option-group provider-status-select","data-testid":"provider-status-select",children:[o.jsx("div",{className:"section-title",children:t("provider.authTitle")}),o.jsx(Fe,{groups:x,value:g,onChange:q,triggerSub:w?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),o.jsxs("div",{className:"provider-status-line","data-tone":P,role:"status","aria-live":"polite",children:[o.jsx(Cs,{tone:P}),o.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),o.jsx("span",{className:"provider-status-line__value",children:j})]}),w&&i.observedAt!==null?o.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,w&&d.code==="selected-missing"&&i.catalog?.comfy?.status==="disconnected"?o.jsx("p",{className:"provider-helper",children:t("comfy.statusOffline")}):null,o.jsxs("div",{className:"provider-auth-chip",title:t(w?"comfy.display.localMethod":"provider.authMethodTitle"),children:[o.jsx("span",{children:M}),P!=="bad"&&!w?o.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),o.jsx(cx,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const ux=[{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"}],mx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function px(){const{t:e}=H(),t=f(a=>a.grokAspectRatio),n=f(a=>a.grokResolution),r=f(a=>a.setGrokAspectRatio),s=f(a=>a.setGrokResolution);return o.jsxs("div",{className:"option-group grok-size-picker",children:[o.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")}),o.jsx("div",{className:"grok-size-picker__aspects",children:ux.map(a=>o.jsx("button",{type:"button",className:`option-btn grok-size-picker__aspect${t===a.value?" active":""}`,onClick:()=>r(a.value),children:a.label},a.value))}),o.jsx("div",{className:"section-title",style:{marginTop:8},children:e("size.grokResolutionTitle")}),o.jsx("div",{className:"grok-size-picker__resolutions",children:mx.map(a=>o.jsx("button",{type:"button",className:`option-btn grok-size-picker__res${n===a.value?" active":""}`,onClick:()=>s(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 hx(){const{t:e}=H(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return o.jsx(Oe,{title:e("quality.grokModelTitle"),items:fx,value:t,onChange:n})}function ad({values:e,value:t,defaultValue:n,onChange:r,allowAuto:s=!1,disabled:a,ariaLabel:i}){const{t:l}=H(),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 o.jsxs("div",{className:`ctl-duration${p?" is-auto":""}${a?" is-disabled":""}`,children:[o.jsxs("div",{className:"ctl-duration__head",children:[o.jsx("output",{htmlFor:c,className:"ctl-duration__value",children:p?`${l("size.autoLabel")} · ${e[u]}s`:`${e[u]}s`}),s?o.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]}),o.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])}),o.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[o.jsxs("span",{children:[m,"s"]}),o.jsxs("span",{children:[h,"s"]})]})]})}const gx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],yx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),oi=[3,5,8,10,12,15],vx=[{value:po,label:"Grok V",sub:"Fast"},{value:pt,label:"Grok V1.5",sub:"HD"}];function bx(){const{t:e}=H(),t=f(k=>k.videoModelSelected),n=f(k=>k.selectVideoModel),r=f(k=>k.activeVideoRefCount()),s=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=>lc(k)).filter(k=>k?.category==="camera-motion"),_=15,S=Ru(r,s),w=mc(I),j=is(t,"1080p",S),P=is(pt,"1080p",S),M=gx.map(k=>k.value==="1080p"?{...k,disabled:!P}:k);v.useEffect(()=>{is(t,c,S)||d("720p")},[S,c,d,t]);const q=k=>{if(k==="1080p"){if(!P)return;j||n(pt)}d(k)},[N,R]=v.useState(null);v.useEffect(()=>{we("/api/config/grok-planner").then(k=>k.json()).then(R).catch(()=>{})},[]);const $=async k=>{const J=N?.model;R(T=>T?{...T,model:k}:null);try{const T=await we("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:k})});if(!T.ok)throw new Error(`HTTP ${T.status}`)}catch(T){if(R(Z=>Z&&J?{...Z,model:J}:Z),T?.code==="LAN_TOKEN_REQUIRED")return;b(e("video.plannerUpdateFailed"),!0)}};return o.jsxs("div",{className:"right-panel-settings video-controls",children:[o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")??"Model"}),o.jsx("div",{className:"option-row",children:vx.map(k=>o.jsxs("button",{type:"button",className:`option-btn${t===k.value?" active":""}`,onClick:()=>n(k.value),children:[k.label,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:k.sub})]},k.value))})]}),o.jsxs("div",{className:"provider-compat-note",role:"note",children:[o.jsx("strong",{children:e("video.modeLabel")}),o.jsx("span",{children:e(`video.mode.${S}`,{n:r})})]}),w?o.jsxs("div",{className:"provider-compat-note",role:"note",children:[o.jsx("strong",{children:e("common.continuity")}),o.jsx("span",{children:w})]}):null,g.length>0&&o.jsx(Wo,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(k=>o.jsx(Uc,{onRemove:()=>y(k.id),removeLabel:e("common.removeNamed",{name:k.name}),children:k.name},k.id))}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.seriesTopicTitle")??"시리즈 주제"}),o.jsx("input",{type:"text",className:"video-topic-input",placeholder:e("video.seriesTopicPlaceholder")??"예: 한국 여행 브이로그",value:m,onChange:k=>h(k.target.value)})]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.durationTitle")}),o.jsx(ad,{values:oi.filter(k=>k<=_),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??oi[0])})]}),r===1&&o.jsx(Oe,{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:s,onChange:a}),o.jsx(Oe,{title:e("video.resolutionTitle"),help:P?void 0:e("video.resolution1080Help"),items:M,value:c,onChange:q}),o.jsx(Oe,{title:e("video.aspectTitle"),items:yx,value:u,onChange:p}),N&&o.jsx("div",{className:"video-controls__pills",children:o.jsx(Fe,{className:"video-controls__pill",items:N.options.map(k=>({value:k,label:k})),value:N.model,onChange:k=>{$(k)},ariaLabel:e("video.plannerModelTitle")})}),o.jsxs("details",{className:"provider-compat-details",style:{marginTop:8},children:[o.jsx("summary",{children:e("common.activePrompt")}),o.jsx("p",{children:Ar})]})]})}const ai=e=>Symbol.iterator in e,ii=e=>"entries"in e,li=(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[s,a]of n)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},xx=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=n.next(),a=r.next()}return!!s.done&&!!a.done};function Ix(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:ai(e)&&ai(t)?ii(e)&&ii(t)?li(e,t):xx(e,t):li({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Sx(e){const t=an.useRef(void 0);return n=>{const r=e(n);return Ix(t.current,r)?t.current:t.current=r}}const wx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function _x(){const{t:e}=H(),t=f(Sx(zm)),n=f(u=>u.setNaiOption),r=f(u=>u.resetNaiOptions),s=f(u=>u.imageModel),a=f(u=>u.setImageModel),i=f(u=>u.sizePreset),l=f(u=>u.setSizePreset),c=$s(s),d=t.seed===null?"":String(t.seed);return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.modelTitle")}),o.jsx(Fe,{items:Gi.map(u=>({value:u.value,label:u.shortLabel})),value:s,onChange:u=>{$s(u)||(n("straightAlpha",!1),n("qualityPresetId","standard")),a(u)},ariaLabel:e("nai.panel.modelTitle")})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.sizeTitle")}),o.jsx("div",{className:"option-row",children:wx.map(u=>o.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"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:u.value.replace("x","×")})]},u.value))})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.samplingTitle")}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.sampler")}),o.jsx(Fe,{items:al.map(u=>({value:u,label:u})),value:t.sampler,onChange:u=>n("sampler",u),ariaLabel:e("nai.field.sampler")})]}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.noiseSchedule")}),o.jsx(Fe,{items:il.map(u=>({value:u,label:u})),value:t.noiseSchedule,onChange:u=>n("noiseSchedule",u),ariaLabel:e("nai.field.noiseSchedule")})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.autoSmea,onChange:u=>n("autoSmea",u.target.checked)}),o.jsx("span",{children:e("nai.field.autoSmea")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.autoSmea")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.steps")}),o.jsx("input",{type:"range",min:Er.min,max:Er.max,step:1,value:t.steps,onChange:u=>n("steps",Number(u.target.value))}),o.jsx("output",{children:t.steps})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.scale")}),o.jsx("input",{type:"range",min:Nr.min,max:Nr.max,step:.1,value:t.scale,onChange:u=>n("scale",Number(u.target.value))}),o.jsx("output",{children:t.scale.toFixed(1)})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.cfgRescale")}),o.jsx("input",{type:"range",min:kr.min,max:kr.max,step:.01,value:t.cfgRescale,onChange:u=>n("cfgRescale",Number(u.target.value))}),o.jsx("output",{children:t.cfgRescale.toFixed(2)})]}),o.jsx("p",{className:"option-help",children:e("nai.help.cfgRescale")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.decrisper,onChange:u=>n("decrisper",u.target.checked)}),o.jsx("span",{children:e("nai.field.decrisper")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.decrisper")})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.presetTitle")}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.ucPreset")}),o.jsx(Fe,{items:ll.map(u=>({value:u,label:e(`nai.ucPreset.${u}`)})),value:t.ucPresetId,onChange:u=>n("ucPresetId",u),ariaLabel:e("nai.field.ucPreset")})]}),c?o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.qualityPreset")}),o.jsx(Fe,{items:cl.map(u=>({value:u,label:e(`nai.qualityPreset.${u}`)})),value:t.qualityPresetId,onChange:u=>n("qualityPresetId",u),ariaLabel:e("nai.field.qualityPreset")})]}):null]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.outputTitle")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.varietyPlus,onChange:u=>n("varietyPlus",u.target.checked)}),o.jsx("span",{children:e("nai.field.varietyPlus")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.varietyPlus")}),c?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.straightAlpha,onChange:u=>n("straightAlpha",u.target.checked)}),o.jsx("span",{children:e("nai.field.straightAlpha")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.straightAlpha")})]}):null,o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.seed")}),o.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),dl))}})]}),o.jsx("p",{className:"option-help",children:e("nai.help.seed")})]}),o.jsx("div",{className:"option-group nai-controls",children:o.jsx("button",{type:"button",className:"option-btn",onClick:r,children:e("nai.resetDefaults")})})]})}const Ex="",id=3;function ci(e,t,n,r){const s=[],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),s.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),s.push({filename:l,current:!1,label:i.name||l,source:i.kind==="element"?"element":"asset"}))}return s}function Nx(e,t){return e[t]??null}function ld(e,t,n){const r=!t||e.some(s=>s.filename===t);return[{value:Ex,label:n("mcp.referenceNone")},...r?[]:[{value:t,label:t,sub:n("mcp.referenceMissing")}],...e.map(s=>({value:s.filename,label:s.label??s.filename,sub:s.current?n("mcp.referenceCurrent"):s.source?n(`mcp.referenceSource.${s.source}`):void 0}))]}function Ps({id:e,label:t,value:n,candidates:r,disabled:s,title:a,help:i,onChange:l,t:c}){return o.jsxs("div",{className:"mcp-reference-slot",children:[o.jsx("label",{className:"mcp-reference-slot__label",htmlFor:e,children:t}),o.jsx(Fe,{id:e,items:ld(r,n??"",c),value:n??"",onChange:l,ariaLabel:t,placeholder:c("mcp.referenceSelect"),disabled:s,title:a,portal:!0}),i?o.jsx("p",{className:"option-help",children:i}):null]})}function kx({index:e,images:t,selection:n,disabled:r,onChange:s,t:a}){const i=Nx(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),s({...n,references:I})},p=b=>{if(!i)return;const I=[...n.references],{tag:x,...y}=i;I[e]={...y,...b?{tag:b}:{}},s({...n,references:I})},m=!!(i?.tag&&!xo(i.tag)),h=`mcp-reference-tag-error-${e}`;return o.jsxs("div",{className:"mcp-reference-slot__reference",children:[o.jsx(Fe,{items:ld(d,i?.filename??"",a),value:i?.filename??"",onChange:u,ariaLabel:a("mcp.imageReferenceAria",{index:e+1}),placeholder:a("mcp.referenceSelect"),disabled:r,portal:!0}),o.jsxs("div",{children:[o.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?o.jsx("p",{id:h,className:"settings-row__microcopy",role:"alert",children:a("mcp.referenceTagInvalid")}):null]})]})}function Cx({selection:e,disabled:t,onChange:n,t:r}){const s=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=id,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 Co(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 o.jsxs("div",{children:[o.jsx("input",{ref:s,className:"sr-only",type:"file",accept:"image/png,image/jpeg,image/webp",onChange:d=>{c(d)},disabled:t||l}),o.jsx("button",{type:"button",className:"option-btn",onClick:()=>s.current?.click(),disabled:t||l,children:r("mcp.referenceAttachLocal")}),o.jsx("p",{className:"option-help",children:r("mcp.referenceAttachHelp")}),a?o.jsx("p",{className:"settings-row__microcopy",role:"alert",children:a}):null]})}function jx({images:e,selection:t,disabled:n,onChange:r,t:s}){return o.jsxs("div",{className:"mcp-reference-slot",children:[o.jsx("div",{className:"mcp-reference-slot__label",children:s("mcp.imageReferencesLabel")}),Array.from({length:id},(a,i)=>o.jsx(kx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:s},i)),o.jsx(Cx,{selection:t,disabled:n,onChange:r,t:s})]})}function Px({inputRoles:e,disabled:t}){const{t:n}=H(),r=f(p=>p.history),s=f(p=>p.currentImage),a=f(p=>p.assets),i=f(p=>p.mcpReferenceSelection)??qe(),l=v.useMemo(()=>ci(r,s,a,!1),[r,s,a]),c=v.useMemo(()=>ci(r,s,a,!0),[r,s,a]),d=p=>Xh(p,f.setState,f.getState),u=i.startFrameFilename?void 0:n("mcp.endFrameNeedsStart");return o.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?o.jsx(Ps,{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")?o.jsx(Ps,{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")?o.jsx(jx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?o.jsx(Ps,{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 Ax(e){return Array.isArray(e)&&e.includes("image_references")}function Rx(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function _w(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 Ew(e){return e.length>3}function Tx({inputRoles:e,disabled:t}){const{t:n}=H(),r=f(d=>d.assets),s=f(d=>d.mcpCharacterElementId??null),a=f(d=>d.selectedElementIds??[]);if(!Ax(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=Rx({mentionElementIds:a,characterElementId:s})==="conflict",c=!!t||a.length>0;return o.jsxs("div",{className:"mcp-character-slot","data-testid":"mcp-character-slot",children:[o.jsx("div",{className:"section-title",children:n("mcp.characterSlotLabel")}),o.jsxs("select",{value:s??"",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:[o.jsx("option",{value:"",children:n("mcp.characterSlotNone")}),i.map(d=>o.jsx("option",{value:d.id,children:d.name},d.id))]}),l?o.jsx("p",{className:"option-help",role:"alert",children:n("mcp.characterSlotConflictHint")}):null]})}const di=new Set(["duration","resolution","quality","mode"]);function ui(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ta(e){return e.options&&e.options.length>0?ui(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):ui([e.min,...e.default!==void 0?[e.default]:[],e.max])}function mi(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 Mx(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function Lx(e){return[...ta(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function Fx({parameter:e,value:t,disabled:n,onChange:r}){const{t:s}=H();if(e.name==="duration"&&e.type==="number"){const l=Lx(e);if(l.length>1){const c=mi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:c}),o.jsx(ad,{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=ta(e);if(a.length===0)return null;const i=mi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:i}),o.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i,children:[e.required?null:o.jsx("button",{type:"button",className:`option-btn${t===void 0?" active":""}`,"aria-pressed":t===void 0,disabled:n,onClick:()=>r(null),children:s("size.autoLabel")}),a.map(l=>o.jsx("button",{type:"button",className:`option-btn${t===l?" active":""}`,"aria-pressed":t===l,disabled:n,onClick:()=>r(l),title:e.description,children:Mx(l,s)},`${typeof l}:${String(l)}`))]})]})}function pi({entries:e,parameters:t,disabled:n,onParameter:r}){return o.jsx(o.Fragment,{children:e.map(s=>o.jsx(Fx,{parameter:s,value:t[s.name],disabled:n,onChange:a=>r(s.name,a)},s.name))})}function Ox({entry:e,ratio:t,parameters:n,disabled:r,onRatio:s,onParameter:a}){const{t:i}=H(),l=e.capabilities.aspectRatios.filter(m=>m!=="auto"),c=e.capabilities.parameters.filter(m=>ta(m).length>0),d=c.filter(m=>di.has(m.name)),u=c.filter(m=>!di.has(m.name)),p=e.capabilities.inputRoles.some(m=>m==="start_image"||m==="end_image"||m==="image_references"||m==="video_references");return o.jsxs("div",{className:"mcp-model-presets","data-capability-source":e.capabilities.source,children:[l.length>0?o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:i("mcp.aspectRatioLabel")}),o.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i("mcp.aspectRatioLabel"),children:[o.jsx("button",{type:"button",className:`option-btn${t===null?" active":""}`,"aria-pressed":t===null,disabled:r,onClick:()=>s(null),children:i("size.autoLabel")}),l.map(m=>o.jsx("button",{type:"button",className:`option-btn${t===m?" active":""}`,"aria-pressed":t===m,disabled:r,onClick:()=>s(m),children:m},m))]})]}):null,o.jsx(pi,{entries:d,parameters:n,disabled:r,onParameter:a}),p?o.jsxs("div",{className:"mcp-tool-inputs",children:[o.jsx("div",{className:"section-title",children:i("mcp.toolInputsLabel")}),o.jsx(Px,{inputRoles:e.capabilities.inputRoles,disabled:r}),o.jsx(Tx,{inputRoles:e.capabilities.inputRoles,disabled:r})]}):null,u.length>0?o.jsxs("details",{className:"mcp-advanced-presets",children:[o.jsx("summary",{children:i("mcp.advancedPresetsLabel")}),o.jsx(pi,{entries:u,parameters:n,disabled:r,onParameter:a})]}):null,l.length===0&&c.length===0?o.jsx("p",{className:"option-help",children:i("mcp.providerDefaultsHelp")}):null]})}const ir={image:[],video:[]},Dx={};function Gx(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function zx({record:e}){const{t}=H(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),s=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??Dx,[c,d]=v.useState(ir),[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(ir),p("idle");return}const _=new AbortController;return d(ir),p("loading"),Mc(n,_.signal).then(S=>{_.signal.aborted||(d(S),p("ready"))}).catch(S=>{S.name!=="AbortError"&&(_.signal.aborted||(d(ir),p("error")))}),()=>_.abort()},[n,I,m]),!n)return null;const x=s==="video"?c.video:c.image,y=x.find(_=>_.id===r)??null,g=_=>Wh(_,f.setState,f.getState);return o.jsxs("div",{className:"mcp-generation-controls","data-testid":"mcp-generation-controls",children:[o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"section-title mcp-generation-controls__header",children:[o.jsxs("span",{children:[Gx(n)," · MCP"]}),o.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>rs(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),I?null:o.jsx("p",{className:"option-help",children:t("mcp.disconnectedSelection")}),b?o.jsx("p",{className:"option-help",children:t("mcp.higgsfieldLocked")}):null]}),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"option-group",children:o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:`option-btn${s==="image"?" active":""}`,"aria-pressed":s==="image",onClick:()=>g("image"),children:t("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${s==="video"?" active":""}`,"aria-pressed":s==="video",onClick:()=>g("video"),children:t("grokMode.video")})]})}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:t("mcp.modelSectionTitle")}),u==="loading"?o.jsx("p",{className:"option-help",role:"status",children:t("mcp.loadingModels")}):u==="error"?o.jsxs("div",{className:"mcp-catalog-state",role:"alert",children:[o.jsx("span",{children:t("mcp.modelsLoadFailed")}),o.jsx("button",{type:"button",className:"settings-action-btn",onClick:()=>h(_=>_+1),children:t("mcp.retryModels")})]}):u==="ready"&&x.length===0?o.jsx("p",{className:"option-help",children:t("mcp.noModels")}):y?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"mcp-selected-model",children:[o.jsx("strong",{children:y.label}),y.description?o.jsx("span",{children:y.description}):null]}),o.jsx(Ox,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>Jh(_,f.setState),onParameter:(_,S)=>Yh(_,S,f.setState,f.getState)})]}):o.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function qx(e,t,n,r){const s=e.catalog?.comfy,a=e.phase==="ready"&&s?.status==="ready",i=[];for(const l of["image","video"])i.push({label:r(l==="image"?"comfy.kindImage":"comfy.kindVideo"),items:(s?.models[l]??[]).map(c=>({value:l==="video"?`${zt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!Ot(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 $x(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(zt),s=r?e.slice(zt.length):e;Et(Zo(),r?{comfyVideoWorkflow:s}:{comfyWorkflow:s}).selectedAvailable&&(r?n.setComfyVideoWorkflow(s):n.setComfyWorkflow(s))}function Ux(){const{t:e}=H(),t=v.useId(),n=`${t}-status`,r=`${t}-workflow`,s=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=qn(),u=Et(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${zt}${l}`:i??"",m=qx(d,u,p,e);return s!=="comfy"||a?null:o.jsxs("div",{className:"option-group comfy-generation-controls","data-testid":"comfy-generation-controls","aria-busy":d.phase==="loading",children:[o.jsx("label",{className:"section-title",htmlFor:r,children:e("comfy.workflowsTitle")}),o.jsxs("p",{id:n,className:"option-help",children:[e($t(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),o.jsx(Fe,{id:r,groups:m,value:p,onChange:h=>$x(h,{provider:s,mcpProvider:a}),ariaLabel:e("comfy.display.chooseWorkflow"),ariaDescribedBy:n,placeholder:e("comfy.display.chooseWorkflow"),portal:!0}),u.selected?o.jsxs("p",{className:"option-help",children:[e(u.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage"),": ",u.selected.label,o.jsx("br",{}),o.jsx("code",{children:u.selected.id})]}):null,o.jsx("p",{className:"option-help",children:e("comfy.display.controlsHelp")}),o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:"option-btn",onClick:()=>{d.refresh()},children:e("comfy.display.refresh")}),o.jsx("button",{type:"button",className:"option-btn",onClick:()=>c("providers"),children:e("comfy.display.manage")})]})]})}const Hx=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],lr=[{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"}],Kx=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Lr={"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 Vx(e){for(const[t,n]of Object.entries(Lr))for(const[r,s]of Object.entries(n))if(s===e)return{ratio:t,res:r};return null}function Bx(e,t){const n=e/t;let r="1:1",s=1/0;const a=[...Object.keys(Lr),"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<s&&(s=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 cd(){const{t:e}=H(),t=f(D=>D.provider),n=f(D=>D.quality),r=f(D=>D.setQuality),s=f(D=>D.format),a=f(D=>D.setFormat),i=f(D=>D.moderation),l=f(D=>D.setModeration),c=f(D=>D.multimode),d=f(D=>D.setMultimode),u=f(D=>D.imageModel),p=f(D=>D.setImageModel),m=f(D=>D.selectVideoModel),h=f(D=>D.sizePreset),b=f(D=>D.customW),I=f(D=>D.customH),x=f(D=>D.setSizePreset),y=f(D=>D.setCustomSize),g=f(D=>D.uiMode),_=f(D=>D.videoModelSelected),S=f(D=>D.mcpProvider??null),{providers:w}=Lc(),j=g==="classic",P=t==="grok"||t==="grok-api",M=t==="agy",q=t==="gemini-api",N=M||q,R=t==="nai",$=t==="comfy",k=P||N||R,J=h==="custom"?`${b}x${I}`:"1024x1024",T=q&&h==="auto",Z=q&&!T?Vx(J):null,te=Z??{ratio:"",res:""},de=q&&!T&&h==="custom"&&!Z,ye=u==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[ve,F]=v.useState(!1),[O,Q]=v.useState(String(b)),[V,ae]=v.useState(String(I)),fe=(D,le)=>{const se=Lr[D||"1:1"]?.[le||"1K"]||"1024x1024",[G,C]=se.split("x").map(Number);F(!1),x("custom"),y(G,C)},ie=()=>{const D=Number(O),le=Number(V);!Number.isFinite(D)||!Number.isFinite(le)||D<=0||le<=0||(x("custom"),y(D,le),F(!1))},Ee=[{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")}],he=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],Se=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],Ne=P?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:M?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:q?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:R?{title:e("nai.compatTitle"),body:e("nai.compatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},ke=D=>{D==="video"?m("grok-imagine-video"):p(u)};return S?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(zx,{record:w.find(D=>D.id===S)??null})]}):$?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(Ux,{})]}):o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsxs("details",{className:"provider-compat-details",children:[o.jsx("summary",{children:Ne.title}),o.jsx("p",{children:Ne.body})]}),P&&o.jsx("div",{className:"option-group grok-mode-toggle",children:o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:`option-btn${_?"":" active"}`,onClick:()=>ke("image"),children:e("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>ke("video"),children:e("grokMode.video")})]})}),_?o.jsx(bx,{}):o.jsxs(o.Fragment,{children:[M?null:P?o.jsxs(o.Fragment,{children:[o.jsx(hx,{}),o.jsx(px,{})]}):R?o.jsx(_x,{}):q?o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("quality.grokModelTitle"),items:Se,value:ye,onChange:p}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")||"Aspect Ratio"}),[lr.slice(0,3),lr.slice(3,6),lr.slice(6,8),lr.slice(8)].map((D,le)=>o.jsx("div",{className:"option-row",children:D.map(se=>o.jsx("button",{type:"button",className:`option-btn${te.ratio===se.value?" active":""}`,onClick:()=>fe(se.value,te.res),children:se.label},se.value))},le))]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("size.grokResolutionTitle")||"Resolution"}),o.jsx("div",{className:"gemini-resolution-grid",children:Kx.map(D=>o.jsxs("button",{type:"button",className:`option-btn${te.res===D.value?" active":""}`,onClick:()=>fe(te.ratio,D.value),children:[o.jsx("span",{children:D.label}),o.jsx("br",{}),o.jsx("small",{children:Lr[te.ratio]?.[D.value]?.replace("x","×")||""})]},D.value))})]}),o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"option-row",children:[o.jsxs("button",{type:"button",className:`option-btn${T?" active":""}`,onClick:()=>{F(!1),x("auto")},children:[e("size.autoLabel"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.autoSub")})]}),o.jsxs("button",{type:"button",className:`option-btn${de||ve?" active":""}`,onClick:()=>F(D=>!D),children:[e("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),ve?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"option-row size-picker__custom-row",children:[o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:O,onChange:D=>Q(D.target.value.replace(/\D/g,"")),placeholder:e("size.width")}),o.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:V,onChange:D=>ae(D.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(O)>0&&Number(V)>0?o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:e("size.normalizedPreview")}),o.jsx("strong",{children:(()=>{const D=Bx(Number(O),Number(V));return`${D.ratio} · ${D.res}`})()})]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:ie,children:e("settings.apiKeys.save")})]}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("quality.title"),items:Ee,value:n,onChange:r}),o.jsx(Qb,{})]}),k?null:o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("format.title"),items:Hx,value:s,onChange:a}),o.jsx(Oe,{title:e("moderation.title"),items:he,value:i,onChange:l}),o.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),j&&!N&&!R&&o.jsx("div",{className:"option-group multimode-toggle",children:o.jsxs("button",{type:"button",className:`multimode-toggle__button${c?" active":""}`,"aria-pressed":c,title:e("multimode.tooltip"),onClick:()=>d(!c),children:[o.jsx("span",{children:e("multimode.label")}),o.jsx("span",{children:e("multimode.shortHint")})]})}),N||R?null:o.jsx(ex,{}),R?null:o.jsx(ix,{})]})]})}const Wx=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-BFWQO8OT.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Jx=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-DBycmShA.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),Yx=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-DZtYZm-D.js"),__vite__mapDeps([6,1,2])).then(e=>({default:e.GenerationRequestLogPanel})));function Xx(){const e=f(y=>y.rightPanelOpen),t=f(y=>y.toggleRightPanel),n=f(y=>y.promptLibraryOpen),r=f(y=>y.setPromptLibraryOpen),s=f(y=>y.promptBuilderOpen),a=f(y=>y.togglePromptBuilder),i=f(y=>y.workspaceProfile),{t:l}=H(),[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=Bf(i)&&!c,h=c?e:!0,b=Ue(c&&e,t),I=u?"log":s&&m?"builder":n?"library":"settings",x=y=>{p(y==="log"),y==="builder"?(s||a(),n&&r(!1)):y==="library"?(s&&a(),n||r(!0)):(s&&a(),n&&r(!1))};return o.jsxs(o.Fragment,{children:[c&&e?o.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":l("panel.closeSettings"),onClick:t}):null,o.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&&o.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?">":"<"}),o.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!e,children:[o.jsxs("div",{className:"right-panel-tabs",role:"tablist","aria-label":l("panel.detailSettings"),children:[m?o.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,o.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")}),o.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")}),o.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?o.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Jx,{variant:"sidebar"})})}):I==="library"?o.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Wx,{variant:"embedded"})})}):I==="log"?o.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Yx,{})})}):o.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:o.jsx(cd,{})})]})]})]})}function Zx(e){const t=e.currentTarget;if(t.scrollWidth<=t.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const r=t.scrollLeft<=0,s=t.scrollLeft+t.clientWidth>=t.scrollWidth-1,a=e.deltaY<0,i=e.deltaY>0;a&&r||i&&s||(e.preventDefault(),t.scrollLeft+=e.deltaY)}function Qx({id:e}){const{t}=H();return o.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function eI({id:e,count:t}){const{t:n}=H(),r=Math.min(t,4);return o.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":n("history.generatingCollection",{count:t}),children:Array.from({length:r},(s,a)=>o.jsx("div",{className:"collection-mini collection-mini--skeleton"},a))},`coll-${e}`)}function tI({sequenceId:e,images:t}){const n=f(l=>l.showHistorySequence),s=f(l=>l.multimodePreviewFlightId)===`history:${e}`,a=t.slice(0,4),{t:i}=H();return o.jsx("button",{type:"button",className:`history-thumb history-thumb--collection${s?" active":""}`,onClick:()=>n(e),"aria-label":i("common.imageCollection",{n:t.length}),children:a.map((l,c)=>!l.thumb&&(Ye(l.url)||Ye(l.image))?o.jsx(Ut,{className:"collection-mini"},c):o.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,s]=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&&s(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 rI(){const e=f(g=>g.history),t=f(g=>g.currentImage),n=f(g=>g.historyStripLayout),r=f(g=>g.selectHistory),s=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}=H(),m=t?Ae(t):null,h=v.useMemo(()=>xr(e.filter(mn)),[e]),b=v.useMemo(()=>{const g=[];for(const _ of a){const S=i[_.id];if(_.kind==="multimode"&&S){g.push({type:"collection-skeleton",id:_.id,count:S.requested});for(let w=0;w<S.requested;w++)S.images[w]||g.push({type:"skeleton",id:`${_.id}_${w}`,count:1})}else g.push({type:"skeleton",id:_.id,count:1})}return g},[a,i]),{completedSequences:I,sequenceFirstKeys:x}=v.useMemo(()=>{const g=new Map,_=new Set;for(const S of h)if(S.sequenceId&&(S.sequenceTotalRequested??0)>1){g.has(S.sequenceId)||_.add(Ae(S));const w=g.get(S.sequenceId)||[];w.push(S),g.set(S.sequenceId,w)}return{completedSequences:g,sequenceFirstKeys:_}},[h]);v.useEffect(()=>{m&&l.current[m]?.scrollIntoView({block:"nearest",inline:"nearest"})},[m,h]);const y=(g,_)=>{const S=u.supported?u.visibleKeys.has(g):!0;return o.jsx("div",{ref:w=>{l.current[g]=w,u.register(g,w)},className:"history-thumb","data-history-lazy-key":g,"aria-hidden":S?void 0:!0,style:{padding:0,overflow:"hidden"},children:S?_:null},g)};return o.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:Zx,"data-layout":n,children:[o.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:s,"aria-label":p("history.openGalleryAria"),title:p("history.openGalleryTitle"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),b.map(g=>g.type==="collection-skeleton"?o.jsx(eI,{id:g.id,count:g.count},`coll-${g.id}`):o.jsx(Qx,{id:g.id},g.id)),h.map(g=>{const _=Ae(g),S=m===_;if(g.sequenceId&&I.has(g.sequenceId)&&x.has(_)){const w=I.get(g.sequenceId);return[y(`coll-${g.sequenceId}`,o.jsx(tI,{sequenceId:g.sequenceId,images:w})),...w.map(j=>{const P=Ae(j),M=m===P;return xe(j)?y(P,o.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${M?" active":""}`,onClick:()=>r(j),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(j))),q.dataTransfer.effectAllowed="copy"},children:[j.thumb?o.jsx("img",{src:j.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Ut,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(P,o.jsx("img",{src:j.thumb||j.url||j.image,alt:"",className:`history-thumb history-thumb--fade-in${M?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(j),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:j.url||j.image,filename:j.filename})),q.dataTransfer.effectAllowed="copy"}}))})]}return g.sequenceId&&I.has(g.sequenceId)&&!x.has(_)?null:xe(g)?y(_,o.jsxs("div",{className:`history-thumb history-thumb--video${S?" active":""}`,onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(g))),w.dataTransfer.effectAllowed="copy"},children:[g.thumb?o.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Ut,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(_,o.jsx("img",{src:g.thumb||g.url||g.image,alt:"",className:`history-thumb${S?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:g.url||g.image,filename:g.filename})),w.dataTransfer.effectAllowed="copy"}}))})]})}const fi=3e3;function sI(){const{t:e}=H(),t=f(d=>d.toastLog),n=f(d=>d.errorCardLog),r=f(d=>d.dismissToast),s=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)},fi);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),s(p.id)},fi);d.set(m,h)}}},[s,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=Ve[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:o.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 o.jsxs("div",{className:u,role:d.error?"alert":"status",children:[o.jsx("span",{className:"toast__message",children:d.message}),d.kind==="error-card"&&(d.cta==="reauth"||d.cta==="reload")?o.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,o.jsx("button",{type:"button",className:"toast__dismiss","aria-label":e("common.dismiss"),onClick:()=>d.kind==="error-card"?s(d.id):r(d.id),children:o.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round"})})})]},d.key)})})}function oI(){return null}function aI(e,t="en"){if(!e)return"earlier";const n=new Date(e);if(Number.isNaN(n.getTime()))return"earlier";const s=Math.floor((new Date().getTime()-n.getTime())/864e5);return s===0?"today":s===1?"yesterday":s<7?"thisWeek":new Intl.DateTimeFormat(t,{year:"numeric",month:"short",day:"numeric"}).format(n)}function iI(e,t,n){async function r(i){if(i.setId)try{await Ie.getState().loadSet(i.setId),f.getState().setUIMode("card-news"),e()}catch{t(n("gallery.openCardNewsSetFailed"),!0)}}async function s(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($v(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:a}}const lI=["ArrowLeft","ArrowRight","Home","End"];function cI(){return v.useCallback(e=>{if(!lI.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,s=r?n.indexOf(r):-1,a=e.key==="Home"?0:e.key==="End"?n.length-1:s<0?0:(s+(e.key==="ArrowRight"?1:-1)+n.length)%n.length,i=n[a];i?.focus(),i?.click()},[])}function As({className:e,ariaLabel:t,tabs:n,value:r,onChange:s}){const a=cI(),i=n.find(c=>c.value===r),l=i&&!i.disabled?i.value:n.find(c=>!c.disabled)?.value;return o.jsx("div",{className:e,role:"tablist","aria-label":t,onKeyDown:a,children:n.map(c=>o.jsx("button",{type:"button",role:"tab","aria-selected":c.value===r,tabIndex:c.value===l?0:-1,className:c.value===r?"active":"",onClick:()=>s(c.value),disabled:c.disabled,children:c.label},c.value))})}function dI({item:e,onOpen:t,onCopyPath:n,onDownloadManifest:r}){const{t:s}=H(),i=e.cards?.find(l=>l.headline)?.headline||e.headline||s("gallery.cardNewsSet");return o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>t(e),title:i,children:[e.image?o.jsx("img",{src:e.image,alt:i,loading:"lazy"}):null,o.jsxs("div",{className:"gallery__caption",children:[o.jsx("small",{children:s("gallery.cardNewsSet")}),o.jsx("span",{className:"gallery__caption-text",children:i})]}),o.jsx("div",{className:"gallery-card-news-strip",children:(e.cards||[]).slice(0,5).map((l,c)=>o.jsxs("span",{children:[l.url?o.jsx("img",{src:l.url,alt:l.headline??"",loading:"lazy"}):null,o.jsx("em",{children:l.cardOrder??c+1})]},`${l.url}-${c}`))})]}),o.jsxs("div",{className:"gallery-card-news-actions",children:[o.jsx("span",{children:s("gallery.cardNewsCount",{n:e.cards?.length??0})}),o.jsx("button",{type:"button",onClick:()=>t(e),children:s("gallery.openCardNewsSet")}),o.jsx("button",{type:"button",onClick:l=>n(e,l),children:s("gallery.copyCardNewsSetPath")}),o.jsx("button",{type:"button",onClick:l=>r(e,l),children:s("gallery.downloadCardNewsManifest")})]})]})}const uI=[{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 mI(e,t,n,r){const s=n();switch(e){case"animate":{if(!t.filename)return;try{await s.animateImage(t.filename,t.prompt??void 0)&&s.showToast(r("toast.animateDone"))}catch(a){s.showToast(a instanceof Error?a.message:r("toast.animateFailed"),!0)}break}case"edit":{s.selectHistory(t),s.openCanvas();break}case"useAsRef":{const a=t.url||t.image;if(!a)return;try{const l=await(await we(a)).blob(),c=new File([l],t.filename||"reference.png",{type:l.type});await s.addReferences([c]),s.showToast(r("chain.refAdded"))}catch(i){if(i?.code==="LAN_TOKEN_REQUIRED")return;s.showToast(r("chain.refFailed"),!0)}break}case"rebake":{try{const{continueFromItem:i}=await Me(async()=>{const{continueFromItem:c}=await Promise.resolve().then(()=>rv);return{continueFromItem:c}},void 0),l=await i(t);s.showToast(r(l.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))}catch{s.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 s.saveToAssets(t);s.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{s.showToast(r("chain.saveToAssetsFailed"),!0)}break}case"saveAsElement":{try{const a=await s.saveAsElement?.(t);s.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{s.showToast(r("chain.saveToAssetsFailed"),!0)}break}}}function pI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function fI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function hI(e){return{modelLabel:zi(e.model,e.provider),derivation:pI(e),sourceLabel:fI(e)}}function gI(e){return!e.modelLabel&&!e.derivation}function yI({view:e,size:t="sm"}){const{t:n}=H();return gI(e)?null:o.jsxs("span",{className:`provenance-chip provenance-chip--${t}`,children:[e.modelLabel?o.jsx("span",{className:"provenance-chip__model",children:e.modelLabel}):null,e.derivation?o.jsx("span",{className:"provenance-chip__derivation",children:n(`provenance.${e.derivation}`)}):null]})}function vI({id:e}){switch(e){case"animate":return o.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:o.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})});case"edit":return o.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:[o.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),o.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 o.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:[o.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),o.jsx("polyline",{points:"17 8 12 3 7 8"}),o.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]});case"rebake":return o.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:[o.jsx("polyline",{points:"23 4 23 10 17 10"}),o.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]});case"saveToAssets":return o.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:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),o.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),o.jsx("path",{d:"M10 12h4"})]})}}function bI({item:e,active:t,itemRef:n,onSelect:r,onDelete:s,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>uI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await mI(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)?vn(e):{image:e.url||e.image,filename:e.filename})),p.dataTransfer.effectAllowed="copy"};return o.jsxs("div",{ref:n,className:`gallery__tile-wrap${t?" gallery__tile-wrap--active":""}${e.isFavorite?" gallery__tile-wrap--favorite":""}`,children:[o.jsxs("button",{type:"button",className:`gallery__tile${t?" gallery__tile--active":""}`,onClick:()=>r(e),title:e.prompt??"",draggable:!0,onDragStart:u,children:[xe(e)?o.jsxs("div",{className:"gallery__tile-video-wrap",children:[e.thumb?o.jsx("img",{src:e.thumb,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async",className:"gallery__tile-video"}):o.jsx(Ut,{className:"gallery__tile-video"}),o.jsx("span",{className:"gallery__play-badge","aria-hidden":"true",children:"▶"})]}):o.jsx("img",{src:e.thumb||e.image,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),e.prompt&&o.jsx("div",{className:"gallery__caption",children:o.jsx("span",{className:"gallery__caption-text",children:e.prompt})})]}),c.length>0?o.jsx("div",{className:"gallery__chain-overlay",role:"group","aria-label":l("chain.ariaLabel"),children:c.map(p=>o.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:m=>{d(p.id,m)},title:l(p.labelKey),"aria-label":l(p.labelKey),children:o.jsx(vI,{id:p.id})},p.id))}):null,e.filename&&a&&o.jsx(Hc,{variant:"gallery",active:!!e.isFavorite,busy:i,label:e.isFavorite?l("gallery.unfavoriteAria"):l("gallery.favoriteAria"),onToggle:()=>a(e)}),e.filename&&o.jsx("button",{type:"button",className:"gallery__delete",onClick:p=>s(e,p),title:l("gallery.deleteTitle"),"aria-label":l("gallery.deleteAria"),children:"×"}),o.jsx(yI,{view:hI(e)})]})}function xI(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,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=s[c];if(!d){const u=t[c*2];d=s[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(s,a,i)}})}function Mt(e,t,n){let r=n.initialDeps??[],s,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==d))&&(r=l,s=t(...l),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return i.updateDeps=l=>{r=l},i}function hi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const II=(e,t)=>Math.abs(e-t)<1.01,SI=(e,t,n)=>{let r;return Object.assign(function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)},{cancel:()=>{e.clearTimeout(r)}})};let on;const Rs=()=>{if(on!==void 0)return on;if(typeof navigator>"u")return on=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return on=!0;const e=navigator.maxTouchPoints;return on=navigator.platform==="MacIntel"&&e!==void 0&&e>0},gi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},wI=e=>e,_I=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},EI=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(s(gi(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){s({width:d.inlineSize,height:d.blockSize});return}}s(gi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Fr={passive:!0},NI=typeof window>"u"?!0:"onscrollend"in window,kI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&NI;let i=0;const l=a?null:SI(s,()=>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()}},CI=(e,t)=>kI(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),jI=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??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),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},PI=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},AI=PI;class RI{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,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.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 s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:wI,rangeExtractor:_I,onChange:()=>{},measureElement:jI,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?((s=b[m-1])==null?void 0:s.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 S=a.followOnAppend===!0?"auto":a.followOnAppend||null;S&&h>m&&this.isAtEnd(i.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==x)&&(c=S)}}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,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Mt(()=>(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,!(!Rs()||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 s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=s;a!==null&&!l&&(Rs()&&(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 s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,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=Mt(()=>[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,s,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:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d}),{key:!1}),this.isIndexInRange=n=>n>=0&&n<this.options.count,this.getMeasurements=Mt(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,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 w=new Float64Array(y);g&&m>0&&w.set(g.subarray(0,m*2)),g=w,this._flatMeasurements=g}let _;if(m===0)_=r+s;else{const w=m-1;_=g[w*2]+g[w*2+1]+d}for(let w=m;w<n;w++){const j=a(w),P=p.get(j),M=typeof P=="number"?P:this.options.estimateSize(w);g[w*2]=_,g[w*2+1]=M,_+=M+d}const S=xI(n,g,a);return this.measurementsCache=S,S}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 S,w;const j=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){S=_;const N=b[S],R=N!==void 0?h[N]:void 0;w=R?R.end+d:r+s}else if(x===l){let N=0,R=I[0],$=b[0];for(let k=1;k<l;k++){const J=I[k];(J<R||J===R&&b[k]<$)&&(N=k,R=J,$=b[k])}S=N,w=R+d,j&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,w=r+s,j&&this.laneAssignments.set(y,S);const P=p.get(g),M=typeof P=="number"?P:this.options.estimateSize(y),q=w+M;h[y]={index:y,start:w,size:M,end:q,key:g,lane:S},b[S]===void 0&&x++,b[S]=y,I[S]=q}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Mt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=MI(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Mt(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,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 s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-a),l=Math.min(this.options.count-1,s+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 s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,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"&&((s=this.scrollState)==null?void 0:s.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=Mt(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,i=dd(0,r.length-1,a?l=>s[l*2]:l=>hi(r[l]).start,n);return hi(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,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+a?"end":"start"),r==="center"?n+=(s-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 s=this.getSize(),a=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=a+s-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:s="auto"}={})=>{this._iosDeferredAdjustment=0;const a=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="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:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{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 s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?s=i[a*2]+i[a*2+1]:s=((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--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,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:Rs()&&(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,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&II(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,d||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const dd=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function TI(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function MI(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const d=TI(s,a,n);let u=d;const p=n+t;for(;u<a&&s[u*2]+s[u*2+1]<p;)u++;return{startIndex:d,endIndex:u}}let l=dd(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 Ts=typeof document<"u"?v.useLayoutEffect:v.useEffect;function LI({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=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?ss.flushSync(s):s()),(m=r.onChange)==null||m.call(r,u,p)}},[d]=v.useState(()=>{const u=new RI(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),Ts(()=>d._didMount(),[]),Ts(()=>(i(d),d._willUpdate())),Ts(()=>{l(d)}),d}function FI(e){return LI({observeElementRect:EI,observeElementOffset:CI,scrollToFn:AI,...e})}const Or=170,Dr=10,ud=36,OI=44;function DI(e){const t=Math.max(Or,e-ud);return Math.max(1,Math.floor((t+Dr)/(Or+Dr)))}function GI(e,t){const n=Math.max(Or,e-ud);return Math.max(Or,Math.floor((n-Dr*Math.max(0,t-1))/t))+Dr}function zI(e,t){const n=[];for(const[r,s]of e){n.push({type:"header",id:`h-${r}`,label:r,count:s.length});for(let a=0;a<s.length;a+=t)n.push({type:"items",id:`r-${r}-${a}`,items:s.slice(a,a+t)})}return n}function qI({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:s}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>DI(i||960),[i]),d=v.useMemo(()=>GI(i||960,c),[i,c]),u=v.useMemo(()=>zI(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=FI({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?OI: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]),o.jsx("div",{ref:a,className:"gallery__virtual",style:{height:p.getTotalSize()},children:p.getVirtualItems().map(m=>{const h=u[m.index];return h?o.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${m.start}px)`},children:h.type==="header"?o.jsxs("header",{className:"gallery__group-header gallery__group-header--virtual",children:[o.jsx("span",{className:"gallery__group-label",children:r(h.label)}),o.jsx("span",{className:"gallery__group-count",children:h.count})]}):o.jsx("div",{className:"gallery__grid gallery__grid--virtual",children:h.items.map((b,I)=>s(b,h.id,I))})},h.id):null})})}function yi({showSessions:e,favoritesOnly:t,query:n,historyNextCursor:r,favoriteHistoryNextCursor:s,historyLoadingOlder:a,favoriteHistoryLoadingOlder:i,onLoadOlder:l,onLoadOlderFavorites:c,t:d}){return e?o.jsx("div",{className:"gallery__load-more gallery__load-more--hint",children:d("gallery.sessionPaginationHint")}):n.trim()?null:t?s?o.jsx("div",{className:"gallery__load-more",children:o.jsx("button",{type:"button",onClick:c,disabled:i,children:d(i?"gallery.loadingOlderFavorites":"gallery.loadOlderFavorites")})}):null:r?o.jsx("div",{className:"gallery__load-more",children:o.jsx("button",{type:"button",onClick:l,disabled:a,children:d(a?"gallery.loadingOlder":"gallery.loadOlder")})}):null}function $I({groups:e,loose:t,favoritesOnly:n,galleryScope:r,setGalleryScope:s,renderTile:a,t:i}){return e.length===0&&t.length===0?o.jsx("div",{className:"gallery__empty",children:n?i("gallery.emptyFavorites"):r==="current-session"?o.jsxs(o.Fragment,{children:[o.jsx("p",{children:i("gallery.empty.currentSession")}),o.jsx("button",{type:"button",onClick:()=>s("all"),children:i("gallery.scope.all")})]}):i("gallery.emptySessions")}):o.jsxs(o.Fragment,{children:[e.map(l=>o.jsxs("section",{className:"gallery__group",children:[o.jsxs("header",{className:"gallery__group-header",children:[o.jsx("span",{className:"gallery__group-label",title:l.sessionId,children:l.title?l.displayLabel:i("gallery.sessionLabel",{name:l.displayLabel})}),o.jsx("span",{className:"gallery__group-count",children:l.items.length})]}),o.jsx("div",{className:"gallery__grid",children:l.items.map((c,d)=>a(c,l.sessionId,d))})]},l.sessionId)),t.length>0&&o.jsxs("section",{className:"gallery__group",children:[o.jsxs("header",{className:"gallery__group-header",children:[o.jsx("span",{className:"gallery__group-label",children:i("gallery.standalone")}),o.jsx("span",{className:"gallery__group-count",children:t.length})]}),o.jsx("div",{className:"gallery__grid",children:t.map((l,c)=>a(l,"loose",c))})]})]})}function UI({status:e,dismissed:t,onOpenFolder:n,onDismiss:r,t:s}){const a=e!=null&&e.state!=="ok"&&!t,i=e?.state==="recoverable"?"gallery.storageNoticeRecoverable":e?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return o.jsxs("div",{className:`gallery__storage-bar${a?" gallery__storage-bar--notice":""}`,children:[a?o.jsxs("div",{className:"gallery__storage-copy",children:[o.jsx("div",{className:"gallery__storage-title",children:s("gallery.storageNoticeTitle")}),o.jsx("div",{className:"gallery__storage-text",children:s(i)})]}):o.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:e?.generatedDirLabel??"~/.ima2/generated"}),o.jsxs("div",{className:"gallery__storage-actions",children:[o.jsx("button",{type:"button",className:"gallery__storage-button",onClick:n,title:s("gallery.openGeneratedDirTitle"),children:s("gallery.openGeneratedDir")}),a&&o.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:r,children:s("common.close")})]})]})}const vi="ima2.storageNoticeDismissed.0.09.23";function HI(e){const t=v.useRef(null),n=v.useRef(new Map),[r,s]=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&&s(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 KI(){const{t:e,locale:t}=H(),n=f(L=>L.galleryOpen),r=f(L=>L.closeGallery),s=f(L=>L.history),a=f(L=>L.selectHistory),i=f(L=>L.currentImage),l=f(L=>L.trashHistoryItem),c=f(L=>L.showToast),d=f(L=>L.toggleGalleryFavorite),u=f(L=>L.galleryScope),p=f(L=>L.setGalleryScope),m=f(L=>L.historyNextCursor),h=f(L=>L.historyLoadingOlder),b=f(L=>L.favoriteHistoryNextCursor),I=f(L=>L.favoriteHistoryLoadingOlder),x=f(L=>L.loadOlderHistory),y=f(L=>L.loadFavoriteHistory),g=f(L=>L.loadOlderFavoriteHistory),_=f(rp),[S,w]=v.useState(""),[j,P]=v.useState("date"),[M,q]=v.useState(!1),[N,R]=v.useState(()=>new Set),$=v.useRef(new Set),[k,J]=v.useState([]),[T,Z]=v.useState([]),[te,de]=v.useState(!1),[ye,ve]=v.useState(!1),[F,O]=v.useState(!1),[Q,V]=v.useState(0),[ae,fe]=v.useState(null),[ie,Ee]=v.useState(()=>{try{return localStorage.getItem(vi)==="1"}catch{return!1}}),he=v.useRef(null),Se=v.useRef({}),[Ne,ke]=v.useState(null),D=v.useRef(0),le=v.useRef({open:!1,selectedKey:null}),se=v.useMemo(()=>xr(s.filter(mn)),[s]),G=v.useCallback(L=>{he.current=L,ke(L)},[]),C=HI(Ne),X=Ue(n,r);v.useEffect(()=>{n||w("")},[n]),v.useEffect(()=>{if(!n)return;let L=!1;return(async()=>{try{const Y=await Xd();L||fe(Y)}catch{L||fe({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}})}})(),()=>{L=!0}},[n]),v.useEffect(()=>{if(!n||j!=="session")return;let L=!1;return J([]),Z([]),de(!0),ve(!1),O(!1),(async()=>{try{const Y=await Jd({limit:500,sessionId:u==="current-session"?_:void 0});if(L)return;O(Y.nextCursor!==null||Y.total>=500);const je=U=>{const me=U.kind,rt=me==="classic"||me==="edit"||me==="generate"||me==="card-news-card"||me==="card-news-set"?me:null,sa=U.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(U.filename??"");return{image:U.url,url:U.url,filename:U.filename,thumb:U.thumb??(sa?void 0:U.url),mediaType:U.mediaType,video:U.video??null,videoSeries:U.videoSeries??null,videoContinuity:U.videoContinuity??null,prompt:U.prompt??void 0,userPrompt:U.userPrompt??null,revisedPrompt:U.revisedPrompt??null,promptMode:U.promptMode??null,composerPrompt:U.composerPrompt??null,composerInsertedPrompts:U.composerInsertedPrompts??null,size:U.size??void 0,quality:U.quality??void 0,format:U.format,moderation:U.moderation??void 0,model:U.model??void 0,reasoningEffort:U.reasoningEffort,provider:U.provider,providerUrl:U.providerUrl??null,usage:U.usage,elapsed:U.elapsed??void 0,createdAt:U.createdAt,sessionId:U.sessionId??null,nodeId:U.nodeId??null,parentNodeId:U.parentNodeId??null,clientNodeId:U.clientNodeId??null,requestId:U.requestId??null,kind:rt,setId:U.setId??null,cardId:U.cardId??null,cardOrder:U.cardOrder??null,headline:U.headline??null,body:U.body??null,cards:U.cards,refsCount:U.refsCount??0,webSearchCalls:U.webSearchCalls??0,sequenceId:U.sequenceId??null,sequenceIndex:U.sequenceIndex??null,sequenceTotalRequested:U.sequenceTotalRequested??null,sequenceTotalReturned:U.sequenceTotalReturned??null,sequenceStatus:U.sequenceStatus??null,isFavorite:U.isFavorite??!1}};J(Y.sessions.map(U=>({sessionId:U.sessionId,title:U.title??null,label:U.label??null,displayLabel:U.title||U.label||U.sessionId.slice(0,8),items:xr(U.items.filter(mn).map(je))})).filter(U=>U.items.length>0)),Z(xr(Y.loose.filter(mn).map(je)))}catch{L||ve(!0)}finally{L||de(!1)}})(),()=>{L=!0}},[n,j,u,_,Q]),v.useEffect(()=>{!n||j==="session"||!M||y()},[n,j,M,y]);const re=v.useMemo(()=>{const L=S.trim().toLowerCase().normalize("NFC");return se.filter(Y=>M&&!Y.isFavorite?!1:L?(Y.prompt??"").toLowerCase().normalize("NFC").includes(L)||(Y.filename??"").toLowerCase().normalize("NFC").includes(L):!0)},[se,S,M]),K=v.useMemo(()=>M?k.map(L=>({...L,items:L.items.filter(Y=>Y.isFavorite)})).filter(L=>L.items.length>0):k,[k,M]),be=v.useMemo(()=>M?T.filter(L=>L.isFavorite):T,[T,M]),Te=v.useMemo(()=>{const L=new Map;for(const Y of re){const je=aI(Y.createdAt,t);L.has(je)||L.set(je,[]),L.get(je).push(Y)}return Array.from(L.entries())},[re,t]),He=j==="session"?K.reduce((L,Y)=>L+Y.items.length,0)+be.length:re.length;v.useLayoutEffect(()=>{const L=i?Ae(i):null;if(!n){le.current={open:!1,selectedKey:L};return}const Y=le.current,je=!Y.open||Y.selectedKey!==L;le.current={open:!0,selectedKey:L};const U=L?Se.current[L]:null;if(je&&U){U.scrollIntoView({block:"center"});return}he.current&&(he.current.scrollTop=D.current)},[n,i?.filename,i?.image,j,He,Te.length,K.length,be.length]);async function gt(L,Y){Y.stopPropagation();const je=Ae(L);await l(L),delete Se.current[je],window.requestAnimationFrame(()=>he.current?.focus())}async function lt(L){const Y=L.filename;if(!(!Y||$.current.has(Y))){$.current.add(Y),R(new Set($.current));try{const je=await d(L);if(je===null)return;J(U=>U.map(me=>({...me,items:me.items.map(rt=>rt.filename===Y?{...rt,isFavorite:je}:rt)}))),Z(U=>U.map(me=>me.filename===Y?{...me,isFavorite:je}:me))}finally{$.current.delete(Y),R(new Set($.current))}}}async function $n(){try{await Zd(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Un,handleCopyCardNewsSetPath:Hn,handleDownloadCardNewsManifest:E}=iI(r,c,e);function B(){Ee(!0);try{localStorage.setItem(vi,"1")}catch{}}if(!n)return null;const ee=L=>L==="earlier"||L==="today"||L==="yesterday"||L==="thisWeek"?e(`gallery.${L}`):L,oe=(L,Y,je)=>{const U=i?.image===L.image,me=Ae(L),rt=Rt=>{Se.current[me]=Rt,C.register(me,Rt)};return(C.supported?C.visibleKeys.has(me):!0)?L.kind==="card-news-set"?o.jsx("div",{ref:rt,className:"gallery__tile-wrap gallery-card-news-set",children:o.jsx(dI,{item:L,onOpen:Rt=>{Un(Rt)},onCopyPath:Hn,onDownloadManifest:E})},`${Y}-${me}`):o.jsx(bI,{item:L,active:U,itemRef:rt,onSelect:Rt=>{a(Rt),r()},onDelete:gt,onToggleFavorite:lt,favoriteBusy:!!(L.filename&&N.has(L.filename)),t:e},`${Y}-${me}`):o.jsx("div",{ref:rt,className:"gallery__tile-wrap","data-gallery-lazy-key":me,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Y}-${me}`)},ue=j==="session",Le=i?Ae(i):null;return o.jsx("div",{className:"gallery-backdrop",onClick:r,role:"presentation",children:o.jsxs("div",{ref:X,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:L=>L.stopPropagation(),children:[o.jsxs("div",{className:"gallery__header",children:[o.jsxs("div",{className:"gallery__title-row",children:[o.jsx("div",{className:"gallery__title",children:e("gallery.title")}),o.jsxs("div",{className:"gallery__meta",children:[e("gallery.total",{n:He}),S||M?e("gallery.totalFiltered",{n:se.length}):""]}),o.jsx(As,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:M?"favorites":"all",onChange:L=>q(L==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),o.jsx(As,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:j,onChange:P,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),o.jsx(As,{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")}]})]}),o.jsx("input",{type:"text",className:"gallery__search",...ue?{}:{"data-modal-initial-focus":!0},placeholder:e(ue?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:S,onChange:L=>w(L.target.value),disabled:ue}),o.jsx("button",{type:"button",className:"gallery__close",onClick:r,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),o.jsx(UI,{status:ae,dismissed:ie,onOpenFolder:$n,onDismiss:B,t:e}),o.jsx("div",{className:"gallery__scroll",ref:G,tabIndex:-1,onScroll:()=>{D.current=he.current?.scrollTop??0},children:ue?te?o.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):ye?o.jsxs("div",{className:"gallery__empty",role:"alert",children:[o.jsx("span",{children:e("gallery.sessionLoadFailed")}),o.jsx("button",{type:"button",onClick:()=>V(L=>L+1),children:e("gallery.retry")})]}):o.jsxs(o.Fragment,{children:[F?o.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,o.jsx($I,{groups:K,loose:be,favoritesOnly:M,galleryScope:u,setGalleryScope:p,renderTile:oe,t:e}),o.jsx(yi,{showSessions:ue,favoritesOnly:M,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):re.length===0?o.jsx("div",{className:"gallery__empty",children:se.length===0?e("gallery.emptyAll"):e(M?"gallery.emptyFavorites":"gallery.noResults")}):o.jsxs(o.Fragment,{children:[o.jsx(qI,{dateGroups:Te,selectedKey:Le,scrollElement:Ne,localizeBucket:ee,renderTile:oe}),o.jsx(yi,{showSessions:ue,favoritesOnly:M,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function VI(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 BI(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=H(),s=Ue(!!e,n);if(!e)return null;const a=`${e.requestedW}x${e.requestedH}`,i=`${e.adjustedW}x${e.adjustedH}`;return o.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:o.jsxs("div",{ref:s,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:[o.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:r("sizeConfirm.title")}),o.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[o.jsx("p",{children:r("sizeConfirm.body")}),o.jsxs("dl",{className:"size-confirm__pairs",children:[o.jsxs("div",{className:"size-confirm__pair",children:[o.jsx("dt",{children:r("sizeConfirm.requested")}),o.jsx("dd",{children:a})]}),o.jsxs("div",{className:"size-confirm__pair",children:[o.jsx("dt",{children:r("sizeConfirm.adjusted")}),o.jsx("dd",{children:i})]})]}),o.jsx("p",{className:"size-confirm__reason",children:r(VI(e.reasons))})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button","data-modal-initial-focus":!0,className:"modal__btn modal__btn--secondary",onClick:n,children:r("sizeConfirm.cancel")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{t()},children:r("sizeConfirm.approve")})]})]})})}function cr(e){return e==null||e===""?"-":String(e)}function WI(){const{t:e}=H(),t=f(c=>c.metadataRestore),n=f(c=>c.applyMetadataRestore),r=f(c=>c.addMetadataRestoreAsReference),s=f(c=>c.cancelMetadataRestore),a=Ue(!!t,s);if(!t)return null;const i=t.metadata,l=i.userPrompt||i.prompt||i.revisedPrompt||"";return o.jsx("div",{className:"modal-backdrop metadata-restore-backdrop",role:"presentation",children:o.jsxs("div",{ref:a,className:"modal metadata-restore",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-restore-title",tabIndex:-1,children:[o.jsx("div",{id:"metadata-restore-title",className:"modal__title",children:e("metadata.restoreTitle")}),o.jsxs("div",{className:"modal__body metadata-restore__body",children:[o.jsx("p",{children:e("metadata.restoreBody")}),o.jsxs("div",{className:"metadata-restore__preview",children:[o.jsx("img",{src:t.image,alt:e("metadata.imageAlt")}),o.jsxs("div",{className:"metadata-restore__details",children:[o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.prompt")}),o.jsx("strong",{title:l,children:cr(l)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.size")}),o.jsx("strong",{children:cr(i.size)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.quality")}),o.jsx("strong",{children:cr(i.quality)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.model")}),o.jsx("strong",{children:cr(i.model)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.source")}),o.jsx("strong",{children:t.source==="png-comment"?e("metadata.sourcePngComment"):e("metadata.sourceXmp")})]})]})]})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:s,"data-modal-initial-focus":!0,children:e("common.cancel")}),o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:r,children:e("metadata.useAsReferenceOnly")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:n,children:e("metadata.applySettings")})]})]})})}const JI=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Nt(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Gt(e){return!e||typeof e!="object"||Array.isArray(e)?Nt():e}function Xs(e){return typeof e!="string"||!e.trim()?Nt():e}function md(e){return e===void 0?{}:typeof e!="boolean"?Nt():{executable:e}}function YI(e){const t=Gt(e),n=Gt(t.status);return typeof t.enabled!="boolean"||!JI.has(n.state)?Nt():{id:Xs(t.id),enabled:t.enabled,...md(t.executable),status:{state:n.state}}}function bi(e){return Array.isArray(e)?e.map(t=>{const n=Gt(t);return{id:Xs(n.id),label:Xs(n.label),...md(n.executable)}}):Nt()}function xi(e,t){const n=Gt(e);if(n.ok!==!0||!Array.isArray(n.providers))return Nt();const r=n.providers.map(YI);if(t===null)return{providers:r,catalog:null};const s=Gt(t),a=Gt(s.models);return s.ok!==!0?Nt():{providers:r,catalog:{image:bi(a.image),video:bi(a.video)}}}function XI(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 s=e.providers.find(i=>i.id===t.provider);if(!s)return r("missing");if(!s.enabled)return r("disabled");if(s.status.state!=="connected")return r("disconnected");if(s.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 ZI(){const{t:e}=H(),t=f(u=>u.mcpProvider??""),n=f(u=>u.mcpModel??null),r=f(u=>u.mcpMediaKind??"image"),[s,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 Fh(u.signal),I=xi(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Oh(t,u.signal):null,y=xi(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,s]),!t)return null;const c=XI(i,{provider:t,model:n,kind:r}),d=`readiness.mcp.${c.code}`;return o.jsxs("div",{className:"provider-readiness__body","data-mcp-readiness":c.code,"aria-busy":c.code==="loading",children:[o.jsx("p",{role:"status","aria-live":"polite",children:o.jsx("strong",{children:e(d)})}),o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsxs("dd",{children:[t," · MCP"]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.model")}),o.jsx("dd",{style:{minWidth:0,overflowWrap:"anywhere"},children:c.modelLabel??e("readiness.mcp.default")})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colKind")}),o.jsx("dd",{children:e(r==="video"?"grokMode.video":"grokMode.image")})]})]}),c.observedAt!==null?o.jsx("small",{children:e("readiness.mcp.observed",{time:new Date(c.observedAt).toLocaleTimeString()})}):null,o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:()=>a(u=>u+1),children:e("readiness.mcp.refresh")})]})}const Ii={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 QI(){const{t:e}=H(),t=f(w=>w.readinessPopupOpen),n=f(w=>w.closeReadinessPopup),r=f(w=>w.openSettings),s=f(w=>w.provider),a=f(w=>w.mcpProvider??null),i=f(w=>w.imageModel),l=f(w=>w.reasoningEffort),c=f(w=>w.webSearchEnabled),d=f(w=>w.comfyWorkflow),u=f(w=>w.comfyVideoWorkflow),p=od(),m=qn(),h=s==="grok",b=Xe.find(w=>w.value===i),I=Ue(t,n);if(!t)return null;const x=p[s],y=Et(m,{comfyWorkflow:d,comfyVideoWorkflow:u}),g=s==="comfy"&&!a,_=g?y.selectedAvailable:x.ok,S=()=>{n(),r("providers")};return o.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:n,role:"presentation",children:o.jsxs("div",{ref:I,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:w=>w.stopPropagation(),children:[o.jsx("div",{id:"provider-readiness-title",className:"modal__title",children:e("readiness.title")}),o.jsxs("div",{className:"modal__body provider-readiness__body",children:[a?o.jsx(ZI,{}):null,!a&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`provider-readiness__status${_?" is-ok":" is-blocked"}`,children:[o.jsx("span",{"aria-hidden":"true"}),o.jsx("strong",{children:e(g?$t(y,m):_?"readiness.ready":"readiness.blocked")}),o.jsx("small",{children:g?e("comfy.display.controlsHelp"):_?e("readiness.readyBody"):x.reason})]}),!g&&x.hint?o.jsx("p",{className:"modal__hint",children:x.hint}):null,g?o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsx("dd",{children:Ii.comfy})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.workflowsTitle")}),o.jsx("dd",{children:y.selected?.label??e("comfy.display.chooseWorkflow")})]}),y.selected?o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colId")}),o.jsx("dd",{children:y.selected.id})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colKind")}),o.jsx("dd",{children:e(y.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage")})]})]}):null,m.observedAt!==null?o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colStatus")}),o.jsx("dd",{children:e("comfy.display.lastChecked",{time:new Date(m.observedAt).toLocaleTimeString()})})]}):null]}):o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsx("dd",{children:Ii[s]??"GPT API"})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.model")}),o.jsx("dd",{children:b?e(b.fullLabelKey):i})]}),h?o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.grokApi")}),o.jsx("dd",{children:e("readiness.grokApiBody")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.reasoning")}),o.jsx("dd",{children:l})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.webSearch")}),o.jsx("dd",{children:e(c?"settings.webSearch.on":"settings.webSearch.off")})]})]})]})]})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:n,"data-modal-initial-focus":!0,children:e("common.close")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:S,children:e(g?"comfy.display.manage":"readiness.openAccount")})]})]})})}const Si="ima2.onboardingDismissed";function eS(){const{t:e}=H(),t=f(x=>x.openSettings),n=nd(),r=rd(),{data:s}=sd(),[a,i]=v.useState(()=>{try{return localStorage.getItem(Si)==="1"}catch{return!1}}),l=n!==null&&r!==null&&s!=null,c=n?.status==="auth_required"||n?.status==="offline",d=r?.status==="offline"||r?.status==="error",u=s?!s.gemini?.configured&&!s.vertex?.configured:!1,m=!a&&(l&&c&&d&&u),h=()=>{try{localStorage.setItem(Si,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=Ue(m,h);return m?o.jsx("div",{className:"modal-backdrop",role:"presentation",children:o.jsxs("div",{ref:I,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[o.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),o.jsx("div",{className:"modal__body",children:o.jsx("p",{children:e("onboarding.body")})}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:h,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:b,children:e("onboarding.login")})]})]})}):null}function tS(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=H(),[s,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?o.jsxs("div",{className:"trash-undo-toast",children:[o.jsx("span",{children:r("gallery.deleted",{filename:e.filename})}),o.jsx("button",{type:"button",onClick:()=>{t()},children:r("gallery.undo")}),o.jsx("span",{className:"trash-undo-toast__timer",children:r("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((e.expiresAt-s)/1e3))})})]}):null}function nS(){return o.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:[o.jsx("line",{x1:"4",y1:"6",x2:"14",y2:"6"}),o.jsx("circle",{cx:"17",cy:"6",r:"2.2"}),o.jsx("line",{x1:"4",y1:"12",x2:"8",y2:"12"}),o.jsx("circle",{cx:"11",cy:"12",r:"2.2"}),o.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),o.jsx("line",{x1:"4",y1:"18",x2:"14",y2:"18"}),o.jsx("circle",{cx:"17",cy:"18",r:"2.2"})]})}function rS(){const e=f(d=>d.composeSheetOpen),t=f(d=>d.composeSheetTab),n=f(d=>d.openComposeSheet),r=f(d=>d.settingsOpen),s=f(d=>d.uiMode),{t:a}=H();if(!ht()||r||s==="home"||s==="card-news"||s==="agent"||s==="assets"||s==="asset-gen")return null;const l=e&&t==="controls",c=a("sheet.controlsOpen");return o.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:o.jsx(nS,{})})}let Gr=null;function sS(e){Gr=e}function oS(){const e=Gr;Gr=null,e?.isConnected&&e.focus()}function wi(){Gr=null}function aS(){const{t:e}=H(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),s=r==="agent"&&Wt?"agent":r==="node"&&Bt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=ht(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&sS(p.current),t(u==="library"?"library":u==="controls"?"controls":"prompt")};return!a||n||s!=="classic"?null:o.jsxs("header",{className:"mobile-app-bar",role:"banner",children:[o.jsxs("div",{className:"mobile-app-bar__brand",children:[o.jsx("div",{className:"logo-mark","aria-hidden":"true"}),o.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[o.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),o.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),o.jsxs("div",{className:"mobile-app-bar__actions",children:[o.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:o.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:o.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),o.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:o.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:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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"})]})}),o.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:o.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:[o.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),o.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]}),o.jsx("div",{className:"mobile-app-bar__selection",children:o.jsx(Yc,{compact:!0})})]})}const iS={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},_i={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function lS(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=iS[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function cS(){return o.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:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),o.jsx("path",{d:"m21 15-5-5L5 21"})]})}function dS(){return o.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:[o.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),o.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})}function uS(){return o.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:[o.jsx("rect",{x:"2",y:"6",width:"8",height:"6",rx:"1"}),o.jsx("rect",{x:"14",y:"12",width:"8",height:"6",rx:"1"}),o.jsx("path",{d:"M10 9h4"}),o.jsx("path",{d:"M14 15V9a2 2 0 0 1 2-2h0"})]})}function mS(){return o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(-30 12 12)"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(30 12 12)"})]})}function pS(){return o.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:[o.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"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function fS(){return o.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:[o.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"}),o.jsx("path",{d:"M8 12h8"})]})}function hS(){return o.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:[o.jsx("rect",{x:"3",y:"3",width:"13",height:"13",rx:"2"}),o.jsx("path",{d:"M3 12l3.5-3.5a1.4 1.4 0 0 1 2 0L13 13"}),o.jsx("path",{d:"M19 14v6"}),o.jsx("path",{d:"M16 17h6"})]})}const gS=[{id:"home",mode:"home",icon:dS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:cS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:uS,labelKey:"nav.node",enabled:Bt},{id:"agent",mode:"agent",icon:mS,labelKey:"nav.agent",enabled:Wt},{id:"assets",mode:"assets",icon:fS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:hS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:pS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function yS(){const{t:e}=H(),t=f(I=>I.uiMode),n=f(I=>I.setUIMode),r=f(I=>I.settingsOpen),s=f(I=>I.openSettings),a=f(I=>I.closeSettings),i=ht(),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,"",_i[t]||"#create")):(s(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",_i[I.mode]||"#create"))},[t,r,n,s,a]);v.useEffect(()=>{const I=()=>{const x=lS();x&&(x.settings?s():(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=gS.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=>o.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:[o.jsx(I.icon,{}),o.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(I.labelKey)})]},I.id);return i?o.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)}):o.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[o.jsx("div",{className:"nav-rail__top",children:p.map(b)}),o.jsx("div",{className:"nav-rail__bottom",children:m.map(b)})]})}const vS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-BFWQO8OT.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Ke=["prompt","controls","library"],dr="mobile-inflight-panel",ur=e=>`mobile-sheet-tab-${e}`,mr=e=>`mobile-sheet-panel-${e}`;function bS(){const{t:e}=H(),t=f(w=>w.composeSheetOpen),n=f(w=>w.composeSheetTab),r=f(w=>w.setComposeSheetTab),s=f(w=>w.closeComposeSheet),a=f(w=>w.inFlight.length),i=f(w=>w.settingsOpen),l=f(w=>w.uiMode),c=l==="agent"&&Wt?"agent":l==="node"&&Bt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=ht(),[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=w=>{r(w),requestAnimationFrame(()=>I.current[w]?.focus())},g=(w,j)=>{const P=Ke.indexOf(j),M=w.key==="ArrowRight"?Ke[(P+1)%Ke.length]:w.key==="ArrowLeft"?Ke[(P-1+Ke.length)%Ke.length]:w.key==="Home"?Ke[0]:w.key==="End"?Ke[Ke.length-1]:null;M&&(w.preventDefault(),y(M))},_=Ue(t,s,{autoFocus:!1});v.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&p(!1)},[t,n,s,d,i,c]),v.useLayoutEffect(()=>{const w=m.current>0&&a===0;m.current=a,w&&(p(!1),h.current&&b.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),v.useLayoutEffect(()=>{if(t){x.current=!0;const w=requestAnimationFrame(()=>I.current[n]?.focus());return()=>cancelAnimationFrame(w)}x.current&&(x.current=!1,oS())},[t,n]);const S=d&&!i&&c==="classic";return v.useEffect(()=>{S||(x.current=!1,f.getState().composeSheetOpen&&s(),wi())},[S]),v.useEffect(()=>()=>wi(),[]),S?o.jsxs(o.Fragment,{children:[t?o.jsx("button",{type:"button",className:"compose-sheet-backdrop","aria-label":e("sheet.close"),onClick:s}):null,o.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:[o.jsx("button",{type:"button",className:"compose-sheet__handle",onClick:s,"aria-label":e("sheet.close")}),o.jsx("div",{className:"mobile-sheet-tabs",role:"tablist","aria-label":e("sheet.generate"),children:Ke.map(w=>o.jsx("button",{ref:j=>{I.current[w]=j},id:ur(w),type:"button",role:"tab","aria-selected":n===w,"aria-controls":mr(w),tabIndex:n===w?0:-1,className:`mobile-sheet-tabs__button${n===w?" active":""}`,onClick:()=>r(w),onKeyDown:j=>g(j,w),children:e(`sheet.tabs.${w}`)},w))}),o.jsxs("div",{className:"compose-sheet__body",children:[o.jsx("div",{id:mr("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":ur("prompt"),hidden:n!=="prompt",onFocusCapture:w=>{const j=document.getElementById(dr);h.current=j?.contains(w.target)??!1},children:n==="prompt"?o.jsxs(o.Fragment,{children:[o.jsx(Jo,{}),a>0?o.jsxs("section",{className:"compose-sheet__inflight",hidden:!u,children:[o.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{b.current?.querySelector(".inflight-badge")?.focus(),p(!1)},"aria-expanded":u,"aria-controls":dr,"aria-label":e("inflight.inlineCollapse",{n:a}),children:[o.jsxs("span",{children:[e("inflight.title")," (",a,")"]}),o.jsx("span",{"aria-hidden":"true",children:"−"})]}),o.jsx(Xo,{variant:"inline",panelId:dr}),o.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,o.jsxs("div",{ref:b,className:"compose-sheet__actions",children:[o.jsx(Yo,{}),o.jsx(Bc,{variant:"inline",panelId:dr,expanded:u,onToggle:p})]})]}):null}),o.jsx("div",{id:mr("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":ur("controls"),hidden:n!=="controls",children:n==="controls"?o.jsx(cd,{}):null}),o.jsx("div",{id:mr("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":ur("library"),hidden:n!=="library",children:n==="library"?o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:o.jsx(vS,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const xS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function IS(){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=s=>{const a=xS[s.key];a&&(s.defaultPrevented||Ir(s.target)||t&&(s.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const pr=64,pd="Image Gen";let na=pd,Zs=!1,mt=null,ra="",Qs=!1;function fd(){return navigator}function hd(){if(typeof document>"u")return null;if(mt)return mt;const e=document.querySelector('link[rel~="icon"]');if(e)return mt=e,ra=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),mt=t,Qs=!0,t}function SS(e){const t=document.createElement("canvas");t.width=pr,t.height=pr;const n=t.getContext("2d");return n?(n.clearRect(0,0,pr,pr),n.fillStyle="#0a0a0a",wS(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")):ra}function wS(e,t,n,r,s,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+s,a),e.arcTo(t+r,n+s,t,n+s,a),e.arcTo(t,n+s,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}async function _S(e){const t=fd();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function ES(){const e=fd();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function NS(e){document.title=`(${e}) ${na}`;const t=hd();t&&(t.href=SS(e)),_S(e)}function Ei(){document.title=na,mt&&(Qs?(mt.remove(),mt=null,Qs=!1):mt.href=ra),ES()}function Ni(){Zs||typeof document>"u"||(Zs=!0,na=document.title||pd,hd())}function kS(e){v.useEffect(()=>(Ni(),()=>{Zs&&Ei()}),[]),v.useEffect(()=>{Ni(),e>0?NS(e):Ei()},[e])}function CS(){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 jS=v.lazy(()=>Me(()=>import("./NodeCanvas-BvvcCErf.js"),__vite__mapDeps([7,1,2,8])).then(e=>({default:e.NodeCanvas}))),PS=v.lazy(()=>Me(()=>import("./SettingsWorkspace-B5Ghsgdj.js"),__vite__mapDeps([9,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),AS=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-BAOxWLKf.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.CardNewsWorkspace}))),RS=v.lazy(()=>Me(()=>import("./AgentWorkspace-CL3MLv3l.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.AgentWorkspace}))),TS=v.lazy(()=>Me(()=>import("./AssetsWorkspace-CRVeYU2F.js"),__vite__mapDeps([13,1,2,14,12,15])).then(e=>({default:e.AssetsWorkspace}))),MS=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-swWPvXrx.js").then(e=>e.A),__vite__mapDeps([16,1,2,14,12,17])).then(e=>({default:e.AssetGenWorkspace}))),LS=v.lazy(()=>Me(()=>import("./HomeWorkspace-BeZ1s0Jm.js"),__vite__mapDeps([18,1,2])).then(e=>({default:e.HomeWorkspace}))),FS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-BFWQO8OT.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function OS(){return o.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function DS(){IS(),CS();const{locale:e}=H(),t=f(w=>w.hydrateHistory),n=f(w=>w.loadSessions),r=f(w=>w.syncCapabilities),s=f(w=>w.startInFlightPolling),a=f(w=>w.reconcileInflight),i=f(w=>w.syncFromStorage),l=f(w=>w.settingsOpen),c=f(w=>w.unseenGeneratedCount),d=f(w=>w.historyStripLayout),u=f(w=>w.workspaceProfile),p=f(w=>w.uiMode),m=p==="agent"&&Wt?"agent":p==="node"&&Bt?"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=ht(),g=Ln(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",S=!_&&!h&&!b&&!I&&!x;return kS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!ce())return r(),t(),n(),a(),s(),Ct(),ua(()=>a()),ma(w=>{w==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{In(),ua(()=>{}),ma(()=>{})}},[t,n,a,s,r]),v.useEffect(()=>{const w=j=>{const P=j.detail?.assetId;P&&f.getState().openAssetDetail(P)};return window.addEventListener("ima2:open-assets-detail",w),()=>window.removeEventListener("ima2:open-assets-detail",w)},[]),v.useEffect(()=>{const w=j=>{j.key&&(j.key==="ima2.inFlight"||j.key==="ima2.selectedFilename"||j.key===ho||j.key===fo||j.key===yo)&&i()};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[i]),v.useEffect(()=>{const w=()=>{np(f.getState)};return window.addEventListener("beforeunload",w),()=>{window.removeEventListener("beforeunload",w)}},[]),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`app${u==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${S&&d==="horizontal"?" app--history-horizontal":""}${S&&d==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":d,"data-mobile":y?"1":void 0,"data-ui-mode":m,children:[o.jsx(yS,{}),x?null:o.jsx(nb,{}),o.jsx(aS,{}),S?o.jsx(rI,{}):null,o.jsx(v.Suspense,{fallback:o.jsx(OS,{}),children:l?o.jsx(PS,{}):m==="classic"?_?o.jsx(Wb,{}):o.jsx(Ys,{}):m==="node"?o.jsx(jS,{}):m==="card-news"?o.jsx(AS,{}):m==="agent"?o.jsx(RS,{}):m==="assets"?o.jsx(TS,{}):m==="asset-gen"?o.jsx(MS,{}):m==="home"?o.jsx(LS,{}):o.jsx(Ys,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:o.jsx(Xx,{})]}),o.jsx(BI,{}),o.jsx(tS,{}),o.jsx(sI,{}),o.jsx(oI,{}),o.jsx(KI,{}),o.jsx(WI,{}),o.jsx(QI,{}),o.jsx(eS,{}),o.jsx(bS,{}),o.jsx(rS,{}),m==="card-news"?o.jsx(v.Suspense,{fallback:null,children:o.jsx(FS,{})}):null]})}const Nw=Object.freeze(Object.defineProperty({__proto__:null,default:DS},Symbol.toStringTag,{value:"Module"}));export{iw as $,wu as A,Oe as B,Lc as C,hw as D,gw as E,yw as F,Su as G,vw as H,Xe as I,Sw as J,Qo as K,bw as L,xw as M,Iw as N,Iu as O,Ie as P,Zx as Q,Ds as R,sv as S,$u as T,uw as U,Pu as V,ov as W,tt as X,Gy as Y,pw as Z,hu as _,f as a,_p as a0,FI as a1,Hc as a2,ww as a3,Ew as a4,_w as a5,dw as a6,fw as a7,Ob as a8,so as a9,JS as aA,VS as aB,zS as aC,YS as aD,KS as aE,cb as aF,HS as aG,Gb as aH,Ci as aI,A as aJ,qS as aK,US as aL,$S as aM,QS as aN,XS as aO,ew as aP,tw as aQ,ZS as aR,nw as aS,rw as aT,sw as aU,ow as aV,aw as aW,Nw as aX,Ql as aa,cI as ab,Xo as ac,cw as ad,kt as ae,lw as af,es as ag,Wo as ah,Uc as ai,lv as aj,Ae as ak,od as al,cS as am,uS as an,Bt as ao,mS as ap,Wt as aq,fS as ar,_i as as,Dy as at,Tb as au,Db as av,Bs as aw,WS as ax,BS as ay,Ir as az,hI as b,up as c,Qe as d,_t as e,Gu as f,zi as g,mw as h,Ye as i,Zl as j,Ue as k,Ep as l,pu as m,cp as n,z as o,ht as p,we as q,Fe as r,nd as s,rd as t,H as u,lx as v,Bm as w,sd as x,Cu as y,ss as z};
9
+ `);function Tb({imageOverride:e=null,onAfterDeleteFocus:t}){const{t:n}=H(),r=f(G=>G.currentImage),s=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(Tt.subscribe,Tt.getSnapshot),[y,g]=v.useState(!1),[_,S]=v.useState(!1),[w,j]=v.useState(!1),[P,M]=v.useState(!1);v.useEffect(()=>{let G=!0;return Uo().then(C=>{G&&M(C.some(X=>X.id==="runway"&&X.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const q=async G=>{if(!N?.filename||w)return;const C=Nb(N.filename,G);if(!C){s(n("result.upscaleInvalid"),!0);return}j(!0);try{await z("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}),S(!1),s(n("result.upscaleStarted"))}catch{s(n("result.upscaleFailed"),!0)}finally{j(!1)}};v.useEffect(()=>Tt.releaseView,[]);const N=e??r,R=N?.filename??null;v.useEffect(()=>{Tt.select(R)},[R]);const $=x.status==="pending"||x.source===R?x.status:"idle";if(!N)return null;const k=xe(N),J=k?N.url||N.image:"",T=!!N.filename,Z=!!N.filename&&!k,te=k&&!!N.filename,ye=!!((N.provider==="grok"||N.provider==="grok-api")&&!k&&N.providerUrl&&N.createdAt&&Date.now()-N.createdAt<ri),ve=async()=>{if(!(!N.filename||b)){I(!0);try{await f.getState().animateImage(N.filename,N.prompt??void 0)&&s(n("toast.animateDone"))}catch(G){const C=G instanceof Error?G.message:n("toast.animateFailed");s(C,!0)}finally{I(!1)}}},F=async()=>{if(!N.filename||$==="pending"||$==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const C=Tt.start({requestId:G,sourceVideoId:N.filename,prompt:N.prompt?.trim()||void 0,provider:N.provider==="grok-api"?"grok-api":"grok",model:N.model??void 0});if(!C)return;const X=await C;f.getState().addHistoryItem(db(X,N)),s(n("toast.animateDone"))}catch(C){const X=C instanceof DOMException&&C.name==="AbortError",re=tt(C).code;re==="JOB_TRACKING_TIMEOUT"||re==="LAN_TOKEN_REQUIRED"?$e(C,f.getState()):X||s(C instanceof Error?C.message:n("toast.animateFailed"),!0)}},O=()=>Tt.cancel(),Q=()=>{const G=document.createElement("a");G.href=N.image,G.download=N.filename||"generated.png",G.click()},V=async G=>{const X=await(await fetch(G)).blob();let re;if(X.type==="image/png")re=X;else{const K=new Image;K.crossOrigin="anonymous";const be=URL.createObjectURL(X);await new Promise((He,gt)=>{K.onload=()=>He(),K.onerror=gt,K.src=be});const Te=document.createElement("canvas");Te.width=K.naturalWidth,Te.height=K.naturalHeight,Te.getContext("2d").drawImage(K,0,0),URL.revokeObjectURL(be),re=await new Promise((He,gt)=>Te.toBlob(lt=>lt?He(lt):gt(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":re})])},ae=async()=>{try{if(k){const G=await Yt(J);await V(G)}else await V(N.image);s(n(k?"toast.frameCopied":"toast.imageCopied"))}catch{s(n("toast.copyFailed"),!0)}},fe=async()=>{try{const G=await Gl(J);await V(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},ie=async()=>{try{const G=await zl(J);await V(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},Ee=async()=>{if(N.prompt)try{await navigator.clipboard.writeText(N.prompt),s(n("toast.promptCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},he=async G=>{try{await navigator.clipboard.writeText(G),s(n("toast.metadataCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},Se=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await os(N)}catch{}u&&e&&a({id:Pb,name:Ab,text:Rb});const C=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');C&&(C.focus(),C.setSelectionRange(C.value.length,C.value.length)),s(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},Ne=async()=>{if(k||!N.providerUrl||!N.createdAt||Date.now()-N.createdAt>=ri){s(n("toast.continueAsUrlExpired"),!0);return}try{await Kc(N)}catch{}const G=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');G&&(G.focus(),G.setSelectionRange(G.value.length,G.value.length)),s(n("toast.continueAsUrlStarted"))},ke=async()=>{if(!(!N.filename||m)){h(!0);try{const G=await tu({filename:N.filename});s(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const C=G instanceof Error?G.code:void 0;s(n(C==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":C==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":C==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{h(!1)}}},D=()=>{i(N),s(n("toast.nodeRootCreated"))},le=async()=>{try{await l(N)}finally{t?.()}},se=async()=>{try{await d(N)}finally{t?.()}};return o.jsxs("div",{className:"result-actions",children:[o.jsx("button",{type:"button",className:"action-btn",onClick:Q,children:n("result.download")}),o.jsx("button",{type:"button",className:`action-btn${k?" action-btn--frame":""}`,onClick:ae,children:n(k?"result.copyLastFrame":"result.copyImage")}),k&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:fe,children:n("result.copyFirstFrame")}),o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:ie,children:n("result.copyMidFrame")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Ee()},children:n("result.copyPrompt")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const G=await c(N);s(n(G?"chain.savedToAssets":"chain.saveToAssetsFailed"),!G)})()},title:n("chain.saveToAssets"),children:n("chain.saveToAssets")}),o.jsx("button",{type:"button",className:"action-btn action-btn--primary",onClick:Se,title:n("result.continueHereTitle"),children:n("result.continueHere")}),ye&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Ne()},title:n("result.continueAsUrlTitle"),children:n("result.continueAsUrl")}),Z&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ve()},disabled:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),P&&N.filename&&(k?o.jsx("button",{type:"button",className:"action-btn",disabled:w,onClick:()=>{q({})},title:n("result.upscaleTitle"),children:n(w?"inflight.streaming":"result.upscale")}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",disabled:w,onClick:()=>S(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),_?o.jsx(jb,{pending:w,onSubmit:G=>{q(G)},onClose:()=>S(!1)}):null]})),te&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",onClick:F,disabled:$==="pending"||$==="tracking-expired","aria-busy":$==="pending",title:n($==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:$==="pending"?n("inflight.streaming"):$==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),$==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:O,children:n("common.cancel")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:D,title:n("result.firstNodeTitle"),children:n("result.firstNode")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>g(!0),title:n("result.infoTitle"),children:n("result.info")}),!u&&o.jsx("button",{type:"button",className:"action-btn",onClick:p,title:n("canvas.open"),"aria-label":n("canvas.openAria"),children:o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"2","aria-hidden":"true",children:o.jsx("path",{d:"M4 4h8v8M12 4l-8 8"})})}),N.filename&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{le()},title:n("result.deleteTitle"),children:n("result.delete")}),o.jsxs("details",{className:"result-actions__more",children:[o.jsx("summary",{className:"action-btn",children:n("result.more")}),o.jsxs("div",{className:"result-actions__menu",children:[T&&o.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{ke()},title:n("result.sendToComfyUITitle"),disabled:m,children:n("result.sendToComfyUI")}),o.jsx("button",{type:"button",className:"result-actions__menu-item result-actions__danger-item",onClick:()=>{se()},children:n("result.permanentDelete")})]})]})]}),y&&o.jsx(_b,{item:N,onClose:()=>g(!1),onCopy:G=>{he(G)}})]})}const Mb=["auto","flat","detailed","mono"],st={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function Lb(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 Fb(e){return`${Math.round(e/1024)}KB`}function Ob(){const{t:e}=H(),t=f(R=>R.vectorizeTarget),n=f(R=>R.setVectorizeTarget),r=f(R=>R.addAssetGenDerivedItem),s=f(R=>R.selectedProjectId),a=f(R=>R.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=Ue(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(st.colorPrecision),[b,I]=v.useState(st.filterSpeckle),[x,y]=v.useState(st.cornerThreshold),[g,_]=v.useState(!1),[S,w]=v.useState(null),[j,P]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),w(null),P(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const M=v.useCallback(()=>{if(!t?.filename||g)return;const R=t.filename,$=new AbortController;i.current=$,_(!0),w(null),fu({source:R,preset:u,...m!==st.colorPrecision?{colorPrecision:m}:{},...b!==st.filterSpeckle?{filterSpeckle:b}:{},...x!==st.cornerThreshold?{cornerThreshold:x}:{},projectId:s,signal:$.signal}).then(k=>{if(!(i.current!==$||l.current!==R)){if(!k.filePath)throw new Error(e("vectorize.saveError"));P({filePath:k.filePath,pathCount:k.pathCount,bytes:k.bytes}),r(Lb(t,k.filePath)),a(e("vectorize.saved"))}}).catch(k=>{if(k instanceof DOMException&&k.name==="AbortError"||i.current!==$||l.current!==R)return;const J=k instanceof Error?k.message:e("vectorize.saveError");w(J),a(J,!0)}).finally(()=>{i.current!==$||l.current!==R||(i.current=null,_(!1))})},[t,g,u,m,b,x,s,r,a,e]);if(!t)return null;const q=t.url||t.image,N=j?`/generated/${encodeURIComponent(j.filePath)}`:null;return o.jsx("div",{className:"assetgen-popup-backdrop",onClick:c,children:o.jsxs("div",{ref:d,className:"keying-panel vectorize-panel",role:"dialog","aria-modal":"true","aria-label":e("vectorize.title"),onClick:R=>R.stopPropagation(),children:[o.jsxs("header",{className:"keying-panel__head",children:[o.jsx("h2",{children:e("vectorize.title")}),o.jsx("span",{className:"keying-panel__hint",children:e("vectorize.hint")})]}),o.jsxs("div",{className:"keying-panel__compare","aria-busy":g,children:[o.jsxs("figure",{className:"keying-panel__preview",children:[o.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.original")}),o.jsx("div",{className:"keying-panel__stage keying-panel__stage--original",children:o.jsx("img",{src:q??"",alt:e("vectorize.originalAlt")})})]}),o.jsxs("figure",{className:"keying-panel__preview",children:[o.jsx("figcaption",{className:"keying-panel__preview-label",children:e("vectorize.result")}),o.jsx("div",{className:"keying-panel__stage",children:N?o.jsx("img",{src:N,alt:e("vectorize.resultAlt")}):o.jsx("span",{className:"keying-panel__loading",role:"status",children:e(g?"vectorize.running":"vectorize.idle")})})]})]}),o.jsx("div",{className:"keying-panel__modes",role:"group","aria-label":e("vectorize.preset"),children:Mb.map(R=>o.jsx("button",{type:"button",className:u===R?"is-active":"","aria-pressed":u===R,onClick:()=>p(R),children:e(`vectorize.preset_${R}`)},R))}),j?o.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(j.pathCount),size:Fb(j.bytes)})}):null,o.jsxs("details",{className:"keying-panel__advanced",children:[o.jsx("summary",{children:e("vectorize.advanced")}),o.jsxs("div",{className:"keying-panel__controls",children:[o.jsxs("label",{children:[e("vectorize.colorPrecision")," ",o.jsx("output",{children:m}),o.jsx("input",{type:"range",min:1,max:8,value:m,onChange:R=>h(Number(R.target.value))})]}),o.jsxs("label",{children:[e("vectorize.filterSpeckle")," ",o.jsx("output",{children:b}),o.jsx("input",{type:"range",min:0,max:32,value:b,onChange:R=>I(Number(R.target.value))})]}),o.jsxs("label",{children:[e("vectorize.cornerThreshold")," ",o.jsx("output",{children:x}),o.jsx("input",{type:"range",min:0,max:180,value:x,onChange:R=>y(Number(R.target.value))})]}),o.jsx("button",{type:"button",className:"keying-panel__reset",onClick:()=>{h(st.colorPrecision),I(st.filterSpeckle),y(st.cornerThreshold)},children:e("vectorize.reset")})]})]}),o.jsxs("footer",{className:"keying-panel__actions",children:[S?o.jsx("span",{className:"keying-panel__save-error",role:"alert",children:S}):null,o.jsx("button",{type:"button",className:"assetgen-generate",disabled:g||!t.filename,onClick:M,children:e(g?"vectorize.running":"vectorize.run")}),N?o.jsx("a",{className:"assetgen-popup__close",href:N,download:j?.filePath,children:e("vectorize.download")}):null,o.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function Db({prompt:e,onCopy:t}){const{t:n}=H(),r=s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())};return o.jsx("div",{className:"result-prompt",onClick:t,onKeyDown:r,role:"button",tabIndex:0,title:n("result.copyPrompt"),"aria-label":n("result.copyPrompt"),children:o.jsx("span",{className:"result-prompt__text",children:e})})}function Gb(){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),s=f(m=>m.currentImage),a=f(m=>m.openCanvas),{t:i}=H(),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 o.jsxs("section",{className:"multimode-sequence","aria-live":"polite",children:[o.jsxs("div",{className:"multimode-sequence__header",children:[o.jsxs("div",{children:[o.jsx("div",{className:"multimode-sequence__title",children:i("multimode.sequenceTitle")}),o.jsx("div",{className:"multimode-sequence__meta",children:i("multimode.sequenceProgress",{returned:e.returned,requested:e.requested})})]}),n?o.jsx("button",{type:"button",className:"secondary-btn",onClick:t,children:i("multimode.cancel")}):null]}),o.jsx("div",{className:`multimode-sequence__grid count-${Math.min(e.requested,4)}`,children:p.map(({index:m,image:h,partial:b})=>{const I=h&&s?.filename&&h.filename===s.filename;return o.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:[o.jsx("div",{className:"multimode-sequence__badge",children:i("multimode.stageLabel",{index:m+1})}),h?o.jsx("img",{src:h.url??h.image,alt:i("canvas.resultAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):b?o.jsx("img",{src:b.image,alt:i("multimode.partialAlt"),loading:"lazy",decoding:"async",className:"multimode-sequence__img-fade"}):e.status==="pending"||e.status==="complete"?o.jsx("div",{className:"multimode-sequence__skeleton"}):o.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 zb({zoom:e,minZoom:t,maxZoom:n,onZoomIn:r,onZoomOut:s,onReset:a,labels:i}){return o.jsxs("div",{className:"viewer-controls","aria-label":i.controls,onPointerDown:l=>l.stopPropagation(),onDoubleClick:l=>l.stopPropagation(),onWheel:l=>l.stopPropagation(),children:[o.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),s()},disabled:e<=t,"aria-label":i.zoomOut,children:"-"}),o.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),"%"]}),o.jsx("button",{type:"button",className:"viewer-control-btn",onClick:l=>{l.stopPropagation(),r()},disabled:e>=n,"aria-label":i.zoomIn,children:"+"})]})}function Ir(e){return e instanceof HTMLElement?e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLButtonElement||e.isContentEditable:!1}function qb(e,t,n,r){if(!e)return!1;const s=t.find(a=>a.filename===e);return s?!!s.isFavorite:r!==void 0?r:n.has(e)}function ww(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const It=1,ed=5,or=.22;function $b(e){return Math.min(ed,Math.max(It,e))}function Ub(e){const[t,n]=v.useState(1),[r,s]=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),s({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=$b(y+x);return g<=It?(s({x:0,y:0}),It):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?or:-or)},[u]),m=v.useCallback(()=>{if(t>It){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=It||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(()=>{s(y),c.current=null})},[a]),I=v.useCallback(x=>{!a||a.pointerId!==x.pointerId||(cancelAnimationFrame(l.current),l.current=0,c.current&&(s(c.current),c.current=null),i(null),x.currentTarget.releasePointerCapture(x.pointerId))},[a]);return{zoom:t,pan:r,reset:d,zoomIn:()=>u(or),zoomOut:()=>u(-or),handleWheel:p,handleDoubleClick:m,handlePointerDown:h,handlePointerMove:b,handlePointerUp:I}}const Hb=v.lazy(()=>Me(()=>import("./index-BWzT2RyM.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function Kb(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function Vb(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function Bb(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 Ys(){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),s=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}=H(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:S}=cb(),w=v.useRef(null),j=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,P=Ub(j),M=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},q=F=>{if(F.key==="Delete"||F.key==="Backspace"){if(!e||F.target!==F.currentTarget||Ir(F.target))return;if(F.preventDefault(),F.shiftKey){a(e);return}s(e);return}F.key!=="ArrowLeft"&&F.key!=="ArrowRight"&&F.key!=="Home"&&F.key!=="End"||F.target===F.currentTarget&&(Ir(F.target)||(F.preventDefault(),F.key==="ArrowLeft"?r("previous"):F.key==="ArrowRight"?r("next"):F.key==="Home"?r("first"):F.key==="End"&&r("last")))},N=F=>{Ir(F.target)||(i(),F.currentTarget.focus())},R=v.useCallback(()=>{window.requestAnimationFrame(()=>w.current?.focus())},[]),$=async()=>{const F=e?.filename;if(!(!e||!F||y===F)){g(F);try{await h(e)}finally{g(O=>O===F?null:O)}}},k=v.useCallback(F=>{Array.from(F.dataTransfer.types).includes("Files")&&(F.preventDefault(),x(O=>O||!0))},[]),J=v.useCallback(F=>{F.currentTarget.contains(F.relatedTarget)||x(!1)},[]),T=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(Q=>/^image\/(png|jpeg|webp)$/.test(Q.type));O.length!==0&&await t(O[0])},[t]);if(c&&e)return o.jsxs(o.Fragment,{children:[o.jsx(v.Suspense,{fallback:o.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:o.jsx(Hb,{currentImage:e})}),o.jsx(Ob,{})]});const Z=Kb(e?.quality),te=Vb(e?.size),de=zi(e?.model,e?.provider),ye=e?Bb(e):null,ve=qb(e?.filename,p,m,e?.isFavorite);return o.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:k,onDragLeave:J,onDrop:T,children:[I?o.jsx("div",{className:"canvas__drop-overlay","aria-hidden":!0,children:o.jsx("span",{className:"canvas__drop-hint",children:b("canvas.drop.hint")})}):null,o.jsx("div",{className:`progress-bar${l>0?" active":""}`}),n?o.jsx(Gb,{}):e&&ye?o.jsxs("div",{ref:w,className:"result-container visible",tabIndex:0,onMouseDown:N,onKeyDown:q,"aria-label":b("canvas.imageViewerAria"),children:[o.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${P.zoom>It?" 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?o.jsx(Hc,{variant:"result",active:ve,busy:y===e.filename,label:b(ve?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:$}):null,xe(e)?o.jsxs(o.Fragment,{children:[o.jsx("video",{className:"result-img",src:ye,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${P.pan.x}px, ${P.pan.y}px) scale(${P.zoom})`}},j??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:F=>{F.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(e))),F.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}):o.jsxs(o.Fragment,{children:[o.jsx("img",{className:"result-img",src:ye,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()}},j??void 0),o.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")})]}),o.jsx(zb,{zoom:P.zoom,minZoom:It,maxZoom:ed,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")}})]}),o.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,mc(e.videoContinuity),de]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Gu(e.reasoningEffort),Z,te,de]).filter(F=>!!F).join(" · ")}),o.jsx(Tb,{onAfterDeleteFocus:R}),e.prompt?o.jsx(Db,{prompt:e.prompt,onCopy:M}):null]}):e?null:o.jsxs("div",{className:"canvas__blank-entry",children:[o.jsx("div",{className:"canvas__blank-sheet","aria-hidden":!0}),o.jsxs("div",{className:"canvas__blank-copy",children:[o.jsx("strong",{children:b("canvas.blank.title")}),o.jsx("span",{children:b("canvas.blank.subtitle")})]}),o.jsx("button",{type:"button",className:"canvas__blank-button",onClick:()=>{S()},disabled:_,children:b(_?"canvas.blank.creating":"canvas.blank.create")})]})]})}function Wb(){return o.jsxs("div",{className:"classic-workspace",children:[o.jsx("div",{className:"classic-workspace__stage",children:o.jsx(Ys,{})}),o.jsxs("div",{className:"classic-workspace__dock",children:[o.jsx(Jo,{variant:"bottom"}),o.jsx(Yo,{})]})]})}const td="ima2.customSizeSlots";function Jb(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 Yb(){try{const e=localStorage.getItem(td);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?Ft(t.filter(Jb)):[]}catch{return[]}}function Xb(e){try{localStorage.setItem(td,JSON.stringify(Ft(e)))}catch{}}function Zb(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 sn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function Qb(){const e=f(T=>T.sizePreset),t=f(T=>T.setSizePreset),n=f(T=>T.customW),r=f(T=>T.customH),s=f(T=>T.setCustomSize),{t:a}=H(),[i,l]=v.useState(String(n)),[c,d]=v.useState(String(r)),[u,p]=v.useState(e==="custom"),[m,h]=v.useState(()=>Yb()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=bo(i,c,n,r),S=rm().filter(T=>T.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function w(T){h(T),Xb(T)}function j(){const T=Ze(i,n),Z=Ze(c,r);s(T,Z),l(String(T)),d(String(Z))}function P(T){T.key==="Enter"&&(T.preventDefault(),j())}function M(){t("custom"),p(!0),I(m.length>=Lt?m[0]?.id??null:null)}function q(T){t(T),T!=="custom"&&(p(!1),I(null))}function N(T){t("custom"),s(T.w,T.h),l(String(T.w)),d(String(T.h)),p(!1),I(T.id)}function R(T){y(T.id);const Z=Yu(T);Z&&(l(String(Z.w)),d(String(Z.h)))}function $(){const T=Zb(_.w,_.h,x),Z=m.length>=Lt&&b?Zu(m,b,T):Xu(m,T);w(Z),t("custom"),s(_.w,_.h),l(String(_.w)),d(String(_.h)),I(T.id),p(!1)}const k=_.reasons.length>0?_.reasons.map(T=>a(`size.adjustedReasons.${T}`)).join(", "):a("size.noAdjustment"),J=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${Ia}×${Ia}`}):null;return o.jsxs("div",{className:"option-group size-picker",children:[o.jsx("div",{className:"section-title",children:a("size.title")}),o.jsx(Oe,{title:"",items:sn(Qu),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(em),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(tm),value:e,onChange:q}),o.jsx(Oe,{title:"",items:sn(nm),value:e,onChange:q}),o.jsxs("div",{className:"option-row size-picker__quick-row",children:[sn(S).map(T=>o.jsxs("button",{type:"button",className:`option-btn${e===T.value?" active":""}`,onClick:()=>q(T.value),children:[T.label,T.sub?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.sub})]}):null]},T.value)),o.jsxs("button",{type:"button",className:`option-btn${g?" active":""}`,onClick:M,children:[a("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:a("size.customSub")})]})]}),m.length>0?o.jsx("div",{className:"option-row size-picker__slot-row",children:m.map(T=>o.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===T.w&&r===T.h?" active":""}`,onClick:()=>N(T),children:[T.w,"×",T.h,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.ratio||a("size.customSlot")})]},T.id))}):null,u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"size-picker__ratio-row",children:Wu.map(T=>o.jsx("button",{type:"button",className:`size-picker__ratio${x===T.id?" active":""}`,onClick:()=>R(T),children:T.id==="free"?a("size.ratioFree"):T.label},T.id))}),o.jsxs("div",{className:"option-row size-picker__custom-row",children:[o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:i,onChange:T=>l(T.target.value.replace(/\D/g,"")),onBlur:j,onKeyDown:P,placeholder:a("size.width")}),o.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:c,onChange:T=>d(T.target.value.replace(/\D/g,"")),onBlur:j,onKeyDown:P,placeholder:a("size.height")})]}),o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:a("size.normalizedPreview")}),o.jsx("strong",{children:Ju(_.w,_.h)})]}),o.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:k}),J?o.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:J}):null,m.length>=Lt?o.jsxs("div",{className:"size-picker__replace-row",children:[o.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(T=>o.jsxs("button",{type:"button",className:`size-picker__replace${b===T.id?" active":""}`,onClick:()=>I(T.id),children:[T.w,"×",T.h]},T.id))]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:$,children:m.length>=Lt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),o.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const _s=[1,2,4];function ex(){const e=f(g=>g.count),t=f(g=>g.setCount),n=f(g=>g.uiMode),r=f(g=>g.multimode),s=f(g=>g.multimodeMaxImages),a=f(g=>g.setMultimodeMaxImages),{t:i}=H(),l=n==="classic"&&r,c=l?s:e,d=l?a:t,[u,p]=v.useState(!_s.includes(c)),[m,h]=v.useState(String(c));v.useEffect(()=>{p(!_s.includes(c)),h(String(c))},[l,c]);function b(g=m){const _=qs(Number.parseInt(g,10));d(_),h(String(_))}function I(g){p(!1),h(String(g)),d(g)}function x(g){const _=qs(c+g);p(!0),h(String(_)),d(_)}function y(g){g.key==="Enter"&&(g.preventDefault(),b())}return o.jsxs("div",{className:"option-group count-picker",children:[o.jsx("div",{className:"section-title",children:i(l?"multimode.maxStages":"count.title")}),o.jsxs("div",{className:"option-row",children:[_s.map(g=>o.jsx("button",{type:"button",className:`option-btn${c===g&&!u?" active":""}`,onClick:()=>I(g),children:g},g)),o.jsx("button",{type:"button",className:`option-btn${u?" active":""}`,onClick:()=>{p(g=>!g),h(String(c))},children:i("count.customPlus")})]}),u?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"count-picker__custom",children:[o.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(-1),"aria-label":i("count.decrease"),children:"-"}),o.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")}),o.jsx("button",{type:"button",className:"count-picker__step",onClick:()=>x(1),"aria-label":i("count.increase"),children:"+"})]}),o.jsx("p",{className:"option-help",children:c>=5?i(l?"multimode.highCountHint":"count.highCountHint"):i(l?"multimode.minMaxHint":"count.minMaxHint")})]}):null]})}const tx={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}},nx={512:.045,"1K":.067,"2K":.101,"4K":.151},rx={512:.134,"1K":.134,"2K":.134,"4K":.24};function sx(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function ox(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),s=sx(r),i=t==="nano-banana-pro"?rx:nx;return i[s]??i["1K"]??.003}function ax(e,t,n,r){return n==="gemini-api"?ox(t,r):tx[e]?.[t]??0}function ix(){const{t:e}=H(),t=f(m=>m.provider),n=f(m=>m.quality),r=f(m=>m.multimode),s=f(m=>m.multimodeMaxImages),i=f(m=>m.getResolvedSize)(),l=f(m=>m.imageModel),c=t==="oauth"||t==="grok"||t==="agy",d=ax(n,i,t,l),u=c?e("cost.free"):r?e("cost.multimodeApprox",{amount:(d*s).toFixed(3),count:s}):e("cost.approx",{amount:d.toFixed(3)}),p=c?"var(--green)":void 0;return o.jsxs("div",{className:"cost-estimate",children:[o.jsx("span",{children:e("cost.label")}),o.jsx("span",{className:"price",style:p?{color:p}:void 0,children:u})]})}function nd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const s=async()=>{try{const a=await jd();if(n)return;t(a),a.status==="starting"&&(r=setTimeout(s,3e3))}catch{n||t(null)}};return s(),()=>{n=!0,r&&clearTimeout(r)}},[]),e}function lx(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let s=!1;return Pd().then(a=>{s||t(a)}).catch(()=>{s||r(!0)}),()=>{s=!0}},[]),{data:e,error:n}}function rd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(ce())return;const n=pe();let r=!1,s=null;const a=async()=>{if(!(r||ce()||n!==pe()))try{const l=await we("/api/grok/status");if(r)return;const c=await l.json();if(r||ce()||n!==pe())return;t(c),c.status!=="ready"&&(s=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,s&&clearTimeout(s),window.removeEventListener(St,i)};return window.addEventListener(St,i),a(),i},[]),e}function sd(){const[e,t]=v.useState(null),[n,r]=v.useState(null),s=v.useRef(!1),a=v.useCallback(async()=>{if(!s.current||ce())return;const i=pe();try{const c=await(await we("/api/keys/status")).json();if(!s.current||ce()||i!==pe())return;t(c),r(null)}catch(l){if(!s.current||ce()||i!==pe())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return v.useEffect(()=>{if(ce())return;s.current=!0;let i=!1,l=null;const c=async()=>{await a(),i||(l=setInterval(a,3e4))},d=()=>{s.current=!1,i=!0,l&&clearInterval(l),window.removeEventListener(St,d)};return window.addEventListener(St,d),c(),d},[a]),{data:e,error:n,mutate:a}}function od(){const{t:e}=H(),t=nd(),{data:n}=lx(),r=rd(),{data:s}=sd(),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=s?.xai?.valid===!0,m=s?.gemini?.valid===!0||s?.vertex?.valid===!0,h=s?.atlascloud?.valid===!0,b=s?.minimax?.valid===!0,I=s?.nai?.valid===!0,x=qn(),y=Et(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":$t(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function cx({open:e,providerLabel:t,reason:n,hint:r,onClose:s}){const{t:a}=H(),i=Ue(e,s);if(!e)return null;const l=a("apiDisabled.title",{provider:t});return o.jsx("div",{className:"modal-backdrop",onClick:s,role:"presentation",children:o.jsxs("div",{ref:i,className:"modal",role:"dialog","aria-modal":"true","aria-label":l,tabIndex:-1,onClick:c=>c.stopPropagation(),children:[o.jsx("div",{className:"modal__title",children:l}),o.jsxs("div",{className:"modal__body",children:[o.jsx("p",{children:n}),r?o.jsx("p",{className:"modal__hint",children:r}):null]}),o.jsx("div",{className:"modal__actions",children:o.jsx("button",{type:"button",className:"modal__btn",onClick:s,"data-modal-initial-focus":!0,children:a("common.ok")})})]})})}const ar="core:",Es="mcp:",dx={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"}},Ns=io.map(e=>dx[e]);function ks(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function Cs({tone:e}){return o.jsx("span",{className:`status-dot status-dot--${e==="ok"?"ok":e==="warn"?"warn":"bad"}`,"aria-hidden":"true"})}function si(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 js({mcpProviders:e}){const{t}=H(),n=f(N=>N.provider),r=f(N=>N.mcpProvider??null),s=f(N=>N.setProvider),a=od(),i=qn(),l=f(N=>N.comfyWorkflow),c=f(N=>N.comfyVideoWorkflow),d=Et(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=N=>{const R=a[N.value];return N.value==="comfy"?u?t($t(d,i)):R.reason:R.ok?t("provider.statusReady"):R.reason},I=N=>N.enabled?N.status.state==="connected"?N.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):N.status.state==="connecting"?t("mcp.connecting"):N.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Ns.map(N=>{const R=a[N.value];return{value:`${ar}${N.value}`,searchText:`${N.provider} ${N.value==="comfy"?t("comfy.display.localMethod"):N.method}`,label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:N.value==="comfy"&&u?p:R.ok?"ok":"bad"}),o.jsxs("span",{children:[N.provider," ",N.value==="comfy"?t("comfy.display.localMethod"):N.method]})]}),sub:b(N)}})}],y=e.filter(N=>N.enabled).map(N=>({value:`${Es}${N.id}`,searchText:ks(N.id),label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:si(N)}),o.jsx("span",{children:ks(N.id)})]}),sub:I(N)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${Es}${r}`:`${ar}${n}`,_=r?null:Ns.find(N=>N.value===n)??null,S=r?e.find(N=>N.id===r)??null:null,w=_?.value==="comfy",j=w?t($t(d,i)):_?b(_):S?I(S):t("provider.statusDisconnected"),P=w?p:_?a[_.value].ok?"ok":"bad":S?si(S):"bad",M=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",q=N=>{if(N.startsWith(ar)){const k=N.slice(ar.length);if(!jt(k))return;const J=Ns.find(Z=>Z.value===k),T=a[k];if(k==="comfy"){s(k);return}if(!T.ok){h({label:J?`${J.provider} ${J.method}`:k,reason:T.reason,hint:T.hint});return}s(k);return}const R=N.slice(Es.length),$=e.find(k=>k.id===R);if(!$||!$.enabled||$.status.state!=="connected"){h({label:ks(R),reason:!$||!$.enabled?t("mcp.disabledProvider"):t("mcp.disconnectedSelection")});return}rs(R,f.setState,f.getState)};return o.jsxs("div",{className:"option-group provider-status-select","data-testid":"provider-status-select",children:[o.jsx("div",{className:"section-title",children:t("provider.authTitle")}),o.jsx(Fe,{groups:x,value:g,onChange:q,triggerSub:w?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),o.jsxs("div",{className:"provider-status-line","data-tone":P,role:"status","aria-live":"polite",children:[o.jsx(Cs,{tone:P}),o.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),o.jsx("span",{className:"provider-status-line__value",children:j})]}),w&&i.observedAt!==null?o.jsx("p",{className:"provider-helper",children:t("comfy.display.lastChecked",{time:new Date(i.observedAt).toLocaleTimeString()})}):null,w&&d.code==="selected-missing"&&i.catalog?.comfy?.status==="disconnected"?o.jsx("p",{className:"provider-helper",children:t("comfy.statusOffline")}):null,o.jsxs("div",{className:"provider-auth-chip",title:t(w?"comfy.display.localMethod":"provider.authMethodTitle"),children:[o.jsx("span",{children:M}),P!=="bad"&&!w?o.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),o.jsx(cx,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const ux=[{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"}],mx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function px(){const{t:e}=H(),t=f(a=>a.grokAspectRatio),n=f(a=>a.grokResolution),r=f(a=>a.setGrokAspectRatio),s=f(a=>a.setGrokResolution);return o.jsxs("div",{className:"option-group grok-size-picker",children:[o.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")}),o.jsx("div",{className:"grok-size-picker__aspects",children:ux.map(a=>o.jsx("button",{type:"button",className:`option-btn grok-size-picker__aspect${t===a.value?" active":""}`,onClick:()=>r(a.value),children:a.label},a.value))}),o.jsx("div",{className:"section-title",style:{marginTop:8},children:e("size.grokResolutionTitle")}),o.jsx("div",{className:"grok-size-picker__resolutions",children:mx.map(a=>o.jsx("button",{type:"button",className:`option-btn grok-size-picker__res${n===a.value?" active":""}`,onClick:()=>s(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 hx(){const{t:e}=H(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return o.jsx(Oe,{title:e("quality.grokModelTitle"),items:fx,value:t,onChange:n})}function ad({values:e,value:t,defaultValue:n,onChange:r,allowAuto:s=!1,disabled:a,ariaLabel:i}){const{t:l}=H(),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 o.jsxs("div",{className:`ctl-duration${p?" is-auto":""}${a?" is-disabled":""}`,children:[o.jsxs("div",{className:"ctl-duration__head",children:[o.jsx("output",{htmlFor:c,className:"ctl-duration__value",children:p?`${l("size.autoLabel")} · ${e[u]}s`:`${e[u]}s`}),s?o.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]}),o.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])}),o.jsxs("div",{className:"ctl-duration__scale","aria-hidden":"true",children:[o.jsxs("span",{children:[m,"s"]}),o.jsxs("span",{children:[h,"s"]})]})]})}const gx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],yx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),oi=[3,5,8,10,12,15],vx=[{value:po,label:"Grok V",sub:"Fast"},{value:pt,label:"Grok V1.5",sub:"HD"}];function bx(){const{t:e}=H(),t=f(k=>k.videoModelSelected),n=f(k=>k.selectVideoModel),r=f(k=>k.activeVideoRefCount()),s=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=>lc(k)).filter(k=>k?.category==="camera-motion"),_=15,S=Ru(r,s),w=mc(I),j=is(t,"1080p",S),P=is(pt,"1080p",S),M=gx.map(k=>k.value==="1080p"?{...k,disabled:!P}:k);v.useEffect(()=>{is(t,c,S)||d("720p")},[S,c,d,t]);const q=k=>{if(k==="1080p"){if(!P)return;j||n(pt)}d(k)},[N,R]=v.useState(null);v.useEffect(()=>{we("/api/config/grok-planner").then(k=>k.json()).then(R).catch(()=>{})},[]);const $=async k=>{const J=N?.model;R(T=>T?{...T,model:k}:null);try{const T=await we("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:k})});if(!T.ok)throw new Error(`HTTP ${T.status}`)}catch(T){if(R(Z=>Z&&J?{...Z,model:J}:Z),T?.code==="LAN_TOKEN_REQUIRED")return;b(e("video.plannerUpdateFailed"),!0)}};return o.jsxs("div",{className:"right-panel-settings video-controls",children:[o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("quality.grokModelTitle")??"Model"}),o.jsx("div",{className:"option-row",children:vx.map(k=>o.jsxs("button",{type:"button",className:`option-btn${t===k.value?" active":""}`,onClick:()=>n(k.value),children:[k.label,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:k.sub})]},k.value))})]}),o.jsxs("div",{className:"provider-compat-note",role:"note",children:[o.jsx("strong",{children:e("video.modeLabel")}),o.jsx("span",{children:e(`video.mode.${S}`,{n:r})})]}),w?o.jsxs("div",{className:"provider-compat-note",role:"note",children:[o.jsx("strong",{children:e("common.continuity")}),o.jsx("span",{children:w})]}):null,g.length>0&&o.jsx(Wo,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(k=>o.jsx(Uc,{onRemove:()=>y(k.id),removeLabel:e("common.removeNamed",{name:k.name}),children:k.name},k.id))}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.seriesTopicTitle")??"시리즈 주제"}),o.jsx("input",{type:"text",className:"video-topic-input",placeholder:e("video.seriesTopicPlaceholder")??"예: 한국 여행 브이로그",value:m,onChange:k=>h(k.target.value)})]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.durationTitle")}),o.jsx(ad,{values:oi.filter(k=>k<=_),value:i,ariaLabel:e("video.durationTitle"),onChange:k=>l(k??oi[0])})]}),r===1&&o.jsx(Oe,{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:s,onChange:a}),o.jsx(Oe,{title:e("video.resolutionTitle"),help:P?void 0:e("video.resolution1080Help"),items:M,value:c,onChange:q}),o.jsx(Oe,{title:e("video.aspectTitle"),items:yx,value:u,onChange:p}),N&&o.jsx("div",{className:"video-controls__pills",children:o.jsx(Fe,{className:"video-controls__pill",items:N.options.map(k=>({value:k,label:k})),value:N.model,onChange:k=>{$(k)},ariaLabel:e("video.plannerModelTitle")})}),o.jsxs("details",{className:"provider-compat-details",style:{marginTop:8},children:[o.jsx("summary",{children:e("common.activePrompt")}),o.jsx("p",{children:Ar})]})]})}const ai=e=>Symbol.iterator in e,ii=e=>"entries"in e,li=(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[s,a]of n)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},xx=(e,t)=>{const n=e[Symbol.iterator](),r=t[Symbol.iterator]();let s=n.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=n.next(),a=r.next()}return!!s.done&&!!a.done};function Ix(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:ai(e)&&ai(t)?ii(e)&&ii(t)?li(e,t):xx(e,t):li({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Sx(e){const t=an.useRef(void 0);return n=>{const r=e(n);return Ix(t.current,r)?t.current:t.current=r}}const wx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function _x(){const{t:e}=H(),t=f(Sx(zm)),n=f(u=>u.setNaiOption),r=f(u=>u.resetNaiOptions),s=f(u=>u.imageModel),a=f(u=>u.setImageModel),i=f(u=>u.sizePreset),l=f(u=>u.setSizePreset),c=$s(s),d=t.seed===null?"":String(t.seed);return o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.modelTitle")}),o.jsx(Fe,{items:Gi.map(u=>({value:u.value,label:u.shortLabel})),value:s,onChange:u=>{$s(u)||(n("straightAlpha",!1),n("qualityPresetId","standard")),a(u)},ariaLabel:e("nai.panel.modelTitle")})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.sizeTitle")}),o.jsx("div",{className:"option-row",children:wx.map(u=>o.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"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:u.value.replace("x","×")})]},u.value))})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.samplingTitle")}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.sampler")}),o.jsx(Fe,{items:al.map(u=>({value:u,label:u})),value:t.sampler,onChange:u=>n("sampler",u),ariaLabel:e("nai.field.sampler")})]}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.noiseSchedule")}),o.jsx(Fe,{items:il.map(u=>({value:u,label:u})),value:t.noiseSchedule,onChange:u=>n("noiseSchedule",u),ariaLabel:e("nai.field.noiseSchedule")})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.autoSmea,onChange:u=>n("autoSmea",u.target.checked)}),o.jsx("span",{children:e("nai.field.autoSmea")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.autoSmea")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.steps")}),o.jsx("input",{type:"range",min:Er.min,max:Er.max,step:1,value:t.steps,onChange:u=>n("steps",Number(u.target.value))}),o.jsx("output",{children:t.steps})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.scale")}),o.jsx("input",{type:"range",min:Nr.min,max:Nr.max,step:.1,value:t.scale,onChange:u=>n("scale",Number(u.target.value))}),o.jsx("output",{children:t.scale.toFixed(1)})]}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--slider",children:[o.jsx("span",{children:e("nai.field.cfgRescale")}),o.jsx("input",{type:"range",min:kr.min,max:kr.max,step:.01,value:t.cfgRescale,onChange:u=>n("cfgRescale",Number(u.target.value))}),o.jsx("output",{children:t.cfgRescale.toFixed(2)})]}),o.jsx("p",{className:"option-help",children:e("nai.help.cfgRescale")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.decrisper,onChange:u=>n("decrisper",u.target.checked)}),o.jsx("span",{children:e("nai.field.decrisper")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.decrisper")})]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.presetTitle")}),o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.ucPreset")}),o.jsx(Fe,{items:ll.map(u=>({value:u,label:e(`nai.ucPreset.${u}`)})),value:t.ucPresetId,onChange:u=>n("ucPresetId",u),ariaLabel:e("nai.field.ucPreset")})]}),c?o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.qualityPreset")}),o.jsx(Fe,{items:cl.map(u=>({value:u,label:e(`nai.qualityPreset.${u}`)})),value:t.qualityPresetId,onChange:u=>n("qualityPresetId",u),ariaLabel:e("nai.field.qualityPreset")})]}):null]}),o.jsxs("div",{className:"option-group nai-controls",children:[o.jsx("div",{className:"section-title",children:e("nai.panel.outputTitle")}),o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.varietyPlus,onChange:u=>n("varietyPlus",u.target.checked)}),o.jsx("span",{children:e("nai.field.varietyPlus")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.varietyPlus")}),c?o.jsxs(o.Fragment,{children:[o.jsxs("label",{className:"nai-controls__row nai-controls__row--toggle",children:[o.jsx("input",{type:"checkbox",checked:t.straightAlpha,onChange:u=>n("straightAlpha",u.target.checked)}),o.jsx("span",{children:e("nai.field.straightAlpha")})]}),o.jsx("p",{className:"option-help",children:e("nai.help.straightAlpha")})]}):null,o.jsxs("label",{className:"nai-controls__row",children:[o.jsx("span",{children:e("nai.field.seed")}),o.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),dl))}})]}),o.jsx("p",{className:"option-help",children:e("nai.help.seed")})]}),o.jsx("div",{className:"option-group nai-controls",children:o.jsx("button",{type:"button",className:"option-btn",onClick:r,children:e("nai.resetDefaults")})})]})}const Ex="",id=3;function ci(e,t,n,r){const s=[],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),s.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),s.push({filename:l,current:!1,label:i.name||l,source:i.kind==="element"?"element":"asset"}))}return s}function Nx(e,t){return e[t]??null}function ld(e,t,n){const r=!t||e.some(s=>s.filename===t);return[{value:Ex,label:n("mcp.referenceNone")},...r?[]:[{value:t,label:t,sub:n("mcp.referenceMissing")}],...e.map(s=>({value:s.filename,label:s.label??s.filename,sub:s.current?n("mcp.referenceCurrent"):s.source?n(`mcp.referenceSource.${s.source}`):void 0}))]}function Ps({id:e,label:t,value:n,candidates:r,disabled:s,title:a,help:i,onChange:l,t:c}){return o.jsxs("div",{className:"mcp-reference-slot",children:[o.jsx("label",{className:"mcp-reference-slot__label",htmlFor:e,children:t}),o.jsx(Fe,{id:e,items:ld(r,n??"",c),value:n??"",onChange:l,ariaLabel:t,placeholder:c("mcp.referenceSelect"),disabled:s,title:a,portal:!0}),i?o.jsx("p",{className:"option-help",children:i}):null]})}function kx({index:e,images:t,selection:n,disabled:r,onChange:s,t:a}){const i=Nx(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),s({...n,references:I})},p=b=>{if(!i)return;const I=[...n.references],{tag:x,...y}=i;I[e]={...y,...b?{tag:b}:{}},s({...n,references:I})},m=!!(i?.tag&&!xo(i.tag)),h=`mcp-reference-tag-error-${e}`;return o.jsxs("div",{className:"mcp-reference-slot__reference",children:[o.jsx(Fe,{items:ld(d,i?.filename??"",a),value:i?.filename??"",onChange:u,ariaLabel:a("mcp.imageReferenceAria",{index:e+1}),placeholder:a("mcp.referenceSelect"),disabled:r,portal:!0}),o.jsxs("div",{children:[o.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?o.jsx("p",{id:h,className:"settings-row__microcopy",role:"alert",children:a("mcp.referenceTagInvalid")}):null]})]})}function Cx({selection:e,disabled:t,onChange:n,t:r}){const s=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=id,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 Co(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 o.jsxs("div",{children:[o.jsx("input",{ref:s,className:"sr-only",type:"file",accept:"image/png,image/jpeg,image/webp",onChange:d=>{c(d)},disabled:t||l}),o.jsx("button",{type:"button",className:"option-btn",onClick:()=>s.current?.click(),disabled:t||l,children:r("mcp.referenceAttachLocal")}),o.jsx("p",{className:"option-help",children:r("mcp.referenceAttachHelp")}),a?o.jsx("p",{className:"settings-row__microcopy",role:"alert",children:a}):null]})}function jx({images:e,selection:t,disabled:n,onChange:r,t:s}){return o.jsxs("div",{className:"mcp-reference-slot",children:[o.jsx("div",{className:"mcp-reference-slot__label",children:s("mcp.imageReferencesLabel")}),Array.from({length:id},(a,i)=>o.jsx(kx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:s},i)),o.jsx(Cx,{selection:t,disabled:n,onChange:r,t:s})]})}function Px({inputRoles:e,disabled:t}){const{t:n}=H(),r=f(p=>p.history),s=f(p=>p.currentImage),a=f(p=>p.assets),i=f(p=>p.mcpReferenceSelection)??qe(),l=v.useMemo(()=>ci(r,s,a,!1),[r,s,a]),c=v.useMemo(()=>ci(r,s,a,!0),[r,s,a]),d=p=>Xh(p,f.setState,f.getState),u=i.startFrameFilename?void 0:n("mcp.endFrameNeedsStart");return o.jsxs("div",{className:"mcp-reference-slots",children:[e.includes("start_image")?o.jsx(Ps,{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")?o.jsx(Ps,{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")?o.jsx(jx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?o.jsx(Ps,{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 Ax(e){return Array.isArray(e)&&e.includes("image_references")}function Rx(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function _w(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 Ew(e){return e.length>3}function Tx({inputRoles:e,disabled:t}){const{t:n}=H(),r=f(d=>d.assets),s=f(d=>d.mcpCharacterElementId??null),a=f(d=>d.selectedElementIds??[]);if(!Ax(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=Rx({mentionElementIds:a,characterElementId:s})==="conflict",c=!!t||a.length>0;return o.jsxs("div",{className:"mcp-character-slot","data-testid":"mcp-character-slot",children:[o.jsx("div",{className:"section-title",children:n("mcp.characterSlotLabel")}),o.jsxs("select",{value:s??"",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:[o.jsx("option",{value:"",children:n("mcp.characterSlotNone")}),i.map(d=>o.jsx("option",{value:d.id,children:d.name},d.id))]}),l?o.jsx("p",{className:"option-help",role:"alert",children:n("mcp.characterSlotConflictHint")}):null]})}const di=new Set(["duration","resolution","quality","mode"]);function ui(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ta(e){return e.options&&e.options.length>0?ui(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):ui([e.min,...e.default!==void 0?[e.default]:[],e.max])}function mi(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 Mx(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function Lx(e){return[...ta(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function Fx({parameter:e,value:t,disabled:n,onChange:r}){const{t:s}=H();if(e.name==="duration"&&e.type==="number"){const l=Lx(e);if(l.length>1){const c=mi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:c}),o.jsx(ad,{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=ta(e);if(a.length===0)return null;const i=mi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:i}),o.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i,children:[e.required?null:o.jsx("button",{type:"button",className:`option-btn${t===void 0?" active":""}`,"aria-pressed":t===void 0,disabled:n,onClick:()=>r(null),children:s("size.autoLabel")}),a.map(l=>o.jsx("button",{type:"button",className:`option-btn${t===l?" active":""}`,"aria-pressed":t===l,disabled:n,onClick:()=>r(l),title:e.description,children:Mx(l,s)},`${typeof l}:${String(l)}`))]})]})}function pi({entries:e,parameters:t,disabled:n,onParameter:r}){return o.jsx(o.Fragment,{children:e.map(s=>o.jsx(Fx,{parameter:s,value:t[s.name],disabled:n,onChange:a=>r(s.name,a)},s.name))})}function Ox({entry:e,ratio:t,parameters:n,disabled:r,onRatio:s,onParameter:a}){const{t:i}=H(),l=e.capabilities.aspectRatios.filter(m=>m!=="auto"),c=e.capabilities.parameters.filter(m=>ta(m).length>0),d=c.filter(m=>di.has(m.name)),u=c.filter(m=>!di.has(m.name)),p=e.capabilities.inputRoles.some(m=>m==="start_image"||m==="end_image"||m==="image_references"||m==="video_references");return o.jsxs("div",{className:"mcp-model-presets","data-capability-source":e.capabilities.source,children:[l.length>0?o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:i("mcp.aspectRatioLabel")}),o.jsxs("div",{className:"mcp-preset-row__options",role:"group","aria-label":i("mcp.aspectRatioLabel"),children:[o.jsx("button",{type:"button",className:`option-btn${t===null?" active":""}`,"aria-pressed":t===null,disabled:r,onClick:()=>s(null),children:i("size.autoLabel")}),l.map(m=>o.jsx("button",{type:"button",className:`option-btn${t===m?" active":""}`,"aria-pressed":t===m,disabled:r,onClick:()=>s(m),children:m},m))]})]}):null,o.jsx(pi,{entries:d,parameters:n,disabled:r,onParameter:a}),p?o.jsxs("div",{className:"mcp-tool-inputs",children:[o.jsx("div",{className:"section-title",children:i("mcp.toolInputsLabel")}),o.jsx(Px,{inputRoles:e.capabilities.inputRoles,disabled:r}),o.jsx(Tx,{inputRoles:e.capabilities.inputRoles,disabled:r})]}):null,u.length>0?o.jsxs("details",{className:"mcp-advanced-presets",children:[o.jsx("summary",{children:i("mcp.advancedPresetsLabel")}),o.jsx(pi,{entries:u,parameters:n,disabled:r,onParameter:a})]}):null,l.length===0&&c.length===0?o.jsx("p",{className:"option-help",children:i("mcp.providerDefaultsHelp")}):null]})}const ir={image:[],video:[]},Dx={};function Gx(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function zx({record:e}){const{t}=H(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),s=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??Dx,[c,d]=v.useState(ir),[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(ir),p("idle");return}const _=new AbortController;return d(ir),p("loading"),Mc(n,_.signal).then(S=>{_.signal.aborted||(d(S),p("ready"))}).catch(S=>{S.name!=="AbortError"&&(_.signal.aborted||(d(ir),p("error")))}),()=>_.abort()},[n,I,m]),!n)return null;const x=s==="video"?c.video:c.image,y=x.find(_=>_.id===r)??null,g=_=>Wh(_,f.setState,f.getState);return o.jsxs("div",{className:"mcp-generation-controls","data-testid":"mcp-generation-controls",children:[o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"section-title mcp-generation-controls__header",children:[o.jsxs("span",{children:[Gx(n)," · MCP"]}),o.jsx("button",{type:"button",className:"mcp-generation-controls__exit",onClick:()=>rs(null,f.setState,f.getState),children:t("mcp.exitLane")})]}),I?null:o.jsx("p",{className:"option-help",children:t("mcp.disconnectedSelection")}),b?o.jsx("p",{className:"option-help",children:t("mcp.higgsfieldLocked")}):null]}),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"option-group",children:o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:`option-btn${s==="image"?" active":""}`,"aria-pressed":s==="image",onClick:()=>g("image"),children:t("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${s==="video"?" active":""}`,"aria-pressed":s==="video",onClick:()=>g("video"),children:t("grokMode.video")})]})}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:t("mcp.modelSectionTitle")}),u==="loading"?o.jsx("p",{className:"option-help",role:"status",children:t("mcp.loadingModels")}):u==="error"?o.jsxs("div",{className:"mcp-catalog-state",role:"alert",children:[o.jsx("span",{children:t("mcp.modelsLoadFailed")}),o.jsx("button",{type:"button",className:"settings-action-btn",onClick:()=>h(_=>_+1),children:t("mcp.retryModels")})]}):u==="ready"&&x.length===0?o.jsx("p",{className:"option-help",children:t("mcp.noModels")}):y?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"mcp-selected-model",children:[o.jsx("strong",{children:y.label}),y.description?o.jsx("span",{children:y.description}):null]}),o.jsx(Ox,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>Jh(_,f.setState),onParameter:(_,S)=>Yh(_,S,f.setState,f.getState)})]}):o.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function qx(e,t,n,r){const s=e.catalog?.comfy,a=e.phase==="ready"&&s?.status==="ready",i=[];for(const l of["image","video"])i.push({label:r(l==="image"?"comfy.kindImage":"comfy.kindVideo"),items:(s?.models[l]??[]).map(c=>({value:l==="video"?`${zt}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!Ot(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 $x(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(zt),s=r?e.slice(zt.length):e;Et(Zo(),r?{comfyVideoWorkflow:s}:{comfyWorkflow:s}).selectedAvailable&&(r?n.setComfyVideoWorkflow(s):n.setComfyWorkflow(s))}function Ux(){const{t:e}=H(),t=v.useId(),n=`${t}-status`,r=`${t}-workflow`,s=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=qn(),u=Et(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${zt}${l}`:i??"",m=qx(d,u,p,e);return s!=="comfy"||a?null:o.jsxs("div",{className:"option-group comfy-generation-controls","data-testid":"comfy-generation-controls","aria-busy":d.phase==="loading",children:[o.jsx("label",{className:"section-title",htmlFor:r,children:e("comfy.workflowsTitle")}),o.jsxs("p",{id:n,className:"option-help",children:[e($t(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),o.jsx(Fe,{id:r,groups:m,value:p,onChange:h=>$x(h,{provider:s,mcpProvider:a}),ariaLabel:e("comfy.display.chooseWorkflow"),ariaDescribedBy:n,placeholder:e("comfy.display.chooseWorkflow"),portal:!0}),u.selected?o.jsxs("p",{className:"option-help",children:[e(u.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage"),": ",u.selected.label,o.jsx("br",{}),o.jsx("code",{children:u.selected.id})]}):null,o.jsx("p",{className:"option-help",children:e("comfy.display.controlsHelp")}),o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:"option-btn",onClick:()=>{d.refresh()},children:e("comfy.display.refresh")}),o.jsx("button",{type:"button",className:"option-btn",onClick:()=>c("providers"),children:e("comfy.display.manage")})]})]})}const Hx=[{value:"png",label:"PNG"},{value:"jpeg",label:"JPEG"},{value:"webp",label:"WebP"}],lr=[{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"}],Kx=[{value:"512",label:"512px"},{value:"1K",label:"1K"},{value:"2K",label:"2K"},{value:"4K",label:"4K"}],Lr={"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 Vx(e){for(const[t,n]of Object.entries(Lr))for(const[r,s]of Object.entries(n))if(s===e)return{ratio:t,res:r};return null}function Bx(e,t){const n=e/t;let r="1:1",s=1/0;const a=[...Object.keys(Lr),"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<s&&(s=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 cd(){const{t:e}=H(),t=f(D=>D.provider),n=f(D=>D.quality),r=f(D=>D.setQuality),s=f(D=>D.format),a=f(D=>D.setFormat),i=f(D=>D.moderation),l=f(D=>D.setModeration),c=f(D=>D.multimode),d=f(D=>D.setMultimode),u=f(D=>D.imageModel),p=f(D=>D.setImageModel),m=f(D=>D.selectVideoModel),h=f(D=>D.sizePreset),b=f(D=>D.customW),I=f(D=>D.customH),x=f(D=>D.setSizePreset),y=f(D=>D.setCustomSize),g=f(D=>D.uiMode),_=f(D=>D.videoModelSelected),S=f(D=>D.mcpProvider??null),{providers:w}=Lc(),j=g==="classic",P=t==="grok"||t==="grok-api",M=t==="agy",q=t==="gemini-api",N=M||q,R=t==="nai",$=t==="comfy",k=P||N||R,J=h==="custom"?`${b}x${I}`:"1024x1024",T=q&&h==="auto",Z=q&&!T?Vx(J):null,te=Z??{ratio:"",res:""},de=q&&!T&&h==="custom"&&!Z,ye=u==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[ve,F]=v.useState(!1),[O,Q]=v.useState(String(b)),[V,ae]=v.useState(String(I)),fe=(D,le)=>{const se=Lr[D||"1:1"]?.[le||"1K"]||"1024x1024",[G,C]=se.split("x").map(Number);F(!1),x("custom"),y(G,C)},ie=()=>{const D=Number(O),le=Number(V);!Number.isFinite(D)||!Number.isFinite(le)||D<=0||le<=0||(x("custom"),y(D,le),F(!1))},Ee=[{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")}],he=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],Se=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],Ne=P?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:M?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:q?{title:e("provider.geminiApiCompatTitle"),body:e("provider.geminiApiCompatBody")}:R?{title:e("nai.compatTitle"),body:e("nai.compatBody")}:{title:e("provider.gptCompatTitle"),body:e("provider.gptCompatBody")},ke=D=>{D==="video"?m("grok-imagine-video"):p(u)};return S?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(zx,{record:w.find(D=>D.id===S)??null})]}):$?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(Ux,{})]}):o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsxs("details",{className:"provider-compat-details",children:[o.jsx("summary",{children:Ne.title}),o.jsx("p",{children:Ne.body})]}),P&&o.jsx("div",{className:"option-group grok-mode-toggle",children:o.jsxs("div",{className:"option-row",children:[o.jsx("button",{type:"button",className:`option-btn${_?"":" active"}`,onClick:()=>ke("image"),children:e("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>ke("video"),children:e("grokMode.video")})]})}),_?o.jsx(bx,{}):o.jsxs(o.Fragment,{children:[M?null:P?o.jsxs(o.Fragment,{children:[o.jsx(hx,{}),o.jsx(px,{})]}):R?o.jsx(_x,{}):q?o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("quality.grokModelTitle"),items:Se,value:ye,onChange:p}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("size.grokAspectTitle")||"Aspect Ratio"}),[lr.slice(0,3),lr.slice(3,6),lr.slice(6,8),lr.slice(8)].map((D,le)=>o.jsx("div",{className:"option-row",children:D.map(se=>o.jsx("button",{type:"button",className:`option-btn${te.ratio===se.value?" active":""}`,onClick:()=>fe(se.value,te.res),children:se.label},se.value))},le))]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("size.grokResolutionTitle")||"Resolution"}),o.jsx("div",{className:"gemini-resolution-grid",children:Kx.map(D=>o.jsxs("button",{type:"button",className:`option-btn${te.res===D.value?" active":""}`,onClick:()=>fe(te.ratio,D.value),children:[o.jsx("span",{children:D.label}),o.jsx("br",{}),o.jsx("small",{children:Lr[te.ratio]?.[D.value]?.replace("x","×")||""})]},D.value))})]}),o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"option-row",children:[o.jsxs("button",{type:"button",className:`option-btn${T?" active":""}`,onClick:()=>{F(!1),x("auto")},children:[e("size.autoLabel"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.autoSub")})]}),o.jsxs("button",{type:"button",className:`option-btn${de||ve?" active":""}`,onClick:()=>F(D=>!D),children:[e("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),ve?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"option-row size-picker__custom-row",children:[o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:O,onChange:D=>Q(D.target.value.replace(/\D/g,"")),placeholder:e("size.width")}),o.jsx("span",{className:"size-picker__dimension-separator","aria-hidden":"true",children:"×"}),o.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"custom-size-input",value:V,onChange:D=>ae(D.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(O)>0&&Number(V)>0?o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:e("size.normalizedPreview")}),o.jsx("strong",{children:(()=>{const D=Bx(Number(O),Number(V));return`${D.ratio} · ${D.res}`})()})]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:ie,children:e("settings.apiKeys.save")})]}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("quality.title"),items:Ee,value:n,onChange:r}),o.jsx(Qb,{})]}),k?null:o.jsxs(o.Fragment,{children:[o.jsx(Oe,{title:e("format.title"),items:Hx,value:s,onChange:a}),o.jsx(Oe,{title:e("moderation.title"),items:he,value:i,onChange:l}),o.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),j&&!N&&!R&&o.jsx("div",{className:"option-group multimode-toggle",children:o.jsxs("button",{type:"button",className:`multimode-toggle__button${c?" active":""}`,"aria-pressed":c,title:e("multimode.tooltip"),onClick:()=>d(!c),children:[o.jsx("span",{children:e("multimode.label")}),o.jsx("span",{children:e("multimode.shortHint")})]})}),N||R?null:o.jsx(ex,{}),R?null:o.jsx(ix,{})]})]})}const Wx=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-DwFK4ALC.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Jx=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-CJ56MEk2.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),Yx=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-VFu4cAdd.js"),__vite__mapDeps([6,1,2])).then(e=>({default:e.GenerationRequestLogPanel})));function Xx(){const e=f(y=>y.rightPanelOpen),t=f(y=>y.toggleRightPanel),n=f(y=>y.promptLibraryOpen),r=f(y=>y.setPromptLibraryOpen),s=f(y=>y.promptBuilderOpen),a=f(y=>y.togglePromptBuilder),i=f(y=>y.workspaceProfile),{t:l}=H(),[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=Bf(i)&&!c,h=c?e:!0,b=Ue(c&&e,t),I=u?"log":s&&m?"builder":n?"library":"settings",x=y=>{p(y==="log"),y==="builder"?(s||a(),n&&r(!1)):y==="library"?(s&&a(),n||r(!0)):(s&&a(),n&&r(!1))};return o.jsxs(o.Fragment,{children:[c&&e?o.jsx("div",{className:"right-panel-backdrop",role:"button","aria-label":l("panel.closeSettings"),onClick:t}):null,o.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&&o.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?">":"<"}),o.jsxs("div",{id:"right-panel-body",className:"right-panel-body",hidden:!e,children:[o.jsxs("div",{className:"right-panel-tabs",role:"tablist","aria-label":l("panel.detailSettings"),children:[m?o.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,o.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")}),o.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")}),o.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?o.jsx("div",{id:"right-panel-tab-builder",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Jx,{variant:"sidebar"})})}):I==="library"?o.jsx("div",{id:"right-panel-tab-library",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Wx,{variant:"embedded"})})}):I==="log"?o.jsx("div",{id:"right-panel-tab-log",role:"tabpanel",children:o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:l("common.loading")}),children:o.jsx(Yx,{})})}):o.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:o.jsx(cd,{})})]})]})]})}function Zx(e){const t=e.currentTarget;if(t.scrollWidth<=t.clientWidth||!(Math.abs(e.deltaY)>Math.abs(e.deltaX)))return;const r=t.scrollLeft<=0,s=t.scrollLeft+t.clientWidth>=t.scrollWidth-1,a=e.deltaY<0,i=e.deltaY>0;a&&r||i&&s||(e.preventDefault(),t.scrollLeft+=e.deltaY)}function Qx({id:e}){const{t}=H();return o.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function eI({id:e,count:t}){const{t:n}=H(),r=Math.min(t,4);return o.jsx("div",{className:"history-thumb history-thumb--collection-skeleton","aria-label":n("history.generatingCollection",{count:t}),children:Array.from({length:r},(s,a)=>o.jsx("div",{className:"collection-mini collection-mini--skeleton"},a))},`coll-${e}`)}function tI({sequenceId:e,images:t}){const n=f(l=>l.showHistorySequence),s=f(l=>l.multimodePreviewFlightId)===`history:${e}`,a=t.slice(0,4),{t:i}=H();return o.jsx("button",{type:"button",className:`history-thumb history-thumb--collection${s?" active":""}`,onClick:()=>n(e),"aria-label":i("common.imageCollection",{n:t.length}),children:a.map((l,c)=>!l.thumb&&(Ye(l.url)||Ye(l.image))?o.jsx(Ut,{className:"collection-mini"},c):o.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,s]=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&&s(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 rI(){const e=f(g=>g.history),t=f(g=>g.currentImage),n=f(g=>g.historyStripLayout),r=f(g=>g.selectHistory),s=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}=H(),m=t?Ae(t):null,h=v.useMemo(()=>xr(e.filter(mn)),[e]),b=v.useMemo(()=>{const g=[];for(const _ of a){const S=i[_.id];if(_.kind==="multimode"&&S){g.push({type:"collection-skeleton",id:_.id,count:S.requested});for(let w=0;w<S.requested;w++)S.images[w]||g.push({type:"skeleton",id:`${_.id}_${w}`,count:1})}else g.push({type:"skeleton",id:_.id,count:1})}return g},[a,i]),{completedSequences:I,sequenceFirstKeys:x}=v.useMemo(()=>{const g=new Map,_=new Set;for(const S of h)if(S.sequenceId&&(S.sequenceTotalRequested??0)>1){g.has(S.sequenceId)||_.add(Ae(S));const w=g.get(S.sequenceId)||[];w.push(S),g.set(S.sequenceId,w)}return{completedSequences:g,sequenceFirstKeys:_}},[h]);v.useEffect(()=>{m&&l.current[m]?.scrollIntoView({block:"nearest",inline:"nearest"})},[m,h]);const y=(g,_)=>{const S=u.supported?u.visibleKeys.has(g):!0;return o.jsx("div",{ref:w=>{l.current[g]=w,u.register(g,w)},className:"history-thumb","data-history-lazy-key":g,"aria-hidden":S?void 0:!0,style:{padding:0,overflow:"hidden"},children:S?_:null},g)};return o.jsxs("div",{ref:d,className:`history-strip${n==="horizontal"?" history-strip--horizontal":""}${n==="sidebar"?" history-strip--sidebar":""}`,onWheel:Zx,"data-layout":n,children:[o.jsx("button",{type:"button",className:"history-thumb history-thumb--add",onClick:s,"aria-label":p("history.openGalleryAria"),title:p("history.openGalleryTitle"),children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),o.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}),b.map(g=>g.type==="collection-skeleton"?o.jsx(eI,{id:g.id,count:g.count},`coll-${g.id}`):o.jsx(Qx,{id:g.id},g.id)),h.map(g=>{const _=Ae(g),S=m===_;if(g.sequenceId&&I.has(g.sequenceId)&&x.has(_)){const w=I.get(g.sequenceId);return[y(`coll-${g.sequenceId}`,o.jsx(tI,{sequenceId:g.sequenceId,images:w})),...w.map(j=>{const P=Ae(j),M=m===P;return xe(j)?y(P,o.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${M?" active":""}`,onClick:()=>r(j),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(j))),q.dataTransfer.effectAllowed="copy"},children:[j.thumb?o.jsx("img",{src:j.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Ut,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(P,o.jsx("img",{src:j.thumb||j.url||j.image,alt:"",className:`history-thumb history-thumb--fade-in${M?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(j),draggable:!0,onDragStart:q=>{q.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:j.url||j.image,filename:j.filename})),q.dataTransfer.effectAllowed="copy"}}))})]}return g.sequenceId&&I.has(g.sequenceId)&&!x.has(_)?null:xe(g)?y(_,o.jsxs("div",{className:`history-thumb history-thumb--video${S?" active":""}`,onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify(vn(g))),w.dataTransfer.effectAllowed="copy"},children:[g.thumb?o.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Ut,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(_,o.jsx("img",{src:g.thumb||g.url||g.image,alt:"",className:`history-thumb${S?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(g),draggable:!0,onDragStart:w=>{w.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:g.url||g.image,filename:g.filename})),w.dataTransfer.effectAllowed="copy"}}))})]})}const fi=3e3;function sI(){const{t:e}=H(),t=f(d=>d.toastLog),n=f(d=>d.errorCardLog),r=f(d=>d.dismissToast),s=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)},fi);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),s(p.id)},fi);d.set(m,h)}}},[s,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=Ve[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:o.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 o.jsxs("div",{className:u,role:d.error?"alert":"status",children:[o.jsx("span",{className:"toast__message",children:d.message}),d.kind==="error-card"&&(d.cta==="reauth"||d.cta==="reload")?o.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,o.jsx("button",{type:"button",className:"toast__dismiss","aria-label":e("common.dismiss"),onClick:()=>d.kind==="error-card"?s(d.id):r(d.id),children:o.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",focusable:"false",width:"14",height:"14",children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18",stroke:"currentColor",strokeWidth:"2",fill:"none",strokeLinecap:"round"})})})]},d.key)})})}function oI(){return null}function aI(e,t="en"){if(!e)return"earlier";const n=new Date(e);if(Number.isNaN(n.getTime()))return"earlier";const s=Math.floor((new Date().getTime()-n.getTime())/864e5);return s===0?"today":s===1?"yesterday":s<7?"thisWeek":new Intl.DateTimeFormat(t,{year:"numeric",month:"short",day:"numeric"}).format(n)}function iI(e,t,n){async function r(i){if(i.setId)try{await Ie.getState().loadSet(i.setId),f.getState().setUIMode("card-news"),e()}catch{t(n("gallery.openCardNewsSetFailed"),!0)}}async function s(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($v(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:a}}const lI=["ArrowLeft","ArrowRight","Home","End"];function cI(){return v.useCallback(e=>{if(!lI.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,s=r?n.indexOf(r):-1,a=e.key==="Home"?0:e.key==="End"?n.length-1:s<0?0:(s+(e.key==="ArrowRight"?1:-1)+n.length)%n.length,i=n[a];i?.focus(),i?.click()},[])}function As({className:e,ariaLabel:t,tabs:n,value:r,onChange:s}){const a=cI(),i=n.find(c=>c.value===r),l=i&&!i.disabled?i.value:n.find(c=>!c.disabled)?.value;return o.jsx("div",{className:e,role:"tablist","aria-label":t,onKeyDown:a,children:n.map(c=>o.jsx("button",{type:"button",role:"tab","aria-selected":c.value===r,tabIndex:c.value===l?0:-1,className:c.value===r?"active":"",onClick:()=>s(c.value),disabled:c.disabled,children:c.label},c.value))})}function dI({item:e,onOpen:t,onCopyPath:n,onDownloadManifest:r}){const{t:s}=H(),i=e.cards?.find(l=>l.headline)?.headline||e.headline||s("gallery.cardNewsSet");return o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",className:"gallery__tile",onClick:()=>t(e),title:i,children:[e.image?o.jsx("img",{src:e.image,alt:i,loading:"lazy"}):null,o.jsxs("div",{className:"gallery__caption",children:[o.jsx("small",{children:s("gallery.cardNewsSet")}),o.jsx("span",{className:"gallery__caption-text",children:i})]}),o.jsx("div",{className:"gallery-card-news-strip",children:(e.cards||[]).slice(0,5).map((l,c)=>o.jsxs("span",{children:[l.url?o.jsx("img",{src:l.url,alt:l.headline??"",loading:"lazy"}):null,o.jsx("em",{children:l.cardOrder??c+1})]},`${l.url}-${c}`))})]}),o.jsxs("div",{className:"gallery-card-news-actions",children:[o.jsx("span",{children:s("gallery.cardNewsCount",{n:e.cards?.length??0})}),o.jsx("button",{type:"button",onClick:()=>t(e),children:s("gallery.openCardNewsSet")}),o.jsx("button",{type:"button",onClick:l=>n(e,l),children:s("gallery.copyCardNewsSetPath")}),o.jsx("button",{type:"button",onClick:l=>r(e,l),children:s("gallery.downloadCardNewsManifest")})]})]})}const uI=[{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 mI(e,t,n,r){const s=n();switch(e){case"animate":{if(!t.filename)return;try{await s.animateImage(t.filename,t.prompt??void 0)&&s.showToast(r("toast.animateDone"))}catch(a){s.showToast(a instanceof Error?a.message:r("toast.animateFailed"),!0)}break}case"edit":{s.selectHistory(t),s.openCanvas();break}case"useAsRef":{const a=t.url||t.image;if(!a)return;try{const l=await(await we(a)).blob(),c=new File([l],t.filename||"reference.png",{type:l.type});await s.addReferences([c]),s.showToast(r("chain.refAdded"))}catch(i){if(i?.code==="LAN_TOKEN_REQUIRED")return;s.showToast(r("chain.refFailed"),!0)}break}case"rebake":{try{const{continueFromItem:i}=await Me(async()=>{const{continueFromItem:c}=await Promise.resolve().then(()=>rv);return{continueFromItem:c}},void 0),l=await i(t);s.showToast(r(l.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))}catch{s.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 s.saveToAssets(t);s.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{s.showToast(r("chain.saveToAssetsFailed"),!0)}break}case"saveAsElement":{try{const a=await s.saveAsElement?.(t);s.showToast(r(a?"chain.savedToAssets":"chain.saveToAssetsFailed"),!a)}catch{s.showToast(r("chain.saveToAssetsFailed"),!0)}break}}}function pI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function fI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function hI(e){return{modelLabel:zi(e.model,e.provider),derivation:pI(e),sourceLabel:fI(e)}}function gI(e){return!e.modelLabel&&!e.derivation}function yI({view:e,size:t="sm"}){const{t:n}=H();return gI(e)?null:o.jsxs("span",{className:`provenance-chip provenance-chip--${t}`,children:[e.modelLabel?o.jsx("span",{className:"provenance-chip__model",children:e.modelLabel}):null,e.derivation?o.jsx("span",{className:"provenance-chip__derivation",children:n(`provenance.${e.derivation}`)}):null]})}function vI({id:e}){switch(e){case"animate":return o.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:o.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})});case"edit":return o.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:[o.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),o.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 o.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:[o.jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),o.jsx("polyline",{points:"17 8 12 3 7 8"}),o.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]});case"rebake":return o.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:[o.jsx("polyline",{points:"23 4 23 10 17 10"}),o.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]});case"saveToAssets":return o.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:[o.jsx("rect",{x:"2",y:"3",width:"20",height:"5",rx:"1"}),o.jsx("path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"}),o.jsx("path",{d:"M10 12h4"})]})}}function bI({item:e,active:t,itemRef:n,onSelect:r,onDelete:s,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>uI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await mI(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)?vn(e):{image:e.url||e.image,filename:e.filename})),p.dataTransfer.effectAllowed="copy"};return o.jsxs("div",{ref:n,className:`gallery__tile-wrap${t?" gallery__tile-wrap--active":""}${e.isFavorite?" gallery__tile-wrap--favorite":""}`,children:[o.jsxs("button",{type:"button",className:`gallery__tile${t?" gallery__tile--active":""}`,onClick:()=>r(e),title:e.prompt??"",draggable:!0,onDragStart:u,children:[xe(e)?o.jsxs("div",{className:"gallery__tile-video-wrap",children:[e.thumb?o.jsx("img",{src:e.thumb,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async",className:"gallery__tile-video"}):o.jsx(Ut,{className:"gallery__tile-video"}),o.jsx("span",{className:"gallery__play-badge","aria-hidden":"true",children:"▶"})]}):o.jsx("img",{src:e.thumb||e.image,alt:e.prompt??l("gallery.imageAltFallback"),loading:"lazy",decoding:"async"}),e.prompt&&o.jsx("div",{className:"gallery__caption",children:o.jsx("span",{className:"gallery__caption-text",children:e.prompt})})]}),c.length>0?o.jsx("div",{className:"gallery__chain-overlay",role:"group","aria-label":l("chain.ariaLabel"),children:c.map(p=>o.jsx("button",{type:"button",className:"gallery__chain-btn",onClick:m=>{d(p.id,m)},title:l(p.labelKey),"aria-label":l(p.labelKey),children:o.jsx(vI,{id:p.id})},p.id))}):null,e.filename&&a&&o.jsx(Hc,{variant:"gallery",active:!!e.isFavorite,busy:i,label:e.isFavorite?l("gallery.unfavoriteAria"):l("gallery.favoriteAria"),onToggle:()=>a(e)}),e.filename&&o.jsx("button",{type:"button",className:"gallery__delete",onClick:p=>s(e,p),title:l("gallery.deleteTitle"),"aria-label":l("gallery.deleteAria"),children:"×"}),o.jsx(yI,{view:hI(e)})]})}function xI(e,t,n){const r=new Array(e);return new Proxy(r,{get(s,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=s[c];if(!d){const u=t[c*2];d=s[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(s,a,i)}})}function Mt(e,t,n){let r=n.initialDeps??[],s,a=!0;function i(){const l=e();return(l.length!==r.length||l.some((d,u)=>r[u]!==d))&&(r=l,s=t(...l),n?.onChange&&!(a&&n.skipInitialOnChange)&&n.onChange(s),a=!1),s}return i.updateDeps=l=>{r=l},i}function hi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const II=(e,t)=>Math.abs(e-t)<1.01,SI=(e,t,n)=>{let r;return Object.assign(function(...s){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,s),n)},{cancel:()=>{e.clearTimeout(r)}})};let on;const Rs=()=>{if(on!==void 0)return on;if(typeof navigator>"u")return on=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return on=!0;const e=navigator.maxTouchPoints;return on=navigator.platform==="MacIntel"&&e!==void 0&&e>0},gi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},wI=e=>e,_I=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},EI=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const s=i=>{const{width:l,height:c}=i;t({width:Math.round(l),height:Math.round(c)})};if(s(gi(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){s({width:d.inlineSize,height:d.blockSize});return}}s(gi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Fr={passive:!0},NI=typeof window>"u"?!0:"onscrollend"in window,kI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&NI;let i=0;const l=a?null:SI(s,()=>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()}},CI=(e,t)=>kI(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),jI=(e,t,n)=>{if(n.options.useCachedMeasurements){const r=n.indexFromElement(e),s=n.options.getItemKey(r);return n.itemSizeCache.get(s)??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),s=n.options.getItemKey(r),a=n.itemSizeCache.get(s);if(a!==void 0)return a}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},PI=(e,{adjustments:t=0,behavior:n},r)=>{var s,a;(a=(s=r.scrollElement)==null?void 0:s.scrollTo)==null||a.call(s,{[r.options.horizontal?"left":"top"]:e+t,behavior:n})},AI=PI;class RI{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,s;return((s=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:s.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(s=>{s.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 s;(s=r())==null||s.disconnect(),n=null},observe:s=>{var a;return(a=r())==null?void 0:a.observe(s,{box:"border-box"})},unobserve:s=>{var a;return(a=r())==null?void 0:a.unobserve(s)}}})(),this.range=null,this.setOptions=n=>{var r,s;const a={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:wI,rangeExtractor:_I,onChange:()=>{},measureElement:jI,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?((s=b[m-1])==null?void 0:s.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 S=a.followOnAppend===!0?"auto":a.followOnAppend||null;S&&h>m&&this.isAtEnd(i.scrollEndThreshold)&&(m===0||a.getItemKey(h-1)!==x)&&(c=S)}}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,s;(s=(r=this.options).onChange)==null||s.call(r,this,n)},this.maybeNotify=Mt(()=>(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,!(!Rs()||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 s=this.pendingScrollAnchor;if(this.pendingScrollAnchor=null,s&&this.scrollElement&&this.options.enabled){const[a,i,l,c]=s;a!==null&&!l&&(Rs()&&(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 s=this._iosDeferredAdjustment;this._iosDeferredAdjustment=0,this._scrollToOffset(n,{adjustments:this.scrollAdjustments+=s,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=Mt(()=>[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,s,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:s,getItemKey:a,enabled:i,lanes:l,laneAssignmentMode:c,gap:d}),{key:!1}),this.isIndexInRange=n=>n>=0&&n<this.options.count,this.getMeasurements=Mt(()=>[this.getMeasurementOptions(),this.itemSizeCacheVersion],({count:n,paddingStart:r,scrollMargin:s,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 w=new Float64Array(y);g&&m>0&&w.set(g.subarray(0,m*2)),g=w,this._flatMeasurements=g}let _;if(m===0)_=r+s;else{const w=m-1;_=g[w*2]+g[w*2+1]+d}for(let w=m;w<n;w++){const j=a(w),P=p.get(j),M=typeof P=="number"?P:this.options.estimateSize(w);g[w*2]=_,g[w*2+1]=M,_+=M+d}const S=xI(n,g,a);return this.measurementsCache=S,S}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 S,w;const j=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){S=_;const N=b[S],R=N!==void 0?h[N]:void 0;w=R?R.end+d:r+s}else if(x===l){let N=0,R=I[0],$=b[0];for(let k=1;k<l;k++){const J=I[k];(J<R||J===R&&b[k]<$)&&(N=k,R=J,$=b[k])}S=N,w=R+d,j&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,w=r+s,j&&this.laneAssignments.set(y,S);const P=p.get(g),M=typeof P=="number"?P:this.options.estimateSize(y),q=w+M;h[y]={index:y,start:w,size:M,end:q,key:g,lane:S},b[S]===void 0&&x++,b[S]=y,I[S]=q}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Mt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=MI(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Mt(()=>{let n=null,r=null;const s=this.calculateRange();return s&&(n=s.startIndex,r=s.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,s,a,i)=>a===null||i===null?[]:n({startIndex:a,endIndex:i,overscan:r,count:s}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,s=n.getAttribute(r);return s?parseInt(s,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 s=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(s!==void 0&&this.range){const a=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),i=Math.max(0,s-a),l=Math.min(this.options.count-1,s+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 s=this.options.getItemKey(r),a=this.elementsCache.get(s);a!==n&&(a&&this.observer.unobserve(a),this.observer.observe(n),this.elementsCache.set(s,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var s,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"&&((s=this.scrollState)==null?void 0:s.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=Mt(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const s=[];for(let a=0,i=n.length;a<i;a++){const l=n[a],c=r[l];s.push(c)}return s},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length===0)return;const s=this._flatMeasurements,a=this.options.lanes===1&&s!=null,i=dd(0,r.length-1,a?l=>s[l*2]:l=>hi(r[l]).start,n);return hi(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,s=0)=>{if(!this.scrollElement)return 0;const a=this.getSize(),i=this.getScrollOffset();r==="auto"&&(r=n>=i+a?"end":"start"),r==="center"?n+=(s-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 s=this.getSize(),a=this.getScrollOffset(),i=this.measurementsCache[n];if(!i)return;if(r==="auto")if(i.end>=a+s-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:s="auto"}={})=>{this._iosDeferredAdjustment=0;const a=this.getOffsetForAlignment(n,r),i=this.now();this.scrollState={index:null,align:r,behavior:s,startedAt:i,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:s="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:s,startedAt:c,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:s}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const s=this.getScrollOffset()+n,a=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:a,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{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 s;if(r.length===0)s=this.options.paddingStart;else if(this.options.lanes===1){const a=r.length-1,i=this._flatMeasurements;i!=null?s=i[a*2]+i[a*2+1]:s=((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--}s=Math.max(...a.filter(l=>l!==null))}return Math.max(s-this.options.scrollMargin+this.options.paddingEnd,0)},this.takeSnapshot=()=>{const n=[];if(this.itemSizeCache.size===0)return n;const r=this.getMeasurements();for(const s of r)s&&this.itemSizeCache.has(s.key)&&n.push({index:s.index,key:s.key,start:s.start,size:s.size,end:s.end,lane:s.lane});return n},this._scrollToOffset=(n,{adjustments:r,behavior:s})=>{this._intendedScrollOffset=n+(r??0),this.options.scrollToFn(n,{behavior:s,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:Rs()&&(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,s=r?r[0]:this.scrollState.lastTargetOffset,a=1,i=s!==this.scrollState.lastTargetOffset;if(!i&&II(s,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=a){this.getScrollOffset()!==s&&this._scrollToOffset(s,{adjustments:void 0,behavior:"auto"}),this.scrollState=null;return}}else if(this.scrollState.stableFrames=0,i){const l=this.getSize()||600,c=Math.abs(s-this.getScrollOffset()),d=this.scrollState.behavior==="smooth"&&c>l;this.scrollState.lastTargetOffset=s,d||(this.scrollState.behavior="auto"),this._scrollToOffset(s,{adjustments:void 0,behavior:d?"smooth":"auto"})}this.scheduleScrollReconcile()}}const dd=(e,t,n,r)=>{for(;e<=t;){const s=(e+t)/2|0,a=n(s);if(a<r)e=s+1;else if(a>r)t=s-1;else return s}return e>0?e-1:0};function TI(e,t,n){let r=0;for(;r<=t;){const s=(r+t)/2|0,a=e[s*2];if(a<n)r=s+1;else if(a>n)t=s-1;else return s}return r>0?r-1:0}function MI(e,t,n,r,s){const a=e.length-1;if(e.length<=r)return{startIndex:0,endIndex:a};if(r===1&&s!==null){const d=TI(s,a,n);let u=d;const p=n+t;for(;u<a&&s[u*2]+s[u*2+1]<p;)u++;return{startIndex:d,endIndex:u}}let l=dd(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 Ts=typeof document<"u"?v.useLayoutEffect:v.useEffect;function LI({useFlushSync:e=!0,directDomUpdates:t=!1,directDomUpdatesMode:n="transform",...r}){const s=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?ss.flushSync(s):s()),(m=r.onChange)==null||m.call(r,u,p)}},[d]=v.useState(()=>{const u=new RI(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),Ts(()=>d._didMount(),[]),Ts(()=>(i(d),d._willUpdate())),Ts(()=>{l(d)}),d}function FI(e){return LI({observeElementRect:EI,observeElementOffset:CI,scrollToFn:AI,...e})}const Or=170,Dr=10,ud=36,OI=44;function DI(e){const t=Math.max(Or,e-ud);return Math.max(1,Math.floor((t+Dr)/(Or+Dr)))}function GI(e,t){const n=Math.max(Or,e-ud);return Math.max(Or,Math.floor((n-Dr*Math.max(0,t-1))/t))+Dr}function zI(e,t){const n=[];for(const[r,s]of e){n.push({type:"header",id:`h-${r}`,label:r,count:s.length});for(let a=0;a<s.length;a+=t)n.push({type:"items",id:`r-${r}-${a}`,items:s.slice(a,a+t)})}return n}function qI({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:s}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>DI(i||960),[i]),d=v.useMemo(()=>GI(i||960,c),[i,c]),u=v.useMemo(()=>zI(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=FI({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?OI: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]),o.jsx("div",{ref:a,className:"gallery__virtual",style:{height:p.getTotalSize()},children:p.getVirtualItems().map(m=>{const h=u[m.index];return h?o.jsx("div",{className:"gallery__virtual-row",style:{transform:`translateY(${m.start}px)`},children:h.type==="header"?o.jsxs("header",{className:"gallery__group-header gallery__group-header--virtual",children:[o.jsx("span",{className:"gallery__group-label",children:r(h.label)}),o.jsx("span",{className:"gallery__group-count",children:h.count})]}):o.jsx("div",{className:"gallery__grid gallery__grid--virtual",children:h.items.map((b,I)=>s(b,h.id,I))})},h.id):null})})}function yi({showSessions:e,favoritesOnly:t,query:n,historyNextCursor:r,favoriteHistoryNextCursor:s,historyLoadingOlder:a,favoriteHistoryLoadingOlder:i,onLoadOlder:l,onLoadOlderFavorites:c,t:d}){return e?o.jsx("div",{className:"gallery__load-more gallery__load-more--hint",children:d("gallery.sessionPaginationHint")}):n.trim()?null:t?s?o.jsx("div",{className:"gallery__load-more",children:o.jsx("button",{type:"button",onClick:c,disabled:i,children:d(i?"gallery.loadingOlderFavorites":"gallery.loadOlderFavorites")})}):null:r?o.jsx("div",{className:"gallery__load-more",children:o.jsx("button",{type:"button",onClick:l,disabled:a,children:d(a?"gallery.loadingOlder":"gallery.loadOlder")})}):null}function $I({groups:e,loose:t,favoritesOnly:n,galleryScope:r,setGalleryScope:s,renderTile:a,t:i}){return e.length===0&&t.length===0?o.jsx("div",{className:"gallery__empty",children:n?i("gallery.emptyFavorites"):r==="current-session"?o.jsxs(o.Fragment,{children:[o.jsx("p",{children:i("gallery.empty.currentSession")}),o.jsx("button",{type:"button",onClick:()=>s("all"),children:i("gallery.scope.all")})]}):i("gallery.emptySessions")}):o.jsxs(o.Fragment,{children:[e.map(l=>o.jsxs("section",{className:"gallery__group",children:[o.jsxs("header",{className:"gallery__group-header",children:[o.jsx("span",{className:"gallery__group-label",title:l.sessionId,children:l.title?l.displayLabel:i("gallery.sessionLabel",{name:l.displayLabel})}),o.jsx("span",{className:"gallery__group-count",children:l.items.length})]}),o.jsx("div",{className:"gallery__grid",children:l.items.map((c,d)=>a(c,l.sessionId,d))})]},l.sessionId)),t.length>0&&o.jsxs("section",{className:"gallery__group",children:[o.jsxs("header",{className:"gallery__group-header",children:[o.jsx("span",{className:"gallery__group-label",children:i("gallery.standalone")}),o.jsx("span",{className:"gallery__group-count",children:t.length})]}),o.jsx("div",{className:"gallery__grid",children:t.map((l,c)=>a(l,"loose",c))})]})]})}function UI({status:e,dismissed:t,onOpenFolder:n,onDismiss:r,t:s}){const a=e!=null&&e.state!=="ok"&&!t,i=e?.state==="recoverable"?"gallery.storageNoticeRecoverable":e?.state==="not_found"?"gallery.storageNoticeNotFound":"gallery.storageNoticeUnknown";return o.jsxs("div",{className:`gallery__storage-bar${a?" gallery__storage-bar--notice":""}`,children:[a?o.jsxs("div",{className:"gallery__storage-copy",children:[o.jsx("div",{className:"gallery__storage-title",children:s("gallery.storageNoticeTitle")}),o.jsx("div",{className:"gallery__storage-text",children:s(i)})]}):o.jsx("div",{className:"gallery__storage-copy gallery__storage-copy--quiet",children:e?.generatedDirLabel??"~/.ima2/generated"}),o.jsxs("div",{className:"gallery__storage-actions",children:[o.jsx("button",{type:"button",className:"gallery__storage-button",onClick:n,title:s("gallery.openGeneratedDirTitle"),children:s("gallery.openGeneratedDir")}),a&&o.jsx("button",{type:"button",className:"gallery__storage-button gallery__storage-button--ghost",onClick:r,children:s("common.close")})]})]})}const vi="ima2.storageNoticeDismissed.0.09.23";function HI(e){const t=v.useRef(null),n=v.useRef(new Map),[r,s]=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&&s(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 KI(){const{t:e,locale:t}=H(),n=f(L=>L.galleryOpen),r=f(L=>L.closeGallery),s=f(L=>L.history),a=f(L=>L.selectHistory),i=f(L=>L.currentImage),l=f(L=>L.trashHistoryItem),c=f(L=>L.showToast),d=f(L=>L.toggleGalleryFavorite),u=f(L=>L.galleryScope),p=f(L=>L.setGalleryScope),m=f(L=>L.historyNextCursor),h=f(L=>L.historyLoadingOlder),b=f(L=>L.favoriteHistoryNextCursor),I=f(L=>L.favoriteHistoryLoadingOlder),x=f(L=>L.loadOlderHistory),y=f(L=>L.loadFavoriteHistory),g=f(L=>L.loadOlderFavoriteHistory),_=f(rp),[S,w]=v.useState(""),[j,P]=v.useState("date"),[M,q]=v.useState(!1),[N,R]=v.useState(()=>new Set),$=v.useRef(new Set),[k,J]=v.useState([]),[T,Z]=v.useState([]),[te,de]=v.useState(!1),[ye,ve]=v.useState(!1),[F,O]=v.useState(!1),[Q,V]=v.useState(0),[ae,fe]=v.useState(null),[ie,Ee]=v.useState(()=>{try{return localStorage.getItem(vi)==="1"}catch{return!1}}),he=v.useRef(null),Se=v.useRef({}),[Ne,ke]=v.useState(null),D=v.useRef(0),le=v.useRef({open:!1,selectedKey:null}),se=v.useMemo(()=>xr(s.filter(mn)),[s]),G=v.useCallback(L=>{he.current=L,ke(L)},[]),C=HI(Ne),X=Ue(n,r);v.useEffect(()=>{n||w("")},[n]),v.useEffect(()=>{if(!n)return;let L=!1;return(async()=>{try{const Y=await Xd();L||fe(Y)}catch{L||fe({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}})}})(),()=>{L=!0}},[n]),v.useEffect(()=>{if(!n||j!=="session")return;let L=!1;return J([]),Z([]),de(!0),ve(!1),O(!1),(async()=>{try{const Y=await Jd({limit:500,sessionId:u==="current-session"?_:void 0});if(L)return;O(Y.nextCursor!==null||Y.total>=500);const je=U=>{const me=U.kind,rt=me==="classic"||me==="edit"||me==="generate"||me==="card-news-card"||me==="card-news-set"?me:null,sa=U.mediaType==="video"||/\.(mp4|webm|mov)$/i.test(U.filename??"");return{image:U.url,url:U.url,filename:U.filename,thumb:U.thumb??(sa?void 0:U.url),mediaType:U.mediaType,video:U.video??null,videoSeries:U.videoSeries??null,videoContinuity:U.videoContinuity??null,prompt:U.prompt??void 0,userPrompt:U.userPrompt??null,revisedPrompt:U.revisedPrompt??null,promptMode:U.promptMode??null,composerPrompt:U.composerPrompt??null,composerInsertedPrompts:U.composerInsertedPrompts??null,size:U.size??void 0,quality:U.quality??void 0,format:U.format,moderation:U.moderation??void 0,model:U.model??void 0,reasoningEffort:U.reasoningEffort,provider:U.provider,providerUrl:U.providerUrl??null,usage:U.usage,elapsed:U.elapsed??void 0,createdAt:U.createdAt,sessionId:U.sessionId??null,nodeId:U.nodeId??null,parentNodeId:U.parentNodeId??null,clientNodeId:U.clientNodeId??null,requestId:U.requestId??null,kind:rt,setId:U.setId??null,cardId:U.cardId??null,cardOrder:U.cardOrder??null,headline:U.headline??null,body:U.body??null,cards:U.cards,refsCount:U.refsCount??0,webSearchCalls:U.webSearchCalls??0,sequenceId:U.sequenceId??null,sequenceIndex:U.sequenceIndex??null,sequenceTotalRequested:U.sequenceTotalRequested??null,sequenceTotalReturned:U.sequenceTotalReturned??null,sequenceStatus:U.sequenceStatus??null,isFavorite:U.isFavorite??!1}};J(Y.sessions.map(U=>({sessionId:U.sessionId,title:U.title??null,label:U.label??null,displayLabel:U.title||U.label||U.sessionId.slice(0,8),items:xr(U.items.filter(mn).map(je))})).filter(U=>U.items.length>0)),Z(xr(Y.loose.filter(mn).map(je)))}catch{L||ve(!0)}finally{L||de(!1)}})(),()=>{L=!0}},[n,j,u,_,Q]),v.useEffect(()=>{!n||j==="session"||!M||y()},[n,j,M,y]);const re=v.useMemo(()=>{const L=S.trim().toLowerCase().normalize("NFC");return se.filter(Y=>M&&!Y.isFavorite?!1:L?(Y.prompt??"").toLowerCase().normalize("NFC").includes(L)||(Y.filename??"").toLowerCase().normalize("NFC").includes(L):!0)},[se,S,M]),K=v.useMemo(()=>M?k.map(L=>({...L,items:L.items.filter(Y=>Y.isFavorite)})).filter(L=>L.items.length>0):k,[k,M]),be=v.useMemo(()=>M?T.filter(L=>L.isFavorite):T,[T,M]),Te=v.useMemo(()=>{const L=new Map;for(const Y of re){const je=aI(Y.createdAt,t);L.has(je)||L.set(je,[]),L.get(je).push(Y)}return Array.from(L.entries())},[re,t]),He=j==="session"?K.reduce((L,Y)=>L+Y.items.length,0)+be.length:re.length;v.useLayoutEffect(()=>{const L=i?Ae(i):null;if(!n){le.current={open:!1,selectedKey:L};return}const Y=le.current,je=!Y.open||Y.selectedKey!==L;le.current={open:!0,selectedKey:L};const U=L?Se.current[L]:null;if(je&&U){U.scrollIntoView({block:"center"});return}he.current&&(he.current.scrollTop=D.current)},[n,i?.filename,i?.image,j,He,Te.length,K.length,be.length]);async function gt(L,Y){Y.stopPropagation();const je=Ae(L);await l(L),delete Se.current[je],window.requestAnimationFrame(()=>he.current?.focus())}async function lt(L){const Y=L.filename;if(!(!Y||$.current.has(Y))){$.current.add(Y),R(new Set($.current));try{const je=await d(L);if(je===null)return;J(U=>U.map(me=>({...me,items:me.items.map(rt=>rt.filename===Y?{...rt,isFavorite:je}:rt)}))),Z(U=>U.map(me=>me.filename===Y?{...me,isFavorite:je}:me))}finally{$.current.delete(Y),R(new Set($.current))}}}async function $n(){try{await Zd(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Un,handleCopyCardNewsSetPath:Hn,handleDownloadCardNewsManifest:E}=iI(r,c,e);function B(){Ee(!0);try{localStorage.setItem(vi,"1")}catch{}}if(!n)return null;const ee=L=>L==="earlier"||L==="today"||L==="yesterday"||L==="thisWeek"?e(`gallery.${L}`):L,oe=(L,Y,je)=>{const U=i?.image===L.image,me=Ae(L),rt=Rt=>{Se.current[me]=Rt,C.register(me,Rt)};return(C.supported?C.visibleKeys.has(me):!0)?L.kind==="card-news-set"?o.jsx("div",{ref:rt,className:"gallery__tile-wrap gallery-card-news-set",children:o.jsx(dI,{item:L,onOpen:Rt=>{Un(Rt)},onCopyPath:Hn,onDownloadManifest:E})},`${Y}-${me}`):o.jsx(bI,{item:L,active:U,itemRef:rt,onSelect:Rt=>{a(Rt),r()},onDelete:gt,onToggleFavorite:lt,favoriteBusy:!!(L.filename&&N.has(L.filename)),t:e},`${Y}-${me}`):o.jsx("div",{ref:rt,className:"gallery__tile-wrap","data-gallery-lazy-key":me,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Y}-${me}`)},ue=j==="session",Le=i?Ae(i):null;return o.jsx("div",{className:"gallery-backdrop",onClick:r,role:"presentation",children:o.jsxs("div",{ref:X,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:L=>L.stopPropagation(),children:[o.jsxs("div",{className:"gallery__header",children:[o.jsxs("div",{className:"gallery__title-row",children:[o.jsx("div",{className:"gallery__title",children:e("gallery.title")}),o.jsxs("div",{className:"gallery__meta",children:[e("gallery.total",{n:He}),S||M?e("gallery.totalFiltered",{n:se.length}):""]}),o.jsx(As,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:M?"favorites":"all",onChange:L=>q(L==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),o.jsx(As,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:j,onChange:P,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),o.jsx(As,{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")}]})]}),o.jsx("input",{type:"text",className:"gallery__search",...ue?{}:{"data-modal-initial-focus":!0},placeholder:e(ue?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:S,onChange:L=>w(L.target.value),disabled:ue}),o.jsx("button",{type:"button",className:"gallery__close",onClick:r,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),o.jsx(UI,{status:ae,dismissed:ie,onOpenFolder:$n,onDismiss:B,t:e}),o.jsx("div",{className:"gallery__scroll",ref:G,tabIndex:-1,onScroll:()=>{D.current=he.current?.scrollTop??0},children:ue?te?o.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):ye?o.jsxs("div",{className:"gallery__empty",role:"alert",children:[o.jsx("span",{children:e("gallery.sessionLoadFailed")}),o.jsx("button",{type:"button",onClick:()=>V(L=>L+1),children:e("gallery.retry")})]}):o.jsxs(o.Fragment,{children:[F?o.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,o.jsx($I,{groups:K,loose:be,favoritesOnly:M,galleryScope:u,setGalleryScope:p,renderTile:oe,t:e}),o.jsx(yi,{showSessions:ue,favoritesOnly:M,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):re.length===0?o.jsx("div",{className:"gallery__empty",children:se.length===0?e("gallery.emptyAll"):e(M?"gallery.emptyFavorites":"gallery.noResults")}):o.jsxs(o.Fragment,{children:[o.jsx(qI,{dateGroups:Te,selectedKey:Le,scrollElement:Ne,localizeBucket:ee,renderTile:oe}),o.jsx(yi,{showSessions:ue,favoritesOnly:M,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function VI(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 BI(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=H(),s=Ue(!!e,n);if(!e)return null;const a=`${e.requestedW}x${e.requestedH}`,i=`${e.adjustedW}x${e.adjustedH}`;return o.jsx("div",{className:"modal-backdrop custom-size-confirm-backdrop",role:"presentation",children:o.jsxs("div",{ref:s,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:[o.jsx("div",{id:"custom-size-confirm-title",className:"modal__title",children:r("sizeConfirm.title")}),o.jsxs("div",{id:"custom-size-confirm-body",className:"modal__body",children:[o.jsx("p",{children:r("sizeConfirm.body")}),o.jsxs("dl",{className:"size-confirm__pairs",children:[o.jsxs("div",{className:"size-confirm__pair",children:[o.jsx("dt",{children:r("sizeConfirm.requested")}),o.jsx("dd",{children:a})]}),o.jsxs("div",{className:"size-confirm__pair",children:[o.jsx("dt",{children:r("sizeConfirm.adjusted")}),o.jsx("dd",{children:i})]})]}),o.jsx("p",{className:"size-confirm__reason",children:r(VI(e.reasons))})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button","data-modal-initial-focus":!0,className:"modal__btn modal__btn--secondary",onClick:n,children:r("sizeConfirm.cancel")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:()=>{t()},children:r("sizeConfirm.approve")})]})]})})}function cr(e){return e==null||e===""?"-":String(e)}function WI(){const{t:e}=H(),t=f(c=>c.metadataRestore),n=f(c=>c.applyMetadataRestore),r=f(c=>c.addMetadataRestoreAsReference),s=f(c=>c.cancelMetadataRestore),a=Ue(!!t,s);if(!t)return null;const i=t.metadata,l=i.userPrompt||i.prompt||i.revisedPrompt||"";return o.jsx("div",{className:"modal-backdrop metadata-restore-backdrop",role:"presentation",children:o.jsxs("div",{ref:a,className:"modal metadata-restore",role:"dialog","aria-modal":"true","aria-labelledby":"metadata-restore-title",tabIndex:-1,children:[o.jsx("div",{id:"metadata-restore-title",className:"modal__title",children:e("metadata.restoreTitle")}),o.jsxs("div",{className:"modal__body metadata-restore__body",children:[o.jsx("p",{children:e("metadata.restoreBody")}),o.jsxs("div",{className:"metadata-restore__preview",children:[o.jsx("img",{src:t.image,alt:e("metadata.imageAlt")}),o.jsxs("div",{className:"metadata-restore__details",children:[o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.prompt")}),o.jsx("strong",{title:l,children:cr(l)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.size")}),o.jsx("strong",{children:cr(i.size)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.quality")}),o.jsx("strong",{children:cr(i.quality)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.model")}),o.jsx("strong",{children:cr(i.model)})]}),o.jsxs("div",{children:[o.jsx("span",{children:e("metadata.source")}),o.jsx("strong",{children:t.source==="png-comment"?e("metadata.sourcePngComment"):e("metadata.sourceXmp")})]})]})]})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:s,"data-modal-initial-focus":!0,children:e("common.cancel")}),o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:r,children:e("metadata.useAsReferenceOnly")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:n,children:e("metadata.applySettings")})]})]})})}const JI=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Nt(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Gt(e){return!e||typeof e!="object"||Array.isArray(e)?Nt():e}function Xs(e){return typeof e!="string"||!e.trim()?Nt():e}function md(e){return e===void 0?{}:typeof e!="boolean"?Nt():{executable:e}}function YI(e){const t=Gt(e),n=Gt(t.status);return typeof t.enabled!="boolean"||!JI.has(n.state)?Nt():{id:Xs(t.id),enabled:t.enabled,...md(t.executable),status:{state:n.state}}}function bi(e){return Array.isArray(e)?e.map(t=>{const n=Gt(t);return{id:Xs(n.id),label:Xs(n.label),...md(n.executable)}}):Nt()}function xi(e,t){const n=Gt(e);if(n.ok!==!0||!Array.isArray(n.providers))return Nt();const r=n.providers.map(YI);if(t===null)return{providers:r,catalog:null};const s=Gt(t),a=Gt(s.models);return s.ok!==!0?Nt():{providers:r,catalog:{image:bi(a.image),video:bi(a.video)}}}function XI(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 s=e.providers.find(i=>i.id===t.provider);if(!s)return r("missing");if(!s.enabled)return r("disabled");if(s.status.state!=="connected")return r("disconnected");if(s.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 ZI(){const{t:e}=H(),t=f(u=>u.mcpProvider??""),n=f(u=>u.mcpModel??null),r=f(u=>u.mcpMediaKind??"image"),[s,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 Fh(u.signal),I=xi(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Oh(t,u.signal):null,y=xi(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,s]),!t)return null;const c=XI(i,{provider:t,model:n,kind:r}),d=`readiness.mcp.${c.code}`;return o.jsxs("div",{className:"provider-readiness__body","data-mcp-readiness":c.code,"aria-busy":c.code==="loading",children:[o.jsx("p",{role:"status","aria-live":"polite",children:o.jsx("strong",{children:e(d)})}),o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsxs("dd",{children:[t," · MCP"]})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.model")}),o.jsx("dd",{style:{minWidth:0,overflowWrap:"anywhere"},children:c.modelLabel??e("readiness.mcp.default")})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colKind")}),o.jsx("dd",{children:e(r==="video"?"grokMode.video":"grokMode.image")})]})]}),c.observedAt!==null?o.jsx("small",{children:e("readiness.mcp.observed",{time:new Date(c.observedAt).toLocaleTimeString()})}):null,o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:()=>a(u=>u+1),children:e("readiness.mcp.refresh")})]})}const Ii={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 QI(){const{t:e}=H(),t=f(w=>w.readinessPopupOpen),n=f(w=>w.closeReadinessPopup),r=f(w=>w.openSettings),s=f(w=>w.provider),a=f(w=>w.mcpProvider??null),i=f(w=>w.imageModel),l=f(w=>w.reasoningEffort),c=f(w=>w.webSearchEnabled),d=f(w=>w.comfyWorkflow),u=f(w=>w.comfyVideoWorkflow),p=od(),m=qn(),h=s==="grok",b=Xe.find(w=>w.value===i),I=Ue(t,n);if(!t)return null;const x=p[s],y=Et(m,{comfyWorkflow:d,comfyVideoWorkflow:u}),g=s==="comfy"&&!a,_=g?y.selectedAvailable:x.ok,S=()=>{n(),r("providers")};return o.jsx("div",{className:"modal-backdrop provider-readiness-backdrop",onClick:n,role:"presentation",children:o.jsxs("div",{ref:I,className:"modal provider-readiness",role:"dialog","aria-modal":"true","aria-labelledby":"provider-readiness-title",tabIndex:-1,onClick:w=>w.stopPropagation(),children:[o.jsx("div",{id:"provider-readiness-title",className:"modal__title",children:e("readiness.title")}),o.jsxs("div",{className:"modal__body provider-readiness__body",children:[a?o.jsx(ZI,{}):null,!a&&o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`provider-readiness__status${_?" is-ok":" is-blocked"}`,children:[o.jsx("span",{"aria-hidden":"true"}),o.jsx("strong",{children:e(g?$t(y,m):_?"readiness.ready":"readiness.blocked")}),o.jsx("small",{children:g?e("comfy.display.controlsHelp"):_?e("readiness.readyBody"):x.reason})]}),!g&&x.hint?o.jsx("p",{className:"modal__hint",children:x.hint}):null,g?o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsx("dd",{children:Ii.comfy})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.workflowsTitle")}),o.jsx("dd",{children:y.selected?.label??e("comfy.display.chooseWorkflow")})]}),y.selected?o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colId")}),o.jsx("dd",{children:y.selected.id})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colKind")}),o.jsx("dd",{children:e(y.selected.kind==="video"?"comfy.kindVideo":"comfy.kindImage")})]})]}):null,m.observedAt!==null?o.jsxs("div",{children:[o.jsx("dt",{children:e("comfy.colStatus")}),o.jsx("dd",{children:e("comfy.display.lastChecked",{time:new Date(m.observedAt).toLocaleTimeString()})})]}):null]}):o.jsxs("dl",{className:"provider-readiness__facts",children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.provider")}),o.jsx("dd",{children:Ii[s]??"GPT API"})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.model")}),o.jsx("dd",{children:b?e(b.fullLabelKey):i})]}),h?o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.grokApi")}),o.jsx("dd",{children:e("readiness.grokApiBody")})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.reasoning")}),o.jsx("dd",{children:l})]}),o.jsxs("div",{children:[o.jsx("dt",{children:e("readiness.webSearch")}),o.jsx("dd",{children:e(c?"settings.webSearch.on":"settings.webSearch.off")})]})]})]})]})]}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:n,"data-modal-initial-focus":!0,children:e("common.close")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:S,children:e(g?"comfy.display.manage":"readiness.openAccount")})]})]})})}const Si="ima2.onboardingDismissed";function eS(){const{t:e}=H(),t=f(x=>x.openSettings),n=nd(),r=rd(),{data:s}=sd(),[a,i]=v.useState(()=>{try{return localStorage.getItem(Si)==="1"}catch{return!1}}),l=n!==null&&r!==null&&s!=null,c=n?.status==="auth_required"||n?.status==="offline",d=r?.status==="offline"||r?.status==="error",u=s?!s.gemini?.configured&&!s.vertex?.configured:!1,m=!a&&(l&&c&&d&&u),h=()=>{try{localStorage.setItem(Si,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=Ue(m,h);return m?o.jsx("div",{className:"modal-backdrop",role:"presentation",children:o.jsxs("div",{ref:I,className:"modal",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",tabIndex:-1,children:[o.jsx("div",{id:"onboarding-title",className:"modal__title",children:e("onboarding.title")}),o.jsx("div",{className:"modal__body",children:o.jsx("p",{children:e("onboarding.body")})}),o.jsxs("div",{className:"modal__actions",children:[o.jsx("button",{type:"button",className:"modal__btn modal__btn--secondary",onClick:h,"data-modal-initial-focus":!0,children:e("onboarding.skip")}),o.jsx("button",{type:"button",className:"modal__btn",onClick:b,children:e("onboarding.login")})]})]})}):null}function tS(){const e=f(i=>i.trashPending),t=f(i=>i.restorePendingTrash),n=f(i=>i.clearPendingTrash),{t:r}=H(),[s,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?o.jsxs("div",{className:"trash-undo-toast",children:[o.jsx("span",{children:r("gallery.deleted",{filename:e.filename})}),o.jsx("button",{type:"button",onClick:()=>{t()},children:r("gallery.undo")}),o.jsx("span",{className:"trash-undo-toast__timer",children:r("gallery.secondsSuffix",{n:Math.max(0,Math.ceil((e.expiresAt-s)/1e3))})})]}):null}function nS(){return o.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:[o.jsx("line",{x1:"4",y1:"6",x2:"14",y2:"6"}),o.jsx("circle",{cx:"17",cy:"6",r:"2.2"}),o.jsx("line",{x1:"4",y1:"12",x2:"8",y2:"12"}),o.jsx("circle",{cx:"11",cy:"12",r:"2.2"}),o.jsx("line",{x1:"14",y1:"12",x2:"20",y2:"12"}),o.jsx("line",{x1:"4",y1:"18",x2:"14",y2:"18"}),o.jsx("circle",{cx:"17",cy:"18",r:"2.2"})]})}function rS(){const e=f(d=>d.composeSheetOpen),t=f(d=>d.composeSheetTab),n=f(d=>d.openComposeSheet),r=f(d=>d.settingsOpen),s=f(d=>d.uiMode),{t:a}=H();if(!ht()||r||s==="home"||s==="card-news"||s==="agent"||s==="assets"||s==="asset-gen")return null;const l=e&&t==="controls",c=a("sheet.controlsOpen");return o.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:o.jsx(nS,{})})}let Gr=null;function sS(e){Gr=e}function oS(){const e=Gr;Gr=null,e?.isConnected&&e.focus()}function wi(){Gr=null}function aS(){const{t:e}=H(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),s=r==="agent"&&Wt?"agent":r==="node"&&Bt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=ht(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&sS(p.current),t(u==="library"?"library":u==="controls"?"controls":"prompt")};return!a||n||s!=="classic"?null:o.jsxs("header",{className:"mobile-app-bar",role:"banner",children:[o.jsxs("div",{className:"mobile-app-bar__brand",children:[o.jsx("div",{className:"logo-mark","aria-hidden":"true"}),o.jsxs("div",{className:"mobile-app-bar__brand-copy",children:[o.jsx("span",{className:"mobile-app-bar__title",children:"ima2-gen"}),o.jsx("span",{className:"mobile-app-bar__mode",children:e("appBar.modeImage")})]})]}),o.jsxs("div",{className:"mobile-app-bar__actions",children:[o.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:o.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:o.jsx("path",{d:"M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"})})}),o.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:o.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:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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"})]})}),o.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:o.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:[o.jsx("path",{d:"M12 3l1.8 5.4L19 10l-5.2 1.6L12 17l-1.8-5.4L5 10l5.2-1.6L12 3z"}),o.jsx("path",{d:"M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8L19 15z"})]})})]}),o.jsx("div",{className:"mobile-app-bar__selection",children:o.jsx(Yc,{compact:!0})})]})}const iS={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},_i={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function lS(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=iS[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function cS(){return o.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:[o.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),o.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),o.jsx("path",{d:"m21 15-5-5L5 21"})]})}function dS(){return o.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:[o.jsx("path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}),o.jsx("polyline",{points:"9 22 9 12 15 12 15 22"})]})}function uS(){return o.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:[o.jsx("rect",{x:"2",y:"6",width:"8",height:"6",rx:"1"}),o.jsx("rect",{x:"14",y:"12",width:"8",height:"6",rx:"1"}),o.jsx("path",{d:"M10 9h4"}),o.jsx("path",{d:"M14 15V9a2 2 0 0 1 2-2h0"})]})}function mS(){return o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[o.jsx("circle",{cx:"12",cy:"12",r:"2.5",fill:"currentColor",stroke:"none"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(-30 12 12)"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"9",ry:"4",transform:"rotate(30 12 12)"})]})}function pS(){return o.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:[o.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"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function fS(){return o.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:[o.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"}),o.jsx("path",{d:"M8 12h8"})]})}function hS(){return o.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:[o.jsx("rect",{x:"3",y:"3",width:"13",height:"13",rx:"2"}),o.jsx("path",{d:"M3 12l3.5-3.5a1.4 1.4 0 0 1 2 0L13 13"}),o.jsx("path",{d:"M19 14v6"}),o.jsx("path",{d:"M16 17h6"})]})}const gS=[{id:"home",mode:"home",icon:dS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:cS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:uS,labelKey:"nav.node",enabled:Bt},{id:"agent",mode:"agent",icon:mS,labelKey:"nav.agent",enabled:Wt},{id:"assets",mode:"assets",icon:fS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:hS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:pS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function yS(){const{t:e}=H(),t=f(I=>I.uiMode),n=f(I=>I.setUIMode),r=f(I=>I.settingsOpen),s=f(I=>I.openSettings),a=f(I=>I.closeSettings),i=ht(),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,"",_i[t]||"#create")):(s(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",_i[I.mode]||"#create"))},[t,r,n,s,a]);v.useEffect(()=>{const I=()=>{const x=lS();x&&(x.settings?s():(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=gS.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=>o.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:[o.jsx(I.icon,{}),o.jsx("span",{className:"nav-rail__label","aria-hidden":"true",children:e(I.labelKey)})]},I.id);return i?o.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)}):o.jsxs("nav",{className:"nav-rail","aria-label":e("nav.ariaLabel"),children:[o.jsx("div",{className:"nav-rail__top",children:p.map(b)}),o.jsx("div",{className:"nav-rail__bottom",children:m.map(b)})]})}const vS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-DwFK4ALC.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),Ke=["prompt","controls","library"],dr="mobile-inflight-panel",ur=e=>`mobile-sheet-tab-${e}`,mr=e=>`mobile-sheet-panel-${e}`;function bS(){const{t:e}=H(),t=f(w=>w.composeSheetOpen),n=f(w=>w.composeSheetTab),r=f(w=>w.setComposeSheetTab),s=f(w=>w.closeComposeSheet),a=f(w=>w.inFlight.length),i=f(w=>w.settingsOpen),l=f(w=>w.uiMode),c=l==="agent"&&Wt?"agent":l==="node"&&Bt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=ht(),[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=w=>{r(w),requestAnimationFrame(()=>I.current[w]?.focus())},g=(w,j)=>{const P=Ke.indexOf(j),M=w.key==="ArrowRight"?Ke[(P+1)%Ke.length]:w.key==="ArrowLeft"?Ke[(P-1+Ke.length)%Ke.length]:w.key==="Home"?Ke[0]:w.key==="End"?Ke[Ke.length-1]:null;M&&(w.preventDefault(),y(M))},_=Ue(t,s,{autoFocus:!1});v.useEffect(()=>{(!t||n!=="prompt"||!d||i||c!=="classic")&&p(!1)},[t,n,s,d,i,c]),v.useLayoutEffect(()=>{const w=m.current>0&&a===0;m.current=a,w&&(p(!1),h.current&&b.current?.querySelector(".generate-btn")?.focus(),h.current=!1)},[a]),v.useLayoutEffect(()=>{if(t){x.current=!0;const w=requestAnimationFrame(()=>I.current[n]?.focus());return()=>cancelAnimationFrame(w)}x.current&&(x.current=!1,oS())},[t,n]);const S=d&&!i&&c==="classic";return v.useEffect(()=>{S||(x.current=!1,f.getState().composeSheetOpen&&s(),wi())},[S]),v.useEffect(()=>()=>wi(),[]),S?o.jsxs(o.Fragment,{children:[t?o.jsx("button",{type:"button",className:"compose-sheet-backdrop","aria-label":e("sheet.close"),onClick:s}):null,o.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:[o.jsx("button",{type:"button",className:"compose-sheet__handle",onClick:s,"aria-label":e("sheet.close")}),o.jsx("div",{className:"mobile-sheet-tabs",role:"tablist","aria-label":e("sheet.generate"),children:Ke.map(w=>o.jsx("button",{ref:j=>{I.current[w]=j},id:ur(w),type:"button",role:"tab","aria-selected":n===w,"aria-controls":mr(w),tabIndex:n===w?0:-1,className:`mobile-sheet-tabs__button${n===w?" active":""}`,onClick:()=>r(w),onKeyDown:j=>g(j,w),children:e(`sheet.tabs.${w}`)},w))}),o.jsxs("div",{className:"compose-sheet__body",children:[o.jsx("div",{id:mr("prompt"),className:"compose-sheet__panel compose-sheet__panel--prompt",role:"tabpanel","aria-labelledby":ur("prompt"),hidden:n!=="prompt",onFocusCapture:w=>{const j=document.getElementById(dr);h.current=j?.contains(w.target)??!1},children:n==="prompt"?o.jsxs(o.Fragment,{children:[o.jsx(Jo,{}),a>0?o.jsxs("section",{className:"compose-sheet__inflight",hidden:!u,children:[o.jsxs("button",{type:"button",className:"compose-sheet__inflight-header",onClick:()=>{b.current?.querySelector(".inflight-badge")?.focus(),p(!1)},"aria-expanded":u,"aria-controls":dr,"aria-label":e("inflight.inlineCollapse",{n:a}),children:[o.jsxs("span",{children:[e("inflight.title")," (",a,")"]}),o.jsx("span",{"aria-hidden":"true",children:"−"})]}),o.jsx(Xo,{variant:"inline",panelId:dr}),o.jsx("p",{className:"compose-sheet__inflight-footer",children:e("inflight.footerHint")})]}):null,o.jsxs("div",{ref:b,className:"compose-sheet__actions",children:[o.jsx(Yo,{}),o.jsx(Bc,{variant:"inline",panelId:dr,expanded:u,onToggle:p})]})]}):null}),o.jsx("div",{id:mr("controls"),className:"compose-sheet__panel compose-sheet__panel--controls",role:"tabpanel","aria-labelledby":ur("controls"),hidden:n!=="controls",children:n==="controls"?o.jsx(cd,{}):null}),o.jsx("div",{id:mr("library"),className:"compose-sheet__panel compose-sheet__panel--library",role:"tabpanel","aria-labelledby":ur("library"),hidden:n!=="library",children:n==="library"?o.jsx(v.Suspense,{fallback:o.jsx("div",{className:"prompt-library-panel__loading",children:e("common.loading")}),children:o.jsx(vS,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const xS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function IS(){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=s=>{const a=xS[s.key];a&&(s.defaultPrevented||Ir(s.target)||t&&(s.preventDefault(),n(a)))};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,e])}const pr=64,pd="Image Gen";let na=pd,Zs=!1,mt=null,ra="",Qs=!1;function fd(){return navigator}function hd(){if(typeof document>"u")return null;if(mt)return mt;const e=document.querySelector('link[rel~="icon"]');if(e)return mt=e,ra=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),mt=t,Qs=!0,t}function SS(e){const t=document.createElement("canvas");t.width=pr,t.height=pr;const n=t.getContext("2d");return n?(n.clearRect(0,0,pr,pr),n.fillStyle="#0a0a0a",wS(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")):ra}function wS(e,t,n,r,s,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+s,a),e.arcTo(t+r,n+s,t,n+s,a),e.arcTo(t,n+s,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}async function _S(e){const t=fd();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function ES(){const e=fd();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function NS(e){document.title=`(${e}) ${na}`;const t=hd();t&&(t.href=SS(e)),_S(e)}function Ei(){document.title=na,mt&&(Qs?(mt.remove(),mt=null,Qs=!1):mt.href=ra),ES()}function Ni(){Zs||typeof document>"u"||(Zs=!0,na=document.title||pd,hd())}function kS(e){v.useEffect(()=>(Ni(),()=>{Zs&&Ei()}),[]),v.useEffect(()=>{Ni(),e>0?NS(e):Ei()},[e])}function CS(){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 jS=v.lazy(()=>Me(()=>import("./NodeCanvas-B6zoJhHr.js"),__vite__mapDeps([7,1,2,8])).then(e=>({default:e.NodeCanvas}))),PS=v.lazy(()=>Me(()=>import("./SettingsWorkspace-BWcNnQ56.js"),__vite__mapDeps([9,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),AS=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-DV4hpvKf.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.CardNewsWorkspace}))),RS=v.lazy(()=>Me(()=>import("./AgentWorkspace-BulKz33A.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.AgentWorkspace}))),TS=v.lazy(()=>Me(()=>import("./AssetsWorkspace-Dxz-Xksp.js"),__vite__mapDeps([13,1,2,14,12,15])).then(e=>({default:e.AssetsWorkspace}))),MS=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-8SYhS2Y2.js").then(e=>e.A),__vite__mapDeps([16,1,2,14,12,17])).then(e=>({default:e.AssetGenWorkspace}))),LS=v.lazy(()=>Me(()=>import("./HomeWorkspace-D1UBgwRZ.js"),__vite__mapDeps([18,1,2])).then(e=>({default:e.HomeWorkspace}))),FS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-DwFK4ALC.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function OS(){return o.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function DS(){IS(),CS();const{locale:e}=H(),t=f(w=>w.hydrateHistory),n=f(w=>w.loadSessions),r=f(w=>w.syncCapabilities),s=f(w=>w.startInFlightPolling),a=f(w=>w.reconcileInflight),i=f(w=>w.syncFromStorage),l=f(w=>w.settingsOpen),c=f(w=>w.unseenGeneratedCount),d=f(w=>w.historyStripLayout),u=f(w=>w.workspaceProfile),p=f(w=>w.uiMode),m=p==="agent"&&Wt?"agent":p==="node"&&Bt?"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=ht(),g=Ln(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",S=!_&&!h&&!b&&!I&&!x;return kS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!ce())return r(),t(),n(),a(),s(),Ct(),ua(()=>a()),ma(w=>{w==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{In(),ua(()=>{}),ma(()=>{})}},[t,n,a,s,r]),v.useEffect(()=>{const w=j=>{const P=j.detail?.assetId;P&&f.getState().openAssetDetail(P)};return window.addEventListener("ima2:open-assets-detail",w),()=>window.removeEventListener("ima2:open-assets-detail",w)},[]),v.useEffect(()=>{const w=j=>{j.key&&(j.key==="ima2.inFlight"||j.key==="ima2.selectedFilename"||j.key===ho||j.key===fo||j.key===yo)&&i()};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[i]),v.useEffect(()=>{const w=()=>{np(f.getState)};return window.addEventListener("beforeunload",w),()=>{window.removeEventListener("beforeunload",w)}},[]),o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:`app${u==="prompt-studio"?" app--prompt-studio":""}${l?" app--settings-open":""}${S&&d==="horizontal"?" app--history-horizontal":""}${S&&d==="sidebar"?" app--history-sidebar":""}`,"data-history-strip-layout":d,"data-mobile":y?"1":void 0,"data-ui-mode":m,children:[o.jsx(yS,{}),x?null:o.jsx(nb,{}),o.jsx(aS,{}),S?o.jsx(rI,{}):null,o.jsx(v.Suspense,{fallback:o.jsx(OS,{}),children:l?o.jsx(PS,{}):m==="classic"?_?o.jsx(Wb,{}):o.jsx(Ys,{}):m==="node"?o.jsx(jS,{}):m==="card-news"?o.jsx(AS,{}):m==="agent"?o.jsx(RS,{}):m==="assets"?o.jsx(TS,{}):m==="asset-gen"?o.jsx(MS,{}):m==="home"?o.jsx(LS,{}):o.jsx(Ys,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:o.jsx(Xx,{})]}),o.jsx(BI,{}),o.jsx(tS,{}),o.jsx(sI,{}),o.jsx(oI,{}),o.jsx(KI,{}),o.jsx(WI,{}),o.jsx(QI,{}),o.jsx(eS,{}),o.jsx(bS,{}),o.jsx(rS,{}),m==="card-news"?o.jsx(v.Suspense,{fallback:null,children:o.jsx(FS,{})}):null]})}const Nw=Object.freeze(Object.defineProperty({__proto__:null,default:DS},Symbol.toStringTag,{value:"Module"}));export{iw as $,wu as A,Oe as B,Lc as C,hw as D,gw as E,yw as F,Su as G,vw as H,Xe as I,Sw as J,Qo as K,bw as L,xw as M,Iw as N,Iu as O,Ie as P,Zx as Q,Ds as R,sv as S,$u as T,uw as U,Pu as V,ov as W,tt as X,Gy as Y,pw as Z,hu as _,f as a,_p as a0,FI as a1,Hc as a2,ww as a3,Ew as a4,_w as a5,dw as a6,fw as a7,Ob as a8,so as a9,JS as aA,VS as aB,zS as aC,YS as aD,KS as aE,cb as aF,HS as aG,Gb as aH,Ci as aI,A as aJ,qS as aK,US as aL,$S as aM,QS as aN,XS as aO,ew as aP,tw as aQ,ZS as aR,nw as aS,rw as aT,sw as aU,ow as aV,aw as aW,Nw as aX,Ql as aa,cI as ab,Xo as ac,cw as ad,kt as ae,lw as af,es as ag,Wo as ah,Uc as ai,lv as aj,Ae as ak,od as al,cS as am,uS as an,Bt as ao,mS as ap,Wt as aq,fS as ar,_i as as,Dy as at,Tb as au,Db as av,Bs as aw,WS as ax,BS as ay,Ir as az,hI as b,up as c,Qe as d,_t as e,Gu as f,zi as g,mw as h,Ye as i,Zl as j,Ue as k,Ep as l,pu as m,cp as n,z as o,ht as p,we as q,Fe as r,nd as s,rd as t,H as u,lx as v,Bm as w,sd as x,Cu as y,ss as z};