ima2-gen 3.15.1 → 3.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +7 -6
- package/bin/commands/grok.js +150 -64
- package/bin/commands/service.js +5 -4
- package/bin/ima2.js +3 -3
- package/bin/lib/doctor-providers.js +6 -1
- package/bin/lib/doctor-runtime.js +1 -1
- package/config.js +0 -9
- package/docs/API.md +7 -7
- package/docs/API.zh-CN.md +7 -7
- package/docs/API.zh-TW.md +7 -7
- package/docs/CLI.md +9 -8
- package/docs/CLI.zh-CN.md +8 -8
- package/docs/CLI.zh-TW.md +8 -8
- package/docs/README.ko.md +5 -6
- package/docs/README.zh-CN.md +6 -5
- package/docs/README.zh-TW.md +6 -5
- package/docs/migration/runtime-test-inventory.md +4 -6
- package/lib/agentPlannerModel.js +17 -16
- package/lib/capabilities.js +3 -2
- package/lib/errors/providerMap.js +13 -0
- package/lib/grokImageCore.js +9 -16
- package/lib/grokImagePlanner.js +15 -3
- package/lib/grokRuntime.js +47 -16
- package/lib/grokVideoAdapter.js +23 -7
- package/lib/grokVideoPoll.js +3 -3
- package/lib/grokVideoShared.js +6 -13
- package/lib/promptBuilder/router.js +22 -6
- package/lib/providers/adapters/grokExecution.js +15 -14
- package/lib/providers/adapters/grokMultimodeOperations.js +9 -7
- package/lib/providers/adapters/grokOperations.js +19 -12
- package/lib/providers/execution/admission.js +20 -4
- package/lib/providers/registry.js +1 -1
- package/lib/runtimeContext.js +0 -12
- package/lib/videoExtendI2vOperation.js +5 -1
- package/lib/xaiAuth.js +369 -0
- package/lib/xaiDeviceLogin.js +157 -0
- package/package.json +2 -4
- package/routes/auth.js +18 -26
- package/routes/grok.js +25 -19
- package/routes/health.js +4 -5
- package/routes/models.js +12 -26
- package/routes/quota.js +2 -1
- package/routes/video.js +7 -2
- package/routes/videoExtended.js +37 -24
- package/server.js +7 -58
- package/skills/ima2/SKILL.md +2 -2
- package/ui/dist/.vite/manifest.json +56 -56
- package/ui/dist/assets/{AgentWorkspace-CLJDCRMQ.js → AgentWorkspace-DlLaTsPK.js} +1 -1
- package/ui/dist/assets/{App-DkvU6Sex.js → App-BfpvLzSs.js} +4 -4
- package/ui/dist/assets/{AssetGenWorkspace-BepUrz23.js → AssetGenWorkspace-C8eIs-bS.js} +2 -2
- package/ui/dist/assets/{AssetsWorkspace-IipC1FdD.js → AssetsWorkspace-BcbAM8uC.js} +1 -1
- package/ui/dist/assets/{CardNewsWorkspace-ZXDwYz4l.js → CardNewsWorkspace-CM5hwbRV.js} +1 -1
- package/ui/dist/assets/{GenerationRequestLogPanel-BL2C0DcW.js → GenerationRequestLogPanel-CTs8OymS.js} +1 -1
- package/ui/dist/assets/{HomeWorkspace-DFfrwS9a.js → HomeWorkspace-KGUtIZyG.js} +1 -1
- package/ui/dist/assets/{KeyingPanel-BQkEMTe9.js → KeyingPanel-D8ZHmWcC.js} +1 -1
- package/ui/dist/assets/{NodeCanvas-5u8IO1MA.js → NodeCanvas-D2N3m-1s.js} +1 -1
- package/ui/dist/assets/{PromptBuilderPanel-DNt7LHMi.js → PromptBuilderPanel-BolZnOa7.js} +1 -1
- package/ui/dist/assets/{PromptImportDialog-Bl-SB4mK.js → PromptImportDialog-DBpe7Vkj.js} +2 -2
- package/ui/dist/assets/{PromptImportDiscoverySection-DdZAdRMW.js → PromptImportDiscoverySection-Dk6v6lUZ.js} +1 -1
- package/ui/dist/assets/{PromptImportFolderSection-DLHQKl9T.js → PromptImportFolderSection-BE7Nfq9Y.js} +1 -1
- package/ui/dist/assets/{PromptLibraryPanel-PLWyvEz1.js → PromptLibraryPanel-Qdujpb4L.js} +2 -2
- package/ui/dist/assets/{SettingsWorkspace-Etfeu2IF.js → SettingsWorkspace-Dm4wezu_.js} +1 -1
- package/ui/dist/assets/{SpriteRecipeWorkspace-D7H5seOM.js → SpriteRecipeWorkspace-D9do9V7F.js} +1 -1
- package/ui/dist/assets/index-CfGRmfFv.js +22 -0
- package/ui/dist/assets/{index-BAkbTbUC.js → index-CfrOcJIe.js} +3 -3
- package/ui/dist/assets/{pptxgen.es-Apxh5DQ9.js → pptxgen.es-BLI_YKez.js} +1 -1
- package/ui/dist/assets/{promptBuilderStore-prvdLIUP.js → promptBuilderStore-BMiudG9n.js} +1 -1
- package/ui/dist/assets/useAgentDialogFocus-CCj5EYE9.js +1 -0
- package/ui/dist/index.html +1 -1
- package/lib/grokProxyLauncher.js +0 -279
- package/node_modules/array-flatten/LICENSE +0 -21
- package/node_modules/array-flatten/README.md +0 -43
- package/node_modules/array-flatten/array-flatten.js +0 -64
- package/node_modules/array-flatten/package.json +0 -39
- package/node_modules/bundle-name/index.js +0 -5
- package/node_modules/bundle-name/license +0 -9
- package/node_modules/bundle-name/package.json +0 -45
- package/node_modules/bundle-name/readme.md +0 -23
- package/node_modules/bytes/History.md +0 -97
- package/node_modules/bytes/LICENSE +0 -23
- package/node_modules/bytes/Readme.md +0 -152
- package/node_modules/bytes/index.js +0 -170
- package/node_modules/bytes/package.json +0 -42
- package/node_modules/call-bind-apply-helpers/.eslintrc +0 -17
- package/node_modules/call-bind-apply-helpers/.github/FUNDING.yml +0 -12
- package/node_modules/call-bind-apply-helpers/.nycrc +0 -9
- package/node_modules/call-bind-apply-helpers/CHANGELOG.md +0 -30
- package/node_modules/call-bind-apply-helpers/LICENSE +0 -21
- package/node_modules/call-bind-apply-helpers/README.md +0 -62
- package/node_modules/call-bind-apply-helpers/actualApply.d.ts +0 -1
- package/node_modules/call-bind-apply-helpers/actualApply.js +0 -10
- package/node_modules/call-bind-apply-helpers/applyBind.d.ts +0 -19
- package/node_modules/call-bind-apply-helpers/applyBind.js +0 -10
- package/node_modules/call-bind-apply-helpers/functionApply.d.ts +0 -1
- package/node_modules/call-bind-apply-helpers/functionApply.js +0 -4
- package/node_modules/call-bind-apply-helpers/functionCall.d.ts +0 -1
- package/node_modules/call-bind-apply-helpers/functionCall.js +0 -4
- package/node_modules/call-bind-apply-helpers/index.d.ts +0 -64
- package/node_modules/call-bind-apply-helpers/index.js +0 -15
- package/node_modules/call-bind-apply-helpers/package.json +0 -85
- package/node_modules/call-bind-apply-helpers/reflectApply.d.ts +0 -3
- package/node_modules/call-bind-apply-helpers/reflectApply.js +0 -4
- package/node_modules/call-bind-apply-helpers/test/index.js +0 -63
- package/node_modules/call-bind-apply-helpers/tsconfig.json +0 -9
- package/node_modules/call-bound/.eslintrc +0 -13
- package/node_modules/call-bound/.github/FUNDING.yml +0 -12
- package/node_modules/call-bound/.nycrc +0 -9
- package/node_modules/call-bound/CHANGELOG.md +0 -42
- package/node_modules/call-bound/LICENSE +0 -21
- package/node_modules/call-bound/README.md +0 -53
- package/node_modules/call-bound/index.d.ts +0 -94
- package/node_modules/call-bound/index.js +0 -19
- package/node_modules/call-bound/package.json +0 -99
- package/node_modules/call-bound/test/index.js +0 -61
- package/node_modules/call-bound/tsconfig.json +0 -10
- package/node_modules/commander/LICENSE +0 -22
- package/node_modules/commander/Readme.md +0 -1149
- package/node_modules/commander/esm.mjs +0 -16
- package/node_modules/commander/index.js +0 -24
- package/node_modules/commander/lib/argument.js +0 -149
- package/node_modules/commander/lib/command.js +0 -2662
- package/node_modules/commander/lib/error.js +0 -39
- package/node_modules/commander/lib/help.js +0 -709
- package/node_modules/commander/lib/option.js +0 -367
- package/node_modules/commander/lib/suggestSimilar.js +0 -101
- package/node_modules/commander/package-support.json +0 -16
- package/node_modules/commander/package.json +0 -82
- package/node_modules/commander/typings/esm.d.mts +0 -3
- package/node_modules/commander/typings/index.d.ts +0 -1045
- package/node_modules/content-type/HISTORY.md +0 -29
- package/node_modules/content-type/LICENSE +0 -22
- package/node_modules/content-type/README.md +0 -94
- package/node_modules/content-type/index.js +0 -225
- package/node_modules/content-type/package.json +0 -42
- package/node_modules/cookie/LICENSE +0 -24
- package/node_modules/cookie/README.md +0 -317
- package/node_modules/cookie/SECURITY.md +0 -25
- package/node_modules/cookie/index.js +0 -335
- package/node_modules/cookie/package.json +0 -44
- package/node_modules/default-browser/index.d.ts +0 -29
- package/node_modules/default-browser/index.js +0 -34
- package/node_modules/default-browser/license +0 -9
- package/node_modules/default-browser/package.json +0 -54
- package/node_modules/default-browser/readme.md +0 -24
- package/node_modules/default-browser/windows.js +0 -57
- package/node_modules/default-browser-id/index.js +0 -25
- package/node_modules/default-browser-id/license +0 -9
- package/node_modules/default-browser-id/package.json +0 -41
- package/node_modules/default-browser-id/readme.md +0 -19
- package/node_modules/define-lazy-prop/index.d.ts +0 -31
- package/node_modules/define-lazy-prop/index.js +0 -18
- package/node_modules/define-lazy-prop/license +0 -9
- package/node_modules/define-lazy-prop/package.json +0 -51
- package/node_modules/define-lazy-prop/readme.md +0 -55
- package/node_modules/depd/History.md +0 -103
- package/node_modules/depd/LICENSE +0 -22
- package/node_modules/depd/Readme.md +0 -280
- package/node_modules/depd/index.js +0 -538
- package/node_modules/depd/lib/browser/index.js +0 -77
- package/node_modules/depd/package.json +0 -45
- package/node_modules/destroy/LICENSE +0 -23
- package/node_modules/destroy/README.md +0 -63
- package/node_modules/destroy/index.js +0 -209
- package/node_modules/destroy/package.json +0 -48
- package/node_modules/dunder-proto/.eslintrc +0 -5
- package/node_modules/dunder-proto/.github/FUNDING.yml +0 -12
- package/node_modules/dunder-proto/.nycrc +0 -13
- package/node_modules/dunder-proto/CHANGELOG.md +0 -24
- package/node_modules/dunder-proto/LICENSE +0 -21
- package/node_modules/dunder-proto/README.md +0 -54
- package/node_modules/dunder-proto/get.d.ts +0 -5
- package/node_modules/dunder-proto/get.js +0 -30
- package/node_modules/dunder-proto/package.json +0 -76
- package/node_modules/dunder-proto/set.d.ts +0 -5
- package/node_modules/dunder-proto/set.js +0 -35
- package/node_modules/dunder-proto/test/get.js +0 -34
- package/node_modules/dunder-proto/test/index.js +0 -4
- package/node_modules/dunder-proto/test/set.js +0 -50
- package/node_modules/dunder-proto/tsconfig.json +0 -9
- package/node_modules/ee-first/LICENSE +0 -22
- package/node_modules/ee-first/README.md +0 -80
- package/node_modules/ee-first/index.js +0 -95
- package/node_modules/ee-first/package.json +0 -29
- package/node_modules/encodeurl/LICENSE +0 -22
- package/node_modules/encodeurl/README.md +0 -109
- package/node_modules/encodeurl/index.js +0 -60
- package/node_modules/encodeurl/package.json +0 -40
- package/node_modules/es-define-property/.eslintrc +0 -13
- package/node_modules/es-define-property/.github/FUNDING.yml +0 -12
- package/node_modules/es-define-property/.nycrc +0 -9
- package/node_modules/es-define-property/CHANGELOG.md +0 -29
- package/node_modules/es-define-property/LICENSE +0 -21
- package/node_modules/es-define-property/README.md +0 -49
- package/node_modules/es-define-property/index.d.ts +0 -3
- package/node_modules/es-define-property/index.js +0 -14
- package/node_modules/es-define-property/package.json +0 -81
- package/node_modules/es-define-property/test/index.js +0 -56
- package/node_modules/es-define-property/tsconfig.json +0 -10
- package/node_modules/es-errors/.eslintrc +0 -5
- package/node_modules/es-errors/.github/FUNDING.yml +0 -12
- package/node_modules/es-errors/CHANGELOG.md +0 -40
- package/node_modules/es-errors/LICENSE +0 -21
- package/node_modules/es-errors/README.md +0 -55
- package/node_modules/es-errors/eval.d.ts +0 -3
- package/node_modules/es-errors/eval.js +0 -4
- package/node_modules/es-errors/index.d.ts +0 -3
- package/node_modules/es-errors/index.js +0 -4
- package/node_modules/es-errors/package.json +0 -80
- package/node_modules/es-errors/range.d.ts +0 -3
- package/node_modules/es-errors/range.js +0 -4
- package/node_modules/es-errors/ref.d.ts +0 -3
- package/node_modules/es-errors/ref.js +0 -4
- package/node_modules/es-errors/syntax.d.ts +0 -3
- package/node_modules/es-errors/syntax.js +0 -4
- package/node_modules/es-errors/test/index.js +0 -19
- package/node_modules/es-errors/tsconfig.json +0 -49
- package/node_modules/es-errors/type.d.ts +0 -3
- package/node_modules/es-errors/type.js +0 -4
- package/node_modules/es-errors/uri.d.ts +0 -3
- package/node_modules/es-errors/uri.js +0 -4
- package/node_modules/es-object-atoms/.eslintrc +0 -16
- package/node_modules/es-object-atoms/.github/FUNDING.yml +0 -12
- package/node_modules/es-object-atoms/CHANGELOG.md +0 -37
- package/node_modules/es-object-atoms/LICENSE +0 -21
- package/node_modules/es-object-atoms/README.md +0 -63
- package/node_modules/es-object-atoms/RequireObjectCoercible.d.ts +0 -3
- package/node_modules/es-object-atoms/RequireObjectCoercible.js +0 -11
- package/node_modules/es-object-atoms/ToObject.d.ts +0 -7
- package/node_modules/es-object-atoms/ToObject.js +0 -10
- package/node_modules/es-object-atoms/index.d.ts +0 -3
- package/node_modules/es-object-atoms/index.js +0 -4
- package/node_modules/es-object-atoms/isObject.d.ts +0 -3
- package/node_modules/es-object-atoms/isObject.js +0 -6
- package/node_modules/es-object-atoms/package.json +0 -80
- package/node_modules/es-object-atoms/test/index.js +0 -38
- package/node_modules/es-object-atoms/tsconfig.json +0 -6
- package/node_modules/escape-html/LICENSE +0 -24
- package/node_modules/escape-html/Readme.md +0 -43
- package/node_modules/escape-html/index.js +0 -78
- package/node_modules/escape-html/package.json +0 -24
- package/node_modules/etag/HISTORY.md +0 -83
- package/node_modules/etag/LICENSE +0 -22
- package/node_modules/etag/README.md +0 -159
- package/node_modules/etag/index.js +0 -131
- package/node_modules/etag/package.json +0 -47
- package/node_modules/forwarded/HISTORY.md +0 -21
- package/node_modules/forwarded/LICENSE +0 -22
- package/node_modules/forwarded/README.md +0 -57
- package/node_modules/forwarded/index.js +0 -90
- package/node_modules/forwarded/package.json +0 -45
- package/node_modules/function-bind/.eslintrc +0 -21
- package/node_modules/function-bind/.github/FUNDING.yml +0 -12
- package/node_modules/function-bind/.github/SECURITY.md +0 -3
- package/node_modules/function-bind/.nycrc +0 -13
- package/node_modules/function-bind/CHANGELOG.md +0 -136
- package/node_modules/function-bind/LICENSE +0 -20
- package/node_modules/function-bind/README.md +0 -46
- package/node_modules/function-bind/implementation.js +0 -84
- package/node_modules/function-bind/index.js +0 -5
- package/node_modules/function-bind/package.json +0 -87
- package/node_modules/function-bind/test/.eslintrc +0 -9
- package/node_modules/function-bind/test/index.js +0 -252
- package/node_modules/get-intrinsic/.eslintrc +0 -42
- package/node_modules/get-intrinsic/.github/FUNDING.yml +0 -12
- package/node_modules/get-intrinsic/.nycrc +0 -9
- package/node_modules/get-intrinsic/CHANGELOG.md +0 -186
- package/node_modules/get-intrinsic/LICENSE +0 -21
- package/node_modules/get-intrinsic/README.md +0 -71
- package/node_modules/get-intrinsic/index.js +0 -378
- package/node_modules/get-intrinsic/package.json +0 -97
- package/node_modules/get-intrinsic/test/GetIntrinsic.js +0 -274
- package/node_modules/get-proto/.eslintrc +0 -10
- package/node_modules/get-proto/.github/FUNDING.yml +0 -12
- package/node_modules/get-proto/.nycrc +0 -9
- package/node_modules/get-proto/CHANGELOG.md +0 -21
- package/node_modules/get-proto/LICENSE +0 -21
- package/node_modules/get-proto/Object.getPrototypeOf.d.ts +0 -5
- package/node_modules/get-proto/Object.getPrototypeOf.js +0 -6
- package/node_modules/get-proto/README.md +0 -50
- package/node_modules/get-proto/Reflect.getPrototypeOf.d.ts +0 -3
- package/node_modules/get-proto/Reflect.getPrototypeOf.js +0 -4
- package/node_modules/get-proto/index.d.ts +0 -5
- package/node_modules/get-proto/index.js +0 -27
- package/node_modules/get-proto/package.json +0 -81
- package/node_modules/get-proto/test/index.js +0 -68
- package/node_modules/get-proto/tsconfig.json +0 -9
- package/node_modules/gopd/.eslintrc +0 -16
- package/node_modules/gopd/.github/FUNDING.yml +0 -12
- package/node_modules/gopd/CHANGELOG.md +0 -45
- package/node_modules/gopd/LICENSE +0 -21
- package/node_modules/gopd/README.md +0 -40
- package/node_modules/gopd/gOPD.d.ts +0 -1
- package/node_modules/gopd/gOPD.js +0 -4
- package/node_modules/gopd/index.d.ts +0 -5
- package/node_modules/gopd/index.js +0 -15
- package/node_modules/gopd/package.json +0 -77
- package/node_modules/gopd/test/index.js +0 -36
- package/node_modules/gopd/tsconfig.json +0 -9
- package/node_modules/has-symbols/.eslintrc +0 -11
- package/node_modules/has-symbols/.github/FUNDING.yml +0 -12
- package/node_modules/has-symbols/.nycrc +0 -9
- package/node_modules/has-symbols/CHANGELOG.md +0 -91
- package/node_modules/has-symbols/LICENSE +0 -21
- package/node_modules/has-symbols/README.md +0 -46
- package/node_modules/has-symbols/index.d.ts +0 -3
- package/node_modules/has-symbols/index.js +0 -14
- package/node_modules/has-symbols/package.json +0 -111
- package/node_modules/has-symbols/shams.d.ts +0 -3
- package/node_modules/has-symbols/shams.js +0 -45
- package/node_modules/has-symbols/test/index.js +0 -22
- package/node_modules/has-symbols/test/shams/core-js.js +0 -29
- package/node_modules/has-symbols/test/shams/get-own-property-symbols.js +0 -29
- package/node_modules/has-symbols/test/tests.js +0 -58
- package/node_modules/has-symbols/tsconfig.json +0 -10
- package/node_modules/hasown/.github/FUNDING.yml +0 -12
- package/node_modules/hasown/.nycrc +0 -13
- package/node_modules/hasown/CHANGELOG.md +0 -51
- package/node_modules/hasown/LICENSE +0 -21
- package/node_modules/hasown/README.md +0 -40
- package/node_modules/hasown/eslint.config.mjs +0 -6
- package/node_modules/hasown/index.d.ts +0 -4
- package/node_modules/hasown/index.js +0 -8
- package/node_modules/hasown/package.json +0 -92
- package/node_modules/hasown/tsconfig.json +0 -6
- package/node_modules/http-errors/HISTORY.md +0 -186
- package/node_modules/http-errors/LICENSE +0 -23
- package/node_modules/http-errors/README.md +0 -169
- package/node_modules/http-errors/index.js +0 -290
- package/node_modules/http-errors/package.json +0 -54
- package/node_modules/inherits/LICENSE +0 -16
- package/node_modules/inherits/README.md +0 -42
- package/node_modules/inherits/inherits.js +0 -9
- package/node_modules/inherits/inherits_browser.js +0 -27
- package/node_modules/inherits/package.json +0 -29
- package/node_modules/ipaddr.js/LICENSE +0 -19
- package/node_modules/ipaddr.js/README.md +0 -233
- package/node_modules/ipaddr.js/ipaddr.min.js +0 -1
- package/node_modules/ipaddr.js/lib/ipaddr.js +0 -673
- package/node_modules/ipaddr.js/lib/ipaddr.js.d.ts +0 -68
- package/node_modules/ipaddr.js/package.json +0 -35
- package/node_modules/is-docker/cli.js +0 -5
- package/node_modules/is-docker/index.d.ts +0 -13
- package/node_modules/is-docker/index.js +0 -29
- package/node_modules/is-docker/license +0 -9
- package/node_modules/is-docker/package.json +0 -44
- package/node_modules/is-docker/readme.md +0 -27
- package/node_modules/is-inside-container/cli.js +0 -5
- package/node_modules/is-inside-container/index.d.ts +0 -13
- package/node_modules/is-inside-container/index.js +0 -23
- package/node_modules/is-inside-container/license +0 -9
- package/node_modules/is-inside-container/package.json +0 -51
- package/node_modules/is-inside-container/readme.md +0 -36
- package/node_modules/is-wsl/index.d.ts +0 -15
- package/node_modules/is-wsl/index.js +0 -36
- package/node_modules/is-wsl/license +0 -9
- package/node_modules/is-wsl/package.json +0 -58
- package/node_modules/is-wsl/readme.md +0 -21
- package/node_modules/math-intrinsics/.eslintrc +0 -16
- package/node_modules/math-intrinsics/.github/FUNDING.yml +0 -12
- package/node_modules/math-intrinsics/CHANGELOG.md +0 -24
- package/node_modules/math-intrinsics/LICENSE +0 -21
- package/node_modules/math-intrinsics/README.md +0 -50
- package/node_modules/math-intrinsics/abs.d.ts +0 -1
- package/node_modules/math-intrinsics/abs.js +0 -4
- package/node_modules/math-intrinsics/constants/maxArrayLength.d.ts +0 -3
- package/node_modules/math-intrinsics/constants/maxArrayLength.js +0 -4
- package/node_modules/math-intrinsics/constants/maxSafeInteger.d.ts +0 -3
- package/node_modules/math-intrinsics/constants/maxSafeInteger.js +0 -5
- package/node_modules/math-intrinsics/constants/maxValue.d.ts +0 -3
- package/node_modules/math-intrinsics/constants/maxValue.js +0 -5
- package/node_modules/math-intrinsics/floor.d.ts +0 -1
- package/node_modules/math-intrinsics/floor.js +0 -4
- package/node_modules/math-intrinsics/isFinite.d.ts +0 -3
- package/node_modules/math-intrinsics/isFinite.js +0 -12
- package/node_modules/math-intrinsics/isInteger.d.ts +0 -3
- package/node_modules/math-intrinsics/isInteger.js +0 -16
- package/node_modules/math-intrinsics/isNaN.d.ts +0 -1
- package/node_modules/math-intrinsics/isNaN.js +0 -6
- package/node_modules/math-intrinsics/isNegativeZero.d.ts +0 -3
- package/node_modules/math-intrinsics/isNegativeZero.js +0 -6
- package/node_modules/math-intrinsics/max.d.ts +0 -1
- package/node_modules/math-intrinsics/max.js +0 -4
- package/node_modules/math-intrinsics/min.d.ts +0 -1
- package/node_modules/math-intrinsics/min.js +0 -4
- package/node_modules/math-intrinsics/mod.d.ts +0 -3
- package/node_modules/math-intrinsics/mod.js +0 -9
- package/node_modules/math-intrinsics/package.json +0 -86
- package/node_modules/math-intrinsics/pow.d.ts +0 -1
- package/node_modules/math-intrinsics/pow.js +0 -4
- package/node_modules/math-intrinsics/round.d.ts +0 -1
- package/node_modules/math-intrinsics/round.js +0 -4
- package/node_modules/math-intrinsics/sign.d.ts +0 -3
- package/node_modules/math-intrinsics/sign.js +0 -11
- package/node_modules/math-intrinsics/test/index.js +0 -192
- package/node_modules/math-intrinsics/tsconfig.json +0 -3
- package/node_modules/methods/HISTORY.md +0 -29
- package/node_modules/methods/LICENSE +0 -24
- package/node_modules/methods/README.md +0 -51
- package/node_modules/methods/index.js +0 -69
- package/node_modules/methods/package.json +0 -36
- package/node_modules/mime/.npmignore +0 -0
- package/node_modules/mime/CHANGELOG.md +0 -164
- package/node_modules/mime/LICENSE +0 -21
- package/node_modules/mime/README.md +0 -90
- package/node_modules/mime/cli.js +0 -8
- package/node_modules/mime/mime.js +0 -108
- package/node_modules/mime/package.json +0 -44
- package/node_modules/mime/src/build.js +0 -53
- package/node_modules/mime/src/test.js +0 -60
- package/node_modules/mime/types.json +0 -1
- package/node_modules/ms/index.js +0 -162
- package/node_modules/ms/license.md +0 -21
- package/node_modules/ms/package.json +0 -38
- package/node_modules/ms/readme.md +0 -59
- package/node_modules/object-inspect/.eslintrc +0 -53
- package/node_modules/object-inspect/.github/FUNDING.yml +0 -12
- package/node_modules/object-inspect/.nycrc +0 -13
- package/node_modules/object-inspect/CHANGELOG.md +0 -424
- package/node_modules/object-inspect/LICENSE +0 -21
- package/node_modules/object-inspect/example/all.js +0 -23
- package/node_modules/object-inspect/example/circular.js +0 -6
- package/node_modules/object-inspect/example/fn.js +0 -5
- package/node_modules/object-inspect/example/inspect.js +0 -10
- package/node_modules/object-inspect/index.js +0 -544
- package/node_modules/object-inspect/package-support.json +0 -20
- package/node_modules/object-inspect/package.json +0 -105
- package/node_modules/object-inspect/readme.markdown +0 -84
- package/node_modules/object-inspect/test/bigint.js +0 -58
- package/node_modules/object-inspect/test/browser/dom.js +0 -15
- package/node_modules/object-inspect/test/circular.js +0 -16
- package/node_modules/object-inspect/test/deep.js +0 -12
- package/node_modules/object-inspect/test/element.js +0 -53
- package/node_modules/object-inspect/test/err.js +0 -48
- package/node_modules/object-inspect/test/fakes.js +0 -29
- package/node_modules/object-inspect/test/fn.js +0 -76
- package/node_modules/object-inspect/test/global.js +0 -17
- package/node_modules/object-inspect/test/has.js +0 -15
- package/node_modules/object-inspect/test/holes.js +0 -15
- package/node_modules/object-inspect/test/indent-option.js +0 -271
- package/node_modules/object-inspect/test/inspect.js +0 -139
- package/node_modules/object-inspect/test/lowbyte.js +0 -12
- package/node_modules/object-inspect/test/number.js +0 -58
- package/node_modules/object-inspect/test/quoteStyle.js +0 -26
- package/node_modules/object-inspect/test/toStringTag.js +0 -40
- package/node_modules/object-inspect/test/undef.js +0 -12
- package/node_modules/object-inspect/test/values.js +0 -261
- package/node_modules/object-inspect/test-core-js.js +0 -26
- package/node_modules/object-inspect/util.inspect.js +0 -1
- package/node_modules/on-finished/HISTORY.md +0 -98
- package/node_modules/on-finished/LICENSE +0 -23
- package/node_modules/on-finished/README.md +0 -162
- package/node_modules/on-finished/index.js +0 -234
- package/node_modules/on-finished/package.json +0 -39
- package/node_modules/open/index.d.ts +0 -158
- package/node_modules/open/index.js +0 -366
- package/node_modules/open/license +0 -9
- package/node_modules/open/node_modules/wsl-utils/index.d.ts +0 -21
- package/node_modules/open/node_modules/wsl-utils/index.js +0 -57
- package/node_modules/open/node_modules/wsl-utils/license +0 -9
- package/node_modules/open/node_modules/wsl-utils/package.json +0 -46
- package/node_modules/open/node_modules/wsl-utils/readme.md +0 -50
- package/node_modules/open/package.json +0 -68
- package/node_modules/open/readme.md +0 -183
- package/node_modules/open/xdg-open +0 -1267
- package/node_modules/parseurl/HISTORY.md +0 -58
- package/node_modules/parseurl/LICENSE +0 -24
- package/node_modules/parseurl/README.md +0 -133
- package/node_modules/parseurl/index.js +0 -158
- package/node_modules/parseurl/package.json +0 -40
- package/node_modules/progrok/LICENSE +0 -21
- package/node_modules/progrok/README.md +0 -331
- package/node_modules/progrok/THIRD_PARTY_NOTICES.md +0 -13
- package/node_modules/progrok/dist/index.js +0 -1626
- package/node_modules/progrok/dist/index.js.map +0 -1
- package/node_modules/progrok/dist/public/app.js +0 -529
- package/node_modules/progrok/dist/public/index.html +0 -47
- package/node_modules/progrok/dist/public/style.css +0 -392
- package/node_modules/progrok/node_modules/accepts/HISTORY.md +0 -243
- package/node_modules/progrok/node_modules/accepts/LICENSE +0 -23
- package/node_modules/progrok/node_modules/accepts/README.md +0 -140
- package/node_modules/progrok/node_modules/accepts/index.js +0 -238
- package/node_modules/progrok/node_modules/accepts/package.json +0 -47
- package/node_modules/progrok/node_modules/body-parser/HISTORY.md +0 -686
- package/node_modules/progrok/node_modules/body-parser/LICENSE +0 -23
- package/node_modules/progrok/node_modules/body-parser/README.md +0 -476
- package/node_modules/progrok/node_modules/body-parser/index.js +0 -156
- package/node_modules/progrok/node_modules/body-parser/lib/read.js +0 -205
- package/node_modules/progrok/node_modules/body-parser/lib/types/json.js +0 -243
- package/node_modules/progrok/node_modules/body-parser/lib/types/raw.js +0 -101
- package/node_modules/progrok/node_modules/body-parser/lib/types/text.js +0 -121
- package/node_modules/progrok/node_modules/body-parser/lib/types/urlencoded.js +0 -299
- package/node_modules/progrok/node_modules/body-parser/package.json +0 -55
- package/node_modules/progrok/node_modules/content-disposition/HISTORY.md +0 -60
- package/node_modules/progrok/node_modules/content-disposition/LICENSE +0 -22
- package/node_modules/progrok/node_modules/content-disposition/README.md +0 -142
- package/node_modules/progrok/node_modules/content-disposition/index.js +0 -458
- package/node_modules/progrok/node_modules/content-disposition/package.json +0 -44
- package/node_modules/progrok/node_modules/cookie-signature/History.md +0 -42
- package/node_modules/progrok/node_modules/cookie-signature/Readme.md +0 -42
- package/node_modules/progrok/node_modules/cookie-signature/index.js +0 -51
- package/node_modules/progrok/node_modules/cookie-signature/package.json +0 -18
- package/node_modules/progrok/node_modules/debug/.coveralls.yml +0 -1
- package/node_modules/progrok/node_modules/debug/.eslintrc +0 -11
- package/node_modules/progrok/node_modules/debug/.npmignore +0 -9
- package/node_modules/progrok/node_modules/debug/.travis.yml +0 -14
- package/node_modules/progrok/node_modules/debug/CHANGELOG.md +0 -362
- package/node_modules/progrok/node_modules/debug/LICENSE +0 -19
- package/node_modules/progrok/node_modules/debug/Makefile +0 -50
- package/node_modules/progrok/node_modules/debug/README.md +0 -312
- package/node_modules/progrok/node_modules/debug/component.json +0 -19
- package/node_modules/progrok/node_modules/debug/karma.conf.js +0 -70
- package/node_modules/progrok/node_modules/debug/node.js +0 -1
- package/node_modules/progrok/node_modules/debug/node_modules/ms/index.js +0 -152
- package/node_modules/progrok/node_modules/debug/node_modules/ms/license.md +0 -21
- package/node_modules/progrok/node_modules/debug/node_modules/ms/package.json +0 -37
- package/node_modules/progrok/node_modules/debug/node_modules/ms/readme.md +0 -51
- package/node_modules/progrok/node_modules/debug/package.json +0 -49
- package/node_modules/progrok/node_modules/debug/src/browser.js +0 -185
- package/node_modules/progrok/node_modules/debug/src/debug.js +0 -202
- package/node_modules/progrok/node_modules/debug/src/index.js +0 -10
- package/node_modules/progrok/node_modules/debug/src/inspector-log.js +0 -15
- package/node_modules/progrok/node_modules/debug/src/node.js +0 -248
- package/node_modules/progrok/node_modules/express/History.md +0 -3676
- package/node_modules/progrok/node_modules/express/LICENSE +0 -24
- package/node_modules/progrok/node_modules/express/Readme.md +0 -260
- package/node_modules/progrok/node_modules/express/index.js +0 -11
- package/node_modules/progrok/node_modules/express/lib/application.js +0 -661
- package/node_modules/progrok/node_modules/express/lib/express.js +0 -116
- package/node_modules/progrok/node_modules/express/lib/middleware/init.js +0 -43
- package/node_modules/progrok/node_modules/express/lib/middleware/query.js +0 -47
- package/node_modules/progrok/node_modules/express/lib/request.js +0 -525
- package/node_modules/progrok/node_modules/express/lib/response.js +0 -1179
- package/node_modules/progrok/node_modules/express/lib/router/index.js +0 -673
- package/node_modules/progrok/node_modules/express/lib/router/layer.js +0 -181
- package/node_modules/progrok/node_modules/express/lib/router/route.js +0 -230
- package/node_modules/progrok/node_modules/express/lib/utils.js +0 -304
- package/node_modules/progrok/node_modules/express/lib/view.js +0 -182
- package/node_modules/progrok/node_modules/express/package.json +0 -102
- package/node_modules/progrok/node_modules/finalhandler/HISTORY.md +0 -216
- package/node_modules/progrok/node_modules/finalhandler/LICENSE +0 -22
- package/node_modules/progrok/node_modules/finalhandler/README.md +0 -147
- package/node_modules/progrok/node_modules/finalhandler/SECURITY.md +0 -25
- package/node_modules/progrok/node_modules/finalhandler/index.js +0 -341
- package/node_modules/progrok/node_modules/finalhandler/package.json +0 -47
- package/node_modules/progrok/node_modules/fresh/HISTORY.md +0 -70
- package/node_modules/progrok/node_modules/fresh/LICENSE +0 -23
- package/node_modules/progrok/node_modules/fresh/README.md +0 -119
- package/node_modules/progrok/node_modules/fresh/index.js +0 -137
- package/node_modules/progrok/node_modules/fresh/package.json +0 -46
- package/node_modules/progrok/node_modules/iconv-lite/Changelog.md +0 -162
- package/node_modules/progrok/node_modules/iconv-lite/LICENSE +0 -21
- package/node_modules/progrok/node_modules/iconv-lite/README.md +0 -156
- package/node_modules/progrok/node_modules/iconv-lite/encodings/dbcs-codec.js +0 -555
- package/node_modules/progrok/node_modules/iconv-lite/encodings/dbcs-data.js +0 -176
- package/node_modules/progrok/node_modules/iconv-lite/encodings/index.js +0 -22
- package/node_modules/progrok/node_modules/iconv-lite/encodings/internal.js +0 -188
- package/node_modules/progrok/node_modules/iconv-lite/encodings/sbcs-codec.js +0 -72
- package/node_modules/progrok/node_modules/iconv-lite/encodings/sbcs-data-generated.js +0 -451
- package/node_modules/progrok/node_modules/iconv-lite/encodings/sbcs-data.js +0 -174
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/big5-added.json +0 -122
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/cp936.json +0 -264
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/cp949.json +0 -273
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/cp950.json +0 -177
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/eucjp.json +0 -182
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/gb18030-ranges.json +0 -1
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/gbk-added.json +0 -55
- package/node_modules/progrok/node_modules/iconv-lite/encodings/tables/shiftjis.json +0 -125
- package/node_modules/progrok/node_modules/iconv-lite/encodings/utf16.js +0 -177
- package/node_modules/progrok/node_modules/iconv-lite/encodings/utf7.js +0 -290
- package/node_modules/progrok/node_modules/iconv-lite/lib/bom-handling.js +0 -52
- package/node_modules/progrok/node_modules/iconv-lite/lib/extend-node.js +0 -217
- package/node_modules/progrok/node_modules/iconv-lite/lib/index.d.ts +0 -24
- package/node_modules/progrok/node_modules/iconv-lite/lib/index.js +0 -153
- package/node_modules/progrok/node_modules/iconv-lite/lib/streams.js +0 -121
- package/node_modules/progrok/node_modules/iconv-lite/package.json +0 -46
- package/node_modules/progrok/node_modules/media-typer/HISTORY.md +0 -22
- package/node_modules/progrok/node_modules/media-typer/LICENSE +0 -22
- package/node_modules/progrok/node_modules/media-typer/README.md +0 -81
- package/node_modules/progrok/node_modules/media-typer/index.js +0 -270
- package/node_modules/progrok/node_modules/media-typer/package.json +0 -26
- package/node_modules/progrok/node_modules/merge-descriptors/HISTORY.md +0 -21
- package/node_modules/progrok/node_modules/merge-descriptors/LICENSE +0 -23
- package/node_modules/progrok/node_modules/merge-descriptors/README.md +0 -49
- package/node_modules/progrok/node_modules/merge-descriptors/index.js +0 -60
- package/node_modules/progrok/node_modules/merge-descriptors/package.json +0 -39
- package/node_modules/progrok/node_modules/mime-db/HISTORY.md +0 -507
- package/node_modules/progrok/node_modules/mime-db/LICENSE +0 -23
- package/node_modules/progrok/node_modules/mime-db/README.md +0 -100
- package/node_modules/progrok/node_modules/mime-db/db.json +0 -8519
- package/node_modules/progrok/node_modules/mime-db/index.js +0 -12
- package/node_modules/progrok/node_modules/mime-db/package.json +0 -60
- package/node_modules/progrok/node_modules/mime-types/HISTORY.md +0 -397
- package/node_modules/progrok/node_modules/mime-types/LICENSE +0 -23
- package/node_modules/progrok/node_modules/mime-types/README.md +0 -113
- package/node_modules/progrok/node_modules/mime-types/index.js +0 -188
- package/node_modules/progrok/node_modules/mime-types/package.json +0 -44
- package/node_modules/progrok/node_modules/negotiator/HISTORY.md +0 -108
- package/node_modules/progrok/node_modules/negotiator/LICENSE +0 -24
- package/node_modules/progrok/node_modules/negotiator/README.md +0 -203
- package/node_modules/progrok/node_modules/negotiator/index.js +0 -82
- package/node_modules/progrok/node_modules/negotiator/lib/charset.js +0 -169
- package/node_modules/progrok/node_modules/negotiator/lib/encoding.js +0 -184
- package/node_modules/progrok/node_modules/negotiator/lib/language.js +0 -179
- package/node_modules/progrok/node_modules/negotiator/lib/mediaType.js +0 -294
- package/node_modules/progrok/node_modules/negotiator/package.json +0 -42
- package/node_modules/progrok/node_modules/path-to-regexp/LICENSE +0 -21
- package/node_modules/progrok/node_modules/path-to-regexp/Readme.md +0 -35
- package/node_modules/progrok/node_modules/path-to-regexp/index.js +0 -158
- package/node_modules/progrok/node_modules/path-to-regexp/package.json +0 -30
- package/node_modules/progrok/node_modules/raw-body/LICENSE +0 -22
- package/node_modules/progrok/node_modules/raw-body/README.md +0 -223
- package/node_modules/progrok/node_modules/raw-body/index.d.ts +0 -87
- package/node_modules/progrok/node_modules/raw-body/index.js +0 -336
- package/node_modules/progrok/node_modules/raw-body/package.json +0 -47
- package/node_modules/progrok/node_modules/send/HISTORY.md +0 -538
- package/node_modules/progrok/node_modules/send/LICENSE +0 -23
- package/node_modules/progrok/node_modules/send/README.md +0 -327
- package/node_modules/progrok/node_modules/send/SECURITY.md +0 -24
- package/node_modules/progrok/node_modules/send/index.js +0 -1142
- package/node_modules/progrok/node_modules/send/package.json +0 -62
- package/node_modules/progrok/node_modules/serve-static/HISTORY.md +0 -493
- package/node_modules/progrok/node_modules/serve-static/LICENSE +0 -25
- package/node_modules/progrok/node_modules/serve-static/README.md +0 -257
- package/node_modules/progrok/node_modules/serve-static/index.js +0 -209
- package/node_modules/progrok/node_modules/serve-static/package.json +0 -42
- package/node_modules/progrok/node_modules/type-is/HISTORY.md +0 -259
- package/node_modules/progrok/node_modules/type-is/LICENSE +0 -23
- package/node_modules/progrok/node_modules/type-is/README.md +0 -170
- package/node_modules/progrok/node_modules/type-is/index.js +0 -266
- package/node_modules/progrok/node_modules/type-is/package.json +0 -45
- package/node_modules/progrok/package.json +0 -52
- package/node_modules/progrok/skills/progrok/SKILL.md +0 -293
- package/node_modules/proxy-addr/HISTORY.md +0 -161
- package/node_modules/proxy-addr/LICENSE +0 -22
- package/node_modules/proxy-addr/README.md +0 -139
- package/node_modules/proxy-addr/index.js +0 -327
- package/node_modules/proxy-addr/package.json +0 -47
- package/node_modules/qs/.editorconfig +0 -46
- package/node_modules/qs/.github/FUNDING.yml +0 -12
- package/node_modules/qs/.github/SECURITY.md +0 -11
- package/node_modules/qs/.github/THREAT_MODEL.md +0 -78
- package/node_modules/qs/.nycrc +0 -13
- package/node_modules/qs/CHANGELOG.md +0 -822
- package/node_modules/qs/LICENSE.md +0 -29
- package/node_modules/qs/README.md +0 -758
- package/node_modules/qs/dist/qs.js +0 -141
- package/node_modules/qs/eslint.config.mjs +0 -57
- package/node_modules/qs/lib/formats.js +0 -23
- package/node_modules/qs/lib/index.js +0 -11
- package/node_modules/qs/lib/parse.js +0 -403
- package/node_modules/qs/lib/stringify.js +0 -363
- package/node_modules/qs/lib/utils.js +0 -342
- package/node_modules/qs/package.json +0 -94
- package/node_modules/qs/test/empty-keys-cases.js +0 -267
- package/node_modules/qs/test/parse.js +0 -1703
- package/node_modules/qs/test/stringify.js +0 -1448
- package/node_modules/qs/test/utils.js +0 -432
- package/node_modules/range-parser/HISTORY.md +0 -56
- package/node_modules/range-parser/LICENSE +0 -23
- package/node_modules/range-parser/README.md +0 -84
- package/node_modules/range-parser/index.js +0 -162
- package/node_modules/range-parser/package.json +0 -44
- package/node_modules/run-applescript/index.d.ts +0 -66
- package/node_modules/run-applescript/index.js +0 -37
- package/node_modules/run-applescript/license +0 -9
- package/node_modules/run-applescript/package.json +0 -42
- package/node_modules/run-applescript/readme.md +0 -78
- package/node_modules/safe-buffer/LICENSE +0 -21
- package/node_modules/safe-buffer/README.md +0 -584
- package/node_modules/safe-buffer/index.d.ts +0 -187
- package/node_modules/safe-buffer/index.js +0 -65
- package/node_modules/safe-buffer/package.json +0 -51
- package/node_modules/safer-buffer/LICENSE +0 -21
- package/node_modules/safer-buffer/Porting-Buffer.md +0 -268
- package/node_modules/safer-buffer/Readme.md +0 -156
- package/node_modules/safer-buffer/dangerous.js +0 -58
- package/node_modules/safer-buffer/package.json +0 -34
- package/node_modules/safer-buffer/safer.js +0 -77
- package/node_modules/safer-buffer/tests.js +0 -406
- package/node_modules/setprototypeof/LICENSE +0 -13
- package/node_modules/setprototypeof/README.md +0 -31
- package/node_modules/setprototypeof/index.d.ts +0 -2
- package/node_modules/setprototypeof/index.js +0 -17
- package/node_modules/setprototypeof/package.json +0 -38
- package/node_modules/setprototypeof/test/index.js +0 -24
- package/node_modules/side-channel/.editorconfig +0 -9
- package/node_modules/side-channel/.eslintrc +0 -12
- package/node_modules/side-channel/.github/FUNDING.yml +0 -12
- package/node_modules/side-channel/.nycrc +0 -13
- package/node_modules/side-channel/CHANGELOG.md +0 -110
- package/node_modules/side-channel/LICENSE +0 -21
- package/node_modules/side-channel/README.md +0 -61
- package/node_modules/side-channel/index.d.ts +0 -14
- package/node_modules/side-channel/index.js +0 -43
- package/node_modules/side-channel/package.json +0 -85
- package/node_modules/side-channel/test/index.js +0 -104
- package/node_modules/side-channel/tsconfig.json +0 -9
- package/node_modules/side-channel-list/.editorconfig +0 -9
- package/node_modules/side-channel-list/.eslintrc +0 -11
- package/node_modules/side-channel-list/.github/FUNDING.yml +0 -12
- package/node_modules/side-channel-list/.nycrc +0 -13
- package/node_modules/side-channel-list/CHANGELOG.md +0 -36
- package/node_modules/side-channel-list/LICENSE +0 -21
- package/node_modules/side-channel-list/README.md +0 -62
- package/node_modules/side-channel-list/index.d.ts +0 -13
- package/node_modules/side-channel-list/index.js +0 -111
- package/node_modules/side-channel-list/list.d.ts +0 -14
- package/node_modules/side-channel-list/package.json +0 -77
- package/node_modules/side-channel-list/test/index.js +0 -154
- package/node_modules/side-channel-list/tsconfig.json +0 -9
- package/node_modules/side-channel-map/.editorconfig +0 -9
- package/node_modules/side-channel-map/.eslintrc +0 -11
- package/node_modules/side-channel-map/.github/FUNDING.yml +0 -12
- package/node_modules/side-channel-map/.nycrc +0 -13
- package/node_modules/side-channel-map/CHANGELOG.md +0 -22
- package/node_modules/side-channel-map/LICENSE +0 -21
- package/node_modules/side-channel-map/README.md +0 -62
- package/node_modules/side-channel-map/index.d.ts +0 -15
- package/node_modules/side-channel-map/index.js +0 -68
- package/node_modules/side-channel-map/package.json +0 -80
- package/node_modules/side-channel-map/test/index.js +0 -114
- package/node_modules/side-channel-map/tsconfig.json +0 -9
- package/node_modules/side-channel-weakmap/.editorconfig +0 -9
- package/node_modules/side-channel-weakmap/.eslintrc +0 -12
- package/node_modules/side-channel-weakmap/.github/FUNDING.yml +0 -12
- package/node_modules/side-channel-weakmap/.nycrc +0 -13
- package/node_modules/side-channel-weakmap/CHANGELOG.md +0 -28
- package/node_modules/side-channel-weakmap/LICENSE +0 -21
- package/node_modules/side-channel-weakmap/README.md +0 -62
- package/node_modules/side-channel-weakmap/index.d.ts +0 -15
- package/node_modules/side-channel-weakmap/index.js +0 -84
- package/node_modules/side-channel-weakmap/package.json +0 -87
- package/node_modules/side-channel-weakmap/test/index.js +0 -114
- package/node_modules/side-channel-weakmap/tsconfig.json +0 -9
- package/node_modules/statuses/HISTORY.md +0 -87
- package/node_modules/statuses/LICENSE +0 -23
- package/node_modules/statuses/README.md +0 -139
- package/node_modules/statuses/codes.json +0 -65
- package/node_modules/statuses/index.js +0 -146
- package/node_modules/statuses/package.json +0 -49
- package/node_modules/toidentifier/HISTORY.md +0 -9
- package/node_modules/toidentifier/LICENSE +0 -21
- package/node_modules/toidentifier/README.md +0 -61
- package/node_modules/toidentifier/index.js +0 -32
- package/node_modules/toidentifier/package.json +0 -38
- package/node_modules/unpipe/HISTORY.md +0 -4
- package/node_modules/unpipe/LICENSE +0 -22
- package/node_modules/unpipe/README.md +0 -43
- package/node_modules/unpipe/index.js +0 -69
- package/node_modules/unpipe/package.json +0 -27
- package/node_modules/utils-merge/.npmignore +0 -9
- package/node_modules/utils-merge/LICENSE +0 -20
- package/node_modules/utils-merge/README.md +0 -34
- package/node_modules/utils-merge/index.js +0 -23
- package/node_modules/utils-merge/package.json +0 -40
- package/node_modules/vary/HISTORY.md +0 -39
- package/node_modules/vary/LICENSE +0 -22
- package/node_modules/vary/README.md +0 -101
- package/node_modules/vary/index.js +0 -149
- package/node_modules/vary/package.json +0 -43
- package/ui/dist/assets/index-DYtUJ4t0.js +0 -22
- package/ui/dist/assets/useAgentDialogFocus-B2snKbzK.js +0 -1
- package/vendor/progrok-0.2.0.tgz +0 -0
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{R as un,i as de,c as Ye,r as Ai,g as ge,a as wd,b as _d,L as _t,z as Ed,d as Nd,e as kd,k as Cd,f as v,s as jd,l as Ad,j as o,h as Pd,_ as Me}from"./index-DYtUJ4t0.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},Rd=(e=>e?oa(e):oa),Td=e=>e;function Md(e,t=Td){const n=un.useSyncExternalStore(e.subscribe,un.useCallback(()=>t(e.getState()),[e,t]),un.useCallback(()=>t(e.getInitialState()),[e,t]));return un.useDebugValue(n),n}const aa=e=>{const t=Rd(e),n=r=>Md(t,r);return Object.assign(n,t),n},Pi=(e=>e?aa(e):aa);async function Ee(e,t){const n=ge();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&&de())throw Ye(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"){Ai(n);try{await s.body?.cancel()}catch{}throw Ye(n)}}return s}async function q(e,t){const n=await Ee(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 Ri(e,t){t?.throwIfAborted();const n=await Ee(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 sn=null;function Ti(){if(!sn){const e=localStorage.getItem("ima2.browserId");e?sn=e:(sn=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",sn))}return sn}function Wt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Ti()};return q(e,{...t,headers:n})}function Mi(){return q("/api/capabilities")}function Li(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 q(`/api/inflight${n}`)}function Ce(e){return q(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function Ld(){return q("/api/oauth/status")}function Od(){return q("/api/billing")}const Fd=5400*1e3,Dd=2e3,ia=3e4;let ye=null,Sr="";const Ms=new Set;let Ls=null,We=null,la=!1,fr=0,wr=0,ca=!1;const Gd=3;let eo=null;const zd=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function qd(){return Sr?`/api/events?lastEventId=${encodeURIComponent(Sr)}`:"/api/events"}function $d(){wr+=1;const e=ye;ye=null,e?.close(),We&&(clearTimeout(We),We=null)}function Ud(){ca||typeof window>"u"||(window.addEventListener(_t,$d),ca=!0)}function da(e,t){if(e!==wr||t!==ge()||de()||ye)return;const n=Math.min(Dd*Math.pow(1.5,fr),ia),r=Math.min(n*(.8+Math.random()*.4),ia);fr+=1,We=setTimeout(to,r),eo?.(fr>=Gd?"failed":"reconnecting")}function to(){if(Ud(),de()||ye&&ye.readyState!==EventSource.CLOSED)return;wr+=1;const e=new EventSource(qd());ye=e,We&&(clearTimeout(We),We=null),e.onopen=()=>{if(ye!==e)return;We&&(clearTimeout(We),We=null),fr=0;const t=la;la=!0,t&&Ls?.(),ye===e&&eo?.("connected")};for(const t of zd)e.addEventListener(t,n=>{ye!==e||typeof n.data!="string"||Hd(t,n)});e.addEventListener("replay-gap",()=>{ye===e&&(Sr="",Ls?.())}),e.onerror=t=>{if(ye!==e||typeof t.data=="string")return;ye=null,e.close();const n=++wr,r=ge();if(wd()?.mode==="lan"){const s=()=>da(n,r);_d().then(s,s)}else da(n,r)}}function Hd(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 jt(e,t,n){const r={jobId:e,event:t,handler:n};return Ms.add(r),(!ye||ye.readyState===EventSource.CLOSED)&&to(),()=>{Ms.delete(r)}}function Jt(e,t=Fd){const n=setTimeout(e,t);return()=>clearTimeout(n)}function ua(e){Ls=e}function ma(e){eo=e}function At(){(!ye||ye.readyState===EventSource.CLOSED)&&to()}function no(e=1e4){const t=ge();return de()?Promise.reject(Ye(t-1)):(At(),ye&&ye.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const s=Date.now(),a=()=>{if(t!==ge()||de()){r(Ye(t));return}if(ye&&ye.readyState===EventSource.OPEN){n();return}if(Date.now()-s>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const Vd=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],Kd={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 Bd(e){return typeof e=="string"&&Vd.includes(e)}function pa(e){if(typeof e=="string")return Kd[e]}const Oi="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Be={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 Wd=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function Jd(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 st(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:Be.LAN_TOKEN_REQUIRED,message:Ye().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=s&&s in Be?s:a&&a in Be?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Be.JOB_TRACKING_TIMEOUT,message:Oi};const c=Bd(i)?pa(i):void 0,d=l?Wd.includes(l):!1,u=pa(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=Be[l]):u?(p=fa(r),m=u):(p=fa(r),m=Be[p]??Be.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||Jd(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 Yd(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function Ze(e,t="Generation failed"){const n=e.error;let r=t,s,a,i,l;const c=Yd(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=st({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 Xd(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 Zd(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=ge();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!==ge())throw Ye(a);if(de())throw Ye(a-1);const c=await Ee(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(Zd(c,d)){await l(Xd(c.headers.get("Retry-After")));continue}throw s(c,d)}}async function Fi(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return At(),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=jt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>s(Ze(m,"Generation failed"))))}),u=Jt(()=>{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=Ze(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 Qd(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return At(),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=jt(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(Ze(h,"Multimode generation failed"))))}),p=Jt(()=>{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 rw(e){return q("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function eu(e){const t=await e.arrayBuffer(),n=await Ee("/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 sw(e){return q("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ow(){return q("/api/prompt-builder/config")}function aw(e){return q("/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 At(),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=jt(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(Ze(h,"Video generation failed"))))}),p=Jt(()=>{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 Yt(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"),Wt(`/api/history?${t.toString()}`)}function tu(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),Wt(`/api/history?${t.toString()}`)}function nu(e){return Wt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function ru(){return(await q("/api/storage/status")).data}function su(){return q("/api/storage/open-generated-dir",{method:"POST"})}function Di(e){return q(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function ou(e){return q(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function au(e,t){return q(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function iu(e){return q("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function lu(){return q("/api/sessions")}function cu(e){return q("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function Gi(e){return q(`/api/sessions/${encodeURIComponent(e)}`)}function du(e,t){return q(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function uu(e){return q(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function mu(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),q(`/api/sessions/${encodeURIComponent(e)}/graph`,{method:"PUT",headers:a,body:JSON.stringify({nodes:n,edges:r})})}function pu(e){return q("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function iw(e){return Wt(`/api/annotations/${encodeURIComponent(e)}`)}async function lw(e,t){await Wt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function cw(e){await Wt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function dw(e){const t=new URLSearchParams({sourceFilename:e.sourceFilename});return q(`/api/canvas-versions?${t.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e.image})}function uw(e,t){const n=new URLSearchParams;t.sourceFilename&&n.set("sourceFilename",t.sourceFilename);const r=n.size>0?`?${n.toString()}`:"";return q(`/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 mw(e,t,n){return q(`/api/canvas-versions/${encodeURIComponent(e)}/annotation-bake`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshot:t,annotationOnly:n})})}function pw(e){return q(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function fu(e){const t=new URLSearchParams;return q(`/api/prompts?${t.toString()}`)}function hu(e){return q("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function gu(e){return q(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function yu(e){return q(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function vu(e){return q("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function fw(e){return q("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function hw(e){return q("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function gw(){return q("/api/prompts/import/curated-sources")}function yw(e){return q("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function vw(e){return q("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function bw(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return q(`/api/prompts/import/discovery${n}`)}function xw(e){return q("/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 Iw(e){return q("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Sw(e){return q("/api/prompts/import/folder-files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input}})})}function ww(e){return q("/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 q(`/api/assets${n?`?${n}`:""}`)}function bu(e){return q(`/api/assets/${encodeURIComponent(e)}`)}function $r(e){return q("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function _w(e){return q("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function zi(e,t){return q(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Ew(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 Ee(`/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 xu(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 Ee(`/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 Nw(e){return q("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function Iu(e){return q(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function oo(){return q("/api/assets/folders")}function Su(e){return q("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function qi(e,t){return q(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function wu(e){return q(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ao(){return q("/api/assets/tags")}function kw(){return q("/api/assets/all",{method:"DELETE"})}async function _u(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return At(),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=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(Ze(h,"Node generation failed"))))}),p=Jt(()=>{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"],Eu=new Set(io);function Pt(e){return typeof e=="string"&&Eu.has(e)}const An={oauth:{image:["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-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-imagine-video-1.5-2026-05-30"]},"grok-api":{image:["grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality"],video:["grok-imagine-video","grok-imagine-video-1.5","grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]},agy:{image:["nano-banana-2","nano-banana-pro"],video:[]},"gemini-api":{image:["nano-banana-2","nano-banana-pro"],video:[]},atlascloud:{image:["openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit"],video:[]},minimax:{image:["image-01","image-01-live"],video:[]},nai:{image:["nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],video:[]},comfy:{image:[],video:[]}},Nu=["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"],$i={oauth:{},api:{},grok:{image:5,edit:5,video:14},"grok-api":{image:5,edit:5,video:14},agy:{image:3,edit:3},"gemini-api":{image:3,edit:3},atlascloud:{image:10,edit:10},minimax:{image:1,edit:1},nai:{},comfy:{image:4,edit:4}},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",Qe=[{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(An["gemini-api"].image),co=new Set(An.atlascloud.image),uo=new Set(An.minimax.image),mo=new Set(An.nai.image),ku=Qe.filter(e=>!e.value.startsWith("grok-")&&!Ur.has(e.value)&&!co.has(e.value)&&!uo.has(e.value)&&!mo.has(e.value)),Cu=Qe.filter(e=>e.value.startsWith("grok-")),ju=Qe.filter(e=>Ur.has(e.value)),Au=Qe.filter(e=>co.has(e.value)),Pu=Qe.filter(e=>uo.has(e.value)),Ui=Qe.filter(e=>mo.has(e.value)),Cw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Ru(e){return Qe.some(t=>t.value===e)}function Tu(e){return typeof e=="string"&&e.startsWith("grok-")}function Mu(e){return typeof e=="string"&&Ur.has(e)}function Lu(e){return e==="grok"||e==="grok-api"?Cu:e==="agy"||e==="gemini-api"?ju:e==="atlascloud"?Au:e==="minimax"?Pu:e==="nai"?Ui:e==="comfy"?[]:ku}function Hi(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)?Qe.find(n=>n.value===e)?.shortLabel??e:Qe.find(n=>n.value===e)?.shortLabel??e:null}const po="grok-imagine-video",et="grok-imagine-video-1.5",Vi="grok-imagine-video-1.5-preview",Ki="grok-imagine-video-1.5-2026-05-30",Ou=15,Fu=10,ya=15,Du=[{value:po,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:et,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Gu(e){return e===po||e===et||e===Vi||e===Ki}function Rt(e){return Gu(e)?e===Vi||e===Ki?et:e:!1}function va(e,t){if(t!=="reference-to-video")return ya;const n=Rt(e);return n?n===et?Ou:Fu:ya}function zu(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===et&&(n==="text-to-video"||n==="image-to-video")}const Ht="comfy-video:",Bi="video:";function qu(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Ht}${a}`:s??"":(t==="grok"||t==="grok-api")&&r?`${Bi}${r}`:n}const Os=new Set(Nu),$u={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"&&Os.has(t)&&An[e].image.includes(t)}function hn(e){return typeof e=="string"&&e.trim().length>0?e:null}function Wi(e,t){if(Rt(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Hr(n,e))return n;return"oauth"}function lt(e){const t=Pt(e.provider)?e.provider:Wi(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=hn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Os.has(e.imageModel)?e.imageModel:hr,videoModelSelected:!1,comfyWorkflow:hn(e.comfyWorkflow)??(n&&!Os.has(n)?n:null),comfyVideoWorkflow:hn(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Hr(t,e.imageModel)?e.imageModel:$u[t],videoModelSelected:t==="grok"||t==="grok-api"?Rt(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Uu(e,t){return Pt(e)&&Hr(e,t)?e:Wi(t,!1)}function Hu(e,t,n){return e.provider===t?e:lt(n?t==="comfy"?{provider:t,imageModel:e.imageModel,comfyWorkflow:n.image,comfyVideoWorkflow:n.kind==="video"?n.video:null}:{provider:t,imageModel:n.image,videoModelSelected:n.kind==="video"?n.video:!1}:{provider:t,imageModel:e.imageModel})}function ba(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 Ji(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Fs(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"?hn(s.image):Hr(n,s.image)?s.image:null,i=n==="comfy"?hn(s.video):n==="grok"||n==="grok-api"?Rt(s.video):!1;t[n]={kind:s.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Vu="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 Yi(e){return Ds.some(t=>t.value===e)}const Ku={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Bu(e){return!Yi(e)||e==="none"?null:`R:${Ku[e]}`}const Ne=["ima2.rightPanelOpen","ima2.uiMode","ima2.historyStripLayout","ima2.canvas.exportBackground.v1","ima2.imageModel","ima2.reasoningEffort","ima2.webSearchEnabled","ima2.generationDefaults","ima2.inFlight","ima2.selectedFilename","ima2.activeSessionId","ima2.graphTabId","ima2.galleryScope","ima2.galleryDefaultScope","ima2.locale","ima2.workspaceProfile","ima2.workspaceOverrides","ima2.videoDefaults","ima2.agentPanePreference","ima2.naiOptions","ima2.coreSelectionMemory.v1"],Xi=Ne[0],Zi=Ne[1],Qi=Ne[2],el=Ne[3],fo=Ne[4],tl=Ne[5],nl=Ne[6],ho=Ne[7],rl=Ne[8],Gs=Ne[9],zs=Ne[10],xa=Ne[11],go=Ne[12],sl=Ne[13],yo=Ne[17],ol=Ne[19],al=Ne[20],Wu=!0,Ju=!1,Xt=!0,il=Ju,Zt=!0,Yu=24;function qs(e){return Math.min(Yu,Math.max(1,Math.trunc(e||1)))}const Ia={ko:Cd,en:kd,"zh-Hant":Nd,"zh-Hans":Ed};function Sa(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function Xu(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function L(e,t){const n=f.getState().locale;return ll(n,e,t)}function ll(e,t,n){const r=Sa(Ia[e],t),s=typeof r=="string"?r:Sa(Ia.en,t),a=typeof s=="string"?s:t;return n?Xu(a,n):a}function H(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>ll(e,t,n)}}function Zu(e){return Math.round(e/16)*16}const St=16,vo=3840,ls=655360,gr=8294400,Qu=3,Gt=3,wa=Math.floor(Math.sqrt(gr)/St)*St,cl=St,em=vo,Vn=Qu;function _a(e){return Math.floor(e/16)*16}function _r(e){return Math.ceil(e/16)*16}function Ge(e){return Math.min(em,Math.max(cl,e))}function tt(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function Et(e,t){e.includes(t)||e.push(t)}function Ea(e,t){const n=Zu(e);return n!==e&&Et(t,"snap"),n}function Na(e,t){return e<cl&&Et(t,"min"),e>vo&&Et(t,"maxEdge"),Ge(e)}function ka(e,t,n){return e>t*Vn?(Et(n,"ratio"),{w:e,h:Ge(_r(e/Vn))}):t>e*Vn?(Et(n,"ratio"),{w:Ge(_r(t/Vn)),h:t}):{w:e,h:t}}function tm(e,t,n){if(e*t<ls){Et(n,"minPixels");const i=Math.sqrt(ls/(e*t));let l=Ge(_r(e*i)),c=Ge(_r(t*i));for(;l*c<ls;)l<=c?l=Ge(l+St):c=Ge(c+St);return{w:l,h:c}}if(e*t<=gr)return{w:e,h:t};Et(n,"maxPixels");const r=Math.sqrt(gr/(e*t));let s=Ge(_a(e*r)),a=Ge(_a(t*r));for(;s*a>gr;)s>=a?s=Ge(s-St):a=Ge(a-St);return{w:s,h:a}}function bo(e,t,n,r){const s=[],a=tt(e,n),i=tt(t,r);let l=Na(Ea(a,s),s),c=Na(Ea(i,s),s);return{w:l,h:c}=ka(l,c,s),{w:l,h:c}=tm(l,c,s),{w:l,h:c}=ka(l,c,s),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:s}}function dl(e,t,n,r){const s=bo(e,t,n,r);return{w:s.w,h:s.h}}const nm=[{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 rm(e,t){return`${e}x${t}`}function sm(e,t=1024){if(e.id==="free")return null;const n=t,r=e.w>=e.h,s=r?Math.round(n*e.w/e.h):n,a=r?n:Math.round(n*e.h/e.w);return dl(s,a,s,a)}function Vr(e){const t=dl(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function zt(e){return e.slice(0,Gt).map(Vr)}function om(e,t){const n=Vr(t),r=e.findIndex(s=>s.id===n.id);return r>=0?zt(e.map((s,a)=>a===r?n:s)):e.length>=Gt?zt(e):zt([...e,n])}function am(e,t,n){const r=Vr({...n,id:t});return zt(e.map(s=>s.id===t?r:s))}const im=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],lm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],cm=[{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"}],dm=[{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 um(){return[{value:"auto",label:L("size.autoLabel"),sub:L("size.autoSub")},{value:"custom",label:L("size.customLabel"),sub:L("size.customSub")}]}const ul=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],ml=["native","karras","exponential","polyexponential"],pl=["heavy","light","furryFocus","humanFocus","none"],fl=["standard","light","none"],mm={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},hl=2**32-1;function pm(e,t){return{...mm,...e??{},...t}}function $s(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Kn(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 gl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Kn(t.sampler,ul);r!==void 0&&(n.sampler=r);const s=Kn(t.noiseSchedule,ml);s!==void 0&&(n.noiseSchedule=s);const a=Kn(t.ucPresetId,pl);a!==void 0&&(n.ucPresetId=a);const i=Kn(t.qualityPresetId,fl);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<=hl&&(n.seed=t.seed),n}function $e(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Us="vid:",Hs="img:",fm=/^[\p{L}\p{N}_-]{1,32}$/u;function xo(e){return fm.test(e)}function hm(e){return e.references.some(t=>t.tag!==void 0&&!xo(t.tag))}function yl(e){return e==="video"?"video":"image"}function Kr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function gm(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)&&gm(r)))}function Ca(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 vl(e,t,n){const r=Kr(t),s=Br(n),a={};for(const i of e.parameters){const l=s[i.name];l!==void 0&&Ca(i,l)?a[i.name]=l:i.default!==void 0&&Ca(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function ym(e){return e?vl(e,null,{}):{ratio:null,parameters:{}}}function vm(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function bl(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 $e();const t=e,n=Array.isArray(t.references)?t.references.map(bl).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 xl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function bm(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:yl(e.mcpMediaKind),ratio:Kr(e.mcpRatio),parameters:Br(e.mcpParameters)}}function Bn(e,t){return`${e==="video"?Us:Hs}${t}`}function xm(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 Il(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 Im(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const s=yl(e.mcpMediaKind),a=Kr(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(bl).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 Pn(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-CfrOcJIe.js","assets/index-CfGRmfFv.js","assets/index-D0NhOovz.css","assets/PromptLibraryPanel-Qdujpb4L.js","assets/PromptBuilderPanel-BolZnOa7.js","assets/promptBuilderStore-BMiudG9n.js","assets/GenerationRequestLogPanel-CTs8OymS.js","assets/NodeCanvas-D2N3m-1s.js","assets/NodeCanvas-BnuhLJ6X.css","assets/SettingsWorkspace-Dm4wezu_.js","assets/CardNewsWorkspace-CM5hwbRV.js","assets/AgentWorkspace-DlLaTsPK.js","assets/useAgentDialogFocus-CCj5EYE9.js","assets/AssetsWorkspace-BcbAM8uC.js","assets/KeyingPanel-D8ZHmWcC.js","assets/AssetsWorkspace-BdptASFf.css","assets/AssetGenWorkspace-C8eIs-bS.js","assets/AssetGenWorkspace-B7tTK0Sx.css","assets/HomeWorkspace-KGUtIZyG.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as un,i as de,c as Ye,r as Ai,g as ge,a as wd,b as _d,L as _t,z as Ed,d as Nd,e as kd,k as Cd,f as v,s as jd,l as Ad,j as o,h as Pd,_ as Me}from"./index-CfGRmfFv.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},Rd=(e=>e?oa(e):oa),Td=e=>e;function Md(e,t=Td){const n=un.useSyncExternalStore(e.subscribe,un.useCallback(()=>t(e.getState()),[e,t]),un.useCallback(()=>t(e.getInitialState()),[e,t]));return un.useDebugValue(n),n}const aa=e=>{const t=Rd(e),n=r=>Md(t,r);return Object.assign(n,t),n},Pi=(e=>e?aa(e):aa);async function Ee(e,t){const n=ge();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&&de())throw Ye(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"){Ai(n);try{await s.body?.cancel()}catch{}throw Ye(n)}}return s}async function q(e,t){const n=await Ee(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 Ri(e,t){t?.throwIfAborted();const n=await Ee(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 sn=null;function Ti(){if(!sn){const e=localStorage.getItem("ima2.browserId");e?sn=e:(sn=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`,localStorage.setItem("ima2.browserId",sn))}return sn}function Wt(e,t){const n={...t?.headers,"X-Ima2-Browser-Id":Ti()};return q(e,{...t,headers:n})}function Mi(){return q("/api/capabilities")}function Li(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 q(`/api/inflight${n}`)}function Ce(e){return q(`/api/inflight/${encodeURIComponent(e)}`,{method:"DELETE"})}function Ld(){return q("/api/oauth/status")}function Od(){return q("/api/billing")}const Fd=5400*1e3,Dd=2e3,ia=3e4;let ye=null,Sr="";const Ms=new Set;let Ls=null,We=null,la=!1,fr=0,wr=0,ca=!1;const Gd=3;let eo=null;const zd=["phase","partial","image","done","error","submitted","progress","planning","keying-start","keying-progress","keying-done","keying-error"];function qd(){return Sr?`/api/events?lastEventId=${encodeURIComponent(Sr)}`:"/api/events"}function $d(){wr+=1;const e=ye;ye=null,e?.close(),We&&(clearTimeout(We),We=null)}function Ud(){ca||typeof window>"u"||(window.addEventListener(_t,$d),ca=!0)}function da(e,t){if(e!==wr||t!==ge()||de()||ye)return;const n=Math.min(Dd*Math.pow(1.5,fr),ia),r=Math.min(n*(.8+Math.random()*.4),ia);fr+=1,We=setTimeout(to,r),eo?.(fr>=Gd?"failed":"reconnecting")}function to(){if(Ud(),de()||ye&&ye.readyState!==EventSource.CLOSED)return;wr+=1;const e=new EventSource(qd());ye=e,We&&(clearTimeout(We),We=null),e.onopen=()=>{if(ye!==e)return;We&&(clearTimeout(We),We=null),fr=0;const t=la;la=!0,t&&Ls?.(),ye===e&&eo?.("connected")};for(const t of zd)e.addEventListener(t,n=>{ye!==e||typeof n.data!="string"||Hd(t,n)});e.addEventListener("replay-gap",()=>{ye===e&&(Sr="",Ls?.())}),e.onerror=t=>{if(ye!==e||typeof t.data=="string")return;ye=null,e.close();const n=++wr,r=ge();if(wd()?.mode==="lan"){const s=()=>da(n,r);_d().then(s,s)}else da(n,r)}}function Hd(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 jt(e,t,n){const r={jobId:e,event:t,handler:n};return Ms.add(r),(!ye||ye.readyState===EventSource.CLOSED)&&to(),()=>{Ms.delete(r)}}function Jt(e,t=Fd){const n=setTimeout(e,t);return()=>clearTimeout(n)}function ua(e){Ls=e}function ma(e){eo=e}function At(){(!ye||ye.readyState===EventSource.CLOSED)&&to()}function no(e=1e4){const t=ge();return de()?Promise.reject(Ye(t-1)):(At(),ye&&ye.readyState===EventSource.OPEN?Promise.resolve():new Promise((n,r)=>{const s=Date.now(),a=()=>{if(t!==ge()||de()){r(Ye(t));return}if(ye&&ye.readyState===EventSource.OPEN){n();return}if(Date.now()-s>=e){r(new Error("SSE channel open timed out"));return}setTimeout(a,50)};a()}))}const Vd=["BILLING_REQUIRED","AUTH_INVALID","AUTH_EXPIRED"],Kd={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 Bd(e){return typeof e=="string"&&Vd.includes(e)}function pa(e){if(typeof e=="string")return Kd[e]}const Oi="Job tracking expired; upstream completion is unknown. Inspect history before retrying.",Be={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 Wd=["GROK_API_KEY_MISSING","NAI_API_KEY_MISSING","NAI_AUTH_FAILED","NAI_SUBSCRIPTION_REQUIRED","NAI_USAGE_EXHAUSTED"];function Jd(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 st(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:Be.LAN_TOKEN_REQUIRED,message:Ye().message};const a=typeof n.rawCode=="string"?n.rawCode:void 0,i=typeof n.errorClass=="string"?n.errorClass:void 0,l=s&&s in Be?s:a&&a in Be?a:void 0;if(l==="JOB_TRACKING_TIMEOUT"||l==="UNKNOWN"&&a==="JOB_TRACKING_TIMEOUT")return{code:"JOB_TRACKING_TIMEOUT",spec:Be.JOB_TRACKING_TIMEOUT,message:Oi};const c=Bd(i)?pa(i):void 0,d=l?Wd.includes(l):!1,u=pa(i);let p,m;c&&!d?(p=l??"UNKNOWN",m=c):d&&l||l?(p=l,m=Be[l]):u?(p=fa(r),m=u):(p=fa(r),m=Be[p]??Be.UNKNOWN);const h=p==="MODERATION_REFUSED"||p==="SAFETY_REFUSAL"?(typeof n.moderationStage=="string"?n.moderationStage:void 0)||Jd(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 Yd(e){const t=e.envelope;return!t||typeof t!="object"?null:t}function Ze(e,t="Generation failed"){const n=e.error;let r=t,s,a,i,l;const c=Yd(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=st({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 Xd(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 Zd(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=ge();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!==ge())throw Ye(a);if(de())throw Ye(a-1);const c=await Ee(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(Zd(c,d)){await l(Xd(c.headers.get("Retry-After")));continue}throw s(c,d)}}async function Fi(e,t={}){const n=e.requestId??`freq_${crypto.randomUUID()}`;return At(),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=jt(n,null,(p,m)=>{a||(p==="done"?c(()=>r(m)):p==="error"&&c(()=>s(Ze(m,"Generation failed"))))}),u=Jt(()=>{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=Ze(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 Qd(e,t={},n={}){const r=e.requestId??`req_${crypto.randomUUID()}`;return At(),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=jt(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(Ze(h,"Multimode generation failed"))))}),p=Jt(()=>{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 rw(e){return q("/api/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}async function eu(e){const t=await e.arrayBuffer(),n=await Ee("/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 sw(e){return q("/api/prompt-builder/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function ow(){return q("/api/prompt-builder/config")}function aw(e){return q("/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 At(),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=jt(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(Ze(h,"Video generation failed"))))}),p=Jt(()=>{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 Yt(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"),Wt(`/api/history?${t.toString()}`)}function tu(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),Wt(`/api/history?${t.toString()}`)}function nu(e){return Wt("/api/history/favorite",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e})})}async function ru(){return(await q("/api/storage/status")).data}function su(){return q("/api/storage/open-generated-dir",{method:"POST"})}function Di(e){return q(`/api/history/${encodeURIComponent(e)}`,{method:"DELETE"})}function ou(e){return q(`/api/history/${encodeURIComponent(e)}/permanent`,{method:"DELETE"})}function au(e,t){return q(`/api/history/${encodeURIComponent(e)}/restore`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trashId:t})})}function iu(e){return q("/api/comfy/export-image",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filename:e.filename})})}function lu(){return q("/api/sessions")}function cu(e){return q("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:e})})}function Gi(e){return q(`/api/sessions/${encodeURIComponent(e)}`)}function du(e,t){return q(`/api/sessions/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t})})}function uu(e){return q(`/api/sessions/${encodeURIComponent(e)}`,{method:"DELETE"})}function mu(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),q(`/api/sessions/${encodeURIComponent(e)}/graph`,{method:"PUT",headers:a,body:JSON.stringify({nodes:n,edges:r})})}function pu(e){return q("/api/metadata/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function iw(e){return Wt(`/api/annotations/${encodeURIComponent(e)}`)}async function lw(e,t){await Wt(`/api/annotations/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({annotations:t})})}async function cw(e){await Wt(`/api/annotations/${encodeURIComponent(e)}`,{method:"DELETE"})}function dw(e){const t=new URLSearchParams({sourceFilename:e.sourceFilename});return q(`/api/canvas-versions?${t.toString()}`,{method:"POST",headers:{"Content-Type":"image/png"},body:e.image})}function uw(e,t){const n=new URLSearchParams;t.sourceFilename&&n.set("sourceFilename",t.sourceFilename);const r=n.size>0?`?${n.toString()}`:"";return q(`/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 mw(e,t,n){return q(`/api/canvas-versions/${encodeURIComponent(e)}/annotation-bake`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({snapshot:t,annotationOnly:n})})}function pw(e){return q(`/api/canvas-versions/${encodeURIComponent(e)}/revert-annotations`,{method:"POST"})}function fu(e){const t=new URLSearchParams;return q(`/api/prompts?${t.toString()}`)}function hu(e){return q("/api/prompts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function gu(e){return q(`/api/prompts/${encodeURIComponent(e)}`,{method:"DELETE"})}function yu(e){return q(`/api/prompts/${encodeURIComponent(e)}/favorite`,{method:"POST"})}function vu(e){return q("/api/prompts/import",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function fw(e){return q("/api/prompts/import/preview",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function hw(e){return q("/api/prompts/import/commit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function gw(){return q("/api/prompts/import/curated-sources")}function yw(e){return q("/api/prompts/import/curated-search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function vw(e){return q("/api/prompts/import/curated-refresh",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function bw(e){const t=new URLSearchParams,n=t.size>0?`?${t.toString()}`:"";return q(`/api/prompts/import/discovery${n}`)}function xw(e){return q("/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 Iw(e){return q("/api/prompts/import/discovery-review",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function Sw(e){return q("/api/prompts/import/folder-files",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source:{kind:"github-folder",input:e.source.input}})})}function ww(e){return q("/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 q(`/api/assets${n?`?${n}`:""}`)}function bu(e){return q(`/api/assets/${encodeURIComponent(e)}`)}function $r(e){return q("/api/assets",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function _w(e){return q("/api/assets/promote-element",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function zi(e,t){return q(`/api/assets/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}async function Ew(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 Ee(`/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 xu(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 Ee(`/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 Nw(e){return q("/api/video/keying",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,projectId:e.projectId??void 0})})}function Iu(e){return q(`/api/assets/${encodeURIComponent(e)}`,{method:"DELETE"})}function oo(){return q("/api/assets/folders")}function Su(e){return q("/api/assets/folders",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function qi(e,t){return q(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})}function wu(e){return q(`/api/assets/folders/${encodeURIComponent(e)}`,{method:"DELETE"})}function ao(){return q("/api/assets/tags")}function kw(){return q("/api/assets/all",{method:"DELETE"})}async function _u(e,t={},n={}){const r=e.requestId??`nreq_${crypto.randomUUID()}`;return At(),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=jt(r,null,(m,h)=>{i||(m==="partial"?t.onPartial?.(h):m==="phase"?t.onPhase?.(h):m==="done"?d(()=>s(h)):m==="error"&&d(()=>a(Ze(h,"Node generation failed"))))}),p=Jt(()=>{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"],Eu=new Set(io);function Pt(e){return typeof e=="string"&&Eu.has(e)}const An={oauth:{image:["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna","gpt-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-imagine-video-1.5-2026-05-30"]},"grok-api":{image:["grok-imagine-image-2.0","grok-imagine-image","grok-imagine-image-quality"],video:["grok-imagine-video","grok-imagine-video-1.5","grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]},agy:{image:["nano-banana-2","nano-banana-pro"],video:[]},"gemini-api":{image:["nano-banana-2","nano-banana-pro"],video:[]},atlascloud:{image:["openai/gpt-image-2/text-to-image","openai/gpt-image-2/edit"],video:[]},minimax:{image:["image-01","image-01-live"],video:[]},nai:{image:["nai-diffusion-5-full","nai-diffusion-5-curated","nai-diffusion-4-5-full","nai-diffusion-4-5-curated"],video:[]},comfy:{image:[],video:[]}},Nu=["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"],$i={oauth:{},api:{},grok:{image:5,edit:5,video:14},"grok-api":{image:5,edit:5,video:14},agy:{image:3,edit:3},"gemini-api":{image:3,edit:3},atlascloud:{image:10,edit:10},minimax:{image:1,edit:1},nai:{},comfy:{image:4,edit:4}},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",Qe=[{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(An["gemini-api"].image),co=new Set(An.atlascloud.image),uo=new Set(An.minimax.image),mo=new Set(An.nai.image),ku=Qe.filter(e=>!e.value.startsWith("grok-")&&!Ur.has(e.value)&&!co.has(e.value)&&!uo.has(e.value)&&!mo.has(e.value)),Cu=Qe.filter(e=>e.value.startsWith("grok-")),ju=Qe.filter(e=>Ur.has(e.value)),Au=Qe.filter(e=>co.has(e.value)),Pu=Qe.filter(e=>uo.has(e.value)),Ui=Qe.filter(e=>mo.has(e.value)),Cw=[{value:"gpt-5.3-codex-spark",fullLabelKey:"settings.imageModel.gpt53CodexSpark"}];function Ru(e){return Qe.some(t=>t.value===e)}function Tu(e){return typeof e=="string"&&e.startsWith("grok-")}function Mu(e){return typeof e=="string"&&Ur.has(e)}function Lu(e){return e==="grok"||e==="grok-api"?Cu:e==="agy"||e==="gemini-api"?ju:e==="atlascloud"?Au:e==="minimax"?Pu:e==="nai"?Ui:e==="comfy"?[]:ku}function Hi(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)?Qe.find(n=>n.value===e)?.shortLabel??e:Qe.find(n=>n.value===e)?.shortLabel??e:null}const po="grok-imagine-video",et="grok-imagine-video-1.5",Vi="grok-imagine-video-1.5-preview",Ki="grok-imagine-video-1.5-2026-05-30",Ou=15,Fu=10,ya=15,Du=[{value:po,shortLabel:"grokv",fullLabelKey:"settings.videoModel.grokImagine"},{value:et,shortLabel:"grokv1.5",fullLabelKey:"settings.videoModel.grokImagine15"}];function Gu(e){return e===po||e===et||e===Vi||e===Ki}function Rt(e){return Gu(e)?e===Vi||e===Ki?et:e:!1}function va(e,t){if(t!=="reference-to-video")return ya;const n=Rt(e);return n?n===et?Ou:Fu:ya}function zu(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===et&&(n==="text-to-video"||n==="image-to-video")}const Ht="comfy-video:",Bi="video:";function qu(e){const{provider:t,imageModel:n,videoModel:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e;return t==="comfy"?a?`${Ht}${a}`:s??"":(t==="grok"||t==="grok-api")&&r?`${Bi}${r}`:n}const Os=new Set(Nu),$u={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"&&Os.has(t)&&An[e].image.includes(t)}function hn(e){return typeof e=="string"&&e.trim().length>0?e:null}function Wi(e,t){if(Rt(t))return"grok";for(const n of["grok","agy","atlascloud","minimax","nai"])if(Hr(n,e))return n;return"oauth"}function lt(e){const t=Pt(e.provider)?e.provider:Wi(e.imageModel,e.videoModelSelected);if(t==="comfy"){const n=hn(e.imageModel);return{provider:t,imageModel:typeof e.imageModel=="string"&&Os.has(e.imageModel)?e.imageModel:hr,videoModelSelected:!1,comfyWorkflow:hn(e.comfyWorkflow)??(n&&!Os.has(n)?n:null),comfyVideoWorkflow:hn(e.comfyVideoWorkflow)}}return{provider:t,imageModel:Hr(t,e.imageModel)?e.imageModel:$u[t],videoModelSelected:t==="grok"||t==="grok-api"?Rt(e.videoModelSelected):!1,comfyWorkflow:null,comfyVideoWorkflow:null}}function Uu(e,t){return Pt(e)&&Hr(e,t)?e:Wi(t,!1)}function Hu(e,t,n){return e.provider===t?e:lt(n?t==="comfy"?{provider:t,imageModel:e.imageModel,comfyWorkflow:n.image,comfyVideoWorkflow:n.kind==="video"?n.video:null}:{provider:t,imageModel:n.image,videoModelSelected:n.kind==="video"?n.video:!1}:{provider:t,imageModel:e.imageModel})}function ba(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 Ji(e){return e.provider==="comfy"?e.comfyWorkflow??void 0:e.imageModel}function Fs(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"?hn(s.image):Hr(n,s.image)?s.image:null,i=n==="comfy"?hn(s.video):n==="grok"||n==="grok-api"?Rt(s.video):!1;t[n]={kind:s.kind,...a?{image:a}:{},...i?{video:i}:{}}}return t}const Vu="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 Yi(e){return Ds.some(t=>t.value===e)}const Ku={low:"l",medium:"m",high:"h",xhigh:"x",max:"M"};function Bu(e){return!Yi(e)||e==="none"?null:`R:${Ku[e]}`}const Ne=["ima2.rightPanelOpen","ima2.uiMode","ima2.historyStripLayout","ima2.canvas.exportBackground.v1","ima2.imageModel","ima2.reasoningEffort","ima2.webSearchEnabled","ima2.generationDefaults","ima2.inFlight","ima2.selectedFilename","ima2.activeSessionId","ima2.graphTabId","ima2.galleryScope","ima2.galleryDefaultScope","ima2.locale","ima2.workspaceProfile","ima2.workspaceOverrides","ima2.videoDefaults","ima2.agentPanePreference","ima2.naiOptions","ima2.coreSelectionMemory.v1"],Xi=Ne[0],Zi=Ne[1],Qi=Ne[2],el=Ne[3],fo=Ne[4],tl=Ne[5],nl=Ne[6],ho=Ne[7],rl=Ne[8],Gs=Ne[9],zs=Ne[10],xa=Ne[11],go=Ne[12],sl=Ne[13],yo=Ne[17],ol=Ne[19],al=Ne[20],Wu=!0,Ju=!1,Xt=!0,il=Ju,Zt=!0,Yu=24;function qs(e){return Math.min(Yu,Math.max(1,Math.trunc(e||1)))}const Ia={ko:Cd,en:kd,"zh-Hant":Nd,"zh-Hans":Ed};function Sa(e,t){return t.split(".").reduce((n,r)=>{if(n!=null)return n[r]},e)}function Xu(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>r in t?String(t[r]):`{${r}}`)}function L(e,t){const n=f.getState().locale;return ll(n,e,t)}function ll(e,t,n){const r=Sa(Ia[e],t),s=typeof r=="string"?r:Sa(Ia.en,t),a=typeof s=="string"?s:t;return n?Xu(a,n):a}function H(){const e=f(t=>t.locale);return{locale:e,t:(t,n)=>ll(e,t,n)}}function Zu(e){return Math.round(e/16)*16}const St=16,vo=3840,ls=655360,gr=8294400,Qu=3,Gt=3,wa=Math.floor(Math.sqrt(gr)/St)*St,cl=St,em=vo,Vn=Qu;function _a(e){return Math.floor(e/16)*16}function _r(e){return Math.ceil(e/16)*16}function Ge(e){return Math.min(em,Math.max(cl,e))}function tt(e,t){const n=typeof e=="number"?e:Number.parseInt(e,10);return Number.isFinite(n)?n:t}function Et(e,t){e.includes(t)||e.push(t)}function Ea(e,t){const n=Zu(e);return n!==e&&Et(t,"snap"),n}function Na(e,t){return e<cl&&Et(t,"min"),e>vo&&Et(t,"maxEdge"),Ge(e)}function ka(e,t,n){return e>t*Vn?(Et(n,"ratio"),{w:e,h:Ge(_r(e/Vn))}):t>e*Vn?(Et(n,"ratio"),{w:Ge(_r(t/Vn)),h:t}):{w:e,h:t}}function tm(e,t,n){if(e*t<ls){Et(n,"minPixels");const i=Math.sqrt(ls/(e*t));let l=Ge(_r(e*i)),c=Ge(_r(t*i));for(;l*c<ls;)l<=c?l=Ge(l+St):c=Ge(c+St);return{w:l,h:c}}if(e*t<=gr)return{w:e,h:t};Et(n,"maxPixels");const r=Math.sqrt(gr/(e*t));let s=Ge(_a(e*r)),a=Ge(_a(t*r));for(;s*a>gr;)s>=a?s=Ge(s-St):a=Ge(a-St);return{w:s,h:a}}function bo(e,t,n,r){const s=[],a=tt(e,n),i=tt(t,r);let l=Na(Ea(a,s),s),c=Na(Ea(i,s),s);return{w:l,h:c}=ka(l,c,s),{w:l,h:c}=tm(l,c,s),{w:l,h:c}=ka(l,c,s),{requestedW:a,requestedH:i,w:l,h:c,adjusted:l!==a||c!==i,reasons:s}}function dl(e,t,n,r){const s=bo(e,t,n,r);return{w:s.w,h:s.h}}const nm=[{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 rm(e,t){return`${e}x${t}`}function sm(e,t=1024){if(e.id==="free")return null;const n=t,r=e.w>=e.h,s=r?Math.round(n*e.w/e.h):n,a=r?n:Math.round(n*e.h/e.w);return dl(s,a,s,a)}function Vr(e){const t=dl(e.w,e.h,2400,1024);return{...e,w:t.w,h:t.h,label:e.label||`${t.w}×${t.h}`}}function zt(e){return e.slice(0,Gt).map(Vr)}function om(e,t){const n=Vr(t),r=e.findIndex(s=>s.id===n.id);return r>=0?zt(e.map((s,a)=>a===r?n:s)):e.length>=Gt?zt(e):zt([...e,n])}function am(e,t,n){const r=Vr({...n,id:t});return zt(e.map(s=>s.id===t?r:s))}const im=[{value:"1024x1024",label:"1024×1024",sub:"1:1"},{value:"1536x1024",label:"1536×1024",sub:"3:2"},{value:"1024x1536",label:"1024×1536",sub:"2:3"}],lm=[{value:"1360x1024",label:"1360×1024",sub:"4:3"},{value:"1024x1360",label:"1024×1360",sub:"3:4"},{value:"1824x1024",label:"1824×1024",sub:"16:9"}],cm=[{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"}],dm=[{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 um(){return[{value:"auto",label:L("size.autoLabel"),sub:L("size.autoSub")},{value:"custom",label:L("size.customLabel"),sub:L("size.customSub")}]}const ul=["k_euler_ancestral","k_dpmpp_2s_ancestral","k_dpmpp_2m_sde","k_euler","k_dpmpp_2m","k_dpmpp_sde"],ml=["native","karras","exponential","polyexponential"],pl=["heavy","light","furryFocus","humanFocus","none"],fl=["standard","light","none"],mm={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},hl=2**32-1;function pm(e,t){return{...mm,...e??{},...t}}function $s(e){return e==="nai-diffusion-5-full"||e==="nai-diffusion-5-curated"}function Kn(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 gl(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=e,n={},r=Kn(t.sampler,ul);r!==void 0&&(n.sampler=r);const s=Kn(t.noiseSchedule,ml);s!==void 0&&(n.noiseSchedule=s);const a=Kn(t.ucPresetId,pl);a!==void 0&&(n.ucPresetId=a);const i=Kn(t.qualityPresetId,fl);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<=hl&&(n.seed=t.seed),n}function $e(){return{startFrameFilename:null,endFrameFilename:null,references:[],referenceVideoFilename:null}}const Us="vid:",Hs="img:",fm=/^[\p{L}\p{N}_-]{1,32}$/u;function xo(e){return fm.test(e)}function hm(e){return e.references.some(t=>t.tag!==void 0&&!xo(t.tag))}function yl(e){return e==="video"?"video":"image"}function Kr(e){return typeof e=="string"&&/^\d{1,3}:\d{1,3}$/.test(e)?e:null}function gm(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)&&gm(r)))}function Ca(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 vl(e,t,n){const r=Kr(t),s=Br(n),a={};for(const i of e.parameters){const l=s[i.name];l!==void 0&&Ca(i,l)?a[i.name]=l:i.default!==void 0&&Ca(i,i.default)&&(a[i.name]=i.default)}return{ratio:r&&e.aspectRatios.includes(r)?r:null,parameters:a}}function ym(e){return e?vl(e,null,{}):{ratio:null,parameters:{}}}function vm(e,t){return e.ratio===t.ratio&&JSON.stringify(e.parameters)===JSON.stringify(t.parameters)}function bl(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 $e();const t=e,n=Array.isArray(t.references)?t.references.map(bl).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 xl(e,t){return JSON.stringify(e)===JSON.stringify(t)}function bm(e){return{provider:typeof e.mcpProvider=="string"?e.mcpProvider:null,model:typeof e.mcpModel=="string"?e.mcpModel:null,kind:yl(e.mcpMediaKind),ratio:Kr(e.mcpRatio),parameters:Br(e.mcpParameters)}}function Bn(e,t){return`${e==="video"?Us:Hs}${t}`}function xm(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 Il(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 Im(e,t,n){const r=e.mcpProvider??null;if(!r||!t)return null;const s=yl(e.mcpMediaKind),a=Kr(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(bl).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 Pn(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 Sm(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 Rn(e){if(!Array.isArray(e))return null;const t=e.map(Sm);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 wm(e){const t=Rn(e.composerInsertedPrompts);return typeof e.composerPrompt=="string"?{prompt:e.composerPrompt,insertedPrompts:t??[]}:t?{insertedPrompts:t}:{}}function _m(){try{const e=localStorage.getItem(Xi);return e===null?!0:JSON.parse(e)===!0}catch{return!0}}function Em(){try{const e=localStorage.getItem(Zi);if(e==="agent")return Zt?e:"classic";if(e==="card-news")return il?e:"classic";if(e==="node")return Xt?e:"classic";if(e==="assets"||e==="asset-gen"||e==="home"||e==="classic")return e}catch{}return"classic"}function Nm(){try{const e=localStorage.getItem(Qi);if(e==="rail"||e==="horizontal"||e==="sidebar")return e}catch{}return"rail"}function ja(e){try{const t=localStorage.getItem(e);if(t==="current-session"||t==="all")return t}catch{}return"current-session"}function Aa(){if(typeof window>"u")return{mode:"alpha",matteColor:"#ffffff"};try{const e=window.localStorage.getItem(el);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 Sl(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(el,JSON.stringify({mode:e,matteColor:t}))}catch{}}function wl(e){try{localStorage.setItem(fo,e)}catch{}}function km(){try{const e=localStorage.getItem(tl);if(Yi(e))return e}catch{}return Vu}function Cm(e){try{localStorage.setItem(tl,e)}catch{}}function jm(){try{const e=localStorage.getItem(ol);return e?gl(JSON.parse(e)):{}}catch{return{}}}function _l(e){try{localStorage.setItem(ol,JSON.stringify(e))}catch{}}function Am(){try{const e=localStorage.getItem(nl);if(e==="false")return!1;if(e==="true")return!0}catch{}return Wu}function Pm(e){try{localStorage.setItem(nl,String(e))}catch{}}const Pa={model:!1,duration:5,resolution:"480p",aspectRatio:"auto",singleRefMode:"image-to-video"};function Wr(){try{const e=localStorage.getItem(yo);if(!e)return Pa;const t=JSON.parse(e);return{model:Rt(t.model),duration:typeof t.duration=="number"?t.duration:5,resolution:t.resolution==="480p"||t.resolution==="720p"||t.resolution==="1080p"?t.resolution:"480p",aspectRatio:typeof t.aspectRatio=="string"?t.aspectRatio:"auto",singleRefMode:t.singleRefMode==="reference-to-video"?"reference-to-video":"image-to-video"}}catch{return Pa}}function mn(e){try{const t=Wr();localStorage.setItem(yo,JSON.stringify({...t,...e}))}catch{}}function El(){try{const e=localStorage.getItem(Gs);return typeof e=="string"&&e.length>0?e:null}catch{return null}}function ot(e){try{e?localStorage.setItem(Gs,e):localStorage.removeItem(Gs)}catch{}}function Rm(){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 Tm(e,t){return`${e}x${t}`}function bn(e){return qs(e)}const Nl=new Set(["1024x1024","1536x1024","1024x1536","1360x1024","1024x1360","1824x1024","1024x1824","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840","auto","custom"]);function Mm(e){if(typeof e!="string")return{};if(Nl.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 kl(e){return e==="low"||e==="medium"||e==="high"}function Cl(e){return e==="png"||e==="jpeg"||e==="webp"}function jl(e){return e==="low"||e==="auto"}function Lm(e){return Pt(e)}function Om(e){return e==="auto"||e==="direct"}function Fm(e){return typeof e=="string"&&Nl.has(e)}function Tn(){try{const e=localStorage.getItem(ho);if(!e)return{};const t=JSON.parse(e),n={};Lm(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=Kr(t.mcpRatio)),"mcpParameters"in t&&(n.mcpParameters=Br(t.mcpParameters)),kl(t.quality)&&(n.quality=t.quality),Fm(t.sizePreset)&&(n.sizePreset=t.sizePreset),typeof t.customW=="number"&&Number.isFinite(t.customW)&&(n.customW=tt(t.customW,1920)),typeof t.customH=="number"&&Number.isFinite(t.customH)&&(n.customH=tt(t.customH,1088)),Cl(t.format)&&(n.format=t.format),jl(t.moderation)&&(n.moderation=t.moderation),typeof t.count=="number"&&(n.count=bn(t.count)),typeof t.multimode=="boolean"&&(n.multimode=t.multimode),typeof t.multimodeMaxImages=="number"&&(n.multimodeMaxImages=bn(t.multimodeMaxImages)),Om(t.promptMode)&&(n.promptMode=t.promptMode),typeof t.prompt=="string"&&(n.prompt=t.prompt),typeof t.negativePrompt=="string"&&(n.negativePrompt=t.negativePrompt);const a=Rn(t.insertedPrompts);return a&&(n.insertedPrompts=a),n}catch{return{}}}function Dm(){return bm(Tn())}function Mn(e,t,n="image"){te({mcpProvider:e,mcpModel:t,mcpMediaKind:n})}function te(e){try{const t=Tn();localStorage.setItem(ho,JSON.stringify({...t,...e}))}catch{}}function Al(){const e=localStorage.getItem(al);if(!e)return null;const t=JSON.parse(e);return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Pl(){try{const e=Al();return e?.version===1?Fs(e.lanes):{}}catch{return{}}}function Gm(e){try{let t=null;try{t=Al()}catch{}if(t&&t.version!==void 0&&t.version!==1)return;const r={...t?.version===1?Fs(t.lanes):{},...Fs(e)};localStorage.setItem(al,JSON.stringify({version:1,lanes:r}))}catch{}}function Rl(){const e=Tn(),t=Wr();let n=null;try{n=localStorage.getItem(fo)}catch{}return lt({provider:e.provider,imageModel:n,videoModelSelected:t.model,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function zm(e){wl(e.imageModel),mn({model:e.videoModelSelected}),te({provider:e.provider,comfyWorkflow:e.comfyWorkflow,comfyVideoWorkflow:e.comfyVideoWorkflow})}function qm(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 Tl(e){return e.filter(t=>t.selected).map(t=>t.id)}function xn(e,t){const n=new Set(t);return e.map(r=>({...r,selected:n.has(r.id)}))}function $m(e,t,n,r){const s=new Set(qm(e,t,n));if(!s.size)return e;if(!r)return xn(e,s);const a=e.find(c=>c.id===n),i=e.some(c=>s.has(c.id)&&c.selected),l=new Set(Tl(e));if(i)a?.selected?l.delete(n):l.add(n);else for(const c of s)l.add(c);return xn(e,l)}const Um={maxB64Bytes:6e6,preserveTransparency:!1,maxEdge:4096,qualityLadder:[.85,.7,.55]},Ra=16777216;function Ta(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>Ra){const i=Math.sqrt(Ra/(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={...Um,...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}=Ta(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=Ta(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 Ml(e){return(e.type||"").toLowerCase()==="image/png"}const Ll=18e4;function Hm(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)In(n,t)||t.push({kind:n.kind??"classic",...n.kind==="node"?{sessionId:n.sessionId??void 0}:{}});return t}function In(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 Ol(e){const t=await Promise.all(e.map(n=>Li({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:Vs(e.kind)??Vs(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:Rn(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 Vm(e){const t=typeof e.errorCode=="string"&&e.errorCode?e.errorCode:"UNKNOWN",n=new Error(t==="JOB_TRACKING_TIMEOUT"?Oi: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 Qt(e){if(!e||typeof e!="object")return!1;const t=e;return t.code==="GENERATION_CANCELED"||t.status===499}function Ma(e){return e.filename||e.image}function La(e,t){const n=new Map(e.map(r=>[Ma(r),r]));for(const r of t)n.set(Ma(r),r);return[...n.values()].sort((r,s)=>(r.sequenceIndex??Number.MAX_SAFE_INTEGER)-(s.sequenceIndex??Number.MAX_SAFE_INTEGER))}function Fl({includeExpired:e=!1}={}){try{const t=localStorage.getItem(rl);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<Ll)).map(s=>({id:s.id,prompt:s.prompt,startedAt:s.startedAt,composerPrompt:typeof s.composerPrompt=="string"?s.composerPrompt:void 0,composerInsertedPrompts:Rn(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:Vs(s.kind)}))}catch{return[]}}function Vs(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 qe=500,No=5;function Km(e){return e==="classic"||e==="edit"||e==="generate"||e==="card-news-card"||e==="card-news-set"?e:null}function Ln(e){const t=Rn(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:Km(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 ze(e){return e.filename??e.image}function Dl(e,t){const n=ze(t);return e.filter(r=>ze(r)!==n)}function Gl(e,t){const n=ze(t);return e.find(r=>ze(r)===n)}function zl(e,t){return t?{...t,...e,createdAt:e.createdAt??t.createdAt,requestId:e.requestId??t.requestId,sessionId:e.sessionId??t.sessionId,kind:e.kind??t.kind,refsCount:e.refsCount??t.refsCount,isFavorite:e.isFavorite??t.isFavorite}:e}function ql(e,t){const n=new Map(e.map(r=>[ze(r),r]));for(const r of t)n.set(ze(r),r);return[...e.map(r=>n.get(ze(r))??r),...t.filter(r=>!e.some(s=>ze(s)===ze(r)))]}function Jr(e,t){return e.slice(0,Math.max(qe,t))}function ko(e){return e.replace(/^data:[^;]+;base64,/,"")}async function On(e,t="reference.png"){const n=await Ee(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 Bm(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(rl,JSON.stringify(e))}catch(t){const n=window;n.__ima2QuotaWarned||(n.__ima2QuotaWarned=!0,console.warn("[ima2] localStorage write failed:",t))}}function Wm(e){return pm(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 Jm(e){const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.trunc(t)):No}async function Ym(e){try{const t=await Mi();e({referenceLimit:Jm(t.limits?.maxRefCount),naiServerDefaults:gl(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 Xm(e){const t=await Ee(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 Zm(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 Qm(e,t){return e.find(n=>n.target===t)??null}function ep(e,t,n){return e.some(r=>r.target===n&&r.source!==t)}function tp(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 jw(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 nt(e,t){const n=new Map(e.map(r=>[r.id,r]));return e.map(r=>{const s=Qm(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 $l="ima2.nodeRefs.v1";function jo(){try{const e=localStorage.getItem($l);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function Ul(e){try{localStorage.setItem($l,JSON.stringify(e))}catch{}}function np(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,Ul(r)}function Ao(e,t){Xr(e,t,[])}function rp(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,Ul(n)}const sp=/\.(mp4|webm|mov)$/i;function Xe(e){if(!e||e.startsWith("data:image/"))return!1;const t=e.split("?")[0];return sp.test(t)||e.startsWith("data:video/")}function ve(e){return e?e.mediaType==="video"?!0:Xe(e.filename)||Xe(e.url)||Xe(e.image):!1}const op=15e3;function Po(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")))},op),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 en(e,t){return Po(e,n=>n-.1,t)}function Hl(e,t){return Po(e,n=>Math.min(n*.3,.4),t)}function Vl(e,t){return Po(e,n=>n/2,t)}function Kl(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:np(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:nt(t,n),graphEdges:n,graphVersion:e.graphVersion}}const ap=800;let Je=null,yr=!1,vr=!1,It=null,Bl=0;function Wl(){try{const e=sessionStorage.getItem(xa);if(e)return e;const t=`tab_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`;return sessionStorage.setItem(xa,t),t}catch{return"tab_unavailable"}}function Jl(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 Yl(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 Xl(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 Yt({sessionId:n,limit:qe})).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}),Ql(e,t,"recovery"))}async function ip(e,t){const n=e().activeSessionId;if(!n)return;const{session:r}=await Gi(n),{graphNodes:s,graphEdges:a,graphVersion:i}=Kl(r);t({graphNodes:s,graphEdges:a,activeSessionGraphVersion:i}),e().showToast(L("toast.sessionReloadedElsewhere"),!0),await Xl(e,t).catch(()=>{})}async function lp(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:Jl(p.data)})),d=Yl(i),u=`gs_${Date.now().toString(36)}_${++Bl}`;try{const p=await mu(r,s,c,d,{saveId:u,saveReason:n,tabId:Wl()});return e().activeSessionId!==r?"skipped":(rp(r,e().graphNodes.map(m=>m.id)),t({activeSessionGraphVersion:p.graphVersion}),"saved")}catch(p){return p.status===409?(await ip(e,t),"conflict"):(console.warn("[sessions] save failed:",p),"failed")}}async function Zl(e,t,n){return yr?(vr=!0,It||"skipped"):(yr=!0,It=(async()=>{let r=n,s="skipped";do{if(vr=!1,s=await lp(e,t,r),s==="conflict"||s==="failed")break;r="queued"}while(vr);return s})().finally(()=>{yr=!1,It=null}),It)}function Ql(e,t,n="debounced"){const r=e();r.activeSessionId&&(r.sessionLoading||(Je&&clearTimeout(Je),Je=setTimeout(()=>{Je=null,Zl(e,t,n)},ap)))}async function cp(e,t,n="manual"){let r=!1;if(Je&&(clearTimeout(Je),Je=null,r=!0),yr){if(vr=!0,(It?await It:"skipped")==="failed")throw new Error(L("modal.graphSaveFailed"));return}if(r&&await Zl(e,t,n)==="failed")throw new Error(L("modal.graphSaveFailed"))}function dp(e){const t=e();if(!t.activeSessionId||t.activeSessionGraphVersion==null||t.sessionLoading||t.graphNodes.length===0&&t.activeSessionGraphVersion>0)return;Je&&(clearTimeout(Je),Je=null);const n=t.graphNodes.map(i=>({id:i.id,x:i.position.x,y:i.position.y,data:Jl(i.data)})),r=Yl(t.graphEdges),s=`/api/sessions/${encodeURIComponent(t.activeSessionId)}/graph`,a=JSON.stringify({nodes:n,edges:r});try{Ee(s,{method:"PUT",headers:{"Content-Type":"application/json","If-Match":String(t.activeSessionGraphVersion),"X-Ima2-Graph-Save-Id":`gs_${Date.now().toString(36)}_${++Bl}`,"X-Ima2-Graph-Save-Reason":"beforeunload","X-Ima2-Tab-Id":Wl()},body:a,keepalive:!0}).catch(()=>{})}catch{}}async function gt(e,t,n,r={}){const s=ve(e)?void 0:await Zm(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=Gl(l.history,i),d=zl(i,c),u=Dl(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&&ot(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 up(e){for(const t of e.history)if(t.sessionId)return t.sessionId;return null}const mp=30;function us(e,t,n){return{nodes:structuredClone(e),edges:structuredClone(t),label:n,at:Date.now()}}function pp(e,t,n=mp){const r=[...e,t];return r.length>n?r.slice(r.length-n):r}function fp(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 hp(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 gp=["status","pendingRequestId","recoveryRequestId","pendingPhase","pendingStartedAt","partialImageUrl","error","errorInfo"];function Oa(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 gp)l[c]=a.data[c];return{...s,data:l}}),edges:e.edges}}function yp(e){return e.data.status==="ready"&&!!e.data.imageUrl}function vp(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 bp(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 xp(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 Ip(e,t,n){const r=new Set(n);return e.filter(s=>s.source===t&&!r.has(s.target)).map(s=>s.target)}function Sp(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 wp(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 Ue(e,t){const{code:n,spec:r,message:s}=st(e);if(n==="LAN_TOKEN_REQUIRED"){const a=e?.authEpoch;return Ai(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?L(r.toastKey):s||L("toast.generateFailed");if(t.showToast(a,!0),n==="JOB_TRACKING_TIMEOUT")return{code:n,message:a}}return{code:n,message:s}}const _p=["AUTH_CHATGPT_EXPIRED","AUTH_API_KEY_INVALID","APIKEY_DISABLED","AGY_QUOTA_EXHAUSTED"],Ep=["EMPTY_RESPONSE","DB_ERROR","UNKNOWN"];function Np(e){if(_p.includes(e))return"auth";const t=Be[e]?.cta;return t==="reauth"?"auth":t==="retry"||t==="reload"||Ep.includes(e)?"retry":"fix-input"}function ec(e){const{code:t,message:n}=st(e),r=Np(t);return{message:n,code:t,retryable:r==="retry",action:r,occurredAt:Date.now()}}const kp=$i.grok.video,Cp=3;function jp(e,t){return $i[e]?.[t]}function tc(e){if(e.mcpProvider)return Cp;if(e.videoModelSelected)return Math.min(e.serverLimit,kp);if(Pt(e.provider)&&!lo[e.provider].generate.references)return 0;const t=jp(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 Ar=new Map;function tn(e,t){Ar.set(e,t)}function nn(e){Ar.delete(e)}function nc(e){Ar.get(e)?.abort(),Ar.delete(e)}const Ap="element-source:",Pp=500;function Rp(e){return`${Ap}${e}`}function Aw(e,t){const n=Rp(t);return e.find(r=>r.kind==="element"&&(r.metadata?.sourceAssetId===t||r.tags.includes(n)))??null}function rc(e){const t=e.metadata?.refs;return Array.isArray(t)?t.find(n=>typeof n=="string"&&n.length>0)??null:null}async function Tp(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:Pp});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 sc(e){return`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function Pw(e){const t=e.filePath??(e.kind==="element"?rc(e)??"":""),n=sc(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 Fa=32,Da="Image_",Mp=/@([\p{L}\p{N}_-]+)/gu,Lp=new Set([" "," ",`
|
|
5
5
|
`,"(","["]);function oc(e,t){const n=new Set(t);let r=Math.max(1,Math.trunc(e)||1);for(;n.has(`${Da}${r}`);)r+=1;return{tag:`${Da}${r}`,nextAttachmentOrdinal:r+1}}function Op(e,t){const n=new Set(t),r=e.slice(0,Fa)||"Element";if(!n.has(r))return r;let s=2;for(;;){const a=`_${s}`,i=`${r.slice(0,Fa-a.length)}${a}`;if(!n.has(i))return i;s+=1}}function Fn(e){return e.trayItems.filter(t=>t.kind==="attachment")}function ac(e){return e.trayItems.filter(t=>t.kind==="element")}function Fp(e){return Fn(e).map(t=>t.source.dataUrl)}function Dp(e){return ac(e).map(t=>t.source.elementId)}function Gp(e){const t={trayItems:e};return{referenceImages:Fp(t),selectedElementIds:Dp(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 zp(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Mo(e,t){if(!zp(e,t))return e;const n={...e};return delete n[t],n}function qp(e){const t=[];for(const n of e.matchAll(Mp)){const r=n.index,s=r>0?e[r-1]:void 0;s!==void 0&&!Lp.has(s)||t.push({tag:n[1],start:r,end:r+n[0].length})}return t}function $p(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:cc(a,l),...Gp(a)}}),n}function Up(e){const t=new Set;return e.filter(n=>n.kind!=="element"||t.has(n.id)?!1:(t.add(n.id),!0))}function ic(e,t){const n=e??[],r=n.findIndex(s=>s.id===t.id);return r<0?[...n,t]:n.map((s,a)=>a===r?t:s)}function Hp(e,t,n){return n??e.elementCatalog?.find(r=>r.id===t)??e.assets.find(r=>r.id===t&&r.kind==="element")}function lc(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=Hp(i,e,r),c=l?Il(l.name):null;if(!l||!c)return{result:null};const d=Op(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:lc(l)}};return{result:u,patch:{trayItems:[...s.trayItems,u],retiredTags:Mo(s.retiredTags,d),elementCatalog:ic(i.elementCatalog,l)}}})}function cc(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 Ks(e,t){return e.find(n=>n.kind==="element"&&n.source.elementId===t)}function Vp(e,t,n){Lo(t,r=>{const s=Ks(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 dc(e,t,n){const r=Up(e);t(s=>({elementCatalog:r,missingElementIds:cc(s.trayItems,r)}))}function uc(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 bt=new Set;async function Kp(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 bu(l.elementId)).asset}catch{return{ok:!1,name:l.name}}const d=ic(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 lc(c))try{const m=await Xm(sc(p));r.includes(m)||r.push(m)}catch{}}return{ok:!0,referenceDataUrls:r,notes:s,elementIds:a,revisions:i}}function Bp(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 Wp(e,t,n,r,s){if(bt.has(e))return null;bt.add(e);const a=r().graphNodes,i=nt(a,r().graphEdges);i.some((R,V)=>R.data.parentServerNodeId!==a[V]?.data.parentServerNodeId)&&n({graphNodes:i});const l=i.find(R=>R.id===e);if(!l)return bt.delete(e),null;const c=uc(r().graphNodes,r().graphEdges,[e]),d=await Kp(c,n,r);if(d.ok===!1)return r().showToast(L("node.elementMissing",{name:d.name}),!0),bt.delete(e),null;const{prompt:u,parentServerNodeId:p}=l.data;if(!u.trim())return r().showToast(L("toast.promptRequired"),!0),bt.delete(e),null;const m=r(),h=typeof l.data.provider=="string"&&l.data.provider?l.data.provider:m.provider,b=tc({provider:h,serverLimit:m.referenceLimit,videoModelSelected:!!m.videoModelSelected,mcpProvider:m.mcpProvider??null}),I=Bp(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(L("node.parentImageRequired"),!0),bt.delete(e),null;const S=m.activeSessionId,w=Date.now(),k=Math.random().toString(36).slice(2,6),N=`fn_${e}_${w}_${k}`,O=new AbortController;tn(N,O);const $=[...m.inFlight,{id:N,prompt:u,startedAt:w,kind:"node",sessionId:S,clientNodeId:e}];s($),n({graphNodes:r().graphNodes.map(R=>R.id===e?{...R,data:{...R.data,status:"pending",pendingRequestId:N,recoveryRequestId:N,pendingPhase:"queued",pendingStartedAt:w,partialImageUrl:null,error:void 0,errorInfo:null,size:y}}:R),activeGenerations:m.activeGenerations+1,inFlight:$}),r().startInFlightPolling();let j=!0;try{const R=await _u({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:N,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:V=>{r().activeSessionId===S&&n({graphNodes:r().graphNodes.map(C=>C.id===e?{...C,data:{...C.data,status:"pending",partialImageUrl:V.image,pendingPhase:"partial"}}:C)})},onPhase:V=>{r().activeSessionId===S&&V.phase&&n({graphNodes:r().graphNodes.map(C=>C.id===e?{...C,data:{...C.data,pendingPhase:V.phase??C.data.pendingPhase}}:C)})}},{signal:O.signal});return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(V=>{if(V.id!==e)return V;const C={...V.data};return delete C.partialImageUrl,{...V,data:{...C,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}}})}),j=!0,t.suppressToast||r().showToast(L("toast.nodeCreated",{id:R.nodeId.slice(0,8),elapsed:R.elapsed}))),R.nodeId}catch(R){if(Qt(R))return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(C=>C.id===e?{...C,data:{...C.data,status:C.data.imageUrl?"ready":"empty",pendingRequestId:null,recoveryRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:void 0,errorInfo:null}}:C)}),j=!0),null;const V=R instanceof Error?R.message:L("toast.nodeCreateFailed");return r().activeSessionId===S&&(n({graphNodes:r().graphNodes.map(C=>C.id===e?{...C,data:{...C.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,partialImageUrl:null,error:V,errorInfo:ec(R)}}:C)}),j=!0,Ue(R,r())),null}finally{bt.delete(e);const R=r().inFlight.filter(V=>V.id!==N);s(R),nn(N),n({activeGenerations:Math.max(0,r().activeGenerations-1),inFlight:R}),r().activeSessionId===S&&j&&(r().scheduleGraphSave(),r().flushGraphSave("node-complete"))}}async function Jp(e,t,n){if(n().nodeBatchRunning)return;const r=Tl(n().graphNodes).filter(x=>n().graphNodes.find(y=>y.id===x)?.type!=="elementReferenceNode");if(r.length===0){n().showToast(L("nodeBatch.noneSelected"),!0);return}const s=Sp(n().graphNodes,n().graphEdges,r);if(s.length>0){n().showToast(L("nodeBatch.parentRequired",{count:s.length}),!0);return}const a=wp(n().graphNodes,n().graphEdges,r);if(a.length>0){n().showToast(L("nodeBatch.cycleBlocked",{count:a.length}),!0);return}const i=vp(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?!yp(y):!1});if(c.length===0){n().showToast(L("nodeBatch.nothingToRun"));return}const u=uc(n().graphNodes,n().graphEdges,c).find(x=>x.missing);if(u){n().showToast(L("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(N=>N.target===x),g=y?p.get(y.source)??n().graphNodes.find(N=>N.id===x)?.data.parentServerNodeId??null:null,_=n().videoModelSelected?await n().runVideoGenerate(x).then(()=>n().graphNodes.find(O=>O.id===x)?.data.serverNodeId??null):await n().runGenerateNodeInPlace(x,{parentServerNodeIdOverride:g,suppressToast:!0});if(!_){h+=1;for(const N of xp(n().graphEdges,x))I.add(N);continue}m+=1,p.set(x,_);const S=Ip(n().graphEdges,x,l),w=n().graphEdges.filter(N=>N.source===x&&l.has(N.target)).map(N=>N.target),k=new Set(bp(n().graphEdges,l));t({graphNodes:n().graphNodes.map(N=>w.includes(N.id)?{...N,data:{...N.data,parentServerNodeId:_}}:k.has(N.id)?{...N,data:{...N.data,status:"stale",parentServerNodeId:S.includes(N.id)?_:N.data.parentServerNodeId,error:L("nodeBatch.staleBecauseParentChanged")}}:N)})}h>0?n().showToast(L("nodeBatch.partialFinished",{done:m,failed:h,skipped:b,total:c.length}),!0):n().showToast(L("nodeBatch.finished",{done:m,total:c.length})),n().scheduleGraphSave()}finally{t({nodeBatchRunning:!1,nodeBatchStopping:!1})}}function Bs(e){return Array.isArray(e.images)}function Yp(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||!Yp(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 Xp=[{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"]}],Zp=[{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"]}],Qp=[{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"]}],mc=[...Xp,...Zp,...Qp];function pc(e){return mc.find(t=>t.id===e)}function es(){return[...mc]}function fc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function hc(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function ef(e,t,n){const r=n();if(r.uiMode!=="classic")return;const s=Pn(r.prompt,r.insertedPrompts);if(!s)return;const a=Qr({catalog:es(),presetIds:r.selectedPresetIds,provider:hc(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;tn(u,p);const m=Date.now(),h=m,b=bn(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:Ji(r),reasoningEffort:r.reasoningEffort,webSearchEnabled:r.webSearchEnabled,requestId:u,mode:r.promptMode,composerPrompt:l,composerInsertedPrompts:c,presetIds:a.appliedPresetIds,elementIds:fc(r),...Ro(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(ko)}:{}},g=await Qd(y,{onPartial:w=>{t(k=>{const N=k.multimodeSequences[u];return N?{multimodeSequences:{...k.multimodeSequences,[u]:{...N,partials:[...N.partials,{image:w.image,index:w.index??null}].slice(-b)}}}:{}})},onImage:w=>{t(k=>{const N=k.multimodeSequences[u];if(!N)return{};const O=La(N.images,[w]);return O.length===N.images.length?{}:{multimodeSequences:{...k.multimodeSequences,[u]:{...N,sequenceId:w.sequenceId??N.sequenceId,returned:O.length,images:O,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 gt(w,t,n,{autoSelectStartedAt:h});t(w=>({multimodeSequences:{...w.multimodeSequences,[u]:(()=>{const k=w.multimodeSequences[u],N=La(k?.images??[],_);return{sequenceId:g.sequenceId,requestId:u,requested:g.requested,returned:N.length,images:N,partials:[],status:g.status,elapsed:g.elapsed}})()}}));const S=g.status==="complete"?"multimode.complete":"multimode.partial";n().showToast(L(S,{returned:g.returned,requested:g.requested,elapsed:g.elapsed}))}catch(y){y.name==="AbortError"||Qt(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}}}:{}}),Ue(y,n()))}finally{const y=n().inFlight.filter(g=>g.id!==u);Re(y),nn(u),t(g=>{const _=new Set(g.activeFlightIds);_.delete(u);let S=g.multimodePreviewFlightId;const w=g.multimodeSequences[u]?.status,k=w==="complete"||w==="partial";if(S===u&&!k){const O=[..._];S=O.length>0?O[O.length-1]:null}const N={...g.multimodeSequences};return k&&S!==u&&delete N[u],{activeGenerations:Math.max(0,g.activeGenerations-1),inFlight:y,activeFlightIds:_,multimodePreviewFlightId:S,multimodeSequences:N}})}}async function tf(e,t,n){const r=n(),s=Pn(r.prompt,r.insertedPrompts);if(!s)return;const a=Qr({catalog:es(),presetIds:r.selectedPresetIds,provider:hc(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;tn(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:Ji(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:fc(r),...Ro(r),...r.providerUrlReference?{providerUrl:r.providerUrlReference}:r.referenceImages.length?{references:r.referenceImages.map(ko)}:{}},x=await Fi(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 gt(g,t,n,{autoSelectStartedAt:h})}n().showToast(L("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 gt(y,t,n,{autoSelectStartedAt:h}),n().showToast(L("toast.generatedSingle",{elapsed:x.elapsed}))}}catch(I){!(I instanceof Error&&I.name==="AbortError")&&!Qt(I)&&Ue(I,n())}finally{const I=n().inFlight.filter(x=>x.id!==u);Re(I),nn(u),t({activeGenerations:Math.max(0,n().activeGenerations-1),inFlight:I})}}function nf(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 rf(e,t,n={}){const r=`/api/video/frame?file=${encodeURIComponent(e)}&position=${t}`,s=await Ee(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 sf(e){return{async extractFrame(t,n,r={}){if(t.kind==="generated"&&n==="last")try{return{dataUrl:await e.fetchGeneratedFrame(t.filename,"last",r),via:"server-ffmpeg"}}catch(a){if(!nf(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 of=sf({fetchGeneratedFrame:rf,extractFromElement:(e,t,n)=>t==="last"?en(e,n):t==="first"?Hl(e,n):Vl(e,n)}),Pr="Your video prompt should describe: visual flow, motion flow, sound/no-music intent, dialogue/no-dialogue, and the desired ending frame. Pace the scene to fill the selected duration naturally — opening composition, connected action/emotion change, and a stable ending frame.";function af(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 gc(e){if(e.videoContinuity?.entries?.length)return{...e.videoContinuity,parentFilename:e.filename??e.videoContinuity.parentFilename??null,sourceFrame:"last",entries:af(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 Sn(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 lf(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 yc(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 vc(e){return e.provider==="comfy"&&e.comfyVideoWorkflow||(e.provider==="grok"||e.provider==="grok-api")&&e.videoModelSelected?"video":e.uiMode==="classic"&&e.multimode&&e.provider!=="nai"&&Pt(e.provider)&&lo[e.provider].multimode.supported?"multimode":"image"}function cf(e){return e.mcpProvider?e.multimode:vc(e)==="multimode"}async function df(e,t){const n=t();if(!Pn(n.prompt,n.insertedPrompts)||Oo(t))return;const s=vc(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 uf(e,t){const n=t().multimodePreviewFlightId;n&&(nc(n),t().cancelInFlightJob(n),e(r=>{const s=r.multimodeSequences[n];return s?{multimodeSequences:{...r.multimodeSequences,[n]:{...s,status:"canceled"}}}:{}}))}function Oo(e){return(e().missingElementIds??[]).length>0?(e().showToast(L("toast.missingElements"),!0),!0):!1}async function mf(e,t){const n=t().customSizeConfirm;if(!n||(n.continuation.kind==="classic"||n.continuation.kind==="multimode")&&Oo(t))return;const r=Tm(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 pf(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(L("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 ff(e,t,n){const r=n().graphNodes.find(a=>a.id===e);if(!r)return;if(!r.data.prompt.trim()){n().showToast(L("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 hf(e,t,n,r){const s=r().graphNodes.find(i=>i.id===e);if(!s)return;if(!s.data.prompt.trim()){r().showToast(L("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 gf(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 bc(e){const t=e.selectedElementIds;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function xc(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 Ic(e){return e==="grok"||e==="grok-api"?"grok":e==="gemini-api"?"gemini":"gpt"}async function yf(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():Pn(n().prompt,n().insertedPrompts);if(!i.trim()){n().showToast(Pr,!0);return}const l=n(),c=Qr({catalog:es(),presetIds:l.selectedPresetIds,provider:Ic(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(Xe(S.data.imageUrl))try{const w=S.data.imageUrl.replace(/^\/generated\//,"");p=(await of.extractFrame({kind:"generated",filename:w},"last")).dataUrl,m=S.data.videoContinuity??gc({filename:w,prompt:S.data.prompt,userPrompt:S.data.prompt,revisedPrompt:S.data.prompt,createdAt:Date.now(),videoContinuity:null}),h=w}catch{n().showToast(L("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;tn(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,...xc(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,...n().videoReferenceVoices.length>0?{referenceAudios:n().videoReferenceVoices}:{},topic:n().videoTopic||void 0,storyboard:n().storyboardActive||void 0,presetIds:c.appliedPresetIds,elementIds:bc(n()),sessionId:g,clientNodeId:e??null,...S?{providerUrl:S}:{}},k=await ro(w,{onPlanning:()=>t({inFlight:n().inFlight.map(N=>N.id===x?{...N,phase:"planning"}:N)}),onSubmitted:()=>t({inFlight:n().inFlight.map(N=>N.id===x?{...N,phase:"streaming"}:N)}),onProgress:({progress:N})=>t({videoProgress:N??null})},{signal:y.signal});if(r&&k&&n().activeSessionId===g&&(t({graphNodes:n().graphNodes.map(N=>N.id===e?{...N,data:{...N.data,serverNodeId:k.filename.replace(/\.[^.]+$/,""),imageUrl:k.url,status:"ready",error:void 0,errorInfo:null,pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,elapsed:k.elapsed??void 0,model:k.effectiveModel??k.requestedModel??r.data.model??null,videoContinuity:k.videoContinuity??m,video:{...k.video??{},...k.videoSeries?.topic?{topic:k.videoSeries.topic}:{}}}}:N)}),n().scheduleGraphSave(),n().flushGraphSave("video-node-complete")),k){const N={image:k.url,filename:k.filename,url:k.url,mediaType:"video",prompt:d,elapsed:k.elapsed,video:k.video??{},videoSeries:k.videoSeries??null,videoContinuity:k.videoContinuity??null,revisedPrompt:k.revisedPrompt??null,requestId:k.requestId??x,createdAt:Date.now(),sessionId:g};await gt(N,t,n,{autoSelectStartedAt:I})}}catch(S){if(Qt(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=st(S).code==="JOB_TRACKING_TIMEOUT",k=w?Ue(S,n()).message:S instanceof Error?S.message:"Video generation failed",N=w?{...ec(S),message:k}:null;r&&n().activeSessionId===g&&t({graphNodes:n().graphNodes.map(O=>O.id===e?{...O,data:{...O.data,status:"error",pendingRequestId:null,pendingPhase:null,pendingStartedAt:null,error:k,errorInfo:N}}:O)}),w||n().showToast(k,!0)}}finally{const S=n().inFlight.filter(w=>w.id!==x);Re(S),nn(x),t({inFlight:S,activeGenerations:S.length,videoProgress:null}),n().startInFlightPolling()}}async function vf(e,t,n,r){const s=t?.trim();if(!s)throw r().showToast(Pr,!0),new Error(Pr);if(Oo(r))return!1;const a=r(),i=Qr({catalog:es(),presetIds:a.selectedPresetIds,provider:Ic(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;tn(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:bc(r()),requestId:u,...xc(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 gt(I,n,r,{autoSelectStartedAt:d})}catch(h){return Qt(h)||(st(h).code==="JOB_TRACKING_TIMEOUT"?Ue(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),nn(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 wn(e){const t=new Map([...Fl({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:Hm({uiMode:e.uiMode,activeSessionId:e.activeSessionId,inFlight:[...t.values()]})}}function Fo(e,t){return e.uiMode===t.uiMode&&e.activeSessionId===(t.activeSessionId??null)}function Sc(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&&In(r,e.scopes)}).map(([n])=>n))}function bf(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 xf(e,t,n,r,s){if(t&&(s.mode==="reconcile"||!n))return[In(jr(t),r.scopes)?bf(e,t,s.mode):e];if(n)return In(jr(n),r.scopes)?(n.status==="error"&&s.terminalErrors.push(Vm(n)),[]):[e];const a=s.now-e.startedAt;return(s.mode==="poll"?a<=5e3:a<1e4)?[e]:[]}function wc(e,t,n,r){if(!Fo(e,t))return null;const s=wn(t),a=Sc(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)?xf(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);In(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 _n=0;function En(){if(_n+=1,typeof window>"u")return;const e=window;e.__ima2InflightTimer!==void 0&&clearInterval(e.__ima2InflightTimer),e.__ima2InflightTimer=void 0,e.__ima2StopTicks=0,window.removeEventListener(_t,En)}function If(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)Ue(s,n())}function Sf(e,t){e.length&&t(n=>{const r=new Set(n.history.map(ze)),s=e.filter(a=>{const i=ze(a);return r.has(i)?!1:(r.add(i),!0)});return s.length?(!n.currentImage&&s[0]?.filename&&ot(s[0].filename),{history:Jr([...s,...n.history],Math.max(qe,n.history.length+s.length)),currentImage:n.currentImage??s[0],loadedHistoryRetainLimit:Math.max(n.loadedHistoryRetainLimit,n.history.length+s.length)}):{}})}function wf(e,t,n){const r=wn(n()),s=Sc(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<Ll);i.length!==r.local.size&&(Re(i),t({inFlight:i,activeGenerations:i.length}))}async function _f(e,t,n,r,s){try{const a=r().history.reduce((l,c)=>Math.max(l,c.createdAt??0),0),{items:i}=await Yt({limit:qe,since:a});if(!s()||!Fo(e,r()))return;Sf(i.map(Ln),n),t&&wf(t,n,r)}catch{}}function Ef(e,t){const n=e.inFlight.length===0&&e.activeGenerations===0;return t.__ima2StopTicks=n?(t.__ima2StopTicks??0)+1:0,n}async function Nf(e,t,n){if(de()){En();return}const r=ge(),s=_n,a=()=>!de()&&r===ge()&&s===_n,i=wn(t());let l=null;if(!Ef(t(),n))try{const c=await Ol(i.scopes);if(!a())return;const d=wc(i,t(),c,{mode:"poll",now:Date.now()});if(!d)return;If(d,e,t),l={snapshot:wn(t()),eligibleIds:d.eligibleIds,serverActiveIds:d.serverActiveIds}}catch{}a()&&Fo(i,t())&&await _f(i,l,e,t,a),a()&&(n.__ima2StopTicks??0)>=2&&t().inFlight.length===0&&t().activeGenerations===0&&En()}function kf(e,t){if(typeof window>"u"||de())return;const n=window;n.__ima2InflightTimer||(window.addEventListener(_t,En),n.__ima2InflightTimer=window.setInterval(()=>Nf(e,t,n),1500))}async function Cf(e,t){if(de())return;const n=ge(),r=_n;try{const s=wn(t()),a=await Ol(s.scopes);if(de()||n!==ge()||r!==_n)return;const i=wc(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)Ue(l,t());i.inFlight.length&&t().startInFlightPolling()}catch{}}const Nt=()=>"nc_"+Math.random().toString(36).slice(2,10);function Ga(e,t){return{x:e*360,y:t*320}}const jf=360,_c=320;function Af(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 Ga(0,0);const n=Math.max(...t.map(r=>r.position.y));return{x:Ga(0,0).x,y:n+_c}}function Ec(e,t,n){const r=Af(e.id,t,n),s=e.position.x+jf;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+_c}}const Nn="source-right",kn="target-left";function ts(e,t,n,r){return`${e}:${n??"auto"}->${t}:${r??"auto"}`}function Pf(e,t){return e&&e.startsWith(`${t}-`)?e:null}function Rf(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 Tf(e,t){const n=Nt();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 Mf(e,t,n){const r=Nt();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 Lf(e,t,n){const r=n().graphNodes.find(l=>l.id===e);if(!r)return e;n().recordGraphHistory("add-child");const s=Nt(),a={id:s,type:"imageNode",position:Ec(r,n().graphNodes,n().graphEdges),data:{clientId:s,serverNodeId:null,parentServerNodeId:r.data.serverNodeId,prompt:Xe(r.data.imageUrl)&&r.data.prompt||"",imageUrl:null,status:"empty",pendingRequestId:null,pendingPhase:null}},i={id:ts(e,s,Nn,kn),source:e,target:s,sourceHandle:Nn,targetHandle:kn};if(t({graphNodes:[...n().graphNodes,a],graphEdges:[...n().graphEdges,i]}),n().scheduleGraphSave(),r.data.imageUrl&&Xe(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 en(l);t({graphNodes:n().graphNodes.map(d=>d.id===s?{...d,data:{...d.data,referenceImages:[c]}}:d)}),n().scheduleGraphSave()}catch{}})()}return s}function Of(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=Nt(),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=Nt(),c={id:l,type:"imageNode",position:Ec(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,Nn,kn),source:a,target:l,sourceHandle:Nn,targetHandle:kn};return t({graphNodes:[...n().graphNodes,c],graphEdges:[...n().graphEdges,d]}),n().scheduleGraphSave(),l}function Ff(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=Nt(),l=Pf(n,"source")??Nn,c=Rf(l)??kn,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 Df(e,t,n){const r=n().graphNodes.find(i=>i.id===e);if(!r)return e;n().recordGraphHistory("duplicate-branch");const s=Nt(),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 On(i,"node-reference.png");t({graphNodes:n().graphNodes.map(c=>c.id===s?{...c,data:{...c.data,referenceImages:[l]}}:c)})}catch{}})()}return s}function Gf(e,t,n,r){n({graphNodes:r().graphNodes.map(s=>s.id===e?{...s,data:{...s.data,prompt:t}}:s)}),r().scheduleGraphSave()}function zf(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),Ao(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:nt(a,i),graphEdges:i}),n().scheduleGraphSave()}function qf(e,t,n){const r=new Set(e);if(r.size===0)return;n().recordGraphHistory("delete-nodes");for(const i of r)Ao(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:nt(s,a),graphEdges:a}),n().scheduleGraphSave()}function $f(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:nt(l,a),graphEdges:a}),n().scheduleGraphSave(),n().flushGraphSave("edge-disconnect"),n().showToast(L("edge.disconnected"))}function Uf(e,t,n,r,s,a){if(e===t||a().graphEdges.find(d=>d.source===e&&d.target===t))return;if(ep(a().graphEdges,e,t)){a().showToast(L("edge.parentConflict"),!0);return}if(tp(a().graphEdges,e,t)){a().showToast(L("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:nt(a().graphNodes,c),graphEdges:c}),a().scheduleGraphSave()}async function Hf(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(L("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:Ml(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(L("toast.refHeicUnsupported"),!0),u.length-m.length>0&&r().showToast(L("toast.refTooLarge"),!0),t.length>l&&r().showToast(L("toast.refLimitExceeded"),!0)}function Nc(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 Vf(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(L("toast.refLimitExceeded"),!0);return}let i;try{i=Xe(t)||Xe(n)?await en(t):await On(t,n||"node-reference.png")}catch{s().showToast(L("toast.currentImageLoadFailed"),!0);return}Nc(e,i,r,s)}function Kf(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 Bf(e,t,n){Ao(n().activeSessionId,e),t({graphNodes:n().graphNodes.map(r=>r.id===e?{...r,data:{...r.data,referenceImages:void 0}}:r)}),n().scheduleGraphSave()}const za=10;function kc(e,t){return t?t.filename&&e.filename===t.filename?!0:e.image===t.image:!1}function Wf(e){return[e.canvasSourceFilename,e.canvasEditableFilename].filter(t=>!!t)}function Tt(e){return e.filter(t=>!t.canvasVersion)}function rt(e,t){if(!t)return null;const n=Tt(e);if(!t.canvasVersion)return n.find(a=>kc(a,t))??null;const r=Wf(t);return n.find(a=>a.filename?r.includes(a.filename):!1)??null}function Jf(e,t){const n=Tt(e),r=rt(e,t);return n.findIndex(s=>kc(s,r))}function Yf(e,t,n){const r=Tt(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=Jf(e,t);if(s<0)return null;if(n==="pagePrevious"||n==="pageNext"){const i=n==="pagePrevious"?-za:za,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 Cc(e,t){const n=Tt(e),r=n.findIndex(s=>s.filename===t);return r<0?null:n[r+1]??n[r-1]??null}function Pe(e){return e.filename||e.image}function gn(e){return!e.canvasVersion}function xr(e){const t=new Set;return e.filter(n=>{const r=Pe(n);return t.has(r)?!1:(t.add(r),!0)})}const jc=72,qa=10;function Ac(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 Xf(e){return e<=1?1:e===2?2:4}function Pc(e){const t=new Set,n=new Map,r=[];for(const s of e){if(!gn(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=Pe(s);t.has(a)||(t.add(a),r.push({type:"image",key:a,item:s}))}for(const s of n.values())s.items.sort(Ac);return r}function Rc(e,t){return t?`sequence:${t}`:e?.sequenceId?`sequence:${e.sequenceId}`:e?Pe(e):null}function ms(e){return e.type==="sequence"?{type:"sequence",sequenceId:e.sequenceId}:{type:"image",item:e.item}}function Zf(e,t,n,r,s=jc){const a=Pc(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=Rc(t,r),d=c?a.findIndex(h=>h.key===c):-1;if(d<0)return null;const u=n==="pagePrevious"?-qa:n==="pageNext"?qa: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 Tc={promptBuilderSurface:"right-panel",composerPlacement:"sidebar",multimodeHistoryGrouping:"individual",restoreComposerFromHistory:!0,viewerTools:"basic"},Qf={promptBuilderSurface:"right-panel",composerPlacement:"bottom",multimodeHistoryGrouping:"sequence",restoreComposerFromHistory:!1,viewerTools:"zoom-pan"},eh={default:Tc,"prompt-studio":Qf};function Dn(e,t){return eh[e]??Tc}function th(e,t){return Dn(e).promptBuilderSurface!=="off"}const nh="history:";function Mc(e,t,n){if(!t||n||!t.startsWith(nh)||!(t in e))return e;const r={...e};return delete r[t],r}function rh(e){const t=e.multimodePreviewFlightId;return t?t.startsWith("history:")?t.slice(8):e.multimodeSequences[t]?.sequenceId??null:null}async function sh(e,t){const n=t().historyNextCursor;if(!(!n||t().historyLoadingOlder)){e({historyLoadingOlder:!0});try{const r=await Yt({limit:qe,cursor:n}),s=r.items.map(Ln);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(L("gallery.loadOlderFailed"),!0)}}}async function oh(e,t){try{const n=await Yt({limit:qe,favoritesOnly:!0}),r=n.items.map(Ln);e(s=>{const a=ql(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(L("gallery.loadOlderFailed"),!0)}}async function ah(e,t){const n=t().favoriteHistoryNextCursor;if(!(!n||t().favoriteHistoryLoadingOlder)){e({favoriteHistoryLoadingOlder:!0});try{const r=await Yt({limit:qe,cursor:n,favoritesOnly:!0}),s=r.items.map(Ln);e(a=>{const i=ql(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(L("gallery.loadOlderFailed"),!0)}}}function ih(e,t,n){const r=Date.now(),s=n().history,a=e.canvasVersion?rt(s,e)??Tt(s)[0]??null:rt(s,e)??e;ot(a?.filename??null);const i=Dn(n().workspaceProfile).restoreComposerFromHistory,l=n().prompt,c=n().insertedPrompts,d=l.trim()!==""||c.length>0,u=i&&a&&!d?wm(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:Mc(b.multimodeSequences,p,!!h),...u}))}function lh(e,t,n){const r=Date.now(),s=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion).sort(Ac);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";ot(null),t(d=>({currentImage:null,lastHistorySelectedAt:r,unseenGeneratedCount:0,canvasOpen:!1,multimodePreviewFlightId:a,multimodeSequences:{...Mc(d.multimodeSequences,d.multimodePreviewFlightId,!1),[a]:{sequenceId:e,requestId:a,requested:i,returned:l,images:s,partials:[],status:c}}}))}function ch(e,t,n){const r=n(),s=Dn(r.workspaceProfile);if(r.uiMode==="classic"&&s.multimodeHistoryGrouping==="sequence"){const i=Zf(r.history,r.currentImage,e,rh(r));if(!i)return;if(i.type==="sequence"){n().showHistorySequence(i.sequenceId);return}n().selectHistory(i.item);return}const a=Yf(r.history,r.currentImage,e);a&&n().selectHistory(a)}async function dh(e,t,n){const r=e.canvasVersion?rt(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(L("gallery.deleteFailed"),!0);return}const s=r.filename,a=n().currentImage,l=(a?rt(n().history,a)??a:null)?.filename===s,c=l?Cc(n().history,s):a;try{await Di(s),t(d=>{const u=Bm(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&&ot(c?.filename??null),n().showToast(L("gallery.movedToSystemTrash",{filename:s}))}catch(d){console.error("[history] trash failed",d),n().showToast(L("gallery.deleteFailed"),!0)}}async function uh(e,t,n){const r=n().history.filter(d=>d.sequenceId===e&&!d.canvasVersion&&!!d.filename);if(r.length===0){n().showToast(L("gallery.deleteFailed"),!0);return}if(!window.confirm(L("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 Di(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&&ot(null),n().showToast(L("history.sequenceDeleted",{count:a.size}))}catch(d){console.error("[history] sequence trash failed",d),n().showToast(L("gallery.deleteFailed"),!0)}}async function mh(e,t){const n=t().trashPending;if(n)try{await au(n.filename,n.trashId),t().addHistoryItem(n.item),e({trashPending:null})}catch(r){console.error("[history] restore failed",r),t().showToast(L("gallery.restoreFailed"),!0)}}async function ph(e,t,n){const r=e.canvasVersion?rt(n().history,e):e;if(!r||r.canvasVersion||!r.filename){n().showToast(L("gallery.deleteFailed"),!0);return}const s=r.filename;if(!window.confirm(L("result.permanentDeleteConfirm",{filename:s})))return;const i=n().currentImage,c=(i?rt(n().history,i)??i:null)?.filename===s,d=c?Cc(n().history,s):i;try{await ou(s),t(u=>({history:u.history.filter(p=>p.filename!==s),currentImage:d,trashPending:u.trashPending?.filename===s?null:u.trashPending})),c&&ot(d?.filename??null),n().showToast(L("gallery.permanentDeleted",{filename:s}))}catch(u){console.error("[history] permanent delete failed",u),n().showToast(L("gallery.deleteFailed"),!0)}}function fh(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&&ot(null)}function hh(e,t,n){const r=n(),s={...e,createdAt:e.createdAt||Date.now()},a=Gl(r.history,s),i=zl(s,a),l=Dl(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 gh(e,t,n){if(!e.type||!/^image\/(png|jpeg|webp)$/.test(e.type))return n().showToast(L("toast.localImportInvalid"),!0),null;try{const r=await eu(e);return n().addHistoryItem(r),t({currentImage:r,unseenGeneratedCount:0}),r.filename&&ot(r.filename),n().showToast(L("toast.localImportSuccess")),r}catch{return n().showToast(L("toast.localImportFailed"),!0),null}}function yh(e,t){(async()=>{try{const n=await Yt({limit:qe}),r=n.items.map(Ln);if(e({historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:qe}),r.length>0){const s=El(),a=s?r.find(c=>c.filename===s):null,i=Tt(r),l=(a?rt(r,a):null)??i[0]??null;e({history:r,currentImage:l,historyNextCursor:n.nextCursor,loadedHistoryRetainLimit:Math.max(qe,r.length)}),l?.filename!==s&&ot(l?.filename??null)}}catch(n){console.warn("[history] load failed:",n)}})()}async function Lc(e,t){try{const{sessions:n}=await lu();if(e({sessions:n}),!t().activeSessionId){const s=Rm(),a=s?n.some(i=>i.id===s):!1;s&&a?await t().switchSession(s):await t().createAndSwitchSession(L("session.firstGraph"))}}catch(n){console.warn("[sessions] load failed:",n),t().showToast(L("modal.sessionInitialLoadFailed"),!0),window.confirm(L("modal.sessionInitialLoadRetry"))&&await Lc(e,t)}}async function vh(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(L("modal.sessionSwitchSaveFailed"),!0);return}t({sessionLoading:!0});try{const{session:r}=await Gi(e),{graphNodes:s,graphEdges:a,graphVersion:i}=Kl(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(L("toast.sessionLoadFailed"),!0)}}}async function bh(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 Li({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:L("session.assetAbortedError")}}});e({graphNodes:c})}await Xl(t,e).catch(()=>{})}async function xh(e,t,n){e==null&&(e=L("session.untitled"));try{const{session:r}=await cu(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(L("toast.sessionCreateFailed"),!0)}}async function Ih(e,t,n){const r=n().activeSessionId;if(r)try{await du(r,e),t({sessions:n().sessions.map(s=>s.id===r?{...s,title:e,updatedAt:Date.now()}:s)})}catch{n().showToast(L("toast.sessionRenameFailed"),!0)}}async function Sh(e,t,n){try{await uu(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(L("session.firstGraph")))}catch{n().showToast(L("toast.sessionDeleteFailed"),!0)}}function wh(e,t){const n={},r=t.userPrompt||t.prompt;typeof r=="string"&&(n.prompt=r),kl(t.quality)&&(n.quality=t.quality),Cl(t.format)&&(n.format=t.format),jl(t.moderation)&&(n.moderation=t.moderation),(t.promptMode==="auto"||t.promptMode==="direct")&&(n.promptMode=t.promptMode),t.model&&Ru(t.model)&&(n.imageModel=t.model);const s=Mm(t.size);return s.preset&&(n.sizePreset=s.preset),s.preset==="custom"&&s.w&&s.h&&(n.customW=tt(s.w,e.customW),n.customH=tt(s.h,e.customH)),n}function Gn(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 Oc(e,t){return{kind:"attachment",tokenId:crypto.randomUUID(),tag:t,insertedAt:Date.now(),source:e}}function zo(e,t){return Gn(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=oc(c,i),p=Oc(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 _h(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 Eh(e,t,n){ns(e,"gallery",t)}async function Nh(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:Ml(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(L("toast.refHeicUnsupported"),!0),l.length-d.length>0&&n().showToast(L("toast.refTooLarge"),!0),(e.length>s||d.length>u.length)&&n().showToast(L("toast.refLimitExceeded"),!0)}async function kh(e,t,n,r){if(!e.type.startsWith("image/"))return!1;let s="";try{s=await Co(e);const a=await pu({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(L("metadata.readFailed"),!0),!1}}function Ch(e,t){const n=t().metadataRestore;if(!n)return;const r=wh(t(),n.metadata);if(r.imageModel&&wl(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(L("metadata.applied"))}function qo(e){return e.insertedPrompts.filter(t=>!t.id.startsWith("video-continuity:"))}function $o(e,t){t.length!==e.length&&te({insertedPrompts:t})}function Fc(e,t,n){const r=n().insertedPrompts;Gn(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=Fn({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 jh(e,t,n){const r=Fn(n())[e];r&&Fc(r.tokenId,t,n)}function Ah(e,t){const n=t().insertedPrompts;Gn(e,r=>{const s=Fn(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 Ph(e,t){const n=t().insertedPrompts;Gn(e,r=>({result:void 0,patch:{trayItems:[],retiredTags:{},canvasReferenceImage:null,videoContinuityLineage:null,insertedPrompts:qo(r),providerUrlReference:null}})),$o(n,t().insertedPrompts)}function Rh(e,t,n){const r=Fn(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=oc(e.nextAttachmentOrdinal,a.map(d=>d.tag)),l=Oc(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 Th(e,t,n,r){let s;try{s=await On(r??e.image,e.filename||"canvas-version-reference.png")}catch{throw n().showToast(L("toast.currentImageLoadFailed"),!0),new Error("canvas_reference_attach_failed")}const a=Go(s);if(!a){n().showToast(L("toast.currentImageLoadFailed"),!0);return}if(!Gn(t,(l,c)=>Rh(l,c,{dataUrl:s,mimeType:a,originalName:e.filename||"canvas-version-reference.png",origin:"canvas"}))){n().showToast(L("toast.refSlotFull"),!0);return}n().showToast(L("canvas.version.usingAsReference"))}function Dc(e){return e.canvasVersion&&e.canvasSourceFilename?`/generated/${encodeURIComponent(e.canvasSourceFilename)}`:e.image}async function Mh(e,t){const n=t().currentImage;if(!n){t().showToast(L("toast.noCurrentImageForRef"),!0);return}if(t().trayItems.length>=t().activeReferenceLimit()){t().showToast(L("toast.refSlotFull"),!0);return}let r;try{r=await On(Dc(n),n.canvasSourceFilename||n.filename||"current-reference.png")}catch{t().showToast(L("toast.currentImageLoadFailed"),!0);return}if(!ns(r,"gallery",e)){t().showToast(L("toast.refSlotFull"),!0);return}t().showToast(L("toast.addedCurrentAsRef"))}async function Lh(e,t,n){if(n().trayItems.length>=n().activeReferenceLimit()){n().showToast(L("toast.refSlotFull"),!0);return}let r;try{r=await On(Dc(e),e.canvasSourceFilename||e.filename||"canvas-reference.png")}catch{n().showToast(L("toast.currentImageLoadFailed"),!0);return}if(!ns(r,"gallery",t)){n().showToast(L("toast.refSlotFull"),!0);return}n().showToast(L("toast.addedCurrentAsRef"))}function zn(e){const{provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:s,comfyVideoWorkflow:a}=e();return lt({provider:t,imageModel:n,videoModelSelected:r,comfyWorkflow:s,comfyVideoWorkflow:a})}function qn(e,t,n,r){const s=Pl();s[e.provider]={...s[e.provider],...ba(e)};const a={...s[t.provider],...ba(t)};r&&delete a[r],s[t.provider]=a,Gm(s),zm(t),n(t)}function Oh(e,t,n){const r=zn(n);if(e===r.provider)return;const s=Pt(e)?Pl()[e]:void 0,a=Hu(r,e,s);qn(r,a,t)}function Fh(e,t,n){const r=zn(n),s=lt({provider:Uu(r.provider,e),imageModel:e,videoModelSelected:!1});qn(r,s,t)}function Dh(e,t,n){const r=zn(n),s=lt({provider:r.provider==="grok-api"?"grok-api":"grok",imageModel:r.imageModel,videoModelSelected:Rt(e)||et});qn(r,s,t)}function Gh(e,t,n){const r=zn(n),s=lt({...r,provider:"comfy",comfyWorkflow:e,comfyVideoWorkflow:null});qn(r,s,t,e===null?"image":void 0)}function zh(e,t,n){const r=zn(n),s=lt({...r,provider:"comfy",comfyVideoWorkflow:e,videoModelSelected:!1});qn(r,s,t,e===null?"video":void 0)}function qh(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 $h(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&&qh(t,e.graphEdges??[],n)?.data?.imageUrl?1:0}return e.referenceImages?.length??0}const Uh=1e4;let Cn=[];async function Uo(e){const t=await q("/api/mcp/providers",{signal:e});return Cn=Array.isArray(t.providers)?t.providers:[],Cn}function Hh(e){return Ri("/api/mcp/providers",e)}function Vh(e,t){return Ri(`/api/mcp/providers/${encodeURIComponent(e)}/models`,t)}function Kh(){return Cn}async function Rw(e){const t=window.open("about:blank",`ima2_mcp_${e}`);try{const n=await q(`/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 Tw(e){return(await q(`/api/mcp/providers/${encodeURIComponent(e)}/refresh`,{method:"POST"})).status}async function Mw(e){return(await q(`/api/mcp/providers/${encodeURIComponent(e)}/connection`,{method:"DELETE"})).status}async function Gc(e,t){const r=(await q(`/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 Bh(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 Wh(e,t){let n=!1;const r=()=>n?!1:(n=!0,s(),a(),!0),s=jt(e,null,(i,l)=>{if(i==="done"){const c=Bh(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?.(Ze(l,typeof l.message=="string"?l.message:"MCP generation failed"))}),a=Jt(()=>{if(!r())return;const i=new Error("MCP generation timed out");i.code="MCP_STREAM_TIMEOUT",t.onError?.(i)});return r}async function Jh(e,t){const n=e.requestId??`mcp_ui_${Date.now()}`,r=Wh(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 q("/api/mcp/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,requestId:n})}),n}catch(s){throw r(),s}}function zc(){const[e,t]=v.useState(()=>[...Cn]),[n,r]=v.useState(Cn.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()},Uh);return()=>window.clearInterval(l)},[i]),{providers:e,loading:n,error:s,refresh:i}}let Rr=null;function qc(e){if(st(e).code==="JOB_TRACKING_TIMEOUT")return L("toast.jobTrackingTimeout");const t=e,n=t.code??t.message??"";return n.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")||t.message?.startsWith("MCP_INPUT_ROLE_UNSUPPORTED")?L("mcp.errorUnsupportedInput"):n==="MCP_END_FRAME_REQUIRES_START"?L("mcp.errorEndRequiresStart"):n==="INVALID_MCP_REFERENCES"?L("mcp.errorInvalidReferences"):n==="INVALID_START_FRAME"?L("mcp.errorInvalidFrame"):n.startsWith("INVALID_MCP_TEMP_REFERENCE")||n==="MCP_TEMP_REFERENCES_FAILED"?L("mcp.errorTempReferences"):L(n==="MCP_NOT_CONNECTED"||n==="MCP_PROVIDER_UNKNOWN"?"mcp.selectionUnavailable":"mcp.generateFailed")}async function Yh(e){const t=e.references.filter(a=>a.dataUrl);if(t.length===0)return{selection:e,batchId:null};const n=await q("/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 Xh(e){try{await q(`/api/mcp/temp-references/${encodeURIComponent(e)}`,{method:"DELETE"})}catch(t){console.error("[mcp] temporary reference cleanup failed",t)}}async function Zh(e,t,n){let r=()=>{};const s=new Promise(i=>{r=i});if(await Jh(e,{onDone:()=>{t().hydrateHistory(),r()},onError:i=>{t().showToast(qc(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 Qh(e){const t=e();if((t.mcpProvider?Kh().find(c=>c.id===t.mcpProvider):void 0)?.executable===!1){e().showToast(L("mcp.higgsfieldLocked"),!0);return}const r=Pn(t.prompt,t.insertedPrompts);if(!r)return;const s=t.mcpReferenceSelection??$e();if(hm(s)){e().showToast(L("mcp.referenceTagInvalid"),!0);return}const a=t.selectedElementIds??[];if(t.mcpCharacterElementId&&a.length>0){e().showToast(L("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?Il(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 Yh(s);l=c.batchId;const d=Im({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 Zh(d,e,!!l)}catch(c){e().showToast(qc(c),!0)}finally{l&&await Xh(l)}}function rn(e){Mn(null,null,"image"),te({mcpRatio:null,mcpParameters:{}}),e({mcpProvider:null,mcpModel:null,mcpMediaKind:"image",mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:$e(),mcpCharacterElementId:null,...Rr?{generate:Rr}:{}})}function rs(e,t,n,r=null,s){if(!e){rn(t);return}Rr||(Rr=n().generate);const a=n().mcpProvider===e?n().mcpModel??r:r,i=s??n().mcpMediaKind??"image",l=n().mcpProvider!==e;Mn(e,a,i),te({count:1,multimode:!1,...l?{mcpRatio:null,mcpParameters:{}}:{}}),t({mcpProvider:e,mcpModel:a,mcpMediaKind:i,...l?{mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:$e()}:{},count:1,multimode:!1,generate:()=>Qh(n)})}function eg(e,t,n){Mn(n().mcpProvider??null,e,n().mcpMediaKind??"image"),te({mcpRatio:null,mcpParameters:{}}),t({mcpModel:e,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:$e()})}function tg(e,t,n,r,s){const a=ym(s);let i=s?So(s.inputRoles,r().mcpReferenceSelection):$e();const l=r().currentImage;s?.inputRoles.includes("start_image")&&!i.startFrameFilename&&l?.filename&&!ve(l)&&(i={...i,startFrameFilename:l.filename}),Mn(r().mcpProvider??null,e,t),te({mcpRatio:a.ratio,mcpParameters:a.parameters}),n({mcpModel:e,mcpMediaKind:t,mcpRatio:a.ratio,mcpParameters:a.parameters,mcpInputRoles:s?[...s.inputRoles]:[],mcpReferenceSelection:i})}function ng(e,t,n){(n().mcpMediaKind??"image")!==e&&(Mn(n().mcpProvider??null,null,e),te({mcpRatio:null,mcpParameters:{}}),t({mcpMediaKind:e,mcpModel:null,mcpRatio:null,mcpParameters:{},mcpInputRoles:[],mcpReferenceSelection:$e()}))}function rg(e,t){te({mcpRatio:e}),t({mcpRatio:e})}function sg(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,te({mcpParameters:s}),n({mcpParameters:s})}function og(e,t,n){const r=So(n().mcpInputRoles??[],Io(e)),s=n().mcpReferenceSelection??$e();xl(s,r)||t({mcpReferenceSelection:r})}function ag(e,t,n){const r={ratio:n().mcpRatio??null,parameters:n().mcpParameters??{}},s=vl(e,r.ratio,r.parameters),a=n().mcpReferenceSelection??$e(),i=So(e.inputRoles,a),l=JSON.stringify(n().mcpInputRoles??[])!==JSON.stringify(e.inputRoles),c=!vm(r,s),d=!xl(a,i);!c&&!d&&!l||(c&&te({mcpRatio:s.ratio,mcpParameters:s.parameters}),t({...c?{mcpRatio:s.ratio,mcpParameters:s.parameters}:{},mcpInputRoles:[...e.inputRoles],mcpReferenceSelection:i}))}function ig(e,t){const n=Dm();n.provider&&(rs(n.provider,e,t,n.model,n.kind),te({mcpRatio:n.ratio,mcpParameters:n.parameters}),e({mcpRatio:n.ratio,mcpParameters:n.parameters}))}function lg(e,t,n){rn(t),Oh(e,t,n)}function cg(e,t){te({quality:e}),t({quality:e})}function dg(e,t){te({sizePreset:e}),t({sizePreset:e})}function ug(e,t,n,r){const s=tt(e,r().customW),a=tt(t,r().customH);te({customW:s,customH:a}),n({customW:s,customH:a})}function mg(e,t){te({grokAspectRatio:e}),t({grokAspectRatio:e})}function pg(e,t){te({grokResolution:e}),t({grokResolution:e})}function fg(e,t){te({format:e}),t({format:e})}function hg(e,t){te({moderation:e}),t({moderation:e})}function gg(e,t,n){rn(t),Fh(e,t,n)}function yg(e,t,n){rn(t),Dh(e,t,n)}function vg(e,t,n){rn(t),Gh(e,t,n)}function bg(e,t,n){rn(t),zh(e,t,n)}function xg(e){return $h(e())}function Ig(e,t){Cm(e),t({reasoningEffort:e})}function Sg(e,t){Pm(e),t({webSearchEnabled:e})}function wg(e,t){const n=bn(e);te({count:n}),t({count:n})}function _g(e,t,n){if(e&&n().uiMode!=="classic")return;te({multimode:e});const r=n();t({multimode:e,multimodeSequences:e?r.multimodeSequences:{},multimodePreviewFlightId:e?r.multimodePreviewFlightId:null})}function Eg(e,t){const n=bn(e);te({multimodeMaxImages:n}),t({multimodeMaxImages:n})}function Ng(e,t){te({promptMode:e}),t({promptMode:e})}function kg(e,t){te({prompt:e}),t({prompt:e})}function Cg(e,t){te({negativePrompt:e}),t({negativePrompt:e})}function jg(e,t,n,r){const s={...r().naiOptionOverrides,[e]:t};_l(s),n({naiOptionOverrides:s})}function Ag(e){_l({}),e({naiOptionOverrides:{}})}function Pg(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 Rg(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=ve({...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 Tg(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 te({insertedPrompts:a}),{insertedPrompts:a}})}function Mg(e,t){t(n=>{const r=n.insertedPrompts.filter(s=>s.id!==e);return te({insertedPrompts:r}),{insertedPrompts:r,videoContinuityLineage:e.startsWith("video-continuity:")?null:n.videoContinuityLineage}})}function Lg(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 te({insertedPrompts:p}),{insertedPrompts:p}})}function Og(e){te({insertedPrompts:[]}),e({insertedPrompts:[],videoContinuityLineage:null})}async function Fg(e){e({promptLibraryLoading:!0});try{const t=await fu();e({promptLibrary:{prompts:t.prompts,folders:t.folders},promptLibraryLoading:!1})}catch(t){console.error("[PromptLibrary] load failed",t),e({promptLibraryLoading:!1})}}async function Dg(e,t,n){try{await hu(e),await n().loadPromptLibrary(),n().showToast(L("promptLibrary.saved"))}catch(r){console.error("[PromptLibrary] save failed",r),n().showToast(L("promptLibrary.saveFailed"),!0)}}async function Gg(e,t,n){try{await gu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] delete failed",r)}}async function zg(e,t,n){try{await yu(e),await n().loadPromptLibrary()}catch(r){console.error("[PromptLibrary] favorite toggle failed",r)}}async function qg(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()||L("promptLibrary.untitled"),text:i.trim(),tags:[]})}if(r.length===0){n().showToast(L("promptLibrary.importNoValidFiles"),!0);return}const s=await vu({prompts:r});await n().loadPromptLibrary(),n().showToast(L("promptLibrary.imported",{count:s.promptsImported}))}catch(r){console.error("[PromptLibrary] import failed",r),n().showToast(L("promptLibrary.importFailed"),!0)}}async function $g(e,t,n){const r=e.filename;if(!r)return null;let s;try{s=(await nu(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(L("gallery.favoriteFailed"),!0),null}if(!s)return s;try{await Rg({...e,filename:r},{getAssets:so,createAsset:$r,updateAsset:zi})!=="noop"&&n().showToast(L("assets.starSaved"))}catch(a){console.error("[GalleryFavorite] asset sync failed",a),n().showToast(L("assets.starSaveFailed"),!0)}return s}async function Ug(e,t,n){if(e){nc(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(L("toast.cancelFailed"),!0)}}}function Hg(e,t){const n=Fl(),r=El(),s=Rl(),a=Wr();e(i=>{const l=r?i.history.find(p=>p.filename===r)??null:null,c=l?rt(i.history,l):null,d=Tt(i.history)[0]??null,u=i.currentImage?.canvasVersion?rt(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 Vg(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 Kg(e,t){const n=t().metadataRestore;n&&(n.targetNodeId?t().addNodeReferenceDataUrl(n.targetNodeId,n.image):t().addReferenceDataUrl(n.image),e({metadataRestore:null}))}function Bg(e,t){const n=!t().rightPanelOpen;try{localStorage.setItem(Xi,JSON.stringify(n))}catch{}e({rightPanelOpen:n})}function Wg(e,t){try{localStorage.setItem(go,e)}catch{}t({galleryScope:e})}function Jg(e,t){try{localStorage.setItem(sl,e),localStorage.setItem(go,e)}catch{}t({galleryDefaultScope:e,galleryScope:e})}function Yg(e,t){const n=e==="card-news"&&!il?"classic":e;try{localStorage.setItem(Zi,n)}catch{}t({uiMode:n})}function Xg(e,t){try{localStorage.setItem(Qi,e)}catch{}t({historyStripLayout:e})}function Zg(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 Qg(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 ey(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 ty(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 ny(e,t,n){t({graphNodes:nt(e,n().graphEdges)}),n().scheduleGraphSave()}function ry(e,t,n){t({graphEdges:e,graphNodes:nt(n().graphNodes,e)}),n().scheduleGraphSave()}function sy(e,t){const n=!t().nodeSelectionMode;e({nodeSelectionMode:n,...n?{}:{graphNodes:xn(t().graphNodes,[])}})}function oy(e,t,n,r){n({graphNodes:$m(r().graphNodes,r().graphEdges,e,t)})}function ay(e,t){t().nodeBatchRunning&&(e({nodeBatchStopping:!0}),t().showToast(L("nodeBatch.stopQueued")))}function iy(e,t,n){n({canvasPanX:Math.max(-4e3,Math.min(4e3,e)),canvasPanY:Math.max(-4e3,Math.min(4e3,t))})}function ly(e,t,n){t({canvasExportBackground:e}),Sl(e,n().canvasExportMatteColor)}function cy(e,t,n){t({canvasExportMatteColor:e}),Sl(n().canvasExportBackground,e)}const ct=e=>console.error("[assets]",e instanceof Error?e.message:String(e));let fs=0;async function $c(e){const{folders:t}=await oo();e({assetsFolders:t})}const Ho=$c;async function Vo(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){ct(a),s===fs&&t({assetsLoading:!1,...r?{assetsLoadError:!0}:{}})}}async function dy(e,t){!t().assetsCursor||t().assetsLoading||await Vo(!1,e,t)}function $a(e,t,n){t(r=>({assetsFilters:{...r.assetsFilters,...e}})),Vo(!0,t,n)}async function uy(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:ve(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 ct(s),!1}}async function my(e,t,n){try{const{asset:r}=await zi(e,t);let s=null;try{s=(await ao()).tags}catch(a){ct(a)}return n(a=>{const i=a.assetsFilters.tag;return{assets:i&&!r.tags.includes(i)?a.assets.filter(c=>c.id!==e):a.assets.map(c=>c.id===e?r:c),...s?{assetsTags:s}:{}}}),!0}catch(r){return ct(r),!1}}async function py(e,t){try{return await Iu(e),t(n=>({assets:n.assets.filter(r=>r.id!==e)})),!0}catch(n){return ct(n),!1}}async function fy(e,t,n){try{return await Su({name:e,parentId:t}),await Ho(n),!0}catch(r){return ct(r),!1}}async function hy(e,t,n){try{return await qi(e,{name:t}),await Ho(n),!0}catch(r){return ct(r),!1}}async function gy(e,t,n){try{return await qi(e,{parentId:t}),await Ho(n),!0}catch(r){return ct(r),!1}}async function yy(e,t){try{await wu(e);const[{folders:n},{tags:r}]=await Promise.all([oo(),ao()]);return t({assetsFolders:n,assetsTags:r}),!0}catch(n){return ct(n),!1}}function vy(e){const t=e.assetGenProvider;if(t==="grok"||t==="grok-api")return"grok-imagine-image-2.0";if(!(Tu(e.imageModel)||Mu(e.imageModel)))return e.imageModel}async function Uc(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 by(e,t,n){const r=n().assetGenItems.find(s=>s.requestId===e);r&&(r.mediaType==="video"?await Hc(r,t,n):await Uc(r,t,n))}async function xy(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 gt(l,t,n,{autoSelectStartedAt:Date.now()}),t(c=>({assetGenItems:[l,...c.assetGenItems]})),await Hc(l,t,n),n().showToast(L("toast.generatedSingle",{elapsed:String(i.elapsed??"")}))}async function Hc(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 Iy(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;tn(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 xy(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:vy(n),requestId:s,mode:n.promptMode,backgroundPreset:n.assetGenBackground},d=await Fi(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 gt(p,e,t,{autoSelectStartedAt:i}),e(m=>({assetGenItems:[p,...m.assetGenItems]})),await Uc(p,e,t),t().showToast(L("toast.generatedSingle",{elapsed:d.elapsed}))}catch(c){if(!Qt(c)){const d=Ue(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),nn(s),e({activeGenerations:Math.max(0,t().activeGenerations-1),inFlight:c})}}function Sy(e){return[...new Set(e.filter(t=>typeof t=="string"))]}function on(e){te({presetIds:e})}const wy=e=>({selectedPresetIds:Tn().presetIds??[],addPreset:t=>e(n=>{if(n.selectedPresetIds.includes(t))return n;const r=[...n.selectedPresetIds,t];return on(r),{selectedPresetIds:r}}),removePreset:t=>e(n=>{const r=n.selectedPresetIds.filter(s=>s!==t);return on(r),{selectedPresetIds:r}}),togglePreset:t=>e(n=>{const r=n.selectedPresetIds.includes(t)?n.selectedPresetIds.filter(s=>s!==t):[...n.selectedPresetIds,t];return on(r),{selectedPresetIds:r}}),clearPresets:()=>{on([]),e({selectedPresetIds:[]})},restorePresetIds:t=>{const n=Sy(t);on(n),e({selectedPresetIds:n})}});function _y(){return{name:"",characterId:"",description:"",style:"",baseAssetId:"",cell:{width:256,height:256,safeMarginX:8,safeMarginY:8},chroma:{preset:"green",hex:"#00ff00"},states:[{key:"idle",frames:4,fps:8,loop:!0,action:"idle"}]}}const $n=(e,t="POST",n)=>({method:t,signal:n,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),Ey=e=>q("/api/sprite-recipes",{signal:e}),Ny=(e,t)=>q(`/api/sprite-recipes/${encodeURIComponent(e)}`,{signal:t}),ky=(e,t)=>q("/api/sprite-recipes",$n(e,"POST",t)),Cy=(e,t,n)=>q(`/api/sprite-recipes/${encodeURIComponent(e)}`,$n(t,"PATCH",n)),jy=(e,t={},n)=>q(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,$n({...t,async:!0},"POST",n)),Ay=(e,t,n)=>q(`/api/sprite-recipes/${encodeURIComponent(e)}/anchor/approve`,$n({assetId:t},"POST",n)),Py=(e,t={},n)=>q(`/api/sprite-recipes/${encodeURIComponent(e)}/generate`,$n({...t,async:!0},"POST",n)),Vt=new Map,Un=e=>e instanceof Error?e.message:String(e),Vc=e=>({id:e.id,name:e.name,anchorStatus:e.anchorStatus,updatedAt:e.updatedAt});async function Ry(e,t){e({spriteRecipeLoading:!0,spriteRecipeError:null});try{const{recipes:n}=await Ey();e({spriteRecipes:n.map(Vc)}),t().activeSpriteRecipeId&&await Ko(t().activeSpriteRecipeId,e,t)}catch(n){e({spriteRecipeError:Un(n)})}finally{e({spriteRecipeLoading:!1})}}async function Ko(e,t,n){if(t({activeSpriteRecipeId:e,spriteRecipeError:null}),!e){t({activeSpriteRecipe:null});return}t({spriteRecipeLoading:!0});try{const{recipe:r}=await Ny(e);t({activeSpriteRecipe:r,spriteRecipeDraft:r,spriteRecipeDirty:!1})}catch(r){t({spriteRecipeError:Un(r)})}finally{t({spriteRecipeLoading:!1})}}async function Ty(e,t){e({spriteRecipeSaving:!0,spriteRecipeError:null});try{const n=t(),r=n.activeSpriteRecipeId?await Cy(n.activeSpriteRecipeId,n.spriteRecipeDraft):await ky(n.spriteRecipeDraft);return e(s=>({activeSpriteRecipeId:r.recipe.id,activeSpriteRecipe:r.recipe,spriteRecipeDraft:r.recipe,spriteRecipeDirty:!1,spriteRecipes:[Vc(r.recipe),...s.spriteRecipes.filter(a=>a.id!==r.recipe.id)]})),r.recipe.id}catch(n){return e({spriteRecipeError:Un(n)}),null}finally{e({spriteRecipeSaving:!1})}}function Kc(e,t,n){Vt.get(e)?.(),Vt.set(e,jt(e,null,(r,s)=>Dy({event:r,data:{...s,requestId:e}},t,n)))}function Bo(e){Vt.get(e)?.(),Vt.delete(e)}function Bc(e,t){return st(e).code==="JOB_TRACKING_TIMEOUT"?Ue(e,t()).message:Un(e)}async function My(e,t){const n=t().activeSpriteRecipeId;if(!n)return;e({spriteRecipeGenerating:!0,spriteRecipeError:null});const r=crypto.randomUUID();try{Kc(r,e,t),await no(),await jy(n,{requestId:r,async:!0})}catch(s){Bo(r),e({spriteRecipeError:Bc(s,t),spriteRecipeGenerating:!1})}}async function Ly(e,t,n){const r=n().activeSpriteRecipeId;if(r){t({spriteRecipeGenerating:!0,spriteRecipeError:null});try{const{recipe:s}=await Ay(r,e);t({activeSpriteRecipe:s,spriteRecipeDraft:s,spriteRecipeDirty:!1})}catch(s){t({spriteRecipeError:Un(s)})}finally{t({spriteRecipeGenerating:!1})}}}async function Oy(e,t,n){const r=n().activeSpriteRecipeId;if(!r)return;t({spriteRecipeGenerating:!0,spriteRecipeError:null});const s=crypto.randomUUID();try{Kc(s,t,n),await no(),await Py(r,{requestId:s,stateKeys:e,async:!0})}catch(a){Bo(s),t({spriteRecipeError:Bc(a,n),spriteRecipeGenerating:!1})}}async function Fy(e,t,n){Vt.get(e)?.(),Vt.delete(e),t({spriteRecipeGenerating:!1})}function Dy(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=Ze(e.data,a),l=st(i).code==="JOB_TRACKING_TIMEOUT"?Ue(i,n()).message:a;t({spriteRecipeError:l,spriteRecipeGenerating:!1})}if(e.event==="done"){t({spriteRecipeGenerating:!1});const a=n().activeSpriteRecipeId;a&&Ko(a,t)}}function Gy(e,t){t(n=>({spriteRecipeDraft:{...n.spriteRecipeDraft,...e},spriteRecipeDirty:!0}))}const Ae=Tn(),Xn=Wr(),Zn=Rl(),f=Pi((e,t,n)=>({...wy(e),assets:[],assetGenWorkflow:"generate",setAssetGenWorkflow:r=>e({assetGenWorkflow:r}),spriteRecipes:[],activeSpriteRecipeId:null,activeSpriteRecipe:null,spriteRecipeDraft:_y(),spriteRecipeDirty:!1,spriteRecipeLoading:!1,spriteRecipeSaving:!1,spriteRecipeGenerating:!1,spriteRecipeError:null,spriteSelectedStates:[],spritePartialPreviews:{},loadSpriteRecipes:()=>Ry(e,t),selectSpriteRecipe:r=>Ko(r,e),updateSpriteRecipeDraft:r=>Gy(r,e),saveSpriteRecipe:()=>Ty(e,t),generateSpriteAnchor:()=>My(e,t),approveSpriteAnchor:r=>Ly(r,e,t),generateSpriteRows:r=>Oy(r,e,t),cancelSpriteJob:r=>Fy(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}),$a({folderId:r},e,t)},loadAssetFolders:()=>$c(e),retryAssetGenSave:r=>by(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:()=>Iy(e,t),loadAssets:r=>Vo(r,e,t),loadMoreAssets:()=>dy(e,t),setAssetsFilters:r=>$a(r,e,t),saveToAssets:r=>uy(r,e,t),updateAssetItem:(r,s)=>my(r,s,e),deleteAssetItem:r=>py(r,e),createAssetFolder:(r,s)=>fy(r,s,e),renameAssetFolder:(r,s)=>hy(r,s,e),moveAssetFolder:(r,s)=>gy(r,s,e),deleteAssetFolder:r=>yy(r,e),...Zn,quality:Ae.quality??"medium",sizePreset:Ae.sizePreset??"1024x1024",customW:Ae.customW??1920,customH:Ae.customH??1088,grokAspectRatio:Ae.grokAspectRatio??"1:1",grokResolution:Ae.grokResolution??"1k",format:Ae.format??"png",moderation:Ae.moderation??"low",count:Ae.count??1,multimode:Ae.multimode??!1,multimodeMaxImages:Ae.multimodeMaxImages??4,multimodeSequences:{},activeFlightIds:new Set,multimodePreviewFlightId:null,promptMode:Ae.promptMode??"auto",prompt:Ae.prompt??"",negativePrompt:Ae.negativePrompt??"",naiOptionOverrides:jm(),naiServerDefaults:null,insertedPrompts:Ae.insertedPrompts??[],mcpInputRoles:[],mcpReferenceSelection:$e(),mcpCharacterElementId:null,trayItems:[],nextAttachmentOrdinal:1,retiredTags:{},elementCatalog:null,missingElementIds:[],pendingAssetDetailId:null,referenceImages:[],selectedElementIds:[],referenceLimit:No,activeReferenceLimit:()=>tc({provider:t().provider,serverLimit:t().referenceLimit,videoModelSelected:!!t().videoModelSelected,mcpProvider:t().mcpProvider??null}),providerUrlReference:null,canvasReferenceImage:null,physicalVideoSourceCount:()=>$p(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:Ti(),canvasOpen:!1,canvasZoom:1,canvasPanX:0,canvasPanY:0,canvasExportBackground:Aa().mode,canvasExportMatteColor:Aa().matteColor,syncCapabilities:()=>Ym(e),addTrayAttachments:async r=>_h(r,e),addTrayAttachmentDataUrl:(r,s)=>ns(r,s,e),addTrayElement:r=>br(r,e),addElementFromMention:r=>br(r.id,e,t,r),syncElementCatalog:r=>dc(r,e),openAssetDetail:r=>e({uiMode:"assets",pendingAssetDetailId:r}),removeTrayItem:r=>Fc(r,e,t),clearTray:()=>Ph(e,t),addElementId:r=>{br(r,e)},removeElementId:r=>Vp(r,e),addReferences:r=>Nh(r,e,t),addReferenceDataUrl:r=>Eh(r,e),metadataRestore:null,readDroppedImageMetadata:(r,s=null)=>kh(r,s,e,t),applyMetadataRestore:()=>Ch(e,t),cancelMetadataRestore:()=>e({metadataRestore:null}),addMetadataRestoreAsReference:()=>Kg(e,t),removeReference:r=>jh(r,e,t),setProviderUrlReference:r=>e({providerUrlReference:r}),clearReferences:()=>Ah(e,t),attachCanvasVersionReference:(r,s)=>Th(r,e,t,s),useCurrentAsReference:()=>Mh(e,t),useImageAsReference:r=>Lh(r,e,t),activeGenerations:0,unseenGeneratedCount:0,inFlight:[],cancelInFlightJob:r=>Ug(r,e,t),startInFlightPolling:()=>{kf(e,t)},reconcileInflight:async()=>{await Cf(e,t)},syncFromStorage:()=>Hg(e,t),currentImage:null,lastHistorySelectedAt:0,applyMergedCanvasImage:r=>Vg(r,e),addGeneratedHistoryItem:async r=>{await gt(r,e,t)},history:[],historyNextCursor:null,historyLoadingOlder:!1,favoriteHistoryNextCursor:null,favoriteHistoryLoadingOlder:!1,loadedHistoryRetainLimit:qe,loadOlderHistory:async()=>sh(e,t),loadFavoriteHistory:async()=>oh(e,t),loadOlderFavoriteHistory:async()=>ah(e,t),trashPending:null,toast:null,toastLog:[],customSizeConfirm:null,errorCard:null,errorCardLog:[],rightPanelOpen:_m(),toggleRightPanel:()=>Bg(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:ja(go),galleryDefaultScope:ja(sl),setGalleryScope:r=>Wg(r,e),setGalleryDefaultScope:r=>Jg(r,e),reasoningEffort:km(),webSearchEnabled:Am(),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:Em(),setUIMode:r=>Yg(r,e),historyStripLayout:Nm(),setHistoryStripLayout:r=>Xg(r,e),locale:Ad(),setLocale:r=>{jd(r),e({locale:r})},graphNodes:[],graphEdges:[],graphHistoryPast:[],graphHistoryFuture:[],recordGraphHistory:r=>{const s=t();e({graphHistoryPast:pp(s.graphHistoryPast,us(s.graphNodes,s.graphEdges,r)),graphHistoryFuture:[]})},undoGraph:()=>{const r=t(),s=fp(r.graphHistoryPast,us(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!s)return!1;const a=Oa(s.restored,r.graphNodes);return e({graphNodes:nt(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),t().scheduleGraphSave(),!0},redoGraph:()=>{const r=t(),s=hp(r.graphHistoryPast,us(r.graphNodes,r.graphEdges,"current"),r.graphHistoryFuture);if(!s)return!1;const a=Oa(s.restored,r.graphNodes);return e({graphNodes:nt(a.nodes,a.edges),graphEdges:a.edges,graphHistoryPast:s.past,graphHistoryFuture:s.future}),t().scheduleGraphSave(),!0},setGraphNodes:r=>ny(r,e,t),setGraphEdges:r=>ry(r,e,t),disconnectEdge:r=>{t().disconnectEdges([r])},disconnectEdges:r=>$f(r,e,t),nodeSelectionMode:!1,nodeBatchRunning:!1,nodeBatchStopping:!1,toggleNodeSelectionMode:()=>sy(e,t),selectAllGraphNodes:()=>{e({graphNodes:xn(t().graphNodes,t().graphNodes.map(r=>r.id))})},selectNodeGraph:(r,s)=>oy(r,s,e,t),clearNodeSelection:()=>{e({graphNodes:xn(t().graphNodes,[])})},cancelNodeBatch:()=>ay(e,t),sessions:[],activeSessionId:null,activeSessionGraphVersion:null,sessionLoading:!1,async loadSessions(){await Lc(e,t)},async switchSession(r){await vh(r,e,t)},async reconcileGraphPending(){await bh(e,t)},async createAndSwitchSession(r){await xh(r,e,t)},async renameCurrentSession(r){await Ih(r,e,t)},async deleteSessionById(r){await Sh(r,e,t)},scheduleGraphSave(){Ql(t,e)},async flushGraphSave(r="manual"){await cp(t,e,r)},addRootNode:()=>Tf(e,t),createRootNodeFromHistoryItem:r=>Mf(r,e,t),addChildNode:r=>Lf(r,e,t),addSiblingNode:r=>Of(r,e,t),updateNodePrompt:(r,s)=>Gf(r,s,e,t),addNodeReferences:async(r,s)=>Hf(r,s,e,t),addNodeReferenceDataUrl:(r,s)=>Nc(r,s,e,t),addNodeReferenceFromUrl:async(r,s,a)=>Vf(r,s,a,e,t),removeNodeReference:(r,s)=>Kf(r,s,e,t),clearNodeReferences:r=>Bf(r,e,t),duplicateBranchRoot:r=>Df(r,e,t),generateNode:r=>pf(r,e,t),generateNodeInPlace:r=>ff(r,e,t),generateNodeVariation:(r,s)=>hf(r,s,e,t),runGenerateNode:(r,s)=>gf(r,s,e,t),async runGenerateNodeInPlace(r,s={}){return Wp(r,s,e,t,Re)},async runNodeBatch(r){await Jp(r,e,t)},deleteNode:r=>zf(r,e,t),deleteNodes:r=>qf(r,e,t),addChildNodeAt:(r,s,a)=>Ff(r,s,a,e,t),connectNodes:(r,s,a,i)=>Uf(r,s,a,i,e,t),setProvider:r=>lg(r,e,t),setQuality:r=>cg(r,e),setSizePreset:r=>dg(r,e),setCustomSize:(r,s)=>ug(r,s,e,t),setGrokAspectRatio:r=>mg(r,e),setGrokResolution:r=>pg(r,e),setFormat:r=>fg(r,e),setModeration:r=>hg(r,e),setImageModel:r=>gg(r,e,t),videoDuration:Xn.duration,videoResolution:Xn.resolution,videoSingleRefMode:Xn.singleRefMode,videoAspectRatio:Xn.aspectRatio,videoReferenceVoices:[],videoTopic:"",videoContinuityLineage:null,videoProgress:null,selectVideoModel:r=>yg(r,e,t),setComfyWorkflow:r=>vg(r,e,t),setComfyVideoWorkflow:r=>bg(r,e,t),setVideoDuration:r=>{e({videoDuration:r}),mn({duration:r})},setVideoResolution:r=>{e({videoResolution:r}),mn({resolution:r})},setVideoAspectRatio:r=>{e({videoAspectRatio:r}),mn({aspectRatio:r})},toggleVideoReferenceVoice:r=>{const s=t().videoReferenceVoices,a=s.includes(r)?s.filter(i=>i!==r):s.length>=3?s:[...s,r];e({videoReferenceVoices:a})},setVideoSingleRefMode:r=>{e({videoSingleRefMode:r}),mn({singleRefMode:r})},setVideoTopic:r=>e({videoTopic:r}),setVideoContinuityLineage:r=>e({videoContinuityLineage:r}),activeVideoRefCount:()=>xg(t),runVideoGenerate:async r=>{await yf(r,e,t)},animateImage:async(r,s)=>vf(r,s,e,t),setReasoningEffort:r=>Ig(r,e),setWebSearchEnabled:r=>Sg(r,e),setCount:r=>wg(r,e),setMultimode:r=>_g(r,e,t),setMultimodeMaxImages:r=>Eg(r,e),setPromptMode:r=>Ng(r,e),setPrompt:r=>kg(r,e),setNegativePrompt:r=>Cg(r,e),setNaiOption:(r,s)=>jg(r,s,e,t),resetNaiOptions:()=>Ag(e),insertPromptToComposer:r=>Tg(r,e),removeInsertedPromptFromComposer:r=>Mg(r,e),moveInsertedPromptInComposer:(r,s)=>Lg(r,s,e),clearInsertedPrompts:()=>Og(e),selectHistory:r=>ih(r,e,t),showHistorySequence:r=>lh(r,e,t),markGeneratedResultsSeen:()=>e({unseenGeneratedCount:0}),selectHistoryShortcutTarget:r=>ch(r,e,t),trashHistoryItem:async r=>dh(r,e,t),trashHistorySequence:async r=>uh(r,e,t),restorePendingTrash:async()=>mh(e,t),clearPendingTrash:()=>e({trashPending:null}),permanentlyDeleteHistoryItemByClick:async r=>{await t().permanentlyDeleteHistoryItemByShortcut(r)},permanentlyDeleteHistoryItemByShortcut:async r=>ph(r,e,t),removeFromHistory:r=>fh(r,e,t),addHistoryItem:r=>hh(r,e,t),importLocalImageToHistory:async r=>gh(r,e,t),getResolvedSize:()=>Pg(t),generate:()=>df(e,t),async generateMultimode(r){await ef(r,e,t)},cancelMultimode:()=>uf(e,t),async runGenerate(r){await tf(r,e,t)},confirmCustomSizeAdjustment:()=>mf(e,t),cancelCustomSizeAdjustment:()=>e({customSizeConfirm:null}),hydrateHistory(){yh(e)},showToast:(r,s=!1)=>Zg(r,s,e),dismissToast:r=>Qg(r,e),showErrorCard:(r,s)=>ey(r,s,e),dismissErrorCard:r=>ty(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:()=>Fg(e),savePromptToLibrary:r=>Dg(r,e,t),deletePromptFromLibrary:r=>Gg(r,e,t),togglePromptFavorite:r=>zg(r,e,t),importPromptsToLibrary:r=>qg(r,e,t),toggleGalleryFavorite:r=>$g(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)=>iy(r,s,e),resetCanvasPan:()=>e({canvasPanX:0,canvasPanY:0}),setCanvasExportBackground:r=>ly(r,e,t),setCanvasExportMatteColor:r=>cy(r,e,t)})),zy=/^[\p{L}\p{N}_-]$/u,qy=new Set([" "," ","(","["]);function $y(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(!zy.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&&!qy.has(a)&&a!==`
|
|
8
|
-
`?null:{start:s,end:n,query:e.slice(r,n)}}function Fe({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=Pd();function Uy(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Hy=(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}]}},Ua=(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 Oe({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:k,rendered:N}=Hy(t,e),O=k.length===0,[$,j]=v.useState(()=>Math.max(0,k.findIndex(F=>F.value===n))),R=v.useRef({buffer:"",at:0}),V=k.find(F=>F.value===n),C=F=>`${b}-opt-${F}`,T=F=>F.searchText?F.searchText:typeof F.label=="string"?F.label:F.value,P=F=>{const ee=Date.now(),J=R.current;J.buffer=ee-J.at>1e3?F:J.buffer+F,J.at=ee;const pe=J.buffer.toLowerCase(),be=J.buffer.length===1?$+1:$;for(let ae=0;ae<k.length;ae+=1){const ke=(be+ae+k.length)%k.length,ie=k[ke];if(!(!ie||ie.disabled)&&T(ie).toLowerCase().startsWith(pe)){j(ke);return}}};v.useEffect(()=>{if(!g)return;const F=ee=>{const J=ee.target;J instanceof Node&&(I.current?.contains(J)||y.current?.contains(J)||_(!1))};return document.addEventListener("pointerdown",F),()=>document.removeEventListener("pointerdown",F)},[g]),v.useLayoutEffect(()=>{if(!d||!g)return;const F=x.current?.getBoundingClientRect();if(F){const be=Math.max(0,window.innerWidth-24),ae=Math.min(300,be,Math.max(190,F.width)),ke=Math.max(12,window.innerWidth-ae-12),ie=Math.min(Math.max(12,F.left),ke),we=window.innerHeight-F.bottom-12,_e=F.top-12,je=we>=160||we>=_e?"down":"up",z=Math.max(0,je==="down"?we:_e),le=Math.min(420,z),ce=8+k.length*44,Te=y.current?.scrollHeight??ce,A=Math.min(Te,le);w({top:je==="down"?F.bottom+4:Math.max(12,F.top-A-4),left:ie,width:ae,maxHeight:le})}const ee=()=>_(!1),J=pe=>{Uy(pe,y.current)&&_(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,g]),v.useEffect(()=>{g&&y.current?.querySelector(`[data-index="${$}"]`)?.scrollIntoView({block:"nearest"})},[g,$]);const B=()=>{O||(j(Math.max(0,k.findIndex(F=>F.value===n))),_(!0))};v.useEffect(()=>{O&&(_(!1),j(0))},[O]);const ne=F=>{let ee=$;for(let J=0;J<k.length&&(ee=(ee+F+k.length)%k.length,!!k[ee]?.disabled);J+=1);j(ee)},oe=F=>{const ee=k[F];!ee||ee.disabled||(r(ee.value),_(!1),x.current?.focus())},ue=F=>{if(!g){["Enter"," ","ArrowDown","ArrowUp"].includes(F.key)&&(F.preventDefault(),B());return}if(F.key==="Escape")F.preventDefault(),_(!1);else if(F.key==="ArrowDown")F.preventDefault(),ne(1);else if(F.key==="ArrowUp")F.preventDefault(),ne(-1);else if(F.key==="Home")F.preventDefault(),j(Ua(k,"first",$));else if(F.key==="End")F.preventDefault(),j(Ua(k,"last",$));else if(F.key==="Enter"||F.key===" "){if(F.key===" "&&Date.now()-R.current.at<=1e3&&R.current.buffer){F.preventDefault(),P(" ");return}F.preventDefault(),oe($)}else F.key==="Tab"?_(!1):F.key.length===1&&!F.metaKey&&!F.ctrlKey&&!F.altKey&&(F.preventDefault(),P(F.key))};let me=-1;const D=g&&!O?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:N.map((F,ee)=>o.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[F.label?o.jsx("div",{className:"ctl-select__group-label",children:F.label}):null,o.jsx("ul",{role:"group","aria-label":typeof F.label=="string"?F.label:void 0,className:"ctl-select__group-items",children:F.items.map(J=>{me+=1;const pe=me;return o.jsxs("li",{role:"option",id:C(pe),"data-index":pe,"aria-selected":J.value===n,"aria-disabled":J.disabled||void 0,title:J.title,className:`ctl-select__item${J.value===n?" is-selected":""}${pe===$?" is-active":""}${J.disabled?" is-disabled":""}${J.stacked?" is-stacked":""}`,onPointerEnter:()=>j(pe),onClick:()=>oe(pe),children:[o.jsx("span",{className:"ctl-select__item-label",children:J.label}),J.sub?o.jsx("span",{className:"ctl-select__item-sub",children:J.sub}):null]},J.value)})})]},`g-${ee}`))}):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&&k[$]?C($):void 0,"aria-label":s,"aria-describedby":a,disabled:c||O,title:h,onClick:()=>g?_(!1):B(),onKeyDown:ue,children:[o.jsx("span",{className:"ctl-select__value",children:u??V?.label??m??""}),p??V?.sub?o.jsx("span",{className:"ctl-select__value-sub",children:p??V?.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"})})]}),D?d?ss.createPortal(D,document.body):D:null]})}function Vy({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 Wc({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 Ky(){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 Jc({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(Ky,{})})}function By(){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 Ha=12,Wy=240;function Jy(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 Yy(e,t){const n=Jy(e,t),r=window.innerHeight-n.bottom,s=r<Wy?"top":"bottom",a=s==="bottom"?r:n.top;return{left:Math.max(Ha,Math.min(n.left,window.innerWidth-332)),top:s==="bottom"?n.bottom+6:Math.max(Ha,n.top-Math.min(320,a-8)),placement:s,maxHeight:Math.max(120,Math.min(320,a-12))}}function Xy(){return window.matchMedia("(max-width: 640px)").matches}function Zy({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 O=s.trim().toLocaleLowerCase();return O?a.filter($=>[$.name,...$.tags??[]].some(j=>j.toLocaleLowerCase().includes(O))):a},[a,s]),w=O=>{b(O),p?.(O)},k=()=>{const O=S[h];O&&d(O)};if(v.useLayoutEffect(()=>{if(!e||!t.current)return;const O=()=>{if(!t.current){u();return}g(Xy()),x(Yy(t.current,r))},$=()=>requestAnimationFrame(O);return O(),window.addEventListener("resize",$),t.current.addEventListener("scroll",$),()=>{window.removeEventListener("resize",$),t.current?.removeEventListener("scroll",$)}},[e,t,r,u]),v.useEffect(()=>{w(0)},[s,S.length]),v.useEffect(()=>{if(!e)return;const O=t.current;if(!O)return;O.setAttribute("aria-controls",m),O.setAttribute("aria-expanded","true");const $=j=>{if(document.activeElement===O&&!(n?.current||j.isComposing||j.keyCode===229)&&!(j.key==="Enter"&&(j.ctrlKey||j.metaKey))){if(j.key==="Escape"){j.preventDefault(),u("escape");return}j.key==="ArrowDown"||j.key==="ArrowUp"?(j.preventDefault(),w((h+(j.key==="ArrowDown"?1:-1)+S.length)%Math.max(1,S.length))):j.key==="Home"?(j.preventDefault(),w(0)):j.key==="End"?(j.preventDefault(),w(Math.max(0,S.length-1))):j.key==="Enter"?S.length&&(j.preventDefault(),k()):j.key==="Tab"&&S.length&&k()}};return O.addEventListener("keydown",$),()=>{O.removeAttribute("aria-controls"),O.removeAttribute("aria-expanded"),O.removeAttribute("aria-activedescendant"),O.removeEventListener("keydown",$)}},[e,t,n,m,h,S,u]),v.useEffect(()=>{const O=t.current,$=S[h];O&&$&&O.setAttribute("aria-activedescendant",`${m}-${$.id}`)},[h,S,m,t]),v.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const N=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((O,$)=>o.jsxs("li",{id:`${m}-${O.id}`,role:"option","aria-selected":$===h,className:`element-mention-menu__option${$===h?" is-active":""}`,onPointerEnter:()=>w($),onMouseDown:j=>{j.preventDefault(),d(O)},children:[O.thumbnail?o.jsx("img",{src:O.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:O.name}),o.jsx("small",{children:c(O.kind)})]})]},O.id)):o.jsx("li",{className:"element-mention-menu__empty",role:"presentation",children:l})})});return ss.createPortal(N,document.body)}function Qy(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function ev(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??Qy(e.source.referenceFilenames[0])}function tv({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=ev(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 nv({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 rv({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(nv,{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 sv=new Set(["character","product","style","scene"]);function ov(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&sv.has(t)?t:"character"}function av(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 iv(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),s=new Set(n);return ac({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:ov(i),thumbnail:av(i)??a.source.thumbnailUrl,missing:s.has(a.source.elementId)||t!==null&&!i}})}function lv(e){const t=iv(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(rv,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const cv=["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 dv({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(()=>qp(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);cv.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=ve(e),r=!!e.prompt;if(t.clearReferences(),t.setPrompt(r&&!n?e.prompt:""),n){const s=e.url||e.image,a=await en(s);t.addReferenceDataUrl(a);const i=gc(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(lf(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 Yc(e){const t=await os(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const uv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:os,continueFromItemAsUrl:Yc},Symbol.toStringTag,{value:"Module"}));function mv({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 pv({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(Vy,{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 fv({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(pv,{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(mv,{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 Va(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 hv(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=Va(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=Va(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}const Xc="grok-imagine-video",gv="grok-imagine-video-1.5",Zc=new Set([gv,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function yv(e){return e.type.startsWith("audio/")}function vv(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function bv(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,s=typeof r=="string"&&Zc.has(r),a=r===Xc;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(yv(i)){r?s?n.audios.push(i):n.rejected.push({file:i,reason:"audio-needs-15"}):n.rejected.push({file:i,reason:"audio-needs-video-model"});continue}if(vv(i)){a?n.videos.length>0?n.rejected.push({file:i,reason:"video-single-only"}):n.videos.push(i):n.rejected.push({file:i,reason:"video-needs-base"});continue}n.rejected.push({file:i,reason:"not-media"})}return n}function xv(e){const t=e.videoModelSelected;return typeof t=="string"&&Zc.has(t)?"image/*,audio/*":t===Xc?"image/*,video/mp4":"image/*"}function Iv(e,t){switch(e){case"audio-needs-video-model":return t("prompt.rejectAudioNeedsVideoModel");case"audio-needs-15":return t("prompt.rejectAudioNeeds15");case"video-needs-base":return t("prompt.rejectVideoNeedsBase");case"video-single-only":return t("prompt.rejectVideoSingleOnly");case"not-media":return t("prompt.rejectNotMedia")}}function Sv({onImages:e}){const{t}=H(),n=f(s=>s.videoModelSelected),r=f(s=>s.showToast);return s=>{if(s.length===0)return;const a=bv(s,{videoModelSelected:n});a.images.length>0&&e(a.images),a.audios.length>0&&r(t("prompt.audioUsePresetVoice"),!0),a.videos.length>0&&r(t("prompt.videoUseCliForEdit"),!0);for(const i of new Set(a.rejected.map(l=>l.reason)))r(Iv(i,t),!0)}}function wv({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 _v(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):br(e.id,f.setState,f.getState,e)}function Ev(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):dc(e,f.setState,f.getState)}function Nv(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 W=b.find(Q=>Q.id===E);return W?_v(W):(p?.(E),null)};v.useEffect(()=>{let E=!1;return Tp().then(W=>{E||(I(W),Ev(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{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()),k=f(E=>E.providerUrlReference),N=f(E=>E.setProviderUrlReference),O=f(E=>E.addReferences),$=f(E=>E.addReferenceDataUrl),j=f(E=>E.useImageAsReference),R=f(E=>E.readDroppedImageMetadata),V=f(E=>E.videoModelSelected),C=v.useRef(null),T=v.useRef(null),P=v.useRef(null),[B,ne]=v.useState(!1),[oe,ue]=v.useState(null),me=v.useRef(!1),D=v.useRef(null),F=v.useRef(null),ee=f(E=>E.promptMode),J=f(cf),pe=f(E=>E.multimodeMaxImages),be=ee==="direct",ae=r==="nai",ke=s.filter(E=>E.placement!=="after"),ie=s.filter(E=>E.placement==="after"),we=[...ke.map(E=>E.id),"__main_prompt__",...ie.map(E=>E.id)],_e=g.length<w,je=J?g.length>0?y("multimode.promptPlaceholderWithRefs"):y("multimode.promptPlaceholder"):g.length>0?y("prompt.placeholderWithRefs"):y("prompt.placeholder"),z=()=>{h.length>0||l()},le=()=>T.current?.selectionStart??f.getState().prompt.length,ce=(E,W)=>{const Q=f.getState().trayItems.filter(U=>U.kind==="attachment"&&!E.has(U.tokenId));if(Q.length===0)return 0;const xe=f.getState().prompt,M=Math.max(0,Math.min(W,xe.length)),Y=Q.map(U=>`@${U.tag} `).join("");n(`${xe.slice(0,M)}${Y}${xe.slice(M)}`);const Ie=M+Y.length;return requestAnimationFrame(()=>T.current?.setSelectionRange(Ie,Ie)),Q.length},Te=(E,W)=>{const Q=`@${E} `,xe=f.getState().prompt,M=`${xe.slice(0,W.start)}${Q}${xe.slice(W.end)}`,Y=W.start+Q.length;n(M),requestAnimationFrame(()=>T.current?.setSelectionRange(Y,Y))},A=(E,W)=>{if(me.current)return;const Q=$y(E,W);ue(Q&&gs(Q)!==F.current?Q:null)},se=async(E,W,Q)=>{if(E.length===0)return 0;const xe=new Set(f.getState().trayItems.map(M=>M.tokenId));try{return Q&&E.length===1&&await R(E[0])?0:(await O(E),ce(xe,W))}catch{return 0}},fe=async E=>{const W=P.current??le();P.current=null,await se(E,W,!0)},K=Sv({onImages:E=>{fe(E)}}),G=()=>{_e&&(P.current=le(),C.current?.click())},X=async(E,W)=>{const Q=new Set(f.getState().trayItems.map(xe=>xe.tokenId));try{const xe=E.url||E.image;if(!xe)return;const M={image:xe,url:E.url,filename:E.filename};if(ve(M)){const Y=await en(xe);Y&&$(Y)}else await j(M);ce(Q,W)}catch{}},re=E=>{E.preventDefault(),ne(!1);const W=E.dataTransfer.getData("application/ima2-ref");if(W){try{const Q=JSON.parse(W);X(Q,le())}catch{}return}K(Array.from(E.dataTransfer.files))},Le=E=>{E.preventDefault(),B||ne(!0)},De=E=>{E.currentTarget.contains(E.relatedTarget)||ne(!1)},Lt=hv({maxRefs:w,trayItemCount:g.length,captureAttachmentCaret:le,addFilesAtCaret:se}),Ve=v.useRef(null),dt=v.useRef(e);v.useLayoutEffect(()=>{const E=T.current;if(!E)return;(Ve.current===null||dt.current!==e)&&(Ve.current=Nv(window.getComputedStyle(E).maxHeight)??0,dt.current=e),E.style.height="auto";const W=Ve.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ut=(E,W)=>{const Q=we.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<we.length-1},vt=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:!ut(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:!ut(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}${B?" composer--drag":""}${be?" composer--direct":""}${J?" composer--multimode":""}${be&&J?" composer--combined-modes":""}`,role:"group","aria-label":J?y("multimode.composerAriaLabel",{count:pe}):y("prompt.label"),onDrop:re,onDragOver:Le,onDragLeave:De,onPaste:Lt,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:[J&&o.jsx("span",{className:"composer__mode-badge",children:y("multimode.composerBadge",{count:pe})}),be&&o.jsx("span",{className:"composer__direct-badge",children:y("prompt.directModeActive")}),k&&o.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>N(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(tv,{items:g,limit:w,onRemove:S,onAdd:G}),ke.length>0&&o.jsx("div",{className:"composer__prompt-chips",children:ke.map(vt)}),c.length>0&&o.jsx(Wo,{ariaLabel:y("home.selectedPresets"),children:c.map(E=>{const W=pc(E);return W?o.jsx(Wc,{onRemove:()=>d(E),removeLabel:y("common.removeNamed",{name:W.name}),children:W.name},E):null})}),o.jsx(lv,{items:g,assets:m,missingElementIds:h,selectedLabel:y("element.selected"),unavailableLabel:y("common.elementUnavailable"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),mentionLabel:(E,W,Q)=>Q?y("element.unavailableAria",{name:E}):y("element.mentionAria",{name:E,kind:W}),removeLabel:E=>y("element.removeAria",{name:E}),onRemove:E=>u.removeElementId?.(E)}),o.jsxs("div",{className:`composer__prompt-panes${ae?" composer__prompt-panes--dual":""}`,children:[o.jsxs("div",{className:"composer__prompt-pane",children:[ae?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(dv,{prompt:t,retiredTags:_,textareaRef:T}),o.jsx("textarea",{id:`positive-prompt-${e}`,ref:T,className:"prompt-area composer__textarea",value:t,placeholder:ae?y("nai.positivePrompt.placeholder"):je,"aria-describedby":ae?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{me.current=!0,ue(null)},onCompositionEnd:E=>{me.current=!1,D.current=E.currentTarget.value,queueMicrotask(()=>{D.current=null}),A(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{F.current=null,n(E.target.value),D.current!==E.target.value&&A(E.target.value,E.target.selectionStart)},onClick:E=>A(E.currentTarget.value,E.currentTarget.selectionStart),onKeyDown:E=>{if(!(me.current||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229)){if(E.key==="Escape"&&oe){E.preventDefault(),F.current=gs(oe),ue(null);return}if(E.key==="Enter"&&(E.metaKey||E.ctrlKey)){if(E.defaultPrevented)return;E.preventDefault(),z()}}}})]}),ae?o.jsx("p",{id:`positive-prompt-${e}-hint`,className:"composer__prompt-hint",children:y("nai.positivePrompt.hint",{count:t.length})}):null]}),o.jsx(wv,{variant:"classic",onSubmit:z})]}),o.jsx(Zy,{open:oe!==null,textareaRef:T,composingRef:me,caret:oe?.end??0,query:oe?.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 W=rc(E);return{id:E.id,name:E.name,kind:typeof E.metadata?.elementKind=="string"?E.metadata.elementKind:"character",thumbnail:W?`/generated/${W.split("/").map(encodeURIComponent).join("/")}`:void 0,tags:E.tags}})],ariaLabel:y("common.elementSuggestions"),emptyLabel:y("common.noMatchingElements"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),onSelect:E=>{const W=Ks(f.getState().trayItems,E.id);if(E.id.startsWith(hs)){const xe=E.id.slice(hs.length),M=f.getState().trayItems.find(Y=>Y.tokenId===xe);M&&oe&&Te(M.tag,oe),ue(null);return}if(x?.(E.id),W){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),ue(null);return}const Q=Ks(f.getState().trayItems,E.id);!Q||!oe||(Te(Q.tag,oe),ue(null))},onClose:E=>{E==="escape"&&oe&&(F.current=gs(oe)),ue(null)}}),ie.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")}),ie.map(vt)]}),o.jsx(fv,{canAddMore:_e,onAttach:G}),B&&o.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:y("prompt.dropHere",{max:w})}),o.jsx("input",{ref:C,type:"file",accept:xv({videoModelSelected:V}),multiple:!0,hidden:!0,onChange:E=>{const W=Array.from(E.target.files??[]);W.length>0?K(W):P.current=null,E.target.value=""}})]})}function 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 Qc(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(jv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s,variant:e.variant,panelId:e.panelId}):o.jsx(kv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s})}function kv(e){return o.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>o.jsx(Cv,{f:t,...e},t.id))})}function Cv({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:Qc(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 jv(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(Av,{f:s,determinateVideoId:n,validVideoProgress:r,...e},s.id))})}function Av({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=Rv(e)??Tv(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(Mv,{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:Qc(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(Pv,{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 Pv({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 Rv(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function Tv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function Mv({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 Ka="(max-width: 800px)";function yt(){const[e,t]=v.useState(()=>typeof window<"u"?window.matchMedia(Ka).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Ka),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const Lv=10,mt=12;function Ov({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:mt,top:mt,caretTop:24}),[m,h]=v.useState(!1);v.useLayoutEffect(()=>{const x=()=>{const _=e.current,S=l.current;if(!_||!S)return;const w=_.getBoundingClientRect(),k=_.closest(".sidebar")?.getBoundingClientRect(),N=S.getBoundingClientRect(),O=k?k.right:w.right,$=Math.max(mt,window.innerWidth-N.width-mt),j=Math.max(mt,window.innerHeight-N.height-mt),R=Math.min(Math.max(O+Lv,mt),$),V=Math.min(Math.max(w.bottom-N.height,mt),j),C=Math.min(Math.max(w.top+w.height/2-V,16),N.height-16);p({left:R,top:V,caretTop:C}),h(!0)},y=()=>{d.current!=null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(x)};x(),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0);const g=new ResizeObserver(y);return e.current&&g.observe(e.current),l.current&&g.observe(l.current),()=>{window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0),g.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),v.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),v.useEffect(()=>{const x=g=>{const _=g.target;_&&(e.current?.contains(_)||l.current?.contains(_))||r(!1)},y=g=>{g.key==="Escape"&&(g.preventDefault(),r(!0))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",y),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",y)}},[e,r]);const b=`${t}-title`,I={left:u.left,top:u.top,"--inflight-caret-top":`${u.caretTop}px`};return 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 Fv=180,Dv=180;function ed({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const s=f(j=>j.inFlight.length),a=yt(),{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 j=document.activeElement;b&&j instanceof HTMLElement&&j.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"),Fv))},S=()=>{m.current!=null&&window.clearTimeout(m.current),m.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),Dv))},w=j=>{I(),c("closed"),u(!1),j&&p.current?.focus()},k=j=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){w(!1);return}u(j.detail===0),c("pinned")},N=j=>{j.pointerType==="mouse"&&_()},O=s>99?"99+":String(s),$=b?"inflight.badgeClose":"inflight.badgeOpen";return o.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:N,onPointerLeave:S,children:[o.jsxs("button",{ref:p,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:k,"aria-live":"polite","aria-expanded":b,"aria-controls":t,"aria-haspopup":e==="popup"?"dialog":void 0,"aria-label":i($,{n:s}),title:i($,{n:s}),children:[o.jsx("span",{className:"inflight-badge__spinner","aria-hidden":"true"}),o.jsx("span",{className:"inflight-badge__count","aria-hidden":"true",children:O})]}),e==="popup"&&b?o.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&b?o.jsx(Ov,{anchorRef:p,panelId:t,focusOnOpen:d,onRequestClose:w,onPointerEnter:g,onPointerLeave:S}):null]})}function Gv(){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(By,{})})]}),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 Lw(){return q("/api/comfy/workflows")}function Ow(e){return q("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function Fw(e){return q("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function Dw(e){return q("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function Gw(e){return q(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function zv(e){return $v(await q("/api/models",e?{signal:e}:{}))}function qv(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function yn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ba(e){if(!pn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return yn();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 yn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return yn();t.executable=e.executable}return t}function $v(e){return!pn(e)||e.ok!==!0||!pn(e.lanes)?yn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!pn(n)||!qv(n.status)||!pn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return yn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Ba),video:n.models.video.map(Ba)}};return[t,r]}))}const td={phase:"idle",catalog:null,observedAt:null,error:null},ft=new Set;let jn=td,Tr=0,pt=null,Qn=null;const Wa=()=>{Qo()};function Zo(){return jn}function fn(e){jn=e;for(const t of[...ft])ft.has(t)&&t()}function ys(e,t){return e===Tr&&pt===t&&!t.signal.aborted&&ft.size>0}function Uv(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(pt?.abort(),pt=null,ft.size===0){fn(td);return}const t=new AbortController;if(pt=t,fn({...jn,phase:"loading",error:null}),!!ys(e,t))try{const n=await zv(t.signal);ys(e,t)&&fn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){ys(e,t)&&fn({...jn,phase:"error",error:Uv(n)})}finally{e===Tr&&pt===t&&(pt=null)}}function Hv(e){const t=ft.size===0;return ft.add(e),t&&(typeof window<"u"&&(Qn=window,Qn.addEventListener("focus",Wa)),Qo()),()=>{!ft.delete(e)||ft.size>0||(++Tr,pt?.abort(),pt=null,Qn?.removeEventListener("focus",Wa),Qn=null,fn({...jn,phase:"idle",error:null}))}}function Hn(){return{...v.useSyncExternalStore(Hv,Zo),refresh:Qo}}function qt(e){return e.executable!==!1&&!e.description?.endsWith("(offline)")}function kt(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(qt)||r.video.some(qt),d=e.phase==="ready"&&n?.status==="ready"&&c,u=!!(d&&i&&qt(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 Vv={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 Kt(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":Vv[e.code]}const nd=[{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"}],Ja=new Map(nd.map(e=>[e.value,e.label])),Kv=new Set(["runway","higgsfield"]),er="mcp:",tr="core:",vs="effort:",bs=Bi,an=Ht;function Bv(e){rs(e,f.setState,f.getState)}function Wv(e){eg(e,f.setState,f.getState)}function Jv(e,t,n){tg(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 Yv(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function rd({compact:e=!1}={}){const{t}=H(),n=f(A=>A.provider),r=f(A=>A.imageModel),s=f(A=>A.videoModelSelected),a=f(A=>A.mcpProvider??null),i=f(A=>A.mcpModel??null),l=f(A=>A.mcpMediaKind??"image"),c=f(A=>A.setProvider),d=f(A=>A.setImageModel),u=f(A=>A.selectVideoModel),p=f(A=>A.setComfyWorkflow),m=f(A=>A.comfyWorkflow),h=f(A=>A.setComfyVideoWorkflow),b=f(A=>A.comfyVideoWorkflow),I=f(A=>A.setReasoningEffort),x=f(A=>A.reasoningEffort),{providers:y,loading:g,error:_}=zc(),[S,w]=v.useState(xs),[k,N]=v.useState(!1),[O,$]=v.useState(0),[j,R]=v.useState(!1),V=Hn(),C=V.catalog??{},T=C.comfy?.models??{image:[],video:[]};v.useEffect(()=>{ig(f.setState,f.getState)},[]);const P=a?y.find(A=>A.id===a)??null:null,B=!!(P?.enabled&&P.status.state==="connected");v.useEffect(()=>{if(!a||!B){w(xs),N(!1);return}const A=new AbortController;return R(!0),N(!1),Gc(a,A.signal).then(se=>{if(A.signal.aborted)return;w(se);const fe=f.getState(),G=(fe.mcpMediaKind==="video"?se.video:se.image).find(X=>X.id===fe.mcpModel);G&&ag(G.capabilities,f.setState,f.getState)}).catch(se=>{se.name!=="AbortError"&&(A.signal.aborted||(w(xs),N(!0)))}).finally(()=>{A.signal.aborted||R(!1)}),()=>A.abort()},[a,B,O]);const ne=v.useMemo(()=>y.filter(A=>A.enabled&&A.status.state==="connected"),[y]),oe=a?`${er}${a}`:`${tr}${n}`,ue=Lu(n),me=n==="comfy"?T.image.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,disabled:V.phase!=="ready"||C.comfy?.status!=="ready"||!qt(A),reason:A.lockReason})):[],D=n==="comfy"?T.video.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,reason:A.lockReason,disabled:V.phase!=="ready"||C.comfy?.status!=="ready"||!qt(A)})):[],F=qu({provider:n,imageModel:r,videoModel:s,comfyWorkflow:m,comfyVideoWorkflow:b}),ee=a?i?Bn(l,i):"":F,J=!a&&(n==="oauth"||n==="api")&&!s,pe=!!(i&&(S.image.some(A=>A.id===i)||S.video.some(A=>A.id===i))),be=P?.executable===!1?P.lockReason??t("mcp.higgsfieldLocked"):null,ae=a?P?P.status.state!=="connected"?t("mcp.disconnectedSelection"):P.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,ke=A=>{if(A.startsWith(tr)){const K=A.slice(tr.length);if(!Ja.has(K))return;c(K);return}const se=A.slice(er.length),fe=y.find(K=>K.id===se);!fe||fe.status.state!=="connected"||Bv(se)},ie=A=>{const se=f.getState();if(se.provider!==n||(se.mcpProvider??null)!==a)return;const fe=Zo();if(se.mcpProvider){if(A.startsWith(an))return;const K=xm(A);if(K){const X=(K.kind==="video"?S.video:S.image).find(re=>re.id===K.model);Jv(K.model,K.kind,X?.capabilities)}else Wv(A||null);return}if(se.provider==="comfy"){const K=A.startsWith(an),G=K?A.slice(an.length):A;if(!kt(fe,K?{comfyVideoWorkflow:G}:{comfyWorkflow:G}).selectedAvailable)return;K?h(G):p(G||null);return}if(!A.startsWith(an)){if(A.startsWith(vs)){I(A.slice(vs.length));return}if(A.startsWith(bs)){u(A.slice(bs.length));return}d(A)}},we=Object.keys(C).filter(A=>!Kv.has(A)),_e=we.length>0?we:nd.map(A=>A.value);_e.includes("comfy")||_e.push("comfy");const je=[{label:t("mcp.coreProviders"),items:_e.map(A=>{const se=C[A],fe=Ja.get(A),K=se?Yv(se.status,t):null;return{value:`${tr}${A}`,label:fe??Is(A),...K?{sub:K}:{},...se?.reason?{title:se.reason}:{},...fe?{}:{disabled:!0}}})}];ne.length>0&&je.push({label:t("mcp.connectedProviders"),items:ne.map(A=>({value:`${er}${A.id}`,label:Is(A.id),sub:A.executable===!1?t("mcp.locked"):void 0}))}),a&&!ne.some(A=>A.id===a)&&je.push({items:[{value:`${er}${a}`,label:Is(a),sub:t("mcp.unavailable"),disabled:!0}]});const z=[];if(a)i&&!pe&&z.push({items:[{value:Bn(l,i),label:i}]}),z.push({label:t("mcp.imageModels"),items:S.image.map(A=>({value:Bn("image",A.id),label:A.label}))}),z.push({label:t("mcp.videoModels"),items:S.video.map(A=>({value:Bn("video",A.id),label:A.label}))});else{const A=C[n]?.models.video.length??0,se=(n==="grok"||n==="grok-api")&&A>0;z.push({label:t("mcp.imageModels"),items:n==="comfy"?me.map(K=>({value:K.id,label:K.label,sub:K.reason,...K.disabled?{disabled:!0}:{}})):ue.map(K=>({value:K.value,label:K.shortLabel}))}),n==="comfy"&&D.length>0&&z.push({label:t("mcp.videoModels"),items:D.map(K=>({value:`${an}${K.id}`,label:K.label,stacked:!0,...K.reason?{sub:t("comfy.videoCatalogShort"),title:K.reason}:{},...K.disabled?{disabled:!0}:{}}))}),(se||s)&&z.push({label:t("mcp.videoModels"),items:Du.map(K=>({value:`${bs}${K.value}`,label:K.shortLabel}))}),J&&z.push({label:t("sidebar.reasoningLabel"),items:Ds.map(K=>({value:`${vs}${K.value}`,label:K.shortLabel,sub:K.value===x?"●":void 0}))});const fe=new Set(z.flatMap(K=>K.items.map(G=>G.value)));F&&!fe.has(F)&&z.unshift({items:[{value:F,label:F.includes(":")?F.split(":").slice(1).join(":"):F,title:t("mcp.unavailable"),...n==="comfy"?{disabled:!0}:{}}]})}const le=Ds.find(A=>A.value===x),ce=n==="comfy"&&!a?kt(V,{comfyWorkflow:m,comfyVideoWorkflow:b}):null,Te=ce?t(Kt(ce,V)):null;return o.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[o.jsx(Oe,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:je,value:oe,onChange:ke,ariaLabel:t("mcp.providerLabel"),title:ae??t("mcp.providerLabel"),triggerSub:"",portal:!0}),o.jsx(Oe,{id:"sidebar-generation-model",className:"gen-provider-model__select gen-provider-model__select--model",groups:z,value:ee,onChange:ie,ariaLabel:t("mcp.modelLabel"),title:ae??t("mcp.modelLabel"),disabled:!!ae,placeholder:a?t(j?"mcp.loadingModels":"mcp.chooseModel"):n==="comfy"?t("mcp.chooseModel"):void 0,triggerSub:J&&le?le.shortLabel:void 0,portal:!0}),ae||be||_||k||Te?o.jsx("span",{className:ce?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:ce&&Te?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:Te}),V.phase==="error"?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{V.refresh()},children:t("comfy.display.refresh")}):null]}):ae??be??(k?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>$(A=>A+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function sd(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function vn(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(sd):[]}}async function Mt(e,t){const n=await Ee(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 Xv(){return Mt("/api/cardnews/image-templates")}function Zv(){return Mt("/api/cardnews/role-templates")}async function Qv(e){const t=await Mt("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:vn(t.plan)}}function eb(e){return Mt("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function tb(e){return Mt(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function nb(e){const n=(await Mt(`/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 Ya(e){return Mt(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:vn(t.plan)}))}function rb(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function sb(e){return e[0]?.id||"academy-lesson-square"}function ob(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function ab(e){return Math.round(e/16)*16}function Mr(e){return Math.min(vo,Math.max(1024,ab(e)))}function Xa(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Mr(e.customW)}x${Mr(e.customH)}`}function od(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 ib(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?od(t.error)||L("cardNews.error"):void 0}}function lb(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:od(s.error)}:r})}}const Se=Pi((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([Xv(),Zv()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:sb(n.templates),roleTemplateId:ob(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 Qv({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:Xa(n)});e({activePlan:vn(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 eb({...s,size:Xa(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 lb(900),i=await tb(i.jobId),e(c=>({activePlan:c.activePlan?Ss(c.activePlan,i):c.activePlan}));const l=await Ya(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?vn(l.plan):c.activePlan?Ss(c.activePlan,i):c.activePlan,selectedTextFieldId:null})),r.showToast(L("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 nb({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?ib(d,sd(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 Ya(n);e({activePlan:vn(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 cb(){const{t:e}=H(),t=Se(S=>S.hydrate),n=Se(S=>S.topic),r=Se(S=>S.audience),s=Se(S=>S.goal),a=Se(S=>S.contentBrief),i=Se(S=>S.outputSizePreset),l=Se(S=>S.customW),c=Se(S=>S.customH),d=Se(S=>S.setBriefField),u=Se(S=>S.setOutputSizePreset),p=Se(S=>S.setCustomSize),m=Se(S=>S.draft),h=Se(S=>S.loading),b=Se(S=>S.generating),I=Se(S=>S.draftError),x=Se(S=>S.generateSet),y=Se(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 Bt({className:e}){return o.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function db({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Pe(e),c=ve(e),d=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?Sn(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(Bt,{}),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 ub({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Xf(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&&ve(u)&&!u.thumb?o.jsx(Bt,{},Pe(u)):u?o.jsx("img",{src:u.thumb||u.url||u.image,alt:"",loading:"lazy",decoding:"async"},Pe(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 Za="ima2.sidebarHistoryCollapsed";function Qa(){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 mb({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 pb(){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(Za)==="1"}catch{return!1}}),{t:h}=H(),b=Rc(t,c),I=v.useMemo(()=>Pc(e).slice(0,jc),[e]);v.useEffect(()=>{!b||p||u.current[b]?.scrollIntoView({block:"nearest",inline:"nearest"})},[b,p,I]),v.useEffect(()=>{try{localStorage.setItem(Za,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(mb,{count:g.requested},`coll-sk-${y.id}`)];for(let S=0;S<g.requested;S++)g.images[S]||_.push(o.jsx(Qa,{},`sk-${y.id}-${S}`));return _}return o.jsx(Qa,{},`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(ub,{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(db,{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 fb="sidebar-inflight-panel";function hb(){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=yt(),i=t==="agent"&&Zt?"agent":t==="node"&&Xt?"node":t==="assets"?"assets":t==="asset-gen"?"asset-gen":"classic",l=Dn(n),c=!a&&i==="classic"&&l.composerPlacement==="bottom"&&l.multimodeHistoryGrouping==="sequence";return o.jsxs(o.Fragment,{children:[o.jsx(gb,{}),i==="classic"?c?o.jsx(o.Fragment,{children:o.jsx(pb,{})}):o.jsxs(o.Fragment,{children:[o.jsx(Jo,{}),o.jsxs("div",{className:"sidebar-generate-with-inflight",children:[o.jsx(Yo,{}),o.jsx(ed,{variant:"popup",panelId:fb})]})]}):i==="card-news"?o.jsx(o.Fragment,{children:o.jsx(cb,{})}):i==="node"?o.jsxs(o.Fragment,{children:[o.jsx(Gv,{}),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 gb(){const e=yt();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(vb,{}),o.jsx(rd,{compact:e})]})]})})}function yb(){return o.jsx("aside",{className:"sidebar",children:o.jsx("div",{className:"sidebar__scroll",children:o.jsx(hb,{})})})}function vb(){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 bb=1024,xb=1024,Ib="blank-canvas.png";function ei(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function Sb(e){const t=ei(e?.width,bb),n=ei(e?.height,xb),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],Ib,{type:"image/png"})}const nr=1024;function wb(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 _b(){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=wb(r()),d=await Sb(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 Eb(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 Nb(e,t){try{const n=await Ee("/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 Ze(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 kb(e,t){const n=ge();return de()?Promise.reject(Ye(n-1)):(At(),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=jt(e.requestId,null,(m,h)=>{m==="done"?c(()=>r(h)):m==="error"&&c(()=>s(Ze(h,"Video extension failed")))}),i=Jt(()=>c(()=>{d(),s(new Error("Video extension stream timed out"))})),t.aborted)return u();t.addEventListener("abort",u,{once:!0}),no().then(()=>{if(n!==ge())throw Ye(n);if(de())throw Ye(n-1);return Nb(e,t)}).catch(m=>c(()=>s(m)))}))}let xt={source:null,status:"idle"},ln=null,ti=0;const Js=new Set;function rr(e,t){xt={source:e,status:t};for(const n of Js)n()}const Ft={getSnapshot:()=>xt,subscribe(e){return Js.add(e),()=>{Js.delete(e)}},select(e){xt.status!=="pending"&&xt.source!==e&&rr(e,"idle")},start(e){if(xt.status==="pending"||xt.source===e.sourceVideoId&&xt.status==="tracking-expired")return null;const t=new AbortController;return ln=t,ti=ge(),rr(e.sourceVideoId,"pending"),kb(e,t.signal).then(n=>(ln=null,rr(e.sourceVideoId,"idle"),n),n=>{ln=null;const r=st(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(){ln?.abort()},releaseView(){!de()&&ti===ge()&&ln?.abort()}};async function Cb(e,t){const n=await fetch("/api/video/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Ze(r,`Request failed: ${n.status}`);if(typeof r.url!="string"||typeof r.filename!="string")throw new Error("Video edit returned no saved artifact");return{requestId:String(r.requestId??""),url:r.url,filename:r.filename,duration:typeof r.duration=="number"?r.duration:null,model:String(r.model??"")}}const jb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),$t=[];function Ab(e){return $t.length>0&&$t[$t.length-1]===e}function He(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;$t.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=r.current,p=()=>Array.from(u?.querySelectorAll(jb)??[]).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(!Ab(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=$t.indexOf(a);x!==-1&&$t.splice(x,1),document.removeEventListener("keydown",h),m(b)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const Pb={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 Rb(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 Rb(e)?String(e):null}function Tb(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function ni(e){return e?e.replace("x","×"):null}function Mb(e){if(e==null)return null;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Z(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||Z(e,t,n,r)}function Lb(e,t,n){const r=Mb(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function Ob(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 Fb(e){return e?Pb[e]??e:null}function Db(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const s=ea(r);if(!s)return;const a=Db(s);!a||t.has(a)||(t.add(a),e.push({label:n,value:s,copyValue:s,pre:!0}))}function ri(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function si(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 Gb(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 zb({item:e,onClose:t,onCopy:n}){const{t:r,locale:s}=H(),a=He(!0,t),i=v.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=Fb(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),ni(e.size),e.elapsed!=null?`${e.elapsed}s`:null,e.usage?.total_tokens!=null?`${e.usage.total_tokens} ${r("metadata.fields.tokens").toLowerCase()}`:null].filter(_=>!!_),u=[],p=[];Z(p,r("metadata.fields.provider"),c,{compact:!0}),Z(p,r("metadata.fields.model"),e.model,{compact:!0}),Z(p,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Z(p,r("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),p.length&&u.push({title:r("metadata.sections.provider"),fields:p,compact:!0});const m=[];Z(m,r("metadata.fields.quality"),e.quality,{compact:!0}),Z(m,r("metadata.fields.size"),ni(e.size),{compact:!0}),Z(m,r("metadata.fields.format"),e.format,{compact:!0}),Z(m,r("metadata.fields.moderation"),e.moderation,{compact:!0}),Z(m,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Z(m,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Z(m,r("metadata.fields.kind"),e.kind,{compact:!0}),Z(m,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),m.length&&u.push({title:r("metadata.sections.settings"),fields:m,compact:!0});const h=[];Z(h,r("metadata.fields.elapsed"),e.elapsed!=null?`${e.elapsed}s`:null,{compact:!0}),Z(h,r("metadata.fields.totalTokens"),e.usage?.total_tokens,{compact:!0}),Z(h,r("metadata.fields.inputTokens"),ri(e.usage,"input_tokens"),{compact:!0}),ws(h,r("metadata.fields.cachedTokens"),si(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),ri(e.usage,"output_tokens"),{compact:!0}),ws(h,r("metadata.fields.reasoningTokens"),si(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&&Z(h,r("metadata.fields.grokCostTicks"),e.usage.grok_cost_usd_ticks,{compact:!0}),h.length&&u.push({title:r("metadata.sections.usage"),fields:h,compact:!0});const b=[];Z(b,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Z(b,r("metadata.fields.createdAt"),Tb(e.createdAt,s)),Z(b,r("metadata.fields.sessionId"),e.sessionId),Z(b,r("metadata.fields.nodeId"),e.nodeId),Z(b,r("metadata.fields.parentNodeId"),e.parentNodeId),Z(b,r("metadata.fields.clientNodeId"),e.clientNodeId),Z(b,r("metadata.fields.refsCount"),e.refsCount),Z(b,r("metadata.fields.sequence"),Ob(e)),Z(b,r("metadata.fields.setId"),e.setId),Z(b,r("metadata.fields.cardId"),e.cardId),b.length&&u.push({title:r("metadata.sections.lineage"),fields:b});const I=[];Z(I,r("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),Z(I,r("metadata.fields.videoResolution"),e.video?.resolution),Z(I,r("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),Z(I,r("metadata.fields.videoRequestedModel"),e.video?.requestedModel),Z(I,r("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),Z(I,r("metadata.fields.videoModelFallback"),e.video?.modelFallback),Z(I,r("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:ea(e.video?.xaiVideoRequestId)??void 0}),Z(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&u.push({title:r("metadata.sections.video"),fields:I});const x=[];Z(x,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Z(x,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Z(x,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Z(x,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Z(x,r("metadata.fields.latestContinuityPrompt"),l?.revisedPrompt,{copyValue:l?.revisedPrompt,pre:!0}),x.length&&u.push({title:r("metadata.sections.videoContinuity"),fields:x});const y=[],g=new Set;return sr(y,g,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),sr(y,g,r("metadata.fields.revisedPrompt"),e.revisedPrompt),sr(y,g,r("metadata.fields.prompt"),e.prompt),sr(y,g,r("metadata.fields.composerPrompt"),e.composerPrompt),Lb(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:Gb(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 qb(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function ad(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 $b(e,t){const n=qb(e);if(!n||ad(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 Ub=[2,4,8,16],Hb=["sublime","photo","photo_denoiser"];function Vb({pending:e,onSubmit:t,onClose:n}){const{t:r}=H(),s=He(!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=ad("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:Ub.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")}),Hb.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 Kb="canvas-mode-context",Bb="Canvas Mode",oi=36e5,Wb=["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 Jb({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(Ft.subscribe,Ft.getSnapshot),[y,g]=v.useState("idle"),[_,S]=v.useState(!1),[w,k]=v.useState(!1),[N,O]=v.useState(!1),[$,j]=v.useState(!1),R=v.useRef(null);v.useEffect(()=>{let G=!0;return Uo().then(X=>{G&&j(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const V=async G=>{if(!C?.filename||N)return;const X=$b(C.filename,G);if(!X){s(n("result.upscaleInvalid"),!0);return}O(!0);try{await q("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),k(!1),s(n("result.upscaleStarted"))}catch{s(n("result.upscaleFailed"),!0)}finally{O(!1)}};v.useEffect(()=>Ft.releaseView,[]);const C=e??r,T=C?.filename??null;v.useEffect(()=>{Ft.select(T)},[T]);const P=x.status==="pending"||x.source===T?x.status:"idle";if(!C)return null;const B=ve(C),ne=B?C.url||C.image:"",oe=!!C.filename,ue=!!C.filename&&!B,me=B&&!!C.filename,F=!!((C.provider==="grok"||C.provider==="grok-api")&&!B&&C.providerUrl&&C.createdAt&&Date.now()-C.createdAt<oi),ee=async()=>{if(!(!C.filename||b)){I(!0);try{await f.getState().animateImage(C.filename,C.prompt??void 0)&&s(n("toast.animateDone"))}catch(G){const X=G instanceof Error?G.message:n("toast.animateFailed");s(X,!0)}finally{I(!1)}}},J=async()=>{if(!C.filename||P==="pending"||P==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const X=Ft.start({requestId:G,sourceVideoId:C.filename,prompt:C.prompt?.trim()||void 0,provider:C.provider==="grok-api"?"grok-api":"grok",model:C.model??void 0});if(!X)return;const re=await X;f.getState().addHistoryItem(Eb(re,C)),s(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Le=st(X).code;Le==="JOB_TRACKING_TIMEOUT"||Le==="LAN_TOKEN_REQUIRED"?Ue(X,f.getState()):re||s(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},pe=()=>Ft.cancel(),be=async()=>{if(!C.filename||y==="pending")return;const G=window.prompt(n("result.editVideoPrompt"))?.trim();if(!G)return;const X=new AbortController;R.current=X,g("pending");try{const re=await Cb({videoUrl:C.filename,prompt:G,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...C,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:G,userPrompt:G,model:re.model||"grok-imagine-video",format:"mp4"}),g("idle"),s(n("toast.animateDone"))}catch(re){const Le=re instanceof DOMException&&re.name==="AbortError";g(Le?"idle":"error"),Le||s(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{R.current===X&&(R.current=null)}},ae=()=>R.current?.abort(),ke=()=>{const G=document.createElement("a");G.href=C.image,G.download=C.filename||"generated.png",G.click()},ie=async G=>{const re=await(await fetch(G)).blob();let Le;if(re.type==="image/png")Le=re;else{const De=new Image;De.crossOrigin="anonymous";const Lt=URL.createObjectURL(re);await new Promise((dt,ut)=>{De.onload=()=>dt(),De.onerror=ut,De.src=Lt});const Ve=document.createElement("canvas");Ve.width=De.naturalWidth,Ve.height=De.naturalHeight,Ve.getContext("2d").drawImage(De,0,0),URL.revokeObjectURL(Lt),Le=await new Promise((dt,ut)=>Ve.toBlob(vt=>vt?dt(vt):ut(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Le})])},we=async()=>{try{if(B){const G=await en(ne);await ie(G)}else await ie(C.image);s(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{s(n("toast.copyFailed"),!0)}},_e=async()=>{try{const G=await Hl(ne);await ie(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},je=async()=>{try{const G=await Vl(ne);await ie(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},z=async()=>{if(C.prompt)try{await navigator.clipboard.writeText(C.prompt),s(n("toast.promptCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},le=async G=>{try{await navigator.clipboard.writeText(G),s(n("toast.metadataCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},ce=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await os(C)}catch{}u&&e&&a({id:Kb,name:Bb,text:Wb});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),s(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},Te=async()=>{if(B||!C.providerUrl||!C.createdAt||Date.now()-C.createdAt>=oi){s(n("toast.continueAsUrlExpired"),!0);return}try{await Yc(C)}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"))},A=async()=>{if(!(!C.filename||m)){h(!0);try{const G=await iu({filename:C.filename});s(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const X=G instanceof Error?G.code:void 0;s(n(X==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":X==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":X==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{h(!1)}}},se=()=>{i(C),s(n("toast.nodeRootCreated"))},fe=async()=>{try{await l(C)}finally{t?.()}},K=async()=>{try{await d(C)}finally{t?.()}};return o.jsxs("div",{className:"result-actions",children:[o.jsx("button",{type:"button",className:"action-btn",onClick:ke,children:n("result.download")}),o.jsx("button",{type:"button",className:`action-btn${B?" action-btn--frame":""}`,onClick:we,children:n(B?"result.copyLastFrame":"result.copyImage")}),B&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:_e,children:n("result.copyFirstFrame")}),o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:je,children:n("result.copyMidFrame")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{z()},children:n("result.copyPrompt")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const G=await c(C);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:ce,title:n("result.continueHereTitle"),children:n("result.continueHere")}),F&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Te()},title:n("result.continueAsUrlTitle"),children:n("result.continueAsUrl")}),ue&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ee()},disabled:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),$&&C.filename&&(B?o.jsx("button",{type:"button",className:"action-btn",disabled:N,onClick:()=>{V({})},title:n("result.upscaleTitle"),children:n(N?"inflight.streaming":"result.upscale")}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",disabled:N,onClick:()=>k(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),w?o.jsx(Vb,{pending:N,onSubmit:G=>{V(G)},onClose:()=>k(!1)}):null]})),me&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",onClick:J,disabled:P==="pending"||P==="tracking-expired","aria-busy":P==="pending",title:n(P==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:P==="pending"?n("inflight.streaming"):P==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),P==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:pe,children:n("common.cancel")}),o.jsx("button",{type:"button",className:"action-btn",onClick:be,disabled:y==="pending","aria-busy":y==="pending",title:n("result.editVideoTitle"),children:n(y==="pending"?"inflight.streaming":y==="error"?"gallery.retry":"result.editVideo")}),y==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:ae,children:n("common.cancel")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:se,title:n("result.firstNodeTitle"),children:n("result.firstNode")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>S(!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"})})}),C.filename&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{fe()},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:[oe&&o.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{A()},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:()=>{K()},children:n("result.permanentDelete")})]})]})]}),_&&o.jsx(zb,{item:C,onClose:()=>S(!1),onCopy:G=>{le(G)}})]})}const Yb=["auto","flat","detailed","mono"],it={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function Xb(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 Zb(e){return`${Math.round(e/1024)}KB`}function Qb(){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=He(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(it.colorPrecision),[b,I]=v.useState(it.filterSpeckle),[x,y]=v.useState(it.cornerThreshold),[g,_]=v.useState(!1),[S,w]=v.useState(null),[k,N]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),w(null),N(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const O=v.useCallback(()=>{if(!t?.filename||g)return;const R=t.filename,V=new AbortController;i.current=V,_(!0),w(null),xu({source:R,preset:u,...m!==it.colorPrecision?{colorPrecision:m}:{},...b!==it.filterSpeckle?{filterSpeckle:b}:{},...x!==it.cornerThreshold?{cornerThreshold:x}:{},projectId:s,signal:V.signal}).then(C=>{if(!(i.current!==V||l.current!==R)){if(!C.filePath)throw new Error(e("vectorize.saveError"));N({filePath:C.filePath,pathCount:C.pathCount,bytes:C.bytes}),r(Xb(t,C.filePath)),a(e("vectorize.saved"))}}).catch(C=>{if(C instanceof DOMException&&C.name==="AbortError"||i.current!==V||l.current!==R)return;const T=C instanceof Error?C.message:e("vectorize.saveError");w(T),a(T,!0)}).finally(()=>{i.current!==V||l.current!==R||(i.current=null,_(!1))})},[t,g,u,m,b,x,s,r,a,e]);if(!t)return null;const $=t.url||t.image,j=k?`/generated/${encodeURIComponent(k.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:$??"",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:j?o.jsx("img",{src:j,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:Yb.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))}),k?o.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(k.pathCount),size:Zb(k.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(it.colorPrecision),I(it.filterSpeckle),y(it.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:O,children:e(g?"vectorize.running":"vectorize.run")}),j?o.jsx("a",{className:"assetgen-popup__close",href:j,download:k?.filePath,children:e("vectorize.download")}):null,o.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function ex({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 tx(){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 nx({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 rx(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 zw(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const wt=1,id=5,or=.22;function sx(e){return Math.min(id,Math.max(wt,e))}function ox(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=sx(y+x);return g<=wt?(s({x:0,y:0}),wt):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?or:-or)},[u]),m=v.useCallback(()=>{if(t>wt){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=wt||x.button!==0||(x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),i({pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,baseX:r.x,baseY:r.y}))},[r.x,r.y,t]),b=v.useCallback(x=>{if(!a||a.pointerId!==x.pointerId)return;const y={x:a.baseX+x.clientX-a.startX,y:a.baseY+x.clientY-a.startY};c.current=y,cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{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 ax=v.lazy(()=>Me(()=>import("./index-BAkbTbUC.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function ix(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function lx(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function cx(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(D=>D.currentImage),t=f(D=>D.importLocalImageToHistory),n=f(D=>{const F=D.multimodePreviewFlightId;return F?D.multimodeSequences[F]??null:null}),r=f(D=>D.selectHistoryShortcutTarget),s=f(D=>D.trashHistoryItem),a=f(D=>D.permanentlyDeleteHistoryItemByShortcut),i=f(D=>D.markGeneratedResultsSeen),l=f(D=>D.activeGenerations),c=f(D=>D.canvasOpen),d=f(D=>D.openCanvas),u=f(D=>D.showToast),p=f(D=>D.history),m=f(D=>D.galleryFavorites),h=f(D=>D.toggleGalleryFavorite),{t:b}=H(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:S}=_b(),w=v.useRef(null),k=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,N=ox(k),O=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},$=D=>{if(D.key==="Delete"||D.key==="Backspace"){if(!e||D.target!==D.currentTarget||Ir(D.target))return;if(D.preventDefault(),D.shiftKey){a(e);return}s(e);return}D.key!=="ArrowLeft"&&D.key!=="ArrowRight"&&D.key!=="Home"&&D.key!=="End"||D.target===D.currentTarget&&(Ir(D.target)||(D.preventDefault(),D.key==="ArrowLeft"?r("previous"):D.key==="ArrowRight"?r("next"):D.key==="Home"?r("first"):D.key==="End"&&r("last")))},j=D=>{Ir(D.target)||(i(),D.currentTarget.focus())},R=v.useCallback(()=>{window.requestAnimationFrame(()=>w.current?.focus())},[]),V=async()=>{const D=e?.filename;if(!(!e||!D||y===D)){g(D);try{await h(e)}finally{g(F=>F===D?null:F)}}},C=v.useCallback(D=>{Array.from(D.dataTransfer.types).includes("Files")&&(D.preventDefault(),x(F=>F||!0))},[]),T=v.useCallback(D=>{D.currentTarget.contains(D.relatedTarget)||x(!1)},[]),P=v.useCallback(async D=>{if(!Array.from(D.dataTransfer.types).includes("Files"))return;D.preventDefault(),x(!1);const F=Array.from(D.dataTransfer.files).filter(ee=>/^image\/(png|jpeg|webp)$/.test(ee.type));F.length!==0&&await t(F[0])},[t]);if(c&&e)return o.jsxs(o.Fragment,{children:[o.jsx(v.Suspense,{fallback:o.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:o.jsx(ax,{currentImage:e})}),o.jsx(Qb,{})]});const B=ix(e?.quality),ne=lx(e?.size),oe=Hi(e?.model,e?.provider),ue=e?cx(e):null,me=rx(e?.filename,p,m,e?.isFavorite);return o.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:C,onDragLeave:T,onDrop:P,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(tx,{}):e&&ue?o.jsxs("div",{ref:w,className:"result-container visible",tabIndex:0,onMouseDown:j,onKeyDown:$,"aria-label":b("canvas.imageViewerAria"),children:[o.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${N.zoom>wt?" canvas-annotation-frame--zoomed":""}`,onWheel:N.handleWheel,onDoubleClick:N.handleDoubleClick,onPointerDown:N.handlePointerDown,onPointerMove:N.handlePointerMove,onPointerUp:N.handlePointerUp,onPointerCancel:N.handlePointerUp,children:[e.filename?o.jsx(Jc,{variant:"result",active:me,busy:y===e.filename,label:b(me?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:V}):null,ve(e)?o.jsxs(o.Fragment,{children:[o.jsx("video",{className:"result-img",src:ue,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${N.pan.x}px, ${N.pan.y}px) scale(${N.zoom})`}},k??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify(Sn(e))),D.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:ue,alt:b("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${N.pan.x}px, ${N.pan.y}px) scale(${N.zoom})`},onDoubleClick:D=>{D.stopPropagation(),d()}},k??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),D.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}),o.jsx(nx,{zoom:N.zoom,minZoom:wt,maxZoom:id,onZoomIn:N.zoomIn,onZoomOut:N.zoomOut,onReset:N.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:(ve(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,yc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Bu(e.reasoningEffort),B,ne,oe]).filter(D=>!!D).join(" · ")}),o.jsx(Jb,{onAfterDeleteFocus:R}),e.prompt?o.jsx(ex,{prompt:e.prompt,onCopy:O}):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 dx(){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 ld="ima2.customSizeSlots";function ux(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 mx(){try{const e=localStorage.getItem(ld);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?zt(t.filter(ux)):[]}catch{return[]}}function px(e){try{localStorage.setItem(ld,JSON.stringify(zt(e)))}catch{}}function fx(e,t,n){return Vr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function cn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function hx(){const e=f(P=>P.sizePreset),t=f(P=>P.setSizePreset),n=f(P=>P.customW),r=f(P=>P.customH),s=f(P=>P.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(()=>mx()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=bo(i,c,n,r),S=um().filter(P=>P.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function w(P){h(P),px(P)}function k(){const P=tt(i,n),B=tt(c,r);s(P,B),l(String(P)),d(String(B))}function N(P){P.key==="Enter"&&(P.preventDefault(),k())}function O(){t("custom"),p(!0),I(m.length>=Gt?m[0]?.id??null:null)}function $(P){t(P),P!=="custom"&&(p(!1),I(null))}function j(P){t("custom"),s(P.w,P.h),l(String(P.w)),d(String(P.h)),p(!1),I(P.id)}function R(P){y(P.id);const B=sm(P);B&&(l(String(B.w)),d(String(B.h)))}function V(){const P=fx(_.w,_.h,x),B=m.length>=Gt&&b?am(m,b,P):om(m,P);w(B),t("custom"),s(_.w,_.h),l(String(_.w)),d(String(_.h)),I(P.id),p(!1)}const C=_.reasons.length>0?_.reasons.map(P=>a(`size.adjustedReasons.${P}`)).join(", "):a("size.noAdjustment"),T=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${wa}×${wa}`}):null;return o.jsxs("div",{className:"option-group size-picker",children:[o.jsx("div",{className:"section-title",children:a("size.title")}),o.jsx(Fe,{title:"",items:cn(im),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(lm),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(cm),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(dm),value:e,onChange:$}),o.jsxs("div",{className:"option-row size-picker__quick-row",children:[cn(S).map(P=>o.jsxs("button",{type:"button",className:`option-btn${e===P.value?" active":""}`,onClick:()=>$(P.value),children:[P.label,P.sub?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:P.sub})]}):null]},P.value)),o.jsxs("button",{type:"button",className:`option-btn${g?" active":""}`,onClick:O,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(P=>o.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===P.w&&r===P.h?" active":""}`,onClick:()=>j(P),children:[P.w,"×",P.h,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:P.ratio||a("size.customSlot")})]},P.id))}):null,u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"size-picker__ratio-row",children:nm.map(P=>o.jsx("button",{type:"button",className:`size-picker__ratio${x===P.id?" active":""}`,onClick:()=>R(P),children:P.id==="free"?a("size.ratioFree"):P.label},P.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:P=>l(P.target.value.replace(/\D/g,"")),onBlur:k,onKeyDown:N,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:P=>d(P.target.value.replace(/\D/g,"")),onBlur:k,onKeyDown:N,placeholder:a("size.height")})]}),o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:a("size.normalizedPreview")}),o.jsx("strong",{children:rm(_.w,_.h)})]}),o.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:C}),T?o.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:T}):null,m.length>=Gt?o.jsxs("div",{className:"size-picker__replace-row",children:[o.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(P=>o.jsxs("button",{type:"button",className:`size-picker__replace${b===P.id?" active":""}`,onClick:()=>I(P.id),children:[P.w,"×",P.h]},P.id))]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:V,children:m.length>=Gt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),o.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const _s=[1,2,4];function gx(){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 yx={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}},vx={512:.045,"1K":.067,"2K":.101,"4K":.151},bx={512:.134,"1K":.134,"2K":.134,"4K":.24};function xx(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function Ix(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),s=xx(r),i=t==="nano-banana-pro"?bx:vx;return i[s]??i["1K"]??.003}function Sx(e,t,n,r){return n==="gemini-api"?Ix(t,r):yx[e]?.[t]??0}function wx(){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=Sx(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 cd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const s=async()=>{try{const a=await Ld();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 _x(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let s=!1;return Od().then(a=>{s||t(a)}).catch(()=>{s||r(!0)}),()=>{s=!0}},[]),{data:e,error:n}}function dd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(de())return;const n=ge();let r=!1,s=null;const a=async()=>{if(!(r||de()||n!==ge()))try{const l=await Ee("/api/grok/status");if(r)return;const c=await l.json();if(r||de()||n!==ge())return;t(c),c.status!=="ready"&&(s=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,s&&clearTimeout(s),window.removeEventListener(_t,i)};return window.addEventListener(_t,i),a(),i},[]),e}function ud(){const[e,t]=v.useState(null),[n,r]=v.useState(null),s=v.useRef(!1),a=v.useCallback(async()=>{if(!s.current||de())return;const i=ge();try{const c=await(await Ee("/api/keys/status")).json();if(!s.current||de()||i!==ge())return;t(c),r(null)}catch(l){if(!s.current||de()||i!==ge())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return v.useEffect(()=>{if(de())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(_t,d)};return window.addEventListener(_t,d),c(),d},[a]),{data:e,error:n,mutate:a}}function md(){const{t:e}=H(),t=cd(),{data:n}=_x(),r=dd(),{data:s}=ud(),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=Hn(),y=kt(x,null);return{oauth:{ok:a,reason:i,hint:l},api:{ok:c,reason:c?"":e("provider.apiInvalid")},grok:{ok:d,reason:u,hint:d?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:p,reason:p?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:m,reason:m?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:h,reason:h?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:b,reason:b?"":e("provider.minimaxApiKeyRequired")},nai:{ok:I,reason:I?"":e("provider.naiApiKeyRequired")},comfy:{ok:y.laneAvailable,reason:e(y.laneAvailable?"comfy.display.available":Kt(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function Ex({open:e,providerLabel:t,reason:n,hint:r,onClose:s}){const{t:a}=H(),i=He(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:",Nx={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=>Nx[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 ai(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(j=>j.provider),r=f(j=>j.mcpProvider??null),s=f(j=>j.setProvider),a=md(),i=Hn(),l=f(j=>j.comfyWorkflow),c=f(j=>j.comfyVideoWorkflow),d=kt(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),u=n==="comfy"&&!r,p=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[m,h]=v.useState(null),b=j=>{const R=a[j.value];return j.value==="comfy"?u?t(Kt(d,i)):R.reason:R.ok?t("provider.statusReady"):R.reason},I=j=>j.enabled?j.status.state==="connected"?j.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):j.status.state==="connecting"?t("mcp.connecting"):j.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Ns.map(j=>{const R=a[j.value];return{value:`${ar}${j.value}`,searchText:`${j.provider} ${j.value==="comfy"?t("comfy.display.localMethod"):j.method}`,label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:j.value==="comfy"&&u?p:R.ok?"ok":"bad"}),o.jsxs("span",{children:[j.provider," ",j.value==="comfy"?t("comfy.display.localMethod"):j.method]})]}),sub:b(j)}})}],y=e.filter(j=>j.enabled).map(j=>({value:`${Es}${j.id}`,searchText:ks(j.id),label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:ai(j)}),o.jsx("span",{children:ks(j.id)})]}),sub:I(j)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${Es}${r}`:`${ar}${n}`,_=r?null:Ns.find(j=>j.value===n)??null,S=r?e.find(j=>j.id===r)??null:null,w=_?.value==="comfy",k=w?t(Kt(d,i)):_?b(_):S?I(S):t("provider.statusDisconnected"),N=w?p:_?a[_.value].ok?"ok":"bad":S?ai(S):"bad",O=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",$=j=>{if(j.startsWith(ar)){const C=j.slice(ar.length);if(!Pt(C))return;const T=Ns.find(B=>B.value===C),P=a[C];if(C==="comfy"){s(C);return}if(!P.ok){h({label:T?`${T.provider} ${T.method}`:C,reason:P.reason,hint:P.hint});return}s(C);return}const R=j.slice(Es.length),V=e.find(C=>C.id===R);if(!V||!V.enabled||V.status.state!=="connected"){h({label:ks(R),reason:!V||!V.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(Oe,{groups:x,value:g,onChange:$,triggerSub:w?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),o.jsxs("div",{className:"provider-status-line","data-tone":N,role:"status","aria-live":"polite",children:[o.jsx(Cs,{tone:N}),o.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),o.jsx("span",{className:"provider-status-line__value",children:k})]}),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:O}),N!=="bad"&&!w?o.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),o.jsx(Ex,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const kx=[{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"}],Cx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function jx(){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:kx.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:Cx.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 Ax=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function Px(){const{t:e}=H(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return o.jsx(Fe,{title:e("quality.grokModelTitle"),items:Ax,value:t,onChange:n})}function pd({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 ii=3;function Rx(){const{t:e}=H(),t=f(p=>p.videoModelSelected),n=f(p=>p.videoReferenceVoices),r=f(p=>p.toggleVideoReferenceVoice),[s,a]=v.useState([]),[i,l]=v.useState("");v.useEffect(()=>{let p=!0;return Mi().then(m=>{p&&a(m.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{p=!1}},[]);const c=Rt(t)===et,d=n.length>=ii,u=()=>{const p=i.trim();!p||d||n.includes(p)||(r(p),l(""))};return s.length===0&&n.length===0?null:o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.voiceSection")}),o.jsx("div",{className:"composer__hint",children:c?e("video.voiceLimit",{max:ii}):e("video.voiceNeeds15")}),o.jsx("div",{className:"option-row",role:"group","aria-label":e("video.voiceSection"),children:s.map(p=>{const m=n.includes(p);return o.jsxs("button",{type:"button",className:`option-btn${m?" active":""}`,"aria-pressed":m,disabled:!c||!m&&d,onClick:()=>r(p),children:[p,m?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:`<AUDIO_${n.indexOf(p)}>`})]}):null]},p)})}),o.jsx("input",{type:"text",className:"text-input",value:i,disabled:!c||d,placeholder:e("video.voiceCustomPlaceholder"),onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())},onBlur:u,"aria-label":e("video.voiceCustomPlaceholder")})]})}const Tx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],Mx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),li=[3,5,8,10,12,15],Lx=[{value:po,label:"Grok V",sub:"Fast"},{value:et,label:"Grok V1.5",sub:"HD"}];function Ox(){const{t:e}=H(),t=f(T=>T.videoModelSelected),n=f(T=>T.selectVideoModel),r=f(T=>T.activeVideoRefCount()),s=f(T=>T.videoSingleRefMode),a=f(T=>T.setVideoSingleRefMode),i=f(T=>T.videoDuration),l=f(T=>T.setVideoDuration),c=f(T=>T.videoResolution),d=f(T=>T.setVideoResolution),u=f(T=>T.videoAspectRatio),p=f(T=>T.setVideoAspectRatio),m=f(T=>T.videoTopic),h=f(T=>T.setVideoTopic),b=f(T=>T.showToast),I=f(T=>T.videoContinuityLineage),x=f(T=>T.selectedPresetIds),y=f(T=>T.removePreset),g=x.map(T=>pc(T)).filter(T=>T?.category==="camera-motion"),_=zu(r,s),S=va(t,_),w=yc(I),k=is(t,"1080p",_),N=is(et,"1080p",_),O=Tx.map(T=>T.value==="1080p"?{...T,disabled:!N}:T);v.useEffect(()=>{is(t,c,_)||d("720p")},[_,c,d,t]),v.useEffect(()=>{i!==null&&i>S&&l(S)},[i,S,l]);const $=T=>{const P=va(T,_);i!==null&&i>P&&b(e("video.durationClampedToModel",{seconds:P})),n(T)},j=T=>{if(T==="1080p"){if(!N)return;k||n(et)}d(T)},[R,V]=v.useState(null);v.useEffect(()=>{Ee("/api/config/grok-planner").then(T=>T.json()).then(V).catch(()=>{})},[]);const C=async T=>{const P=R?.model;V(B=>B?{...B,model:T}:null);try{const B=await Ee("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:T})});if(!B.ok)throw new Error(`HTTP ${B.status}`)}catch(B){if(V(ne=>ne&&P?{...ne,model:P}:ne),B?.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:Lx.map(T=>o.jsxs("button",{type:"button",className:`option-btn${t===T.value?" active":""}`,onClick:()=>$(T.value),children:[T.label,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.sub})]},T.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.${_}`,{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,o.jsx(Rx,{}),g.length>0&&o.jsx(Wo,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(T=>o.jsx(Wc,{onRemove:()=>y(T.id),removeLabel:e("common.removeNamed",{name:T.name}),children:T.name},T.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:T=>h(T.target.value)})]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.durationTitle")}),o.jsx(pd,{values:li.filter(T=>T<=S),value:i,ariaLabel:e("video.durationTitle"),onChange:T=>l(T??li[0])})]}),r===1&&o.jsx(Fe,{title:e("video.singleRefTitle"),help:e("video.singleRefHelp"),items:[{value:"image-to-video",label:e("video.singleRef.source")},{value:"reference-to-video",label:e("video.singleRef.reference")}],value:s,onChange:a}),o.jsx(Fe,{title:e("video.resolutionTitle"),help:N?void 0:e("video.resolution1080Help"),items:O,value:c,onChange:j}),o.jsx(Fe,{title:e("video.aspectTitle"),items:Mx,value:u,onChange:p}),R&&o.jsx("div",{className:"video-controls__pills",children:o.jsx(Oe,{className:"video-controls__pill",items:R.options.map(T=>({value:T,label:T})),value:R.model,onChange:T=>{C(T)},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:Pr})]})]})}const ci=e=>Symbol.iterator in e,di=e=>"entries"in e,ui=(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},Fx=(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 Dx(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:ci(e)&&ci(t)?di(e)&&di(t)?ui(e,t):Fx(e,t):ui({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Gx(e){const t=un.useRef(void 0);return n=>{const r=e(n);return Dx(t.current,r)?t.current:t.current=r}}const zx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function qx(){const{t:e}=H(),t=f(Gx(Wm)),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(Oe,{items:Ui.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:zx.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(Oe,{items:ul.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(Oe,{items:ml.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(Oe,{items:pl.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(Oe,{items:fl.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),hl))}})]}),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 $x="",fd=3;function mi(e,t,n,r){const s=[],a=new Set;for(const i of[t,...e])!i?.filename||a.has(i.filename)||ve(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 Ux(e,t){return e[t]??null}function hd(e,t,n){const r=!t||e.some(s=>s.filename===t);return[{value:$x,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 As({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(Oe,{id:e,items:hd(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 Hx({index:e,images:t,selection:n,disabled:r,onChange:s,t:a}){const i=Ux(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(Oe,{items:hd(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 Vx({selection:e,disabled:t,onChange:n,t:r}){const s=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=fd,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 Kx({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:fd},(a,i)=>o.jsx(Hx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:s},i)),o.jsx(Vx,{selection:t,disabled:n,onChange:r,t:s})]})}function Bx({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)??$e(),l=v.useMemo(()=>mi(r,s,a,!1),[r,s,a]),c=v.useMemo(()=>mi(r,s,a,!0),[r,s,a]),d=p=>og(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(As,{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(As,{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(Kx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?o.jsx(As,{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 Wx(e){return Array.isArray(e)&&e.includes("image_references")}function Jx(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function qw(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 $w(e){return e.length>3}function Yx({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(!Wx(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=Jx({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 pi=new Set(["duration","resolution","quality","mode"]);function fi(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ta(e){return e.options&&e.options.length>0?fi(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):fi([e.min,...e.default!==void 0?[e.default]:[],e.max])}function hi(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 Xx(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function Zx(e){return[...ta(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function Qx({parameter:e,value:t,disabled:n,onChange:r}){const{t:s}=H();if(e.name==="duration"&&e.type==="number"){const l=Zx(e);if(l.length>1){const c=hi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:c}),o.jsx(pd,{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=hi(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:Xx(l,s)},`${typeof l}:${String(l)}`))]})]})}function gi({entries:e,parameters:t,disabled:n,onParameter:r}){return o.jsx(o.Fragment,{children:e.map(s=>o.jsx(Qx,{parameter:s,value:t[s.name],disabled:n,onChange:a=>r(s.name,a)},s.name))})}function eI({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=>pi.has(m.name)),u=c.filter(m=>!pi.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(gi,{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(Bx,{inputRoles:e.capabilities.inputRoles,disabled:r}),o.jsx(Yx,{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(gi,{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:[]},tI={};function nI(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function rI({record:e}){const{t}=H(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),s=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??tI,[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"),Gc(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=_=>ng(_,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:[nI(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(eI,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>rg(_,f.setState),onParameter:(_,S)=>sg(_,S,f.setState,f.getState)})]}):o.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function sI(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"?`${Ht}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!qt(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 oI(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(Ht),s=r?e.slice(Ht.length):e;kt(Zo(),r?{comfyVideoWorkflow:s}:{comfyWorkflow:s}).selectedAvailable&&(r?n.setComfyVideoWorkflow(s):n.setComfyWorkflow(s))}function aI(){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=Hn(),u=kt(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${Ht}${l}`:i??"",m=sI(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(Kt(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),o.jsx(Oe,{id:r,groups:m,value:p,onChange:h=>oI(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 iI=[{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"}],lI=[{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 cI(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 dI(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 gd(){const{t:e}=H(),t=f(z=>z.provider),n=f(z=>z.quality),r=f(z=>z.setQuality),s=f(z=>z.format),a=f(z=>z.setFormat),i=f(z=>z.moderation),l=f(z=>z.setModeration),c=f(z=>z.multimode),d=f(z=>z.setMultimode),u=f(z=>z.imageModel),p=f(z=>z.setImageModel),m=f(z=>z.selectVideoModel),h=f(z=>z.sizePreset),b=f(z=>z.customW),I=f(z=>z.customH),x=f(z=>z.setSizePreset),y=f(z=>z.setCustomSize),g=f(z=>z.uiMode),_=f(z=>z.videoModelSelected),S=f(z=>z.mcpProvider??null),{providers:w}=zc(),k=g==="classic",N=t==="grok"||t==="grok-api",O=t==="agy",$=t==="gemini-api",j=O||$,R=t==="nai",V=t==="comfy",C=N||j||R,T=h==="custom"?`${b}x${I}`:"1024x1024",P=$&&h==="auto",B=$&&!P?cI(T):null,ne=B??{ratio:"",res:""},oe=$&&!P&&h==="custom"&&!B,ue=u==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[me,D]=v.useState(!1),[F,ee]=v.useState(String(b)),[J,pe]=v.useState(String(I)),be=(z,le)=>{const ce=Lr[z||"1:1"]?.[le||"1K"]||"1024x1024",[Te,A]=ce.split("x").map(Number);D(!1),x("custom"),y(Te,A)},ae=()=>{const z=Number(F),le=Number(J);!Number.isFinite(z)||!Number.isFinite(le)||z<=0||le<=0||(x("custom"),y(z,le),D(!1))},ke=[{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")}],ie=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],we=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],_e=N?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:O?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:$?{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")},je=z=>{z==="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(rI,{record:w.find(z=>z.id===S)??null})]}):V?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(aI,{})]}):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:_e.title}),o.jsx("p",{children:_e.body})]}),N&&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:()=>je("image"),children:e("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>je("video"),children:e("grokMode.video")})]})}),_?o.jsx(Ox,{}):o.jsxs(o.Fragment,{children:[O?null:N?o.jsxs(o.Fragment,{children:[o.jsx(Px,{}),o.jsx(jx,{})]}):R?o.jsx(qx,{}):$?o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("quality.grokModelTitle"),items:we,value:ue,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((z,le)=>o.jsx("div",{className:"option-row",children:z.map(ce=>o.jsx("button",{type:"button",className:`option-btn${ne.ratio===ce.value?" active":""}`,onClick:()=>be(ce.value,ne.res),children:ce.label},ce.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:lI.map(z=>o.jsxs("button",{type:"button",className:`option-btn${ne.res===z.value?" active":""}`,onClick:()=>be(ne.ratio,z.value),children:[o.jsx("span",{children:z.label}),o.jsx("br",{}),o.jsx("small",{children:Lr[ne.ratio]?.[z.value]?.replace("x","×")||""})]},z.value))})]}),o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"option-row",children:[o.jsxs("button",{type:"button",className:`option-btn${P?" active":""}`,onClick:()=>{D(!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${oe||me?" active":""}`,onClick:()=>D(z=>!z),children:[e("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),me?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:F,onChange:z=>ee(z.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:J,onChange:z=>pe(z.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(F)>0&&Number(J)>0?o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:e("size.normalizedPreview")}),o.jsx("strong",{children:(()=>{const z=dI(Number(F),Number(J));return`${z.ratio} · ${z.res}`})()})]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:ae,children:e("settings.apiKeys.save")})]}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("quality.title"),items:ke,value:n,onChange:r}),o.jsx(hx,{})]}),C?null:o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("format.title"),items:iI,value:s,onChange:a}),o.jsx(Fe,{title:e("moderation.title"),items:ie,value:i,onChange:l}),o.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),k&&!j&&!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")})]})}),j||R?null:o.jsx(gx,{}),R?null:o.jsx(wx,{})]})]})}const uI=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-PLWyvEz1.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),mI=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-DNt7LHMi.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),pI=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-BL2C0DcW.js"),__vite__mapDeps([6,1,2])).then(e=>({default:e.GenerationRequestLogPanel})));function fI(){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=th(i)&&!c,h=c?e:!0,b=He(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(mI,{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(uI,{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(pI,{})})}):o.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:o.jsx(gd,{})})]})]})]})}function hI(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 gI({id:e}){const{t}=H();return o.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function yI({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 vI({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&&(Xe(l.url)||Xe(l.image))?o.jsx(Bt,{className:"collection-mini"},c):o.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function bI(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 xI(){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=bI(c),{t:p}=H(),m=t?Pe(t):null,h=v.useMemo(()=>xr(e.filter(gn)),[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(Pe(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:hI,"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(yI,{id:g.id,count:g.count},`coll-${g.id}`):o.jsx(gI,{id:g.id},g.id)),h.map(g=>{const _=Pe(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(vI,{sequenceId:g.sequenceId,images:w})),...w.map(k=>{const N=Pe(k),O=m===N;return ve(k)?y(N,o.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${O?" active":""}`,onClick:()=>r(k),draggable:!0,onDragStart:$=>{$.dataTransfer.setData("application/ima2-ref",JSON.stringify(Sn(k))),$.dataTransfer.effectAllowed="copy"},children:[k.thumb?o.jsx("img",{src:k.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Bt,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(N,o.jsx("img",{src:k.thumb||k.url||k.image,alt:"",className:`history-thumb history-thumb--fade-in${O?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(k),draggable:!0,onDragStart:$=>{$.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:k.url||k.image,filename:k.filename})),$.dataTransfer.effectAllowed="copy"}}))})]}return g.sequenceId&&I.has(g.sequenceId)&&!x.has(_)?null:ve(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(Sn(g))),w.dataTransfer.effectAllowed="copy"},children:[g.thumb?o.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Bt,{}),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 yi=3e3;function II(){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)},yi);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)},yi);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=Be[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 SI(){return null}function wI(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 _I(e,t,n){async function r(i){if(i.setId)try{await Se.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(rb(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:a}}const EI=["ArrowLeft","ArrowRight","Home","End"];function NI(){return v.useCallback(e=>{if(!EI.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 Ps({className:e,ariaLabel:t,tabs:n,value:r,onChange:s}){const a=NI(),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 kI({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 CI=[{id:"animate",labelKey:"chain.animate",available:e=>!!e.filename&&!ve(e)},{id:"edit",labelKey:"chain.edit",available:e=>!!e.filename&&!ve(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&&!ve(e)}];async function jI(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 Ee(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(()=>uv);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 AI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function PI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function RI(e){return{modelLabel:Hi(e.model,e.provider),derivation:AI(e),sourceLabel:PI(e)}}function TI(e){return!e.modelLabel&&!e.derivation}function MI({view:e,size:t="sm"}){const{t:n}=H();return TI(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 LI({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 OI({item:e,active:t,itemRef:n,onSelect:r,onDelete:s,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>CI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await jI(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(ve(e)?Sn(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:[ve(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(Bt,{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(LI,{id:p.id})},p.id))}):null,e.filename&&a&&o.jsx(Jc,{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(MI,{view:RI(e)})]})}function FI(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 Dt(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 vi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const DI=(e,t)=>Math.abs(e-t)<1.01,GI=(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 dn;const Rs=()=>{if(dn!==void 0)return dn;if(typeof navigator>"u")return dn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return dn=!0;const e=navigator.maxTouchPoints;return dn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},bi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},zI=e=>e,qI=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},$I=(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(bi(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(bi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Or={passive:!0},UI=typeof window>"u"?!0:"onscrollend"in window,HI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&UI;let i=0;const l=a?null:GI(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,Or),a&&r.addEventListener("scrollend",u,Or),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u),l?.cancel()}},VI=(e,t)=>HI(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),KI=(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"]},BI=(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})},WI=BI;class JI{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:zI,rangeExtractor:qI,onChange:()=>{},measureElement:KI,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=Dt(()=>(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,Or),a.addEventListener("touchend",l,Or),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=Dt(()=>[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=Dt(()=>[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 k=a(w),N=p.get(k),O=typeof N=="number"?N:this.options.estimateSize(w);g[w*2]=_,g[w*2+1]=O,_+=O+d}const S=FI(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 k=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){S=_;const j=b[S],R=j!==void 0?h[j]:void 0;w=R?R.end+d:r+s}else if(x===l){let j=0,R=I[0],V=b[0];for(let C=1;C<l;C++){const T=I[C];(T<R||T===R&&b[C]<V)&&(j=C,R=T,V=b[C])}S=j,w=R+d,k&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,w=r+s,k&&this.laneAssignments.set(y,S);const N=p.get(g),O=typeof N=="number"?N:this.options.estimateSize(y),$=w+O;h[y]={index:y,start:w,size:O,end:$,key:g,lane:S},b[S]===void 0&&x++,b[S]=y,I[S]=$}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Dt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=XI(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Dt(()=>{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=Dt(()=>[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=yd(0,r.length-1,a?l=>s[l*2]:l=>vi(r[l]).start,n);return vi(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&&DI(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 yd=(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 YI(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 XI(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=YI(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=yd(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 ZI({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 JI(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 QI(e){return ZI({observeElementRect:$I,observeElementOffset:VI,scrollToFn:WI,...e})}const Fr=170,Dr=10,vd=36,eS=44;function tS(e){const t=Math.max(Fr,e-vd);return Math.max(1,Math.floor((t+Dr)/(Fr+Dr)))}function nS(e,t){const n=Math.max(Fr,e-vd);return Math.max(Fr,Math.floor((n-Dr*Math.max(0,t-1))/t))+Dr}function rS(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 sS({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:s}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>tS(i||960),[i]),d=v.useMemo(()=>nS(i||960,c),[i,c]),u=v.useMemo(()=>rS(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=QI({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?eS:d,overscan:6});return v.useEffect(()=>{if(!t)return;const m=u.findIndex(h=>h.type==="items"&&h.items.some(b=>Pe(b)===t));m>=0&&p.scrollToIndex(m,{align:"center"})},[u,t,p]),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 xi({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 oS({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 aS({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 Ii="ima2.storageNoticeDismissed.0.09.23";function iS(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 lS(){const{t:e,locale:t}=H(),n=f(M=>M.galleryOpen),r=f(M=>M.closeGallery),s=f(M=>M.history),a=f(M=>M.selectHistory),i=f(M=>M.currentImage),l=f(M=>M.trashHistoryItem),c=f(M=>M.showToast),d=f(M=>M.toggleGalleryFavorite),u=f(M=>M.galleryScope),p=f(M=>M.setGalleryScope),m=f(M=>M.historyNextCursor),h=f(M=>M.historyLoadingOlder),b=f(M=>M.favoriteHistoryNextCursor),I=f(M=>M.favoriteHistoryLoadingOlder),x=f(M=>M.loadOlderHistory),y=f(M=>M.loadFavoriteHistory),g=f(M=>M.loadOlderFavoriteHistory),_=f(up),[S,w]=v.useState(""),[k,N]=v.useState("date"),[O,$]=v.useState(!1),[j,R]=v.useState(()=>new Set),V=v.useRef(new Set),[C,T]=v.useState([]),[P,B]=v.useState([]),[ne,oe]=v.useState(!1),[ue,me]=v.useState(!1),[D,F]=v.useState(!1),[ee,J]=v.useState(0),[pe,be]=v.useState(null),[ae,ke]=v.useState(()=>{try{return localStorage.getItem(Ii)==="1"}catch{return!1}}),ie=v.useRef(null),we=v.useRef({}),[_e,je]=v.useState(null),z=v.useRef(0),le=v.useRef({open:!1,selectedKey:null}),ce=v.useMemo(()=>xr(s.filter(gn)),[s]),Te=v.useCallback(M=>{ie.current=M,je(M)},[]),A=iS(_e),se=He(n,r);v.useEffect(()=>{n||w("")},[n]),v.useEffect(()=>{if(!n)return;let M=!1;return(async()=>{try{const Y=await ru();M||be(Y)}catch{M||be({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{M=!0}},[n]),v.useEffect(()=>{if(!n||k!=="session")return;let M=!1;return T([]),B([]),oe(!0),me(!1),F(!1),(async()=>{try{const Y=await tu({limit:500,sessionId:u==="current-session"?_:void 0});if(M)return;F(Y.nextCursor!==null||Y.total>=500);const Ie=U=>{const he=U.kind,at=he==="classic"||he==="edit"||he==="generate"||he==="card-news-card"||he==="card-news-set"?he: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:at,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}};T(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(gn).map(Ie))})).filter(U=>U.items.length>0)),B(xr(Y.loose.filter(gn).map(Ie)))}catch{M||me(!0)}finally{M||oe(!1)}})(),()=>{M=!0}},[n,k,u,_,ee]),v.useEffect(()=>{!n||k==="session"||!O||y()},[n,k,O,y]);const fe=v.useMemo(()=>{const M=S.trim().toLowerCase().normalize("NFC");return ce.filter(Y=>O&&!Y.isFavorite?!1:M?(Y.prompt??"").toLowerCase().normalize("NFC").includes(M)||(Y.filename??"").toLowerCase().normalize("NFC").includes(M):!0)},[ce,S,O]),K=v.useMemo(()=>O?C.map(M=>({...M,items:M.items.filter(Y=>Y.isFavorite)})).filter(M=>M.items.length>0):C,[C,O]),G=v.useMemo(()=>O?P.filter(M=>M.isFavorite):P,[P,O]),X=v.useMemo(()=>{const M=new Map;for(const Y of fe){const Ie=wI(Y.createdAt,t);M.has(Ie)||M.set(Ie,[]),M.get(Ie).push(Y)}return Array.from(M.entries())},[fe,t]),re=k==="session"?K.reduce((M,Y)=>M+Y.items.length,0)+G.length:fe.length;v.useLayoutEffect(()=>{const M=i?Pe(i):null;if(!n){le.current={open:!1,selectedKey:M};return}const Y=le.current,Ie=!Y.open||Y.selectedKey!==M;le.current={open:!0,selectedKey:M};const U=M?we.current[M]:null;if(Ie&&U){U.scrollIntoView({block:"center"});return}ie.current&&(ie.current.scrollTop=z.current)},[n,i?.filename,i?.image,k,re,X.length,K.length,G.length]);async function Le(M,Y){Y.stopPropagation();const Ie=Pe(M);await l(M),delete we.current[Ie],window.requestAnimationFrame(()=>ie.current?.focus())}async function De(M){const Y=M.filename;if(!(!Y||V.current.has(Y))){V.current.add(Y),R(new Set(V.current));try{const Ie=await d(M);if(Ie===null)return;T(U=>U.map(he=>({...he,items:he.items.map(at=>at.filename===Y?{...at,isFavorite:Ie}:at)}))),B(U=>U.map(he=>he.filename===Y?{...he,isFavorite:Ie}:he))}finally{V.current.delete(Y),R(new Set(V.current))}}}async function Lt(){try{await su(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ve,handleCopyCardNewsSetPath:dt,handleDownloadCardNewsManifest:ut}=_I(r,c,e);function vt(){ke(!0);try{localStorage.setItem(Ii,"1")}catch{}}if(!n)return null;const E=M=>M==="earlier"||M==="today"||M==="yesterday"||M==="thisWeek"?e(`gallery.${M}`):M,W=(M,Y,Ie)=>{const U=i?.image===M.image,he=Pe(M),at=Ot=>{we.current[he]=Ot,A.register(he,Ot)};return(A.supported?A.visibleKeys.has(he):!0)?M.kind==="card-news-set"?o.jsx("div",{ref:at,className:"gallery__tile-wrap gallery-card-news-set",children:o.jsx(kI,{item:M,onOpen:Ot=>{Ve(Ot)},onCopyPath:dt,onDownloadManifest:ut})},`${Y}-${he}`):o.jsx(OI,{item:M,active:U,itemRef:at,onSelect:Ot=>{a(Ot),r()},onDelete:Le,onToggleFavorite:De,favoriteBusy:!!(M.filename&&j.has(M.filename)),t:e},`${Y}-${he}`):o.jsx("div",{ref:at,className:"gallery__tile-wrap","data-gallery-lazy-key":he,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Y}-${he}`)},Q=k==="session",xe=i?Pe(i):null;return o.jsx("div",{className:"gallery-backdrop",onClick:r,role:"presentation",children:o.jsxs("div",{ref:se,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:M=>M.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:re}),S||O?e("gallery.totalFiltered",{n:ce.length}):""]}),o.jsx(Ps,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:O?"favorites":"all",onChange:M=>$(M==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),o.jsx(Ps,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:k,onChange:N,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),o.jsx(Ps,{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",...Q?{}:{"data-modal-initial-focus":!0},placeholder:e(Q?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:S,onChange:M=>w(M.target.value),disabled:Q}),o.jsx("button",{type:"button",className:"gallery__close",onClick:r,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),o.jsx(aS,{status:pe,dismissed:ae,onOpenFolder:Lt,onDismiss:vt,t:e}),o.jsx("div",{className:"gallery__scroll",ref:Te,tabIndex:-1,onScroll:()=>{z.current=ie.current?.scrollTop??0},children:Q?ne?o.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):ue?o.jsxs("div",{className:"gallery__empty",role:"alert",children:[o.jsx("span",{children:e("gallery.sessionLoadFailed")}),o.jsx("button",{type:"button",onClick:()=>J(M=>M+1),children:e("gallery.retry")})]}):o.jsxs(o.Fragment,{children:[D?o.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,o.jsx(oS,{groups:K,loose:G,favoritesOnly:O,galleryScope:u,setGalleryScope:p,renderTile:W,t:e}),o.jsx(xi,{showSessions:Q,favoritesOnly:O,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):fe.length===0?o.jsx("div",{className:"gallery__empty",children:ce.length===0?e("gallery.emptyAll"):e(O?"gallery.emptyFavorites":"gallery.noResults")}):o.jsxs(o.Fragment,{children:[o.jsx(sS,{dateGroups:X,selectedKey:xe,scrollElement:_e,localizeBucket:E,renderTile:W}),o.jsx(xi,{showSessions:Q,favoritesOnly:O,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function cS(e){return e.includes("ratio")?"sizeConfirm.reasonRatio":e.includes("maxPixels")||e.includes("pixels")?"sizeConfirm.reasonPixels":e.includes("minPixels")?"sizeConfirm.reasonMinPixels":e.includes("min")?"sizeConfirm.reasonMin":e.includes("maxEdge")||e.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function dS(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=H(),s=He(!!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(cS(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 uS(){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=He(!!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 mS=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Ct(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Ut(e){return!e||typeof e!="object"||Array.isArray(e)?Ct():e}function Xs(e){return typeof e!="string"||!e.trim()?Ct():e}function bd(e){return e===void 0?{}:typeof e!="boolean"?Ct():{executable:e}}function pS(e){const t=Ut(e),n=Ut(t.status);return typeof t.enabled!="boolean"||!mS.has(n.state)?Ct():{id:Xs(t.id),enabled:t.enabled,...bd(t.executable),status:{state:n.state}}}function Si(e){return Array.isArray(e)?e.map(t=>{const n=Ut(t);return{id:Xs(n.id),label:Xs(n.label),...bd(n.executable)}}):Ct()}function wi(e,t){const n=Ut(e);if(n.ok!==!0||!Array.isArray(n.providers))return Ct();const r=n.providers.map(pS);if(t===null)return{providers:r,catalog:null};const s=Ut(t),a=Ut(s.models);return s.ok!==!0?Ct():{providers:r,catalog:{image:Si(a.image),video:Si(a.video)}}}function fS(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 hS(){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 Hh(u.signal),I=wi(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Vh(t,u.signal):null,y=wi(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=fS(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 _i={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 gS(){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=md(),m=Hn(),h=s==="grok",b=Qe.find(w=>w.value===i),I=He(t,n);if(!t)return null;const x=p[s],y=kt(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(hS,{}):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?Kt(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:_i.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:_i[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 Ei="ima2.onboardingDismissed";function yS(){const{t:e}=H(),t=f(x=>x.openSettings),n=cd(),r=dd(),{data:s}=ud(),[a,i]=v.useState(()=>{try{return localStorage.getItem(Ei)==="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(Ei,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=He(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 vS(){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 bS(){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 xS(){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(!yt()||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(bS,{})})}let Gr=null;function IS(e){Gr=e}function SS(){const e=Gr;Gr=null,e?.isConnected&&e.focus()}function Ni(){Gr=null}function wS(){const{t:e}=H(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),s=r==="agent"&&Zt?"agent":r==="node"&&Xt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=yt(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&IS(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(rd,{compact:!0})})]})}const _S={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},ki={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function ES(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=_S[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function NS(){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 kS(){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 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:"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 jS(){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 AS(){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 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:"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 RS(){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 TS=[{id:"home",mode:"home",icon:kS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:NS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:CS,labelKey:"nav.node",enabled:Xt},{id:"agent",mode:"agent",icon:jS,labelKey:"nav.agent",enabled:Zt},{id:"assets",mode:"assets",icon:PS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:RS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:AS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function MS(){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=yt(),l=v.useRef(null),c=v.useCallback(I=>{const x=l.current;if(!x||!I)return;const y=x.getBoundingClientRect(),g=I.getBoundingClientRect();g.left<y.left?x.scrollLeft-=y.left-g.left:g.right>y.right&&(x.scrollLeft+=g.right-y.right)},[]);v.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=v.useCallback(I=>{if(I.settingsAction){r?(a(),history.replaceState(null,"",ki[t]||"#create")):(s(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",ki[I.mode]||"#create"))},[t,r,n,s,a]);v.useEffect(()=>{const I=()=>{const x=ES();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=TS.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 LS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-PLWyvEz1.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 OS(){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"&&Zt?"agent":l==="node"&&Xt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=yt(),[u,p]=v.useState(!1),m=v.useRef(a),h=v.useRef(!1),b=v.useRef(null),I=v.useRef({}),x=v.useRef(!1),y=w=>{r(w),requestAnimationFrame(()=>I.current[w]?.focus())},g=(w,k)=>{const N=Ke.indexOf(k),O=w.key==="ArrowRight"?Ke[(N+1)%Ke.length]:w.key==="ArrowLeft"?Ke[(N-1+Ke.length)%Ke.length]:w.key==="Home"?Ke[0]:w.key==="End"?Ke[Ke.length-1]:null;O&&(w.preventDefault(),y(O))},_=He(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,SS())},[t,n]);const S=d&&!i&&c==="classic";return v.useEffect(()=>{S||(x.current=!1,f.getState().composeSheetOpen&&s(),Ni())},[S]),v.useEffect(()=>()=>Ni(),[]),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:k=>{I.current[w]=k},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:k=>g(k,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 k=document.getElementById(dr);h.current=k?.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(ed,{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(gd,{}):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(LS,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const FS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function DS(){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=FS[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,xd="Image Gen";let na=xd,Zs=!1,ht=null,ra="",Qs=!1;function Id(){return navigator}function Sd(){if(typeof document>"u")return null;if(ht)return ht;const e=document.querySelector('link[rel~="icon"]');if(e)return ht=e,ra=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),ht=t,Qs=!0,t}function GS(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",zS(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 zS(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 qS(e){const t=Id();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function $S(){const e=Id();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function US(e){document.title=`(${e}) ${na}`;const t=Sd();t&&(t.href=GS(e)),qS(e)}function Ci(){document.title=na,ht&&(Qs?(ht.remove(),ht=null,Qs=!1):ht.href=ra),$S()}function ji(){Zs||typeof document>"u"||(Zs=!0,na=document.title||xd,Sd())}function HS(e){v.useEffect(()=>(ji(),()=>{Zs&&Ci()}),[]),v.useEffect(()=>{ji(),e>0?US(e):Ci()},[e])}function VS(){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 KS=v.lazy(()=>Me(()=>import("./NodeCanvas-5u8IO1MA.js"),__vite__mapDeps([7,1,2,8])).then(e=>({default:e.NodeCanvas}))),BS=v.lazy(()=>Me(()=>import("./SettingsWorkspace-Etfeu2IF.js"),__vite__mapDeps([9,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),WS=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-ZXDwYz4l.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.CardNewsWorkspace}))),JS=v.lazy(()=>Me(()=>import("./AgentWorkspace-CLJDCRMQ.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.AgentWorkspace}))),YS=v.lazy(()=>Me(()=>import("./AssetsWorkspace-IipC1FdD.js"),__vite__mapDeps([13,1,2,14,12,15])).then(e=>({default:e.AssetsWorkspace}))),XS=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-BepUrz23.js").then(e=>e.A),__vite__mapDeps([16,1,2,14,12,17])).then(e=>({default:e.AssetGenWorkspace}))),ZS=v.lazy(()=>Me(()=>import("./HomeWorkspace-DFfrwS9a.js"),__vite__mapDeps([18,1,2])).then(e=>({default:e.HomeWorkspace}))),QS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-PLWyvEz1.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function ew(){return o.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function tw(){DS(),VS();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"&&Zt?"agent":p==="node"&&Xt?"node":p==="home"?"home":p==="assets"?"assets":p==="asset-gen"?"asset-gen":"classic",h=m==="agent",b=m==="assets",I=m==="asset-gen",x=m==="home",y=yt(),g=Dn(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",S=!_&&!h&&!b&&!I&&!x;return HS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!de())return r(),t(),n(),a(),s(),At(),ua(()=>a()),ma(w=>{w==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{En(),ua(()=>{}),ma(()=>{})}},[t,n,a,s,r]),v.useEffect(()=>{const w=k=>{const N=k.detail?.assetId;N&&f.getState().openAssetDetail(N)};return window.addEventListener("ima2:open-assets-detail",w),()=>window.removeEventListener("ima2:open-assets-detail",w)},[]),v.useEffect(()=>{const w=k=>{k.key&&(k.key==="ima2.inFlight"||k.key==="ima2.selectedFilename"||k.key===ho||k.key===fo||k.key===yo)&&i()};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[i]),v.useEffect(()=>{const w=()=>{dp(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(MS,{}),x?null:o.jsx(yb,{}),o.jsx(wS,{}),S?o.jsx(xI,{}):null,o.jsx(v.Suspense,{fallback:o.jsx(ew,{}),children:l?o.jsx(BS,{}):m==="classic"?_?o.jsx(dx,{}):o.jsx(Ys,{}):m==="node"?o.jsx(KS,{}):m==="card-news"?o.jsx(WS,{}):m==="agent"?o.jsx(JS,{}):m==="assets"?o.jsx(YS,{}):m==="asset-gen"?o.jsx(XS,{}):m==="home"?o.jsx(ZS,{}):o.jsx(Ys,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:o.jsx(fI,{})]}),o.jsx(dS,{}),o.jsx(vS,{}),o.jsx(II,{}),o.jsx(SI,{}),o.jsx(lS,{}),o.jsx(uS,{}),o.jsx(gS,{}),o.jsx(yS,{}),o.jsx(OS,{}),o.jsx(xS,{}),m==="card-news"?o.jsx(v.Suspense,{fallback:null,children:o.jsx(QS,{})}):null]})}const Uw=Object.freeze(Object.defineProperty({__proto__:null,default:tw},Symbol.toStringTag,{value:"Module"}));export{_w as $,ju as A,Fe as B,zc as C,Rw as D,Tw as E,Mw as F,Cu as G,Lw as H,Qe as I,Gw as J,Qo as K,Ow as L,Fw as M,Dw as N,ku as O,Se as P,hI as Q,Ds as R,mv as S,Yu as T,Cw as U,Du as V,pv as W,st as X,By as Y,Aw as Z,Iu as _,f as a,Rp as a0,QI as a1,Jc as a2,zw as a3,$w as a4,qw as a5,kw as a6,Pw as a7,Qb as a8,so as a9,mw as aA,cw as aB,rw as aC,pw as aD,lw as aE,_b as aF,iw as aG,tx as aH,Pi as aI,L as aJ,sw as aK,aw as aL,ow as aM,gw as aN,fw as aO,yw as aP,vw as aQ,hw as aR,bw as aS,xw as aT,Iw as aU,Sw as aV,ww as aW,Uw as aX,sc as aa,NI as ab,Xo as ac,Nw as ad,jt as ae,Ew as af,es as ag,Wo as ah,Wc as ai,wv as aj,Pe as ak,md as al,NS as am,CS as an,Xt as ao,jS as ap,Zt as aq,PS as ar,ki as as,Ky as at,Jb as au,ex as av,Bs as aw,uw as ax,dw as ay,Ir as az,RI as b,bp as c,nt as d,Nt as e,Bu as f,Hi as g,jw as h,Xe as i,rc as j,He as k,Tp as l,bu as m,yp as n,q as o,yt as p,Ee as q,Oe as r,cd as s,dd as t,H as u,_x as v,tp as w,ud as x,Mu as y,ss as z};
|
|
8
|
+
`?null:{start:s,end:n,query:e.slice(r,n)}}function Fe({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=Pd();function Uy(e,t){if(!e||!t)return!0;const n=e.target;return!(n&&typeof n=="object"&&"nodeType"in n&&t.contains(n))}const Hy=(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}]}},Ua=(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 Oe({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:k,rendered:N}=Hy(t,e),O=k.length===0,[$,j]=v.useState(()=>Math.max(0,k.findIndex(F=>F.value===n))),R=v.useRef({buffer:"",at:0}),V=k.find(F=>F.value===n),C=F=>`${b}-opt-${F}`,T=F=>F.searchText?F.searchText:typeof F.label=="string"?F.label:F.value,P=F=>{const ee=Date.now(),J=R.current;J.buffer=ee-J.at>1e3?F:J.buffer+F,J.at=ee;const pe=J.buffer.toLowerCase(),be=J.buffer.length===1?$+1:$;for(let ae=0;ae<k.length;ae+=1){const ke=(be+ae+k.length)%k.length,ie=k[ke];if(!(!ie||ie.disabled)&&T(ie).toLowerCase().startsWith(pe)){j(ke);return}}};v.useEffect(()=>{if(!g)return;const F=ee=>{const J=ee.target;J instanceof Node&&(I.current?.contains(J)||y.current?.contains(J)||_(!1))};return document.addEventListener("pointerdown",F),()=>document.removeEventListener("pointerdown",F)},[g]),v.useLayoutEffect(()=>{if(!d||!g)return;const F=x.current?.getBoundingClientRect();if(F){const be=Math.max(0,window.innerWidth-24),ae=Math.min(300,be,Math.max(190,F.width)),ke=Math.max(12,window.innerWidth-ae-12),ie=Math.min(Math.max(12,F.left),ke),we=window.innerHeight-F.bottom-12,_e=F.top-12,je=we>=160||we>=_e?"down":"up",z=Math.max(0,je==="down"?we:_e),le=Math.min(420,z),ce=8+k.length*44,Te=y.current?.scrollHeight??ce,A=Math.min(Te,le);w({top:je==="down"?F.bottom+4:Math.max(12,F.top-A-4),left:ie,width:ae,maxHeight:le})}const ee=()=>_(!1),J=pe=>{Uy(pe,y.current)&&_(!1)};return window.addEventListener("resize",ee),window.addEventListener("scroll",J,!0),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",J,!0)}},[d,g]),v.useEffect(()=>{g&&y.current?.querySelector(`[data-index="${$}"]`)?.scrollIntoView({block:"nearest"})},[g,$]);const B=()=>{O||(j(Math.max(0,k.findIndex(F=>F.value===n))),_(!0))};v.useEffect(()=>{O&&(_(!1),j(0))},[O]);const ne=F=>{let ee=$;for(let J=0;J<k.length&&(ee=(ee+F+k.length)%k.length,!!k[ee]?.disabled);J+=1);j(ee)},oe=F=>{const ee=k[F];!ee||ee.disabled||(r(ee.value),_(!1),x.current?.focus())},ue=F=>{if(!g){["Enter"," ","ArrowDown","ArrowUp"].includes(F.key)&&(F.preventDefault(),B());return}if(F.key==="Escape")F.preventDefault(),_(!1);else if(F.key==="ArrowDown")F.preventDefault(),ne(1);else if(F.key==="ArrowUp")F.preventDefault(),ne(-1);else if(F.key==="Home")F.preventDefault(),j(Ua(k,"first",$));else if(F.key==="End")F.preventDefault(),j(Ua(k,"last",$));else if(F.key==="Enter"||F.key===" "){if(F.key===" "&&Date.now()-R.current.at<=1e3&&R.current.buffer){F.preventDefault(),P(" ");return}F.preventDefault(),oe($)}else F.key==="Tab"?_(!1):F.key.length===1&&!F.metaKey&&!F.ctrlKey&&!F.altKey&&(F.preventDefault(),P(F.key))};let me=-1;const D=g&&!O?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:N.map((F,ee)=>o.jsxs("li",{role:"presentation",className:"ctl-select__group",children:[F.label?o.jsx("div",{className:"ctl-select__group-label",children:F.label}):null,o.jsx("ul",{role:"group","aria-label":typeof F.label=="string"?F.label:void 0,className:"ctl-select__group-items",children:F.items.map(J=>{me+=1;const pe=me;return o.jsxs("li",{role:"option",id:C(pe),"data-index":pe,"aria-selected":J.value===n,"aria-disabled":J.disabled||void 0,title:J.title,className:`ctl-select__item${J.value===n?" is-selected":""}${pe===$?" is-active":""}${J.disabled?" is-disabled":""}${J.stacked?" is-stacked":""}`,onPointerEnter:()=>j(pe),onClick:()=>oe(pe),children:[o.jsx("span",{className:"ctl-select__item-label",children:J.label}),J.sub?o.jsx("span",{className:"ctl-select__item-sub",children:J.sub}):null]},J.value)})})]},`g-${ee}`))}):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&&k[$]?C($):void 0,"aria-label":s,"aria-describedby":a,disabled:c||O,title:h,onClick:()=>g?_(!1):B(),onKeyDown:ue,children:[o.jsx("span",{className:"ctl-select__value",children:u??V?.label??m??""}),p??V?.sub?o.jsx("span",{className:"ctl-select__value-sub",children:p??V?.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"})})]}),D?d?ss.createPortal(D,document.body):D:null]})}function Vy({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 Wc({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 Ky(){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 Jc({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(Ky,{})})}function By(){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 Ha=12,Wy=240;function Jy(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 Yy(e,t){const n=Jy(e,t),r=window.innerHeight-n.bottom,s=r<Wy?"top":"bottom",a=s==="bottom"?r:n.top;return{left:Math.max(Ha,Math.min(n.left,window.innerWidth-332)),top:s==="bottom"?n.bottom+6:Math.max(Ha,n.top-Math.min(320,a-8)),placement:s,maxHeight:Math.max(120,Math.min(320,a-12))}}function Xy(){return window.matchMedia("(max-width: 640px)").matches}function Zy({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 O=s.trim().toLocaleLowerCase();return O?a.filter($=>[$.name,...$.tags??[]].some(j=>j.toLocaleLowerCase().includes(O))):a},[a,s]),w=O=>{b(O),p?.(O)},k=()=>{const O=S[h];O&&d(O)};if(v.useLayoutEffect(()=>{if(!e||!t.current)return;const O=()=>{if(!t.current){u();return}g(Xy()),x(Yy(t.current,r))},$=()=>requestAnimationFrame(O);return O(),window.addEventListener("resize",$),t.current.addEventListener("scroll",$),()=>{window.removeEventListener("resize",$),t.current?.removeEventListener("scroll",$)}},[e,t,r,u]),v.useEffect(()=>{w(0)},[s,S.length]),v.useEffect(()=>{if(!e)return;const O=t.current;if(!O)return;O.setAttribute("aria-controls",m),O.setAttribute("aria-expanded","true");const $=j=>{if(document.activeElement===O&&!(n?.current||j.isComposing||j.keyCode===229)&&!(j.key==="Enter"&&(j.ctrlKey||j.metaKey))){if(j.key==="Escape"){j.preventDefault(),u("escape");return}j.key==="ArrowDown"||j.key==="ArrowUp"?(j.preventDefault(),w((h+(j.key==="ArrowDown"?1:-1)+S.length)%Math.max(1,S.length))):j.key==="Home"?(j.preventDefault(),w(0)):j.key==="End"?(j.preventDefault(),w(Math.max(0,S.length-1))):j.key==="Enter"?S.length&&(j.preventDefault(),k()):j.key==="Tab"&&S.length&&k()}};return O.addEventListener("keydown",$),()=>{O.removeAttribute("aria-controls"),O.removeAttribute("aria-expanded"),O.removeAttribute("aria-activedescendant"),O.removeEventListener("keydown",$)}},[e,t,n,m,h,S,u]),v.useEffect(()=>{const O=t.current,$=S[h];O&&$&&O.setAttribute("aria-activedescendant",`${m}-${$.id}`)},[h,S,m,t]),v.useEffect(()=>{_.current?.querySelector(".is-active")?.scrollIntoView({block:"nearest"})},[h]),!e||!I||typeof document>"u")return null;const N=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((O,$)=>o.jsxs("li",{id:`${m}-${O.id}`,role:"option","aria-selected":$===h,className:`element-mention-menu__option${$===h?" is-active":""}`,onPointerEnter:()=>w($),onMouseDown:j=>{j.preventDefault(),d(O)},children:[O.thumbnail?o.jsx("img",{src:O.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:O.name}),o.jsx("small",{children:c(O.kind)})]})]},O.id)):o.jsx("li",{className:"element-mention-menu__empty",role:"presentation",children:l})})});return ss.createPortal(N,document.body)}function Qy(e){if(e)return e.startsWith("/generated/")?e:`/generated/${e.split("/").map(encodeURIComponent).join("/")}`}function ev(e){return e.kind==="attachment"?e.source.dataUrl:e.source.thumbnailUrl??Qy(e.source.referenceFilenames[0])}function tv({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=ev(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 nv({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 rv({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(nv,{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 sv=new Set(["character","product","style","scene"]);function ov(e){const t=e?.metadata?.elementKind;return typeof t=="string"&&sv.has(t)?t:"character"}function av(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 iv(e,t,n){const r=new Map((t??[]).map(a=>[a.id,a])),s=new Set(n);return ac({trayItems:[...e]}).map(a=>{const i=r.get(a.source.elementId);return{elementId:a.source.elementId,name:i?.name??a.source.nameAtInsertion,kind:ov(i),thumbnail:av(i)??a.source.thumbnailUrl,missing:s.has(a.source.elementId)||t!==null&&!i}})}function lv(e){const t=iv(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(rv,{...n,ariaLabel:e.mentionLabel(n.name,r,n.missing),unavailableLabel:e.unavailableLabel,removeLabel:e.removeLabel(n.name),onRemove:e.onRemove},n.elementId)})})}const cv=["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 dv({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(()=>qp(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);cv.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=ve(e),r=!!e.prompt;if(t.clearReferences(),t.setPrompt(r&&!n?e.prompt:""),n){const s=e.url||e.image,a=await en(s);t.addReferenceDataUrl(a);const i=gc(e);t.setVideoContinuityLineage(i),i&&t.insertPromptToComposer(lf(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 Yc(e){const t=await os(e);return e.providerUrl&&f.getState().setProviderUrlReference(e.providerUrl),t}const uv=Object.freeze(Object.defineProperty({__proto__:null,continueFromItem:os,continueFromItemAsUrl:Yc},Symbol.toStringTag,{value:"Module"}));function mv({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 pv({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(Vy,{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 fv({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(pv,{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(mv,{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 Va(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 hv(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=Va(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=Va(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}const Xc="grok-imagine-video",gv="grok-imagine-video-1.5",Zc=new Set([gv,"grok-imagine-video-1.5-preview","grok-imagine-video-1.5-2026-05-30"]);function yv(e){return e.type.startsWith("audio/")}function vv(e){return e.type.startsWith("video/")||/\.mp4$/i.test(e.name)}function bv(e,t){const n={images:[],audios:[],videos:[],rejected:[]},r=t.videoModelSelected,s=typeof r=="string"&&Zc.has(r),a=r===Xc;for(const i of e){if(i.type.startsWith("image/")){n.images.push(i);continue}if(yv(i)){r?s?n.audios.push(i):n.rejected.push({file:i,reason:"audio-needs-15"}):n.rejected.push({file:i,reason:"audio-needs-video-model"});continue}if(vv(i)){a?n.videos.length>0?n.rejected.push({file:i,reason:"video-single-only"}):n.videos.push(i):n.rejected.push({file:i,reason:"video-needs-base"});continue}n.rejected.push({file:i,reason:"not-media"})}return n}function xv(e){const t=e.videoModelSelected;return typeof t=="string"&&Zc.has(t)?"image/*,audio/*":t===Xc?"image/*,video/mp4":"image/*"}function Iv(e,t){switch(e){case"audio-needs-video-model":return t("prompt.rejectAudioNeedsVideoModel");case"audio-needs-15":return t("prompt.rejectAudioNeeds15");case"video-needs-base":return t("prompt.rejectVideoNeedsBase");case"video-single-only":return t("prompt.rejectVideoSingleOnly");case"not-media":return t("prompt.rejectNotMedia")}}function Sv({onImages:e}){const{t}=H(),n=f(s=>s.videoModelSelected),r=f(s=>s.showToast);return s=>{if(s.length===0)return;const a=bv(s,{videoModelSelected:n});a.images.length>0&&e(a.images),a.audios.length>0&&r(t("prompt.audioUsePresetVoice"),!0),a.videos.length>0&&r(t("prompt.videoUseCliForEdit"),!0);for(const i of new Set(a.rejected.map(l=>l.reason)))r(Iv(i,t),!0)}}function wv({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 _v(e){const t=f.getState();return t.addElementFromMention?t.addElementFromMention(e):br(e.id,f.setState,f.getState,e)}function Ev(e){const t=f.getState();t.syncElementCatalog?t.syncElementCatalog(e):dc(e,f.setState,f.getState)}function Nv(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 W=b.find(Q=>Q.id===E);return W?_v(W):(p?.(E),null)};v.useEffect(()=>{let E=!1;return Tp().then(W=>{E||(I(W),Ev(W))}).catch(W=>console.error("[ElementMention] load failed",W)),()=>{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()),k=f(E=>E.providerUrlReference),N=f(E=>E.setProviderUrlReference),O=f(E=>E.addReferences),$=f(E=>E.addReferenceDataUrl),j=f(E=>E.useImageAsReference),R=f(E=>E.readDroppedImageMetadata),V=f(E=>E.videoModelSelected),C=v.useRef(null),T=v.useRef(null),P=v.useRef(null),[B,ne]=v.useState(!1),[oe,ue]=v.useState(null),me=v.useRef(!1),D=v.useRef(null),F=v.useRef(null),ee=f(E=>E.promptMode),J=f(cf),pe=f(E=>E.multimodeMaxImages),be=ee==="direct",ae=r==="nai",ke=s.filter(E=>E.placement!=="after"),ie=s.filter(E=>E.placement==="after"),we=[...ke.map(E=>E.id),"__main_prompt__",...ie.map(E=>E.id)],_e=g.length<w,je=J?g.length>0?y("multimode.promptPlaceholderWithRefs"):y("multimode.promptPlaceholder"):g.length>0?y("prompt.placeholderWithRefs"):y("prompt.placeholder"),z=()=>{h.length>0||l()},le=()=>T.current?.selectionStart??f.getState().prompt.length,ce=(E,W)=>{const Q=f.getState().trayItems.filter(U=>U.kind==="attachment"&&!E.has(U.tokenId));if(Q.length===0)return 0;const xe=f.getState().prompt,M=Math.max(0,Math.min(W,xe.length)),Y=Q.map(U=>`@${U.tag} `).join("");n(`${xe.slice(0,M)}${Y}${xe.slice(M)}`);const Ie=M+Y.length;return requestAnimationFrame(()=>T.current?.setSelectionRange(Ie,Ie)),Q.length},Te=(E,W)=>{const Q=`@${E} `,xe=f.getState().prompt,M=`${xe.slice(0,W.start)}${Q}${xe.slice(W.end)}`,Y=W.start+Q.length;n(M),requestAnimationFrame(()=>T.current?.setSelectionRange(Y,Y))},A=(E,W)=>{if(me.current)return;const Q=$y(E,W);ue(Q&&gs(Q)!==F.current?Q:null)},se=async(E,W,Q)=>{if(E.length===0)return 0;const xe=new Set(f.getState().trayItems.map(M=>M.tokenId));try{return Q&&E.length===1&&await R(E[0])?0:(await O(E),ce(xe,W))}catch{return 0}},fe=async E=>{const W=P.current??le();P.current=null,await se(E,W,!0)},K=Sv({onImages:E=>{fe(E)}}),G=()=>{_e&&(P.current=le(),C.current?.click())},X=async(E,W)=>{const Q=new Set(f.getState().trayItems.map(xe=>xe.tokenId));try{const xe=E.url||E.image;if(!xe)return;const M={image:xe,url:E.url,filename:E.filename};if(ve(M)){const Y=await en(xe);Y&&$(Y)}else await j(M);ce(Q,W)}catch{}},re=E=>{E.preventDefault(),ne(!1);const W=E.dataTransfer.getData("application/ima2-ref");if(W){try{const Q=JSON.parse(W);X(Q,le())}catch{}return}K(Array.from(E.dataTransfer.files))},Le=E=>{E.preventDefault(),B||ne(!0)},De=E=>{E.currentTarget.contains(E.relatedTarget)||ne(!1)},Lt=hv({maxRefs:w,trayItemCount:g.length,captureAttachmentCaret:le,addFilesAtCaret:se}),Ve=v.useRef(null),dt=v.useRef(e);v.useLayoutEffect(()=>{const E=T.current;if(!E)return;(Ve.current===null||dt.current!==e)&&(Ve.current=Nv(window.getComputedStyle(E).maxHeight)??0,dt.current=e),E.style.height="auto";const W=Ve.current,Q=W?Math.min(E.scrollHeight,W):E.scrollHeight;E.style.height=`${Q}px`},[t,e]);const ut=(E,W)=>{const Q=we.indexOf(E);return Q<0?!1:W==="up"?Q>0:Q<we.length-1},vt=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:!ut(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:!ut(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}${B?" composer--drag":""}${be?" composer--direct":""}${J?" composer--multimode":""}${be&&J?" composer--combined-modes":""}`,role:"group","aria-label":J?y("multimode.composerAriaLabel",{count:pe}):y("prompt.label"),onDrop:re,onDragOver:Le,onDragLeave:De,onPaste:Lt,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:[J&&o.jsx("span",{className:"composer__mode-badge",children:y("multimode.composerBadge",{count:pe})}),be&&o.jsx("span",{className:"composer__direct-badge",children:y("prompt.directModeActive")}),k&&o.jsxs("button",{type:"button",className:"composer__url-ref-badge",onClick:()=>N(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(tv,{items:g,limit:w,onRemove:S,onAdd:G}),ke.length>0&&o.jsx("div",{className:"composer__prompt-chips",children:ke.map(vt)}),c.length>0&&o.jsx(Wo,{ariaLabel:y("home.selectedPresets"),children:c.map(E=>{const W=pc(E);return W?o.jsx(Wc,{onRemove:()=>d(E),removeLabel:y("common.removeNamed",{name:W.name}),children:W.name},E):null})}),o.jsx(lv,{items:g,assets:m,missingElementIds:h,selectedLabel:y("element.selected"),unavailableLabel:y("common.elementUnavailable"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),mentionLabel:(E,W,Q)=>Q?y("element.unavailableAria",{name:E}):y("element.mentionAria",{name:E,kind:W}),removeLabel:E=>y("element.removeAria",{name:E}),onRemove:E=>u.removeElementId?.(E)}),o.jsxs("div",{className:`composer__prompt-panes${ae?" composer__prompt-panes--dual":""}`,children:[o.jsxs("div",{className:"composer__prompt-pane",children:[ae?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(dv,{prompt:t,retiredTags:_,textareaRef:T}),o.jsx("textarea",{id:`positive-prompt-${e}`,ref:T,className:"prompt-area composer__textarea",value:t,placeholder:ae?y("nai.positivePrompt.placeholder"):je,"aria-describedby":ae?`positive-prompt-${e}-hint`:void 0,onCompositionStart:()=>{me.current=!0,ue(null)},onCompositionEnd:E=>{me.current=!1,D.current=E.currentTarget.value,queueMicrotask(()=>{D.current=null}),A(E.currentTarget.value,E.currentTarget.selectionStart)},onChange:E=>{F.current=null,n(E.target.value),D.current!==E.target.value&&A(E.target.value,E.target.selectionStart)},onClick:E=>A(E.currentTarget.value,E.currentTarget.selectionStart),onKeyDown:E=>{if(!(me.current||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229)){if(E.key==="Escape"&&oe){E.preventDefault(),F.current=gs(oe),ue(null);return}if(E.key==="Enter"&&(E.metaKey||E.ctrlKey)){if(E.defaultPrevented)return;E.preventDefault(),z()}}}})]}),ae?o.jsx("p",{id:`positive-prompt-${e}-hint`,className:"composer__prompt-hint",children:y("nai.positivePrompt.hint",{count:t.length})}):null]}),o.jsx(wv,{variant:"classic",onSubmit:z})]}),o.jsx(Zy,{open:oe!==null,textareaRef:T,composingRef:me,caret:oe?.end??0,query:oe?.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 W=rc(E);return{id:E.id,name:E.name,kind:typeof E.metadata?.elementKind=="string"?E.metadata.elementKind:"character",thumbnail:W?`/generated/${W.split("/").map(encodeURIComponent).join("/")}`:void 0,tags:E.tags}})],ariaLabel:y("common.elementSuggestions"),emptyLabel:y("common.noMatchingElements"),kindLabel:E=>y(`element.kind${E[0].toUpperCase()}${E.slice(1)}`),onSelect:E=>{const W=Ks(f.getState().trayItems,E.id);if(E.id.startsWith(hs)){const xe=E.id.slice(hs.length),M=f.getState().trayItems.find(Y=>Y.tokenId===xe);M&&oe&&Te(M.tag,oe),ue(null);return}if(x?.(E.id),W){requestAnimationFrame(()=>document.querySelector(`[data-element-id="${CSS.escape(E.id)}"] .element-mention-chip__body`)?.focus()),ue(null);return}const Q=Ks(f.getState().trayItems,E.id);!Q||!oe||(Te(Q.tag,oe),ue(null))},onClose:E=>{E==="escape"&&oe&&(F.current=gs(oe)),ue(null)}}),ie.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")}),ie.map(vt)]}),o.jsx(fv,{canAddMore:_e,onAttach:G}),B&&o.jsx("div",{className:"composer__dropzone","aria-hidden":"true",children:y("prompt.dropHere",{max:w})}),o.jsx("input",{ref:C,type:"file",accept:xv({videoModelSelected:V}),multiple:!0,hidden:!0,onChange:E=>{const W=Array.from(E.target.files??[]);W.length>0?K(W):P.current=null,E.target.value=""}})]})}function 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 Qc(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(jv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s,variant:e.variant,panelId:e.panelId}):o.jsx(kv,{jobs:t,phaseLabels:a,videoProgress:r,cancelInFlightJob:n,t:s})}function kv(e){return o.jsx("ul",{className:"in-flight-list",children:e.jobs.map(t=>o.jsx(Cv,{f:t,...e},t.id))})}function Cv({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:Qc(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 jv(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(Av,{f:s,determinateVideoId:n,validVideoProgress:r,...e},s.id))})}function Av({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=Rv(e)??Tv(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(Mv,{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:Qc(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(Pv,{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 Pv({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 Rv(e){return!("model"in e)||typeof e.model!="string"?null:e.model.trim()||null}function Tv(e,t){return e?.startsWith("mcp-")?t("inflight.kindMcp"):t(e==="video"?"inflight.kindVideo":e==="node"?"inflight.kindNode":"inflight.kindImage")}function Mv({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 Ka="(max-width: 800px)";function yt(){const[e,t]=v.useState(()=>typeof window<"u"?window.matchMedia(Ka).matches:!1);return v.useEffect(()=>{if(typeof window>"u")return;const n=window.matchMedia(Ka),r=()=>t(n.matches);return n.addEventListener("change",r),()=>n.removeEventListener("change",r)},[]),e}const Lv=10,mt=12;function Ov({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:mt,top:mt,caretTop:24}),[m,h]=v.useState(!1);v.useLayoutEffect(()=>{const x=()=>{const _=e.current,S=l.current;if(!_||!S)return;const w=_.getBoundingClientRect(),k=_.closest(".sidebar")?.getBoundingClientRect(),N=S.getBoundingClientRect(),O=k?k.right:w.right,$=Math.max(mt,window.innerWidth-N.width-mt),j=Math.max(mt,window.innerHeight-N.height-mt),R=Math.min(Math.max(O+Lv,mt),$),V=Math.min(Math.max(w.bottom-N.height,mt),j),C=Math.min(Math.max(w.top+w.height/2-V,16),N.height-16);p({left:R,top:V,caretTop:C}),h(!0)},y=()=>{d.current!=null&&cancelAnimationFrame(d.current),d.current=requestAnimationFrame(x)};x(),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0);const g=new ResizeObserver(y);return e.current&&g.observe(e.current),l.current&&g.observe(l.current),()=>{window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0),g.disconnect(),d.current!=null&&cancelAnimationFrame(d.current)}},[e]),v.useLayoutEffect(()=>{n&&c.current?.focus()},[n]),v.useEffect(()=>{const x=g=>{const _=g.target;_&&(e.current?.contains(_)||l.current?.contains(_))||r(!1)},y=g=>{g.key==="Escape"&&(g.preventDefault(),r(!0))};return document.addEventListener("pointerdown",x,!0),document.addEventListener("keydown",y),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("keydown",y)}},[e,r]);const b=`${t}-title`,I={left:u.left,top:u.top,"--inflight-caret-top":`${u.caretTop}px`};return 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 Fv=180,Dv=180;function ed({variant:e="popup",panelId:t,expanded:n=!1,onToggle:r}){const s=f(j=>j.inFlight.length),a=yt(),{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 j=document.activeElement;b&&j instanceof HTMLElement&&j.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"),Fv))},S=()=>{m.current!=null&&window.clearTimeout(m.current),m.current=null,!(e!=="popup"||l!=="hover")&&(h.current=window.setTimeout(()=>c("closed"),Dv))},w=j=>{I(),c("closed"),u(!1),j&&p.current?.focus()},k=j=>{if(e==="inline"){r?.(!n);return}if(I(),l==="pinned"){w(!1);return}u(j.detail===0),c("pinned")},N=j=>{j.pointerType==="mouse"&&_()},O=s>99?"99+":String(s),$=b?"inflight.badgeClose":"inflight.badgeOpen";return o.jsxs("span",{className:`inflight-badge-wrap inflight-badge-wrap--${e}`,onPointerEnter:N,onPointerLeave:S,children:[o.jsxs("button",{ref:p,type:"button",className:`inflight-badge inflight-badge--${e}`,onClick:k,"aria-live":"polite","aria-expanded":b,"aria-controls":t,"aria-haspopup":e==="popup"?"dialog":void 0,"aria-label":i($,{n:s}),title:i($,{n:s}),children:[o.jsx("span",{className:"inflight-badge__spinner","aria-hidden":"true"}),o.jsx("span",{className:"inflight-badge__count","aria-hidden":"true",children:O})]}),e==="popup"&&b?o.jsx("span",{className:"inflight-badge__bridge","aria-hidden":"true"}):null,e==="popup"&&b?o.jsx(Ov,{anchorRef:p,panelId:t,focusOnOpen:d,onRequestClose:w,onPointerEnter:g,onPointerLeave:S}):null]})}function Gv(){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(By,{})})]}),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 Lw(){return q("/api/comfy/workflows")}function Ow(e){return q("/api/comfy/inspect",{method:"POST",body:JSON.stringify(e)})}function Fw(e){return q("/api/comfy/probe",{method:"POST",body:JSON.stringify({origin:e})})}function Dw(e){return q("/api/comfy/workflows",{method:"POST",body:JSON.stringify(e)})}function Gw(e){return q(`/api/comfy/workflows/${encodeURIComponent(e)}`,{method:"DELETE"})}async function zv(e){return $v(await q("/api/models",e?{signal:e}:{}))}function qv(e){return e==="ready"||e==="locked"||e==="disconnected"||e==="key-missing"}function yn(){throw Object.assign(new Error("Invalid model catalog response"),{code:"MODEL_CATALOG_INVALID"})}function pn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ba(e){if(!pn(e)||typeof e.id!="string"||!e.id.trim()||typeof e.label!="string"||!e.label.trim())return yn();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 yn();t[n]=e[n]}if(e.executable!==void 0){if(typeof e.executable!="boolean")return yn();t.executable=e.executable}return t}function $v(e){return!pn(e)||e.ok!==!0||!pn(e.lanes)?yn():Object.fromEntries(Object.entries(e.lanes).map(([t,n])=>{if(!pn(n)||!qv(n.status)||!pn(n.models)||!Array.isArray(n.models.image)||!Array.isArray(n.models.video)||n.reason!==void 0&&typeof n.reason!="string")return yn();const r={status:n.status,...typeof n.reason=="string"?{reason:n.reason}:{},models:{image:n.models.image.map(Ba),video:n.models.video.map(Ba)}};return[t,r]}))}const td={phase:"idle",catalog:null,observedAt:null,error:null},ft=new Set;let jn=td,Tr=0,pt=null,Qn=null;const Wa=()=>{Qo()};function Zo(){return jn}function fn(e){jn=e;for(const t of[...ft])ft.has(t)&&t()}function ys(e,t){return e===Tr&&pt===t&&!t.signal.aborted&&ft.size>0}function Uv(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(pt?.abort(),pt=null,ft.size===0){fn(td);return}const t=new AbortController;if(pt=t,fn({...jn,phase:"loading",error:null}),!!ys(e,t))try{const n=await zv(t.signal);ys(e,t)&&fn({phase:"ready",catalog:n,observedAt:Date.now(),error:null})}catch(n){ys(e,t)&&fn({...jn,phase:"error",error:Uv(n)})}finally{e===Tr&&pt===t&&(pt=null)}}function Hv(e){const t=ft.size===0;return ft.add(e),t&&(typeof window<"u"&&(Qn=window,Qn.addEventListener("focus",Wa)),Qo()),()=>{!ft.delete(e)||ft.size>0||(++Tr,pt?.abort(),pt=null,Qn?.removeEventListener("focus",Wa),Qn=null,fn({...jn,phase:"idle",error:null}))}}function Hn(){return{...v.useSyncExternalStore(Hv,Zo),refresh:Qo}}function qt(e){return e.executable!==!1&&!e.description?.endsWith("(offline)")}function kt(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(qt)||r.video.some(qt),d=e.phase==="ready"&&n?.status==="ready"&&c,u=!!(d&&i&&qt(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 Vv={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 Kt(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":Vv[e.code]}const nd=[{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"}],Ja=new Map(nd.map(e=>[e.value,e.label])),Kv=new Set(["runway","higgsfield"]),er="mcp:",tr="core:",vs="effort:",bs=Bi,an=Ht;function Bv(e){rs(e,f.setState,f.getState)}function Wv(e){eg(e,f.setState,f.getState)}function Jv(e,t,n){tg(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 Yv(e,t){return e==="key-missing"?t("mcp.lane.keyMissing"):e==="disconnected"?t("mcp.lane.offline"):e==="locked"?t("mcp.lane.locked"):null}function rd({compact:e=!1}={}){const{t}=H(),n=f(A=>A.provider),r=f(A=>A.imageModel),s=f(A=>A.videoModelSelected),a=f(A=>A.mcpProvider??null),i=f(A=>A.mcpModel??null),l=f(A=>A.mcpMediaKind??"image"),c=f(A=>A.setProvider),d=f(A=>A.setImageModel),u=f(A=>A.selectVideoModel),p=f(A=>A.setComfyWorkflow),m=f(A=>A.comfyWorkflow),h=f(A=>A.setComfyVideoWorkflow),b=f(A=>A.comfyVideoWorkflow),I=f(A=>A.setReasoningEffort),x=f(A=>A.reasoningEffort),{providers:y,loading:g,error:_}=zc(),[S,w]=v.useState(xs),[k,N]=v.useState(!1),[O,$]=v.useState(0),[j,R]=v.useState(!1),V=Hn(),C=V.catalog??{},T=C.comfy?.models??{image:[],video:[]};v.useEffect(()=>{ig(f.setState,f.getState)},[]);const P=a?y.find(A=>A.id===a)??null:null,B=!!(P?.enabled&&P.status.state==="connected");v.useEffect(()=>{if(!a||!B){w(xs),N(!1);return}const A=new AbortController;return R(!0),N(!1),Gc(a,A.signal).then(se=>{if(A.signal.aborted)return;w(se);const fe=f.getState(),G=(fe.mcpMediaKind==="video"?se.video:se.image).find(X=>X.id===fe.mcpModel);G&&ag(G.capabilities,f.setState,f.getState)}).catch(se=>{se.name!=="AbortError"&&(A.signal.aborted||(w(xs),N(!0)))}).finally(()=>{A.signal.aborted||R(!1)}),()=>A.abort()},[a,B,O]);const ne=v.useMemo(()=>y.filter(A=>A.enabled&&A.status.state==="connected"),[y]),oe=a?`${er}${a}`:`${tr}${n}`,ue=Lu(n),me=n==="comfy"?T.image.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,disabled:V.phase!=="ready"||C.comfy?.status!=="ready"||!qt(A),reason:A.lockReason})):[],D=n==="comfy"?T.video.map(A=>({id:A.id,label:A.description?.endsWith("(offline)")?`${A.label} — ${t("comfy.statusOffline")}`:A.label,reason:A.lockReason,disabled:V.phase!=="ready"||C.comfy?.status!=="ready"||!qt(A)})):[],F=qu({provider:n,imageModel:r,videoModel:s,comfyWorkflow:m,comfyVideoWorkflow:b}),ee=a?i?Bn(l,i):"":F,J=!a&&(n==="oauth"||n==="api")&&!s,pe=!!(i&&(S.image.some(A=>A.id===i)||S.video.some(A=>A.id===i))),be=P?.executable===!1?P.lockReason??t("mcp.higgsfieldLocked"):null,ae=a?P?P.status.state!=="connected"?t("mcp.disconnectedSelection"):P.enabled?null:t("mcp.disabledProvider"):t("mcp.unknownProvider",{provider:a}):null,ke=A=>{if(A.startsWith(tr)){const K=A.slice(tr.length);if(!Ja.has(K))return;c(K);return}const se=A.slice(er.length),fe=y.find(K=>K.id===se);!fe||fe.status.state!=="connected"||Bv(se)},ie=A=>{const se=f.getState();if(se.provider!==n||(se.mcpProvider??null)!==a)return;const fe=Zo();if(se.mcpProvider){if(A.startsWith(an))return;const K=xm(A);if(K){const X=(K.kind==="video"?S.video:S.image).find(re=>re.id===K.model);Jv(K.model,K.kind,X?.capabilities)}else Wv(A||null);return}if(se.provider==="comfy"){const K=A.startsWith(an),G=K?A.slice(an.length):A;if(!kt(fe,K?{comfyVideoWorkflow:G}:{comfyWorkflow:G}).selectedAvailable)return;K?h(G):p(G||null);return}if(!A.startsWith(an)){if(A.startsWith(vs)){I(A.slice(vs.length));return}if(A.startsWith(bs)){u(A.slice(bs.length));return}d(A)}},we=Object.keys(C).filter(A=>!Kv.has(A)),_e=we.length>0?we:nd.map(A=>A.value);_e.includes("comfy")||_e.push("comfy");const je=[{label:t("mcp.coreProviders"),items:_e.map(A=>{const se=C[A],fe=Ja.get(A),K=se?Yv(se.status,t):null;return{value:`${tr}${A}`,label:fe??Is(A),...K?{sub:K}:{},...se?.reason?{title:se.reason}:{},...fe?{}:{disabled:!0}}})}];ne.length>0&&je.push({label:t("mcp.connectedProviders"),items:ne.map(A=>({value:`${er}${A.id}`,label:Is(A.id),sub:A.executable===!1?t("mcp.locked"):void 0}))}),a&&!ne.some(A=>A.id===a)&&je.push({items:[{value:`${er}${a}`,label:Is(a),sub:t("mcp.unavailable"),disabled:!0}]});const z=[];if(a)i&&!pe&&z.push({items:[{value:Bn(l,i),label:i}]}),z.push({label:t("mcp.imageModels"),items:S.image.map(A=>({value:Bn("image",A.id),label:A.label}))}),z.push({label:t("mcp.videoModels"),items:S.video.map(A=>({value:Bn("video",A.id),label:A.label}))});else{const A=C[n]?.models.video.length??0,se=(n==="grok"||n==="grok-api")&&A>0;z.push({label:t("mcp.imageModels"),items:n==="comfy"?me.map(K=>({value:K.id,label:K.label,sub:K.reason,...K.disabled?{disabled:!0}:{}})):ue.map(K=>({value:K.value,label:K.shortLabel}))}),n==="comfy"&&D.length>0&&z.push({label:t("mcp.videoModels"),items:D.map(K=>({value:`${an}${K.id}`,label:K.label,stacked:!0,...K.reason?{sub:t("comfy.videoCatalogShort"),title:K.reason}:{},...K.disabled?{disabled:!0}:{}}))}),(se||s)&&z.push({label:t("mcp.videoModels"),items:Du.map(K=>({value:`${bs}${K.value}`,label:K.shortLabel}))}),J&&z.push({label:t("sidebar.reasoningLabel"),items:Ds.map(K=>({value:`${vs}${K.value}`,label:K.shortLabel,sub:K.value===x?"●":void 0}))});const fe=new Set(z.flatMap(K=>K.items.map(G=>G.value)));F&&!fe.has(F)&&z.unshift({items:[{value:F,label:F.includes(":")?F.split(":").slice(1).join(":"):F,title:t("mcp.unavailable"),...n==="comfy"?{disabled:!0}:{}}]})}const le=Ds.find(A=>A.value===x),ce=n==="comfy"&&!a?kt(V,{comfyWorkflow:m,comfyVideoWorkflow:b}):null,Te=ce?t(Kt(ce,V)):null;return o.jsxs("div",{className:`image-model-select image-model-select--sidebar gen-provider-model${e?" is-compact":""}`,children:[o.jsx(Oe,{id:"sidebar-generation-provider",className:"gen-provider-model__select gen-provider-model__select--provider",groups:je,value:oe,onChange:ke,ariaLabel:t("mcp.providerLabel"),title:ae??t("mcp.providerLabel"),triggerSub:"",portal:!0}),o.jsx(Oe,{id:"sidebar-generation-model",className:"gen-provider-model__select gen-provider-model__select--model",groups:z,value:ee,onChange:ie,ariaLabel:t("mcp.modelLabel"),title:ae??t("mcp.modelLabel"),disabled:!!ae,placeholder:a?t(j?"mcp.loadingModels":"mcp.chooseModel"):n==="comfy"?t("mcp.chooseModel"):void 0,triggerSub:J&&le?le.shortLabel:void 0,portal:!0}),ae||be||_||k||Te?o.jsx("span",{className:ce?"gen-provider-model__catalog-state":"image-model-select__trigger-effort",role:"status",children:ce&&Te?o.jsxs(o.Fragment,{children:[o.jsx("span",{children:Te}),V.phase==="error"?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>{V.refresh()},children:t("comfy.display.refresh")}):null]}):ae??be??(k?o.jsx("button",{type:"button",className:"image-model-select__retry",onClick:()=>$(A=>A+1),children:t("mcp.modelsLoadFailed")}):t(g?"mcp.loadingProviders":"mcp.providersLoadFailed"))}):null]})}function sd(e){return{...e,textFields:Array.isArray(e.textFields)?e.textFields:[]}}function vn(e){return{...e,cards:Array.isArray(e.cards)?e.cards.map(sd):[]}}async function Mt(e,t){const n=await Ee(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 Xv(){return Mt("/api/cardnews/image-templates")}function Zv(){return Mt("/api/cardnews/role-templates")}async function Qv(e){const t=await Mt("/api/cardnews/draft",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});return{...t,plan:vn(t.plan)}}function eb(e){return Mt("/api/cardnews/jobs",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}function tb(e){return Mt(`/api/cardnews/jobs/${encodeURIComponent(e)}`)}async function nb(e){const n=(await Mt(`/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 Ya(e){return Mt(`/api/cardnews/sets/${encodeURIComponent(e)}`).then(t=>({...t,plan:vn(t.plan)}))}function rb(e){return`/api/cardnews/sets/${encodeURIComponent(e)}/manifest?download=1`}function sb(e){return e[0]?.id||"academy-lesson-square"}function ob(e){return e.find(t=>t.id==="mid-5")?.id||e[0]?.id||"mid-5"}function ab(e){return Math.round(e/16)*16}function Mr(e){return Math.min(vo,Math.max(1024,ab(e)))}function Xa(e){return e.outputSizePreset!=="custom"?e.outputSizePreset:`${Mr(e.customW)}x${Mr(e.customH)}`}function od(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 ib(e,t){const n=t.status||"generated";return{...e,...t,textFields:Array.isArray(t.textFields)?t.textFields:e.textFields,status:n,error:n==="error"?od(t.error)||L("cardNews.error"):void 0}}function lb(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:od(s.error)}:r})}}const Se=Pi((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([Xv(),Zv()]);e({templates:n.templates,roleTemplates:r.templates,imageTemplateId:sb(n.templates),roleTemplateId:ob(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 Qv({topic:n.topic,audience:n.audience,goal:n.goal,contentBrief:n.contentBrief,imageTemplateId:n.imageTemplateId,roleTemplateId:n.roleTemplateId,size:Xa(n)});e({activePlan:vn(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 eb({...s,size:Xa(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 lb(900),i=await tb(i.jobId),e(c=>({activePlan:c.activePlan?Ss(c.activePlan,i):c.activePlan}));const l=await Ya(i.setId).catch(()=>null);e(c=>({generating:!1,activePlan:l?.plan?vn(l.plan):c.activePlan?Ss(c.activePlan,i):c.activePlan,selectedTextFieldId:null})),r.showToast(L("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 nb({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?ib(d,sd(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 Ya(n);e({activePlan:vn(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 cb(){const{t:e}=H(),t=Se(S=>S.hydrate),n=Se(S=>S.topic),r=Se(S=>S.audience),s=Se(S=>S.goal),a=Se(S=>S.contentBrief),i=Se(S=>S.outputSizePreset),l=Se(S=>S.customW),c=Se(S=>S.customH),d=Se(S=>S.setBriefField),u=Se(S=>S.setOutputSizePreset),p=Se(S=>S.setCustomSize),m=Se(S=>S.draft),h=Se(S=>S.loading),b=Se(S=>S.generating),I=Se(S=>S.draftError),x=Se(S=>S.generateSet),y=Se(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 Bt({className:e}){return o.jsx("span",{className:["video-thumb-placeholder",e].filter(Boolean).join(" "),"aria-hidden":"true"})}function db({item:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Pe(e),c=ve(e),d=u=>{u.dataTransfer.setData("application/ima2-ref",JSON.stringify(c?Sn(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(Bt,{}),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 ub({entry:e,active:t,selectLabel:n,deleteLabel:r,setRef:s,onSelect:a,onDelete:i}){const l=Xf(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&&ve(u)&&!u.thumb?o.jsx(Bt,{},Pe(u)):u?o.jsx("img",{src:u.thumb||u.url||u.image,alt:"",loading:"lazy",decoding:"async"},Pe(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 Za="ima2.sidebarHistoryCollapsed";function Qa(){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 mb({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 pb(){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(Za)==="1"}catch{return!1}}),{t:h}=H(),b=Rc(t,c),I=v.useMemo(()=>Pc(e).slice(0,jc),[e]);v.useEffect(()=>{!b||p||u.current[b]?.scrollIntoView({block:"nearest",inline:"nearest"})},[b,p,I]),v.useEffect(()=>{try{localStorage.setItem(Za,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(mb,{count:g.requested},`coll-sk-${y.id}`)];for(let S=0;S<g.requested;S++)g.images[S]||_.push(o.jsx(Qa,{},`sk-${y.id}-${S}`));return _}return o.jsx(Qa,{},`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(ub,{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(db,{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 fb="sidebar-inflight-panel";function hb(){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=yt(),i=t==="agent"&&Zt?"agent":t==="node"&&Xt?"node":t==="assets"?"assets":t==="asset-gen"?"asset-gen":"classic",l=Dn(n),c=!a&&i==="classic"&&l.composerPlacement==="bottom"&&l.multimodeHistoryGrouping==="sequence";return o.jsxs(o.Fragment,{children:[o.jsx(gb,{}),i==="classic"?c?o.jsx(o.Fragment,{children:o.jsx(pb,{})}):o.jsxs(o.Fragment,{children:[o.jsx(Jo,{}),o.jsxs("div",{className:"sidebar-generate-with-inflight",children:[o.jsx(Yo,{}),o.jsx(ed,{variant:"popup",panelId:fb})]})]}):i==="card-news"?o.jsx(o.Fragment,{children:o.jsx(cb,{})}):i==="node"?o.jsxs(o.Fragment,{children:[o.jsx(Gv,{}),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 gb(){const e=yt();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(vb,{}),o.jsx(rd,{compact:e})]})]})})}function yb(){return o.jsx("aside",{className:"sidebar",children:o.jsx("div",{className:"sidebar__scroll",children:o.jsx(hb,{})})})}function vb(){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 bb=1024,xb=1024,Ib="blank-canvas.png";function ei(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0?t:Math.max(1,Math.round(e))}async function Sb(e){const t=ei(e?.width,bb),n=ei(e?.height,xb),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],Ib,{type:"image/png"})}const nr=1024;function wb(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 _b(){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=wb(r()),d=await Sb(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 Eb(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 Nb(e,t){try{const n=await Ee("/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 Ze(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 kb(e,t){const n=ge();return de()?Promise.reject(Ye(n-1)):(At(),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=jt(e.requestId,null,(m,h)=>{m==="done"?c(()=>r(h)):m==="error"&&c(()=>s(Ze(h,"Video extension failed")))}),i=Jt(()=>c(()=>{d(),s(new Error("Video extension stream timed out"))})),t.aborted)return u();t.addEventListener("abort",u,{once:!0}),no().then(()=>{if(n!==ge())throw Ye(n);if(de())throw Ye(n-1);return Nb(e,t)}).catch(m=>c(()=>s(m)))}))}let xt={source:null,status:"idle"},ln=null,ti=0;const Js=new Set;function rr(e,t){xt={source:e,status:t};for(const n of Js)n()}const Ft={getSnapshot:()=>xt,subscribe(e){return Js.add(e),()=>{Js.delete(e)}},select(e){xt.status!=="pending"&&xt.source!==e&&rr(e,"idle")},start(e){if(xt.status==="pending"||xt.source===e.sourceVideoId&&xt.status==="tracking-expired")return null;const t=new AbortController;return ln=t,ti=ge(),rr(e.sourceVideoId,"pending"),kb(e,t.signal).then(n=>(ln=null,rr(e.sourceVideoId,"idle"),n),n=>{ln=null;const r=st(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(){ln?.abort()},releaseView(){!de()&&ti===ge()&&ln?.abort()}};async function Cb(e,t){const n=await fetch("/api/video/edit",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:t}),r=await n.json().catch(()=>({}));if(!n.ok)throw Ze(r,`Request failed: ${n.status}`);if(typeof r.url!="string"||typeof r.filename!="string")throw new Error("Video edit returned no saved artifact");return{requestId:String(r.requestId??""),url:r.url,filename:r.filename,duration:typeof r.duration=="number"?r.duration:null,model:String(r.model??"")}}const jb=["a[href]","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[tabindex]:not([tabindex='-1'])"].join(","),$t=[];function Ab(e){return $t.length>0&&$t[$t.length-1]===e}function He(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;$t.push(a);const d=document.activeElement instanceof HTMLElement?document.activeElement:null,u=r.current,p=()=>Array.from(u?.querySelectorAll(jb)??[]).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(!Ab(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=$t.indexOf(a);x!==-1&&$t.splice(x,1),document.removeEventListener("keydown",h),m(b)&&window.requestAnimationFrame(()=>d?.focus())}},[e,a,i,l,c]),r}const Pb={oauth:"GPT OAuth / Codex login",api:"GPT API key",grok:"Grok OAuth","grok-api":"Grok API key",agy:"Antigravity Gemini CLI","gemini-api":"Gemini API / Vertex",atlascloud:"Atlas Cloud API",minimax:"MiniMax API",nai:"NovelAI API"};function Rb(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 Rb(e)?String(e):null}function Tb(e,t){return typeof e!="number"||!Number.isFinite(e)?null:new Intl.DateTimeFormat(t,{dateStyle:"medium",timeStyle:"short"}).format(new Date(e))}function ni(e){return e?e.replace("x","×"):null}function Mb(e){if(e==null)return null;try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Z(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||Z(e,t,n,r)}function Lb(e,t,n){const r=Mb(n);!r||r==="{}"||r==="[]"||e.push({label:t,value:r,copyValue:r,pre:!0})}function Ob(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 Fb(e){return e?Pb[e]??e:null}function Db(e){return e.trim().replace(/\s+/g," ")}function sr(e,t,n,r){const s=ea(r);if(!s)return;const a=Db(s);!a||t.has(a)||(t.add(a),e.push({label:n,value:s,copyValue:s,pre:!0}))}function ri(e,t){const n=e?.[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function si(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 Gb(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 zb({item:e,onClose:t,onCopy:n}){const{t:r,locale:s}=H(),a=He(!0,t),i=v.useMemo(()=>JSON.stringify(e,null,2),[e]),l=e.videoContinuity?.entries?.[e.videoContinuity.entries.length-1]??null,c=Fb(e.provider),d=[[c,e.model].filter(Boolean).join(" · "),ni(e.size),e.elapsed!=null?`${e.elapsed}s`:null,e.usage?.total_tokens!=null?`${e.usage.total_tokens} ${r("metadata.fields.tokens").toLowerCase()}`:null].filter(_=>!!_),u=[],p=[];Z(p,r("metadata.fields.provider"),c,{compact:!0}),Z(p,r("metadata.fields.model"),e.model,{compact:!0}),Z(p,r("metadata.fields.providerUrl"),e.providerUrl,{copyValue:e.providerUrl??void 0}),Z(p,r("metadata.fields.requestId"),e.requestId,{copyValue:e.requestId??void 0}),p.length&&u.push({title:r("metadata.sections.provider"),fields:p,compact:!0});const m=[];Z(m,r("metadata.fields.quality"),e.quality,{compact:!0}),Z(m,r("metadata.fields.size"),ni(e.size),{compact:!0}),Z(m,r("metadata.fields.format"),e.format,{compact:!0}),Z(m,r("metadata.fields.moderation"),e.moderation,{compact:!0}),Z(m,r("metadata.fields.reasoning"),e.reasoningEffort,{compact:!0}),Z(m,r("metadata.fields.promptMode"),e.promptMode,{compact:!0}),Z(m,r("metadata.fields.kind"),e.kind,{compact:!0}),Z(m,r("metadata.fields.mediaType"),e.mediaType,{compact:!0}),m.length&&u.push({title:r("metadata.sections.settings"),fields:m,compact:!0});const h=[];Z(h,r("metadata.fields.elapsed"),e.elapsed!=null?`${e.elapsed}s`:null,{compact:!0}),Z(h,r("metadata.fields.totalTokens"),e.usage?.total_tokens,{compact:!0}),Z(h,r("metadata.fields.inputTokens"),ri(e.usage,"input_tokens"),{compact:!0}),ws(h,r("metadata.fields.cachedTokens"),si(e.usage,"input_tokens_details","cached_tokens"),{compact:!0}),Z(h,r("metadata.fields.outputTokens"),ri(e.usage,"output_tokens"),{compact:!0}),ws(h,r("metadata.fields.reasoningTokens"),si(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&&Z(h,r("metadata.fields.grokCostTicks"),e.usage.grok_cost_usd_ticks,{compact:!0}),h.length&&u.push({title:r("metadata.sections.usage"),fields:h,compact:!0});const b=[];Z(b,r("metadata.fields.filename"),e.filename,{copyValue:e.filename}),Z(b,r("metadata.fields.createdAt"),Tb(e.createdAt,s)),Z(b,r("metadata.fields.sessionId"),e.sessionId),Z(b,r("metadata.fields.nodeId"),e.nodeId),Z(b,r("metadata.fields.parentNodeId"),e.parentNodeId),Z(b,r("metadata.fields.clientNodeId"),e.clientNodeId),Z(b,r("metadata.fields.refsCount"),e.refsCount),Z(b,r("metadata.fields.sequence"),Ob(e)),Z(b,r("metadata.fields.setId"),e.setId),Z(b,r("metadata.fields.cardId"),e.cardId),b.length&&u.push({title:r("metadata.sections.lineage"),fields:b});const I=[];Z(I,r("metadata.fields.videoDuration"),e.video?.duration?`${e.video.duration}s`:null),Z(I,r("metadata.fields.videoResolution"),e.video?.resolution),Z(I,r("metadata.fields.videoAspectRatio"),e.video?.aspectRatio),Z(I,r("metadata.fields.videoRequestedModel"),e.video?.requestedModel),Z(I,r("metadata.fields.videoEffectiveModel"),e.video?.effectiveModel),Z(I,r("metadata.fields.videoModelFallback"),e.video?.modelFallback),Z(I,r("metadata.fields.xaiVideoRequestId"),e.video?.xaiVideoRequestId,{copyValue:ea(e.video?.xaiVideoRequestId)??void 0}),Z(I,r("metadata.fields.sourceImageFilename"),e.video?.sourceImageFilename),I.length&&u.push({title:r("metadata.sections.video"),fields:I});const x=[];Z(x,r("metadata.fields.lineageId"),e.videoContinuity?.lineageId),Z(x,r("metadata.fields.parentFilename"),e.videoContinuity?.parentFilename),Z(x,r("metadata.fields.sourceFrame"),e.videoContinuity?.sourceFrame),Z(x,r("metadata.fields.continuityEntries"),e.videoContinuity?.entries?.length),Z(x,r("metadata.fields.latestContinuityPrompt"),l?.revisedPrompt,{copyValue:l?.revisedPrompt,pre:!0}),x.length&&u.push({title:r("metadata.sections.videoContinuity"),fields:x});const y=[],g=new Set;return sr(y,g,r("metadata.fields.promptPrimary"),e.userPrompt??e.prompt),sr(y,g,r("metadata.fields.revisedPrompt"),e.revisedPrompt),sr(y,g,r("metadata.fields.prompt"),e.prompt),sr(y,g,r("metadata.fields.composerPrompt"),e.composerPrompt),Lb(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:Gb(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 qb(e){return/\.(png|jpe?g|webp)$/i.test(e)?"image":/\.(mp4|mov)$/i.test(e)?"video":null}function ad(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 $b(e,t){const n=qb(e);if(!n||ad(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 Ub=[2,4,8,16],Hb=["sublime","photo","photo_denoiser"];function Vb({pending:e,onSubmit:t,onClose:n}){const{t:r}=H(),s=He(!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=ad("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:Ub.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")}),Hb.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 Kb="canvas-mode-context",Bb="Canvas Mode",oi=36e5,Wb=["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 Jb({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(Ft.subscribe,Ft.getSnapshot),[y,g]=v.useState("idle"),[_,S]=v.useState(!1),[w,k]=v.useState(!1),[N,O]=v.useState(!1),[$,j]=v.useState(!1),R=v.useRef(null);v.useEffect(()=>{let G=!0;return Uo().then(X=>{G&&j(X.some(re=>re.id==="runway"&&re.status.state==="connected"))}).catch(()=>{}),()=>{G=!1}},[]);const V=async G=>{if(!C?.filename||N)return;const X=$b(C.filename,G);if(!X){s(n("result.upscaleInvalid"),!0);return}O(!0);try{await q("/api/mcp/media-action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),k(!1),s(n("result.upscaleStarted"))}catch{s(n("result.upscaleFailed"),!0)}finally{O(!1)}};v.useEffect(()=>Ft.releaseView,[]);const C=e??r,T=C?.filename??null;v.useEffect(()=>{Ft.select(T)},[T]);const P=x.status==="pending"||x.source===T?x.status:"idle";if(!C)return null;const B=ve(C),ne=B?C.url||C.image:"",oe=!!C.filename,ue=!!C.filename&&!B,me=B&&!!C.filename,F=!!((C.provider==="grok"||C.provider==="grok-api")&&!B&&C.providerUrl&&C.createdAt&&Date.now()-C.createdAt<oi),ee=async()=>{if(!(!C.filename||b)){I(!0);try{await f.getState().animateImage(C.filename,C.prompt??void 0)&&s(n("toast.animateDone"))}catch(G){const X=G instanceof Error?G.message:n("toast.animateFailed");s(X,!0)}finally{I(!1)}}},J=async()=>{if(!C.filename||P==="pending"||P==="tracking-expired")return;const G=`vext_${crypto.randomUUID()}`;try{const X=Ft.start({requestId:G,sourceVideoId:C.filename,prompt:C.prompt?.trim()||void 0,provider:C.provider==="grok-api"?"grok-api":"grok",model:C.model??void 0});if(!X)return;const re=await X;f.getState().addHistoryItem(Eb(re,C)),s(n("toast.animateDone"))}catch(X){const re=X instanceof DOMException&&X.name==="AbortError",Le=st(X).code;Le==="JOB_TRACKING_TIMEOUT"||Le==="LAN_TOKEN_REQUIRED"?Ue(X,f.getState()):re||s(X instanceof Error?X.message:n("toast.animateFailed"),!0)}},pe=()=>Ft.cancel(),be=async()=>{if(!C.filename||y==="pending")return;const G=window.prompt(n("result.editVideoPrompt"))?.trim();if(!G)return;const X=new AbortController;R.current=X,g("pending");try{const re=await Cb({videoUrl:C.filename,prompt:G,model:"grok-imagine-video"},X.signal);f.getState().addHistoryItem({...C,image:re.url,url:re.url,filename:re.filename,mediaType:"video",prompt:G,userPrompt:G,model:re.model||"grok-imagine-video",format:"mp4"}),g("idle"),s(n("toast.animateDone"))}catch(re){const Le=re instanceof DOMException&&re.name==="AbortError";g(Le?"idle":"error"),Le||s(re instanceof Error?re.message:n("toast.animateFailed"),!0)}finally{R.current===X&&(R.current=null)}},ae=()=>R.current?.abort(),ke=()=>{const G=document.createElement("a");G.href=C.image,G.download=C.filename||"generated.png",G.click()},ie=async G=>{const re=await(await fetch(G)).blob();let Le;if(re.type==="image/png")Le=re;else{const De=new Image;De.crossOrigin="anonymous";const Lt=URL.createObjectURL(re);await new Promise((dt,ut)=>{De.onload=()=>dt(),De.onerror=ut,De.src=Lt});const Ve=document.createElement("canvas");Ve.width=De.naturalWidth,Ve.height=De.naturalHeight,Ve.getContext("2d").drawImage(De,0,0),URL.revokeObjectURL(Lt),Le=await new Promise((dt,ut)=>Ve.toBlob(vt=>vt?dt(vt):ut(),"image/png"))}await navigator.clipboard.write([new ClipboardItem({"image/png":Le})])},we=async()=>{try{if(B){const G=await en(ne);await ie(G)}else await ie(C.image);s(n(B?"toast.frameCopied":"toast.imageCopied"))}catch{s(n("toast.copyFailed"),!0)}},_e=async()=>{try{const G=await Hl(ne);await ie(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},je=async()=>{try{const G=await Vl(ne);await ie(G),s(n("toast.frameCopied"))}catch{s(n("toast.copyFailed"),!0)}},z=async()=>{if(C.prompt)try{await navigator.clipboard.writeText(C.prompt),s(n("toast.promptCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},le=async G=>{try{await navigator.clipboard.writeText(G),s(n("toast.metadataCopied"))}catch{s(n("clipboard.writeFailed"),!0)}},ce=async()=>{let G={ok:!1,isVideo:!1,hasPrompt:!1};try{G=await os(C)}catch{}u&&e&&a({id:Kb,name:Bb,text:Wb});const X=document.querySelector('textarea[name="prompt"], textarea#prompt, .sidebar textarea');X&&(X.focus(),X.setSelectionRange(X.value.length,X.value.length)),s(n(G.hasPrompt?"toast.forkStarted":"toast.forkStartedNoPrompt"))},Te=async()=>{if(B||!C.providerUrl||!C.createdAt||Date.now()-C.createdAt>=oi){s(n("toast.continueAsUrlExpired"),!0);return}try{await Yc(C)}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"))},A=async()=>{if(!(!C.filename||m)){h(!0);try{const G=await iu({filename:C.filename});s(n("toast.comfyExported",{filename:G.uploadedFilename}))}catch(G){const X=G instanceof Error?G.code:void 0;s(n(X==="COMFY_URL_NOT_LOCAL"?"toast.comfyExportInvalidUrl":X==="COMFY_IMAGE_INVALID"?"toast.comfyExportInvalidImage":X==="COMFY_IMAGE_NOT_FOUND"?"toast.comfyExportImageNotFound":"toast.comfyExportFailed"),!0)}finally{h(!1)}}},se=()=>{i(C),s(n("toast.nodeRootCreated"))},fe=async()=>{try{await l(C)}finally{t?.()}},K=async()=>{try{await d(C)}finally{t?.()}};return o.jsxs("div",{className:"result-actions",children:[o.jsx("button",{type:"button",className:"action-btn",onClick:ke,children:n("result.download")}),o.jsx("button",{type:"button",className:`action-btn${B?" action-btn--frame":""}`,onClick:we,children:n(B?"result.copyLastFrame":"result.copyImage")}),B&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:_e,children:n("result.copyFirstFrame")}),o.jsx("button",{type:"button",className:"action-btn action-btn--frame",onClick:je,children:n("result.copyMidFrame")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{z()},children:n("result.copyPrompt")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{(async()=>{const G=await c(C);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:ce,title:n("result.continueHereTitle"),children:n("result.continueHere")}),F&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{Te()},title:n("result.continueAsUrlTitle"),children:n("result.continueAsUrl")}),ue&&o.jsx("button",{type:"button",className:"action-btn",onClick:()=>{ee()},disabled:b,title:n("result.animateTitle"),children:n(b?"result.animating":"result.animate")}),$&&C.filename&&(B?o.jsx("button",{type:"button",className:"action-btn",disabled:N,onClick:()=>{V({})},title:n("result.upscaleTitle"),children:n(N?"inflight.streaming":"result.upscale")}):o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",disabled:N,onClick:()=>k(G=>!G),title:n("result.upscaleTitle"),children:n("result.upscale")}),w?o.jsx(Vb,{pending:N,onSubmit:G=>{V(G)},onClose:()=>k(!1)}):null]})),me&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn",onClick:J,disabled:P==="pending"||P==="tracking-expired","aria-busy":P==="pending",title:n(P==="tracking-expired"?"toast.jobTrackingTimeout":"result.extendTitle"),children:P==="pending"?n("inflight.streaming"):P==="error"?n("gallery.retry"):n("result.extend")??"이어가기"}),P==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:pe,children:n("common.cancel")}),o.jsx("button",{type:"button",className:"action-btn",onClick:be,disabled:y==="pending","aria-busy":y==="pending",title:n("result.editVideoTitle"),children:n(y==="pending"?"inflight.streaming":y==="error"?"gallery.retry":"result.editVideo")}),y==="pending"&&o.jsx("button",{type:"button",className:"action-btn",onClick:ae,children:n("common.cancel")})]}),o.jsx("button",{type:"button",className:"action-btn",onClick:se,title:n("result.firstNodeTitle"),children:n("result.firstNode")}),o.jsx("button",{type:"button",className:"action-btn",onClick:()=>S(!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"})})}),C.filename&&o.jsxs(o.Fragment,{children:[o.jsx("button",{type:"button",className:"action-btn action-btn--danger",onClick:()=>{fe()},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:[oe&&o.jsx("button",{type:"button",className:"result-actions__menu-item",onClick:()=>{A()},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:()=>{K()},children:n("result.permanentDelete")})]})]})]}),_&&o.jsx(zb,{item:C,onClose:()=>S(!1),onCopy:G=>{le(G)}})]})}const Yb=["auto","flat","detailed","mono"],it={colorPrecision:8,filterSpeckle:4,cornerThreshold:60};function Xb(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 Zb(e){return`${Math.round(e/1024)}KB`}function Qb(){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=He(!!t,c),[u,p]=v.useState("auto"),[m,h]=v.useState(it.colorPrecision),[b,I]=v.useState(it.filterSpeckle),[x,y]=v.useState(it.cornerThreshold),[g,_]=v.useState(!1),[S,w]=v.useState(null),[k,N]=v.useState(null);v.useEffect(()=>{i.current?.abort(),i.current=null,_(!1),w(null),N(null)},[t?.filename]),v.useEffect(()=>()=>i.current?.abort(),[]);const O=v.useCallback(()=>{if(!t?.filename||g)return;const R=t.filename,V=new AbortController;i.current=V,_(!0),w(null),xu({source:R,preset:u,...m!==it.colorPrecision?{colorPrecision:m}:{},...b!==it.filterSpeckle?{filterSpeckle:b}:{},...x!==it.cornerThreshold?{cornerThreshold:x}:{},projectId:s,signal:V.signal}).then(C=>{if(!(i.current!==V||l.current!==R)){if(!C.filePath)throw new Error(e("vectorize.saveError"));N({filePath:C.filePath,pathCount:C.pathCount,bytes:C.bytes}),r(Xb(t,C.filePath)),a(e("vectorize.saved"))}}).catch(C=>{if(C instanceof DOMException&&C.name==="AbortError"||i.current!==V||l.current!==R)return;const T=C instanceof Error?C.message:e("vectorize.saveError");w(T),a(T,!0)}).finally(()=>{i.current!==V||l.current!==R||(i.current=null,_(!1))})},[t,g,u,m,b,x,s,r,a,e]);if(!t)return null;const $=t.url||t.image,j=k?`/generated/${encodeURIComponent(k.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:$??"",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:j?o.jsx("img",{src:j,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:Yb.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))}),k?o.jsx("p",{className:"vectorize-panel__stats",role:"status",children:e("vectorize.stats",{paths:String(k.pathCount),size:Zb(k.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(it.colorPrecision),I(it.filterSpeckle),y(it.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:O,children:e(g?"vectorize.running":"vectorize.run")}),j?o.jsx("a",{className:"assetgen-popup__close",href:j,download:k?.filePath,children:e("vectorize.download")}):null,o.jsx("button",{type:"button",className:"assetgen-popup__close",onClick:c,children:e("project.close")})]})]})})}function ex({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 tx(){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 nx({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 rx(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 zw(e,t){return t?e.filter(n=>n!=="starred"):Array.from(new Set([...e,"starred"]))}const wt=1,id=5,or=.22;function sx(e){return Math.min(id,Math.max(wt,e))}function ox(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=sx(y+x);return g<=wt?(s({x:0,y:0}),wt):Number(g.toFixed(2))})},[]),p=v.useCallback(x=>{x.preventDefault(),u(x.deltaY<0?or:-or)},[u]),m=v.useCallback(()=>{if(t>wt){d();return}n(2)},[d,t]),h=v.useCallback(x=>{t<=wt||x.button!==0||(x.preventDefault(),x.currentTarget.setPointerCapture(x.pointerId),i({pointerId:x.pointerId,startX:x.clientX,startY:x.clientY,baseX:r.x,baseY:r.y}))},[r.x,r.y,t]),b=v.useCallback(x=>{if(!a||a.pointerId!==x.pointerId)return;const y={x:a.baseX+x.clientX-a.startX,y:a.baseY+x.clientY-a.startY};c.current=y,cancelAnimationFrame(l.current),l.current=requestAnimationFrame(()=>{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 ax=v.lazy(()=>Me(()=>import("./index-CfrOcJIe.js"),__vite__mapDeps([0,1,2])).then(e=>({default:e.CanvasModeWorkspace})));function ix(e){return e==="low"?"l":e==="medium"?"m":e==="high"?"h":e??null}function lx(e){if(!e)return null;const t=e.match(/^(\d+)x\1$/);return t?`${t[1]}²`:e.replace("x","×")}function cx(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(D=>D.currentImage),t=f(D=>D.importLocalImageToHistory),n=f(D=>{const F=D.multimodePreviewFlightId;return F?D.multimodeSequences[F]??null:null}),r=f(D=>D.selectHistoryShortcutTarget),s=f(D=>D.trashHistoryItem),a=f(D=>D.permanentlyDeleteHistoryItemByShortcut),i=f(D=>D.markGeneratedResultsSeen),l=f(D=>D.activeGenerations),c=f(D=>D.canvasOpen),d=f(D=>D.openCanvas),u=f(D=>D.showToast),p=f(D=>D.history),m=f(D=>D.galleryFavorites),h=f(D=>D.toggleGalleryFavorite),{t:b}=H(),[I,x]=v.useState(!1),[y,g]=v.useState(null),{creatingBlankCanvas:_,createBlankCanvas:S}=_b(),w=v.useRef(null),k=e?`${e.filename??e.url??e.image}:${e.canvasMergedAt??""}`:null,N=ox(k),O=()=>{e?.prompt&&(navigator.clipboard.writeText(e.prompt),u(b("toast.promptCopied")))},$=D=>{if(D.key==="Delete"||D.key==="Backspace"){if(!e||D.target!==D.currentTarget||Ir(D.target))return;if(D.preventDefault(),D.shiftKey){a(e);return}s(e);return}D.key!=="ArrowLeft"&&D.key!=="ArrowRight"&&D.key!=="Home"&&D.key!=="End"||D.target===D.currentTarget&&(Ir(D.target)||(D.preventDefault(),D.key==="ArrowLeft"?r("previous"):D.key==="ArrowRight"?r("next"):D.key==="Home"?r("first"):D.key==="End"&&r("last")))},j=D=>{Ir(D.target)||(i(),D.currentTarget.focus())},R=v.useCallback(()=>{window.requestAnimationFrame(()=>w.current?.focus())},[]),V=async()=>{const D=e?.filename;if(!(!e||!D||y===D)){g(D);try{await h(e)}finally{g(F=>F===D?null:F)}}},C=v.useCallback(D=>{Array.from(D.dataTransfer.types).includes("Files")&&(D.preventDefault(),x(F=>F||!0))},[]),T=v.useCallback(D=>{D.currentTarget.contains(D.relatedTarget)||x(!1)},[]),P=v.useCallback(async D=>{if(!Array.from(D.dataTransfer.types).includes("Files"))return;D.preventDefault(),x(!1);const F=Array.from(D.dataTransfer.files).filter(ee=>/^image\/(png|jpeg|webp)$/.test(ee.type));F.length!==0&&await t(F[0])},[t]);if(c&&e)return o.jsxs(o.Fragment,{children:[o.jsx(v.Suspense,{fallback:o.jsx("main",{className:"canvas canvas--mode-open","aria-busy":"true"}),children:o.jsx(ax,{currentImage:e})}),o.jsx(Qb,{})]});const B=ix(e?.quality),ne=lx(e?.size),oe=Hi(e?.model,e?.provider),ue=e?cx(e):null,me=rx(e?.filename,p,m,e?.isFavorite);return o.jsxs("main",{className:`canvas${I?" canvas--drop-active":""}`,onDragOver:C,onDragLeave:T,onDrop:P,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(tx,{}):e&&ue?o.jsxs("div",{ref:w,className:"result-container visible",tabIndex:0,onMouseDown:j,onKeyDown:$,"aria-label":b("canvas.imageViewerAria"),children:[o.jsxs("div",{className:`result-preview-frame canvas-annotation-frame${N.zoom>wt?" canvas-annotation-frame--zoomed":""}`,onWheel:N.handleWheel,onDoubleClick:N.handleDoubleClick,onPointerDown:N.handlePointerDown,onPointerMove:N.handlePointerMove,onPointerUp:N.handlePointerUp,onPointerCancel:N.handlePointerUp,children:[e.filename?o.jsx(Jc,{variant:"result",active:me,busy:y===e.filename,label:b(me?"gallery.unfavoriteAria":"gallery.favoriteAria"),onToggle:V}):null,ve(e)?o.jsxs(o.Fragment,{children:[o.jsx("video",{className:"result-img",src:ue,controls:!0,autoPlay:!0,loop:!0,playsInline:!0,style:{transform:`translate(${N.pan.x}px, ${N.pan.y}px) scale(${N.zoom})`}},k??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify(Sn(e))),D.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:ue,alt:b("canvas.resultAlt"),decoding:"async",fetchPriority:"high",style:{transform:`translate(${N.pan.x}px, ${N.pan.y}px) scale(${N.zoom})`},onDoubleClick:D=>{D.stopPropagation(),d()}},k??void 0),o.jsx("div",{className:"result-drag-handle",draggable:!0,onDragStart:D=>{D.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:e.url||e.image,filename:e.filename})),D.dataTransfer.effectAllowed="copy"},title:b("canvas.dragToComposer"),"aria-label":b("canvas.dragToComposer"),children:b("canvas.dragHint")})]}),o.jsx(nx,{zoom:N.zoom,minZoom:wt,maxZoom:id,onZoomIn:N.zoomIn,onZoomOut:N.zoomOut,onReset:N.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:(ve(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,yc(e.videoContinuity),oe]:[e.elapsed!=null?`${e.elapsed}s`:null,e.usage?b("canvas.tokens",{n:e.usage.total_tokens??"?"}):null,Bu(e.reasoningEffort),B,ne,oe]).filter(D=>!!D).join(" · ")}),o.jsx(Jb,{onAfterDeleteFocus:R}),e.prompt?o.jsx(ex,{prompt:e.prompt,onCopy:O}):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 dx(){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 ld="ima2.customSizeSlots";function ux(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 mx(){try{const e=localStorage.getItem(ld);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?zt(t.filter(ux)):[]}catch{return[]}}function px(e){try{localStorage.setItem(ld,JSON.stringify(zt(e)))}catch{}}function fx(e,t,n){return Vr({id:`slot_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,w:e,h:t,ratio:n,updatedAt:Date.now()})}function cn(e){return e.map(t=>({value:t.value,label:t.label,sub:t.sub}))}function hx(){const e=f(P=>P.sizePreset),t=f(P=>P.setSizePreset),n=f(P=>P.customW),r=f(P=>P.customH),s=f(P=>P.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(()=>mx()),[b,I]=v.useState(null),[x,y]=v.useState("free"),g=e==="custom",_=bo(i,c,n,r),S=um().filter(P=>P.value==="auto");v.useEffect(()=>{l(String(n)),d(String(r))},[n,r]),v.useEffect(()=>{g||(p(!1),I(null))},[g]);function w(P){h(P),px(P)}function k(){const P=tt(i,n),B=tt(c,r);s(P,B),l(String(P)),d(String(B))}function N(P){P.key==="Enter"&&(P.preventDefault(),k())}function O(){t("custom"),p(!0),I(m.length>=Gt?m[0]?.id??null:null)}function $(P){t(P),P!=="custom"&&(p(!1),I(null))}function j(P){t("custom"),s(P.w,P.h),l(String(P.w)),d(String(P.h)),p(!1),I(P.id)}function R(P){y(P.id);const B=sm(P);B&&(l(String(B.w)),d(String(B.h)))}function V(){const P=fx(_.w,_.h,x),B=m.length>=Gt&&b?am(m,b,P):om(m,P);w(B),t("custom"),s(_.w,_.h),l(String(_.w)),d(String(_.h)),I(P.id),p(!1)}const C=_.reasons.length>0?_.reasons.map(P=>a(`size.adjustedReasons.${P}`)).join(", "):a("size.noAdjustment"),T=_.reasons.includes("maxPixels")&&_.requestedW===_.requestedH&&_.w===_.h?a("size.squareMaxHint",{size:`${wa}×${wa}`}):null;return o.jsxs("div",{className:"option-group size-picker",children:[o.jsx("div",{className:"section-title",children:a("size.title")}),o.jsx(Fe,{title:"",items:cn(im),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(lm),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(cm),value:e,onChange:$}),o.jsx(Fe,{title:"",items:cn(dm),value:e,onChange:$}),o.jsxs("div",{className:"option-row size-picker__quick-row",children:[cn(S).map(P=>o.jsxs("button",{type:"button",className:`option-btn${e===P.value?" active":""}`,onClick:()=>$(P.value),children:[P.label,P.sub?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:P.sub})]}):null]},P.value)),o.jsxs("button",{type:"button",className:`option-btn${g?" active":""}`,onClick:O,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(P=>o.jsxs("button",{type:"button",className:`option-btn size-picker__slot${g&&n===P.w&&r===P.h?" active":""}`,onClick:()=>j(P),children:[P.w,"×",P.h,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:P.ratio||a("size.customSlot")})]},P.id))}):null,u?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"size-picker__ratio-row",children:nm.map(P=>o.jsx("button",{type:"button",className:`size-picker__ratio${x===P.id?" active":""}`,onClick:()=>R(P),children:P.id==="free"?a("size.ratioFree"):P.label},P.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:P=>l(P.target.value.replace(/\D/g,"")),onBlur:k,onKeyDown:N,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:P=>d(P.target.value.replace(/\D/g,"")),onBlur:k,onKeyDown:N,placeholder:a("size.height")})]}),o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:a("size.normalizedPreview")}),o.jsx("strong",{children:rm(_.w,_.h)})]}),o.jsx("div",{className:"size-picker__preview size-picker__preview--reason",children:C}),T?o.jsx("div",{className:"size-picker__preview size-picker__preview--detail",children:T}):null,m.length>=Gt?o.jsxs("div",{className:"size-picker__replace-row",children:[o.jsx("span",{children:a("size.replaceCustomSlot")}),m.map(P=>o.jsxs("button",{type:"button",className:`size-picker__replace${b===P.id?" active":""}`,onClick:()=>I(P.id),children:[P.w,"×",P.h]},P.id))]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:V,children:m.length>=Gt?a("size.replaceCustomSlot"):a("size.saveCustomSlot")}),o.jsx("div",{className:"size-hint",children:a("size.hint")})]}):null]})}const _s=[1,2,4];function gx(){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 yx={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}},vx={512:.045,"1K":.067,"2K":.101,"4K":.151},bx={512:.134,"1K":.134,"2K":.134,"4K":.24};function xx(e){return e<=512?"512":e<=1024?"1K":e<=2048?"2K":"4K"}function Ix(e,t){const n=e.match(/^(\d+)x(\d+)$/);if(!n)return .003;const r=Math.max(Number(n[1]),Number(n[2])),s=xx(r),i=t==="nano-banana-pro"?bx:vx;return i[s]??i["1K"]??.003}function Sx(e,t,n,r){return n==="gemini-api"?Ix(t,r):yx[e]?.[t]??0}function wx(){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=Sx(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 cd(){const[e,t]=v.useState(null);return v.useEffect(()=>{let n=!1,r=null;const s=async()=>{try{const a=await Ld();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 _x(){const[e,t]=v.useState(null),[n,r]=v.useState(!1);return v.useEffect(()=>{let s=!1;return Od().then(a=>{s||t(a)}).catch(()=>{s||r(!0)}),()=>{s=!0}},[]),{data:e,error:n}}function dd(){const[e,t]=v.useState(null);return v.useEffect(()=>{if(de())return;const n=ge();let r=!1,s=null;const a=async()=>{if(!(r||de()||n!==ge()))try{const l=await Ee("/api/grok/status");if(r)return;const c=await l.json();if(r||de()||n!==ge())return;t(c),c.status!=="ready"&&(s=setTimeout(a,1e4))}catch{r||t({status:"offline"})}},i=()=>{r=!0,s&&clearTimeout(s),window.removeEventListener(_t,i)};return window.addEventListener(_t,i),a(),i},[]),e}function ud(){const[e,t]=v.useState(null),[n,r]=v.useState(null),s=v.useRef(!1),a=v.useCallback(async()=>{if(!s.current||de())return;const i=ge();try{const c=await(await Ee("/api/keys/status")).json();if(!s.current||de()||i!==ge())return;t(c),r(null)}catch(l){if(!s.current||de()||i!==ge())return;r(l instanceof Error?l:new Error(String(l)))}},[]);return v.useEffect(()=>{if(de())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(_t,d)};return window.addEventListener(_t,d),c(),d},[a]),{data:e,error:n,mutate:a}}function md(){const{t:e}=H(),t=cd(),{data:n}=_x(),r=dd(),{data:s}=ud(),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=Hn(),y=kt(x,null);return{oauth:{ok:a,reason:i,hint:l},api:{ok:c,reason:c?"":e("provider.apiInvalid")},grok:{ok:d,reason:u,hint:d?void 0:e("provider.grokOfflineHint")},"grok-api":{ok:p,reason:p?"":e("provider.xaiApiKeyRequired")},agy:{ok:!0,reason:""},"gemini-api":{ok:m,reason:m?"":e("provider.geminiApiKeyRequired")},atlascloud:{ok:h,reason:h?"":e("provider.atlasCloudApiKeyRequired")},minimax:{ok:b,reason:b?"":e("provider.minimaxApiKeyRequired")},nai:{ok:I,reason:I?"":e("provider.naiApiKeyRequired")},comfy:{ok:y.laneAvailable,reason:e(y.laneAvailable?"comfy.display.available":Kt(y,x)),hint:e("comfy.display.chooseWorkflow")}}}function Ex({open:e,providerLabel:t,reason:n,hint:r,onClose:s}){const{t:a}=H(),i=He(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:",Nx={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=>Nx[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 ai(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(j=>j.provider),r=f(j=>j.mcpProvider??null),s=f(j=>j.setProvider),a=md(),i=Hn(),l=f(j=>j.comfyWorkflow),c=f(j=>j.comfyVideoWorkflow),d=kt(i,{comfyWorkflow:l,comfyVideoWorkflow:c}),u=n==="comfy"&&!r,p=d.selectedAvailable?"ok":["error","disconnected","selected-offline"].includes(d.code)?"bad":"warn",[m,h]=v.useState(null),b=j=>{const R=a[j.value];return j.value==="comfy"?u?t(Kt(d,i)):R.reason:R.ok?t("provider.statusReady"):R.reason},I=j=>j.enabled?j.status.state==="connected"?j.executable===!1?`${t("provider.statusConnected")} · ${t("mcp.locked")}`:t("provider.statusConnected"):j.status.state==="connecting"?t("mcp.connecting"):j.status.state==="auth_required"?t("provider.statusAuthRequired"):t("provider.statusDisconnected"):t("mcp.disabledProvider"),x=[{label:t("mcp.coreProviders"),items:Ns.map(j=>{const R=a[j.value];return{value:`${ar}${j.value}`,searchText:`${j.provider} ${j.value==="comfy"?t("comfy.display.localMethod"):j.method}`,label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:j.value==="comfy"&&u?p:R.ok?"ok":"bad"}),o.jsxs("span",{children:[j.provider," ",j.value==="comfy"?t("comfy.display.localMethod"):j.method]})]}),sub:b(j)}})}],y=e.filter(j=>j.enabled).map(j=>({value:`${Es}${j.id}`,searchText:ks(j.id),label:o.jsxs("span",{className:"provider-option",children:[o.jsx(Cs,{tone:ai(j)}),o.jsx("span",{children:ks(j.id)})]}),sub:I(j)}));y.length>0&&x.push({label:"MCP",items:y});const g=r?`${Es}${r}`:`${ar}${n}`,_=r?null:Ns.find(j=>j.value===n)??null,S=r?e.find(j=>j.id===r)??null:null,w=_?.value==="comfy",k=w?t(Kt(d,i)):_?b(_):S?I(S):t("provider.statusDisconnected"),N=w?p:_?a[_.value].ok?"ok":"bad":S?ai(S):"bad",O=_?_.value==="comfy"?t("comfy.display.localMethod"):_.method:"MCP",$=j=>{if(j.startsWith(ar)){const C=j.slice(ar.length);if(!Pt(C))return;const T=Ns.find(B=>B.value===C),P=a[C];if(C==="comfy"){s(C);return}if(!P.ok){h({label:T?`${T.provider} ${T.method}`:C,reason:P.reason,hint:P.hint});return}s(C);return}const R=j.slice(Es.length),V=e.find(C=>C.id===R);if(!V||!V.enabled||V.status.state!=="connected"){h({label:ks(R),reason:!V||!V.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(Oe,{groups:x,value:g,onChange:$,triggerSub:w?"":void 0,portal:!0,ariaLabel:t("provider.authTitle"),className:"provider-status-select__select"}),o.jsxs("div",{className:"provider-status-line","data-tone":N,role:"status","aria-live":"polite",children:[o.jsx(Cs,{tone:N}),o.jsxs("span",{className:"provider-status-line__key",children:[t("provider.statusLineTitle"),":"]}),o.jsx("span",{className:"provider-status-line__value",children:k})]}),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:O}),N!=="bad"&&!w?o.jsx("span",{className:"provider-auth-chip__state",children:t("provider.authActive")}):null]}),o.jsx(Ex,{open:!!m,providerLabel:m?.label??"",reason:m?.reason??"",hint:m?.hint,onClose:()=>h(null)})]})}const kx=[{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"}],Cx=[{value:"1k",label:"1K"},{value:"2k",label:"2K"}];function jx(){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:kx.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:Cx.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 Ax=[{value:"grok-imagine-image",label:"Grok",sub:"Fast"},{value:"grok-imagine-image-quality",label:"Grok+",sub:"Best"}];function Px(){const{t:e}=H(),t=f(r=>r.imageModel),n=f(r=>r.setImageModel);return o.jsx(Fe,{title:e("quality.grokModelTitle"),items:Ax,value:t,onChange:n})}function pd({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 ii=3;function Rx(){const{t:e}=H(),t=f(p=>p.videoModelSelected),n=f(p=>p.videoReferenceVoices),r=f(p=>p.toggleVideoReferenceVoice),[s,a]=v.useState([]),[i,l]=v.useState("");v.useEffect(()=>{let p=!0;return Mi().then(m=>{p&&a(m.valid?.videoModels?.referenceAudio?.knownPresets??[])}).catch(()=>{}),()=>{p=!1}},[]);const c=Rt(t)===et,d=n.length>=ii,u=()=>{const p=i.trim();!p||d||n.includes(p)||(r(p),l(""))};return s.length===0&&n.length===0?null:o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.voiceSection")}),o.jsx("div",{className:"composer__hint",children:c?e("video.voiceLimit",{max:ii}):e("video.voiceNeeds15")}),o.jsx("div",{className:"option-row",role:"group","aria-label":e("video.voiceSection"),children:s.map(p=>{const m=n.includes(p);return o.jsxs("button",{type:"button",className:`option-btn${m?" active":""}`,"aria-pressed":m,disabled:!c||!m&&d,onClick:()=>r(p),children:[p,m?o.jsxs(o.Fragment,{children:[o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:`<AUDIO_${n.indexOf(p)}>`})]}):null]},p)})}),o.jsx("input",{type:"text",className:"text-input",value:i,disabled:!c||d,placeholder:e("video.voiceCustomPlaceholder"),onChange:p=>l(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),u())},onBlur:u,"aria-label":e("video.voiceCustomPlaceholder")})]})}const Tx=[{value:"480p",label:"480p"},{value:"720p",label:"720p"},{value:"1080p",label:"1080p",sub:"1.5 HD"}],Mx=["auto","1:1","16:9","9:16","4:3","3:4","3:2","2:3"].map(e=>({value:e,label:e})),li=[3,5,8,10,12,15],Lx=[{value:po,label:"Grok V",sub:"Fast"},{value:et,label:"Grok V1.5",sub:"HD"}];function Ox(){const{t:e}=H(),t=f(T=>T.videoModelSelected),n=f(T=>T.selectVideoModel),r=f(T=>T.activeVideoRefCount()),s=f(T=>T.videoSingleRefMode),a=f(T=>T.setVideoSingleRefMode),i=f(T=>T.videoDuration),l=f(T=>T.setVideoDuration),c=f(T=>T.videoResolution),d=f(T=>T.setVideoResolution),u=f(T=>T.videoAspectRatio),p=f(T=>T.setVideoAspectRatio),m=f(T=>T.videoTopic),h=f(T=>T.setVideoTopic),b=f(T=>T.showToast),I=f(T=>T.videoContinuityLineage),x=f(T=>T.selectedPresetIds),y=f(T=>T.removePreset),g=x.map(T=>pc(T)).filter(T=>T?.category==="camera-motion"),_=zu(r,s),S=va(t,_),w=yc(I),k=is(t,"1080p",_),N=is(et,"1080p",_),O=Tx.map(T=>T.value==="1080p"?{...T,disabled:!N}:T);v.useEffect(()=>{is(t,c,_)||d("720p")},[_,c,d,t]),v.useEffect(()=>{i!==null&&i>S&&l(S)},[i,S,l]);const $=T=>{const P=va(T,_);i!==null&&i>P&&b(e("video.durationClampedToModel",{seconds:P})),n(T)},j=T=>{if(T==="1080p"){if(!N)return;k||n(et)}d(T)},[R,V]=v.useState(null);v.useEffect(()=>{Ee("/api/config/grok-planner").then(T=>T.json()).then(V).catch(()=>{})},[]);const C=async T=>{const P=R?.model;V(B=>B?{...B,model:T}:null);try{const B=await Ee("/api/config/grok-planner",{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:T})});if(!B.ok)throw new Error(`HTTP ${B.status}`)}catch(B){if(V(ne=>ne&&P?{...ne,model:P}:ne),B?.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:Lx.map(T=>o.jsxs("button",{type:"button",className:`option-btn${t===T.value?" active":""}`,onClick:()=>$(T.value),children:[T.label,o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:T.sub})]},T.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.${_}`,{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,o.jsx(Rx,{}),g.length>0&&o.jsx(Wo,{ariaLabel:e("video.selectedCameraPresets"),children:g.map(T=>o.jsx(Wc,{onRemove:()=>y(T.id),removeLabel:e("common.removeNamed",{name:T.name}),children:T.name},T.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:T=>h(T.target.value)})]}),o.jsxs("div",{className:"option-group",children:[o.jsx("div",{className:"section-title",children:e("video.durationTitle")}),o.jsx(pd,{values:li.filter(T=>T<=S),value:i,ariaLabel:e("video.durationTitle"),onChange:T=>l(T??li[0])})]}),r===1&&o.jsx(Fe,{title:e("video.singleRefTitle"),help:e("video.singleRefHelp"),items:[{value:"image-to-video",label:e("video.singleRef.source")},{value:"reference-to-video",label:e("video.singleRef.reference")}],value:s,onChange:a}),o.jsx(Fe,{title:e("video.resolutionTitle"),help:N?void 0:e("video.resolution1080Help"),items:O,value:c,onChange:j}),o.jsx(Fe,{title:e("video.aspectTitle"),items:Mx,value:u,onChange:p}),R&&o.jsx("div",{className:"video-controls__pills",children:o.jsx(Oe,{className:"video-controls__pill",items:R.options.map(T=>({value:T,label:T})),value:R.model,onChange:T=>{C(T)},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:Pr})]})]})}const ci=e=>Symbol.iterator in e,di=e=>"entries"in e,ui=(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},Fx=(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 Dx(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:ci(e)&&ci(t)?di(e)&&di(t)?ui(e,t):Fx(e,t):ui({entries:()=>Object.entries(e)},{entries:()=>Object.entries(t)})}function Gx(e){const t=un.useRef(void 0);return n=>{const r=e(n);return Dx(t.current,r)?t.current:t.current=r}}const zx=[{value:"832x1216",label:"nai.size.portrait"},{value:"1216x832",label:"nai.size.landscape"},{value:"1024x1024",label:"nai.size.square"}];function qx(){const{t:e}=H(),t=f(Gx(Wm)),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(Oe,{items:Ui.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:zx.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(Oe,{items:ul.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(Oe,{items:ml.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(Oe,{items:pl.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(Oe,{items:fl.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),hl))}})]}),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 $x="",fd=3;function mi(e,t,n,r){const s=[],a=new Set;for(const i of[t,...e])!i?.filename||a.has(i.filename)||ve(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 Ux(e,t){return e[t]??null}function hd(e,t,n){const r=!t||e.some(s=>s.filename===t);return[{value:$x,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 As({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(Oe,{id:e,items:hd(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 Hx({index:e,images:t,selection:n,disabled:r,onChange:s,t:a}){const i=Ux(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(Oe,{items:hd(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 Vx({selection:e,disabled:t,onChange:n,t:r}){const s=v.useRef(null),[a,i]=v.useState(null),l=e.references.length>=fd,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 Kx({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:fd},(a,i)=>o.jsx(Hx,{index:i,images:e,selection:t,disabled:n,onChange:r,t:s},i)),o.jsx(Vx,{selection:t,disabled:n,onChange:r,t:s})]})}function Bx({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)??$e(),l=v.useMemo(()=>mi(r,s,a,!1),[r,s,a]),c=v.useMemo(()=>mi(r,s,a,!0),[r,s,a]),d=p=>og(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(As,{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(As,{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(Kx,{images:l,selection:i,disabled:t,onChange:d,t:n}):null,e.includes("video_references")?o.jsx(As,{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 Wx(e){return Array.isArray(e)&&e.includes("image_references")}function Jx(e){return e.mentionElementIds.length>0&&e.characterElementId?"conflict":"ok"}function qw(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 $w(e){return e.length>3}function Yx({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(!Wx(e))return null;const i=r.filter(d=>d.kind==="element"&&d.metadata?.elementKind==="character"),l=Jx({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 pi=new Set(["duration","resolution","quality","mode"]);function fi(e){return e.filter((t,n)=>e.findIndex(r=>r===t)===n)}function ta(e){return e.options&&e.options.length>0?fi(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):fi([e.min,...e.default!==void 0?[e.default]:[],e.max])}function hi(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 Xx(e,t){return typeof e=="boolean"?t(e?"mcp.onLabel":"mcp.offLabel"):String(e)}function Zx(e){return[...ta(e).filter(n=>typeof n=="number")].sort((n,r)=>n-r)}function Qx({parameter:e,value:t,disabled:n,onChange:r}){const{t:s}=H();if(e.name==="duration"&&e.type==="number"){const l=Zx(e);if(l.length>1){const c=hi(e.name,s);return o.jsxs("div",{className:"mcp-preset-row",children:[o.jsx("div",{className:"section-title",children:c}),o.jsx(pd,{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=hi(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:Xx(l,s)},`${typeof l}:${String(l)}`))]})]})}function gi({entries:e,parameters:t,disabled:n,onParameter:r}){return o.jsx(o.Fragment,{children:e.map(s=>o.jsx(Qx,{parameter:s,value:t[s.name],disabled:n,onChange:a=>r(s.name,a)},s.name))})}function eI({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=>pi.has(m.name)),u=c.filter(m=>!pi.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(gi,{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(Bx,{inputRoles:e.capabilities.inputRoles,disabled:r}),o.jsx(Yx,{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(gi,{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:[]},tI={};function nI(e){return e.replace(/(^|-)([a-z])/g,(t,n,r)=>`${n}${r.toUpperCase()}`)}function rI({record:e}){const{t}=H(),n=f(_=>_.mcpProvider??null),r=f(_=>_.mcpModel??null),s=f(_=>_.mcpMediaKind??"image"),a=f(_=>_.mcpRatio??null),l=f(_=>_.mcpParameters)??tI,[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"),Gc(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=_=>ng(_,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:[nI(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(eI,{entry:y,ratio:a,parameters:l,disabled:b,onRatio:_=>rg(_,f.setState),onParameter:(_,S)=>sg(_,S,f.setState,f.getState)})]}):o.jsx("p",{className:"option-help",children:t(r?"mcp.providerDefaultsHelp":"mcp.chooseModelForPresets")})]})]})]})}function sI(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"?`${Ht}${c.id}`:c.id,label:c.label,stacked:!0,disabled:!a||!qt(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 oI(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(Ht),s=r?e.slice(Ht.length):e;kt(Zo(),r?{comfyVideoWorkflow:s}:{comfyWorkflow:s}).selectedAvailable&&(r?n.setComfyVideoWorkflow(s):n.setComfyWorkflow(s))}function aI(){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=Hn(),u=kt(d,{comfyWorkflow:i,comfyVideoWorkflow:l}),p=l?`${Ht}${l}`:i??"",m=sI(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(Kt(u,d)),d.observedAt!==null?` · ${e("comfy.display.lastChecked",{time:new Date(d.observedAt).toLocaleTimeString()})}`:""]}),o.jsx(Oe,{id:r,groups:m,value:p,onChange:h=>oI(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 iI=[{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"}],lI=[{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 cI(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 dI(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 gd(){const{t:e}=H(),t=f(z=>z.provider),n=f(z=>z.quality),r=f(z=>z.setQuality),s=f(z=>z.format),a=f(z=>z.setFormat),i=f(z=>z.moderation),l=f(z=>z.setModeration),c=f(z=>z.multimode),d=f(z=>z.setMultimode),u=f(z=>z.imageModel),p=f(z=>z.setImageModel),m=f(z=>z.selectVideoModel),h=f(z=>z.sizePreset),b=f(z=>z.customW),I=f(z=>z.customH),x=f(z=>z.setSizePreset),y=f(z=>z.setCustomSize),g=f(z=>z.uiMode),_=f(z=>z.videoModelSelected),S=f(z=>z.mcpProvider??null),{providers:w}=zc(),k=g==="classic",N=t==="grok"||t==="grok-api",O=t==="agy",$=t==="gemini-api",j=O||$,R=t==="nai",V=t==="comfy",C=N||j||R,T=h==="custom"?`${b}x${I}`:"1024x1024",P=$&&h==="auto",B=$&&!P?cI(T):null,ne=B??{ratio:"",res:""},oe=$&&!P&&h==="custom"&&!B,ue=u==="nano-banana-pro"?"nano-banana-pro":"nano-banana-2",[me,D]=v.useState(!1),[F,ee]=v.useState(String(b)),[J,pe]=v.useState(String(I)),be=(z,le)=>{const ce=Lr[z||"1:1"]?.[le||"1K"]||"1024x1024",[Te,A]=ce.split("x").map(Number);D(!1),x("custom"),y(Te,A)},ae=()=>{const z=Number(F),le=Number(J);!Number.isFinite(z)||!Number.isFinite(le)||z<=0||le<=0||(x("custom"),y(z,le),D(!1))},ke=[{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")}],ie=[{value:"auto",label:e("moderation.autoLabel"),sub:e("moderation.autoSub")},{value:"low",label:e("moderation.lowLabel"),sub:e("moderation.lowSub"),color:"var(--amber)"}],we=[{value:"nano-banana-2",label:"Nano",sub:"Banana 2"},{value:"nano-banana-pro",label:"Nano",sub:"Banana Pro"}],_e=N?{title:e("provider.grokCompatTitle"),body:e("provider.grokCompatBody")}:O?{title:e("provider.agyCompatTitle"),body:e("provider.agyCompatBody")}:$?{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")},je=z=>{z==="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(rI,{record:w.find(z=>z.id===S)??null})]}):V?o.jsxs("div",{className:"right-panel-settings",role:"tabpanel",children:[o.jsx(js,{mcpProviders:w}),o.jsx(aI,{})]}):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:_e.title}),o.jsx("p",{children:_e.body})]}),N&&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:()=>je("image"),children:e("grokMode.image")}),o.jsx("button",{type:"button",className:`option-btn${_?" active":""}`,onClick:()=>je("video"),children:e("grokMode.video")})]})}),_?o.jsx(Ox,{}):o.jsxs(o.Fragment,{children:[O?null:N?o.jsxs(o.Fragment,{children:[o.jsx(Px,{}),o.jsx(jx,{})]}):R?o.jsx(qx,{}):$?o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("quality.grokModelTitle"),items:we,value:ue,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((z,le)=>o.jsx("div",{className:"option-row",children:z.map(ce=>o.jsx("button",{type:"button",className:`option-btn${ne.ratio===ce.value?" active":""}`,onClick:()=>be(ce.value,ne.res),children:ce.label},ce.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:lI.map(z=>o.jsxs("button",{type:"button",className:`option-btn${ne.res===z.value?" active":""}`,onClick:()=>be(ne.ratio,z.value),children:[o.jsx("span",{children:z.label}),o.jsx("br",{}),o.jsx("small",{children:Lr[ne.ratio]?.[z.value]?.replace("x","×")||""})]},z.value))})]}),o.jsxs("div",{className:"option-group",children:[o.jsxs("div",{className:"option-row",children:[o.jsxs("button",{type:"button",className:`option-btn${P?" active":""}`,onClick:()=>{D(!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${oe||me?" active":""}`,onClick:()=>D(z=>!z),children:[e("size.customPlus"),o.jsx("br",{}),o.jsx("span",{className:"option-sub",children:e("size.customSub")})]})]}),me?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:F,onChange:z=>ee(z.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:J,onChange:z=>pe(z.target.value.replace(/\D/g,"")),placeholder:e("size.height")})]}),Number(F)>0&&Number(J)>0?o.jsxs("div",{className:"size-picker__preview",children:[o.jsx("span",{children:e("size.normalizedPreview")}),o.jsx("strong",{children:(()=>{const z=dI(Number(F),Number(J));return`${z.ratio} · ${z.res}`})()})]}):null,o.jsx("button",{type:"button",className:"size-picker__save",onClick:ae,children:e("settings.apiKeys.save")})]}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("quality.title"),items:ke,value:n,onChange:r}),o.jsx(hx,{})]}),C?null:o.jsxs(o.Fragment,{children:[o.jsx(Fe,{title:e("format.title"),items:iI,value:s,onChange:a}),o.jsx(Fe,{title:e("moderation.title"),items:ie,value:i,onChange:l}),o.jsx("p",{className:"option-help",children:e("moderation.explain")})]}),k&&!j&&!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")})]})}),j||R?null:o.jsx(gx,{}),R?null:o.jsx(wx,{})]})]})}const uI=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Qdujpb4L.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel}))),mI=v.lazy(()=>Me(()=>import("./PromptBuilderPanel-BolZnOa7.js"),__vite__mapDeps([4,1,2,5])).then(e=>({default:e.PromptBuilderPanel}))),pI=v.lazy(()=>Me(()=>import("./GenerationRequestLogPanel-CTs8OymS.js"),__vite__mapDeps([6,1,2])).then(e=>({default:e.GenerationRequestLogPanel})));function fI(){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=th(i)&&!c,h=c?e:!0,b=He(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(mI,{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(uI,{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(pI,{})})}):o.jsx("div",{id:"right-panel-tab-settings",role:"tabpanel",children:o.jsx(gd,{})})]})]})]})}function hI(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 gI({id:e}){const{t}=H();return o.jsx("div",{className:"history-thumb history-thumb--skeleton","aria-label":t("common.generating")},e)}function yI({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 vI({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&&(Xe(l.url)||Xe(l.image))?o.jsx(Bt,{className:"collection-mini"},c):o.jsx("img",{className:"collection-mini",src:l.thumb||l.url||l.image,alt:"",loading:"lazy",decoding:"async"},c))})}function bI(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 xI(){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=bI(c),{t:p}=H(),m=t?Pe(t):null,h=v.useMemo(()=>xr(e.filter(gn)),[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(Pe(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:hI,"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(yI,{id:g.id,count:g.count},`coll-${g.id}`):o.jsx(gI,{id:g.id},g.id)),h.map(g=>{const _=Pe(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(vI,{sequenceId:g.sequenceId,images:w})),...w.map(k=>{const N=Pe(k),O=m===N;return ve(k)?y(N,o.jsxs("div",{className:`history-thumb history-thumb--video history-thumb--fade-in${O?" active":""}`,onClick:()=>r(k),draggable:!0,onDragStart:$=>{$.dataTransfer.setData("application/ima2-ref",JSON.stringify(Sn(k))),$.dataTransfer.effectAllowed="copy"},children:[k.thumb?o.jsx("img",{src:k.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Bt,{}),o.jsx("span",{className:"history-thumb__play-badge","aria-hidden":"true",children:"▶"})]})):y(N,o.jsx("img",{src:k.thumb||k.url||k.image,alt:"",className:`history-thumb history-thumb--fade-in${O?" active":""}`,loading:"lazy",decoding:"async",onClick:()=>r(k),draggable:!0,onDragStart:$=>{$.dataTransfer.setData("application/ima2-ref",JSON.stringify({image:k.url||k.image,filename:k.filename})),$.dataTransfer.effectAllowed="copy"}}))})]}return g.sequenceId&&I.has(g.sequenceId)&&!x.has(_)?null:ve(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(Sn(g))),w.dataTransfer.effectAllowed="copy"},children:[g.thumb?o.jsx("img",{src:g.thumb,alt:"",loading:"lazy",decoding:"async"}):o.jsx(Bt,{}),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 yi=3e3;function II(){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)},yi);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)},yi);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=Be[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 SI(){return null}function wI(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 _I(e,t,n){async function r(i){if(i.setId)try{await Se.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(rb(i.setId),"_blank","noopener,noreferrer")}return{handleOpenCardNewsSet:r,handleCopyCardNewsSetPath:s,handleDownloadCardNewsManifest:a}}const EI=["ArrowLeft","ArrowRight","Home","End"];function NI(){return v.useCallback(e=>{if(!EI.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 Ps({className:e,ariaLabel:t,tabs:n,value:r,onChange:s}){const a=NI(),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 kI({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 CI=[{id:"animate",labelKey:"chain.animate",available:e=>!!e.filename&&!ve(e)},{id:"edit",labelKey:"chain.edit",available:e=>!!e.filename&&!ve(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&&!ve(e)}];async function jI(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 Ee(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(()=>uv);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 AI(e){return e.mediaType==="video"?e.videoContinuity?.parentFilename?"v2v":e.sourceImageFilename?"i2v":"t2v":e.canvasSourceFilename||e.sourceImageFilename?"i2i":e.model?"t2i":null}function PI(e){return e.videoContinuity?.parentFilename??e.canvasSourceFilename??e.sourceImageFilename??null}function RI(e){return{modelLabel:Hi(e.model,e.provider),derivation:AI(e),sourceLabel:PI(e)}}function TI(e){return!e.modelLabel&&!e.derivation}function MI({view:e,size:t="sm"}){const{t:n}=H();return TI(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 LI({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 OI({item:e,active:t,itemRef:n,onSelect:r,onDelete:s,onToggleFavorite:a,favoriteBusy:i=!1,t:l}){const c=v.useMemo(()=>CI.filter(p=>p.available(e)),[e]),d=v.useCallback(async(p,m)=>{m.stopPropagation(),await jI(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(ve(e)?Sn(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:[ve(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(Bt,{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(LI,{id:p.id})},p.id))}):null,e.filename&&a&&o.jsx(Jc,{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(MI,{view:RI(e)})]})}function FI(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 Dt(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 vi(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const DI=(e,t)=>Math.abs(e-t)<1.01,GI=(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 dn;const Rs=()=>{if(dn!==void 0)return dn;if(typeof navigator>"u")return dn=!1;if(/iP(hone|od|ad)/.test(navigator.userAgent))return dn=!0;const e=navigator.maxTouchPoints;return dn=navigator.platform==="MacIntel"&&e!==void 0&&e>0},bi=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},zI=e=>e,qI=e=>{const t=Math.max(e.startIndex-e.overscan,0),r=Math.min(e.endIndex+e.overscan,e.count-1)-t+1,s=new Array(r);for(let a=0;a<r;a++)s[a]=t+a;return s},$I=(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(bi(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(bi(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return a.observe(n,{box:"border-box"}),()=>{a.unobserve(n)}},Or={passive:!0},UI=typeof window>"u"?!0:"onscrollend"in window,HI=(e,t,n)=>{const r=e.scrollElement;if(!r)return;const s=e.targetWindow;if(!s)return;const a=e.options.useScrollendEvent&&UI;let i=0;const l=a?null:GI(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,Or),a&&r.addEventListener("scrollend",u,Or),()=>{r.removeEventListener("scroll",d),a&&r.removeEventListener("scrollend",u),l?.cancel()}},VI=(e,t)=>HI(e,t,n=>{const{horizontal:r,isRtl:s}=e.options;return r?n.scrollLeft*(s&&-1||1):n.scrollTop}),KI=(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"]},BI=(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})},WI=BI;class JI{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:zI,rangeExtractor:qI,onChange:()=>{},measureElement:KI,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=Dt(()=>(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,Or),a.addEventListener("touchend",l,Or),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=Dt(()=>[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=Dt(()=>[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 k=a(w),N=p.get(k),O=typeof N=="number"?N:this.options.estimateSize(w);g[w*2]=_,g[w*2+1]=O,_+=O+d}const S=FI(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 k=c==="estimate"||p.has(g);if(_!==void 0&&this.options.lanes>1){S=_;const j=b[S],R=j!==void 0?h[j]:void 0;w=R?R.end+d:r+s}else if(x===l){let j=0,R=I[0],V=b[0];for(let C=1;C<l;C++){const T=I[C];(T<R||T===R&&b[C]<V)&&(j=C,R=T,V=b[C])}S=j,w=R+d,k&&this.laneAssignments.set(y,S)}else S=y%this.options.lanes,w=r+s,k&&this.laneAssignments.set(y,S);const N=p.get(g),O=typeof N=="number"?N:this.options.estimateSize(y),$=w+O;h[y]={index:y,start:w,size:O,end:$,key:g,lane:S},b[S]===void 0&&x++,b[S]=y,I[S]=$}return this.measurementsCache=h,h},{key:!1,debug:()=>this.options.debug}),this.calculateRange=Dt(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,s,a)=>n.length===0||r===0?(this.range=null,null):(this.range=XI(n,r,s,a,a===1&&this._flatMeasurements!=null?this._flatMeasurements:null),this.range),{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=Dt(()=>{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=Dt(()=>[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=yd(0,r.length-1,a?l=>s[l*2]:l=>vi(r[l]).start,n);return vi(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&&DI(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 yd=(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 YI(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 XI(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=YI(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=yd(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 ZI({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 JI(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 QI(e){return ZI({observeElementRect:$I,observeElementOffset:VI,scrollToFn:WI,...e})}const Fr=170,Dr=10,vd=36,eS=44;function tS(e){const t=Math.max(Fr,e-vd);return Math.max(1,Math.floor((t+Dr)/(Fr+Dr)))}function nS(e,t){const n=Math.max(Fr,e-vd);return Math.max(Fr,Math.floor((n-Dr*Math.max(0,t-1))/t))+Dr}function rS(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 sS({dateGroups:e,selectedKey:t,scrollElement:n,localizeBucket:r,renderTile:s}){const a=v.useRef(null),[i,l]=v.useState(0),c=v.useMemo(()=>tS(i||960),[i]),d=v.useMemo(()=>nS(i||960,c),[i,c]),u=v.useMemo(()=>rS(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=QI({count:u.length,getScrollElement:()=>n,estimateSize:m=>u[m]?.type==="header"?eS:d,overscan:6});return v.useEffect(()=>{if(!t)return;const m=u.findIndex(h=>h.type==="items"&&h.items.some(b=>Pe(b)===t));m>=0&&p.scrollToIndex(m,{align:"center"})},[u,t,p]),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 xi({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 oS({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 aS({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 Ii="ima2.storageNoticeDismissed.0.09.23";function iS(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 lS(){const{t:e,locale:t}=H(),n=f(M=>M.galleryOpen),r=f(M=>M.closeGallery),s=f(M=>M.history),a=f(M=>M.selectHistory),i=f(M=>M.currentImage),l=f(M=>M.trashHistoryItem),c=f(M=>M.showToast),d=f(M=>M.toggleGalleryFavorite),u=f(M=>M.galleryScope),p=f(M=>M.setGalleryScope),m=f(M=>M.historyNextCursor),h=f(M=>M.historyLoadingOlder),b=f(M=>M.favoriteHistoryNextCursor),I=f(M=>M.favoriteHistoryLoadingOlder),x=f(M=>M.loadOlderHistory),y=f(M=>M.loadFavoriteHistory),g=f(M=>M.loadOlderFavoriteHistory),_=f(up),[S,w]=v.useState(""),[k,N]=v.useState("date"),[O,$]=v.useState(!1),[j,R]=v.useState(()=>new Set),V=v.useRef(new Set),[C,T]=v.useState([]),[P,B]=v.useState([]),[ne,oe]=v.useState(!1),[ue,me]=v.useState(!1),[D,F]=v.useState(!1),[ee,J]=v.useState(0),[pe,be]=v.useState(null),[ae,ke]=v.useState(()=>{try{return localStorage.getItem(Ii)==="1"}catch{return!1}}),ie=v.useRef(null),we=v.useRef({}),[_e,je]=v.useState(null),z=v.useRef(0),le=v.useRef({open:!1,selectedKey:null}),ce=v.useMemo(()=>xr(s.filter(gn)),[s]),Te=v.useCallback(M=>{ie.current=M,je(M)},[]),A=iS(_e),se=He(n,r);v.useEffect(()=>{n||w("")},[n]),v.useEffect(()=>{if(!n)return;let M=!1;return(async()=>{try{const Y=await ru();M||be(Y)}catch{M||be({generatedDirLabel:"~/.ima2/generated",generatedCount:0,legacyCandidatesScanned:0,legacySourcesFound:0,legacyFilesFound:0,state:"unknown",messageKind:"unknown",recoveryDocsPath:"docs/RECOVER_OLD_IMAGES.md",doctorCommand:"ima2 doctor",overrides:{generatedDir:!1,configDir:!1}})}})(),()=>{M=!0}},[n]),v.useEffect(()=>{if(!n||k!=="session")return;let M=!1;return T([]),B([]),oe(!0),me(!1),F(!1),(async()=>{try{const Y=await tu({limit:500,sessionId:u==="current-session"?_:void 0});if(M)return;F(Y.nextCursor!==null||Y.total>=500);const Ie=U=>{const he=U.kind,at=he==="classic"||he==="edit"||he==="generate"||he==="card-news-card"||he==="card-news-set"?he: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:at,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}};T(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(gn).map(Ie))})).filter(U=>U.items.length>0)),B(xr(Y.loose.filter(gn).map(Ie)))}catch{M||me(!0)}finally{M||oe(!1)}})(),()=>{M=!0}},[n,k,u,_,ee]),v.useEffect(()=>{!n||k==="session"||!O||y()},[n,k,O,y]);const fe=v.useMemo(()=>{const M=S.trim().toLowerCase().normalize("NFC");return ce.filter(Y=>O&&!Y.isFavorite?!1:M?(Y.prompt??"").toLowerCase().normalize("NFC").includes(M)||(Y.filename??"").toLowerCase().normalize("NFC").includes(M):!0)},[ce,S,O]),K=v.useMemo(()=>O?C.map(M=>({...M,items:M.items.filter(Y=>Y.isFavorite)})).filter(M=>M.items.length>0):C,[C,O]),G=v.useMemo(()=>O?P.filter(M=>M.isFavorite):P,[P,O]),X=v.useMemo(()=>{const M=new Map;for(const Y of fe){const Ie=wI(Y.createdAt,t);M.has(Ie)||M.set(Ie,[]),M.get(Ie).push(Y)}return Array.from(M.entries())},[fe,t]),re=k==="session"?K.reduce((M,Y)=>M+Y.items.length,0)+G.length:fe.length;v.useLayoutEffect(()=>{const M=i?Pe(i):null;if(!n){le.current={open:!1,selectedKey:M};return}const Y=le.current,Ie=!Y.open||Y.selectedKey!==M;le.current={open:!0,selectedKey:M};const U=M?we.current[M]:null;if(Ie&&U){U.scrollIntoView({block:"center"});return}ie.current&&(ie.current.scrollTop=z.current)},[n,i?.filename,i?.image,k,re,X.length,K.length,G.length]);async function Le(M,Y){Y.stopPropagation();const Ie=Pe(M);await l(M),delete we.current[Ie],window.requestAnimationFrame(()=>ie.current?.focus())}async function De(M){const Y=M.filename;if(!(!Y||V.current.has(Y))){V.current.add(Y),R(new Set(V.current));try{const Ie=await d(M);if(Ie===null)return;T(U=>U.map(he=>({...he,items:he.items.map(at=>at.filename===Y?{...at,isFavorite:Ie}:at)}))),B(U=>U.map(he=>he.filename===Y?{...he,isFavorite:Ie}:he))}finally{V.current.delete(Y),R(new Set(V.current))}}}async function Lt(){try{await su(),c(e("toast.openGeneratedDirOpened"))}catch{c(e("toast.openGeneratedDirFailed"),!0)}}const{handleOpenCardNewsSet:Ve,handleCopyCardNewsSetPath:dt,handleDownloadCardNewsManifest:ut}=_I(r,c,e);function vt(){ke(!0);try{localStorage.setItem(Ii,"1")}catch{}}if(!n)return null;const E=M=>M==="earlier"||M==="today"||M==="yesterday"||M==="thisWeek"?e(`gallery.${M}`):M,W=(M,Y,Ie)=>{const U=i?.image===M.image,he=Pe(M),at=Ot=>{we.current[he]=Ot,A.register(he,Ot)};return(A.supported?A.visibleKeys.has(he):!0)?M.kind==="card-news-set"?o.jsx("div",{ref:at,className:"gallery__tile-wrap gallery-card-news-set",children:o.jsx(kI,{item:M,onOpen:Ot=>{Ve(Ot)},onCopyPath:dt,onDownloadManifest:ut})},`${Y}-${he}`):o.jsx(OI,{item:M,active:U,itemRef:at,onSelect:Ot=>{a(Ot),r()},onDelete:Le,onToggleFavorite:De,favoriteBusy:!!(M.filename&&j.has(M.filename)),t:e},`${Y}-${he}`):o.jsx("div",{ref:at,className:"gallery__tile-wrap","data-gallery-lazy-key":he,style:{aspectRatio:"1 / 1"},"aria-hidden":"true"},`${Y}-${he}`)},Q=k==="session",xe=i?Pe(i):null;return o.jsx("div",{className:"gallery-backdrop",onClick:r,role:"presentation",children:o.jsxs("div",{ref:se,className:"gallery",role:"dialog","aria-modal":"true","aria-label":e("gallery.ariaLabel"),tabIndex:-1,onClick:M=>M.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:re}),S||O?e("gallery.totalFiltered",{n:ce.length}):""]}),o.jsx(Ps,{className:"gallery__favorite-filter",ariaLabel:e("gallery.favoriteFilterAria"),value:O?"favorites":"all",onChange:M=>$(M==="favorites"),tabs:[{value:"all",label:e("gallery.filterAll")},{value:"favorites",label:e("gallery.filterFavorites")}]}),o.jsx(Ps,{className:"gallery__group-toggle",ariaLabel:e("gallery.sortByAria"),value:k,onChange:N,tabs:[{value:"date",label:e("gallery.sortByDate")},{value:"session",label:e("gallery.sortBySession")}]}),o.jsx(Ps,{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",...Q?{}:{"data-modal-initial-focus":!0},placeholder:e(Q?"gallery.searchDisabledPlaceholder":"gallery.searchPlaceholder"),value:S,onChange:M=>w(M.target.value),disabled:Q}),o.jsx("button",{type:"button",className:"gallery__close",onClick:r,"aria-label":e("gallery.closeAria"),title:e("gallery.closeTitle"),children:"×"})]}),o.jsx(aS,{status:pe,dismissed:ae,onOpenFolder:Lt,onDismiss:vt,t:e}),o.jsx("div",{className:"gallery__scroll",ref:Te,tabIndex:-1,onScroll:()=>{z.current=ie.current?.scrollTop??0},children:Q?ne?o.jsx("div",{className:"gallery__empty",role:"status","aria-live":"polite",children:e("gallery.sessionLoading")}):ue?o.jsxs("div",{className:"gallery__empty",role:"alert",children:[o.jsx("span",{children:e("gallery.sessionLoadFailed")}),o.jsx("button",{type:"button",onClick:()=>J(M=>M+1),children:e("gallery.retry")})]}):o.jsxs(o.Fragment,{children:[D?o.jsx("div",{className:"gallery__limit-notice",role:"status",children:e("gallery.sessionLimitNotice",{count:500})}):null,o.jsx(oS,{groups:K,loose:G,favoritesOnly:O,galleryScope:u,setGalleryScope:p,renderTile:W,t:e}),o.jsx(xi,{showSessions:Q,favoritesOnly:O,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]}):fe.length===0?o.jsx("div",{className:"gallery__empty",children:ce.length===0?e("gallery.emptyAll"):e(O?"gallery.emptyFavorites":"gallery.noResults")}):o.jsxs(o.Fragment,{children:[o.jsx(sS,{dateGroups:X,selectedKey:xe,scrollElement:_e,localizeBucket:E,renderTile:W}),o.jsx(xi,{showSessions:Q,favoritesOnly:O,query:S,historyNextCursor:m,favoriteHistoryNextCursor:b,historyLoadingOlder:h,favoriteHistoryLoadingOlder:I,onLoadOlder:()=>{x()},onLoadOlderFavorites:()=>{g()},t:e})]})})]})})}function cS(e){return e.includes("ratio")?"sizeConfirm.reasonRatio":e.includes("maxPixels")||e.includes("pixels")?"sizeConfirm.reasonPixels":e.includes("minPixels")?"sizeConfirm.reasonMinPixels":e.includes("min")?"sizeConfirm.reasonMin":e.includes("maxEdge")||e.includes("max")?"sizeConfirm.reasonMax":"sizeConfirm.reasonSnap"}function dS(){const e=f(l=>l.customSizeConfirm),t=f(l=>l.confirmCustomSizeAdjustment),n=f(l=>l.cancelCustomSizeAdjustment),{t:r}=H(),s=He(!!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(cS(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 uS(){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=He(!!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 mS=new Set(["disconnected","connecting","auth_required","connected","offline","error"]);function Ct(){throw Object.assign(new Error("MCP_READINESS_INVALID"),{code:"MCP_READINESS_INVALID"})}function Ut(e){return!e||typeof e!="object"||Array.isArray(e)?Ct():e}function Xs(e){return typeof e!="string"||!e.trim()?Ct():e}function bd(e){return e===void 0?{}:typeof e!="boolean"?Ct():{executable:e}}function pS(e){const t=Ut(e),n=Ut(t.status);return typeof t.enabled!="boolean"||!mS.has(n.state)?Ct():{id:Xs(t.id),enabled:t.enabled,...bd(t.executable),status:{state:n.state}}}function Si(e){return Array.isArray(e)?e.map(t=>{const n=Ut(t);return{id:Xs(n.id),label:Xs(n.label),...bd(n.executable)}}):Ct()}function wi(e,t){const n=Ut(e);if(n.ok!==!0||!Array.isArray(n.providers))return Ct();const r=n.providers.map(pS);if(t===null)return{providers:r,catalog:null};const s=Ut(t),a=Ut(s.models);return s.ok!==!0?Ct():{providers:r,catalog:{image:Si(a.image),video:Si(a.video)}}}function fS(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 hS(){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 Hh(u.signal),I=wi(h,null).providers.find(g=>g.id===t),x=I?.enabled&&I.status.state==="connected"&&I.executable!==!1&&n!==null?await Vh(t,u.signal):null,y=wi(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=fS(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 _i={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 gS(){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=md(),m=Hn(),h=s==="grok",b=Qe.find(w=>w.value===i),I=He(t,n);if(!t)return null;const x=p[s],y=kt(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(hS,{}):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?Kt(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:_i.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:_i[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 Ei="ima2.onboardingDismissed";function yS(){const{t:e}=H(),t=f(x=>x.openSettings),n=cd(),r=dd(),{data:s}=ud(),[a,i]=v.useState(()=>{try{return localStorage.getItem(Ei)==="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(Ei,"1")}catch{}i(!0)},b=()=>{h(),t("providers")},I=He(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 vS(){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 bS(){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 xS(){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(!yt()||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(bS,{})})}let Gr=null;function IS(e){Gr=e}function SS(){const e=Gr;Gr=null,e?.isConnected&&e.focus()}function Ni(){Gr=null}function wS(){const{t:e}=H(),t=f(u=>u.openComposeSheet),n=f(u=>u.settingsOpen),r=f(u=>u.uiMode),s=r==="agent"&&Zt?"agent":r==="node"&&Xt?"node":r==="home"?"home":r==="assets"?"assets":r==="asset-gen"?"asset-gen":"classic",a=yt(),i=v.useRef(null),l=v.useRef(null),c=v.useRef(null),d=(u,p)=>{p.current&&IS(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(rd,{compact:!0})})]})}const _S={"#home":"home","#create":"classic","#canvas":"classic","#node":"node","#agent":"agent","#assets":"assets","#asset-gen":"asset-gen"},ki={home:"#home",classic:"#create",node:"#node",agent:"#agent",assets:"#assets","asset-gen":"#asset-gen"};function ES(){const e=location.hash;if(e==="#settings")return{mode:"classic",settings:!0};const t=_S[e];return t&&t!=="settings"?{mode:t,settings:!1}:null}function NS(){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 kS(){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 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:"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 jS(){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 AS(){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 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:"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 RS(){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 TS=[{id:"home",mode:"home",icon:kS,labelKey:"nav.home",enabled:!0},{id:"create",mode:"classic",icon:NS,labelKey:"nav.create",enabled:!0},{id:"node",mode:"node",icon:CS,labelKey:"nav.node",enabled:Xt},{id:"agent",mode:"agent",icon:jS,labelKey:"nav.agent",enabled:Zt},{id:"assets",mode:"assets",icon:PS,labelKey:"nav.assets",enabled:!0},{id:"asset-gen",mode:"asset-gen",icon:RS,labelKey:"nav.assetGen",enabled:!0},{id:"settings",settingsAction:!0,icon:AS,labelKey:"nav.settings",enabled:!0,bottom:!0}];function MS(){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=yt(),l=v.useRef(null),c=v.useCallback(I=>{const x=l.current;if(!x||!I)return;const y=x.getBoundingClientRect(),g=I.getBoundingClientRect();g.left<y.left?x.scrollLeft-=y.left-g.left:g.right>y.right&&(x.scrollLeft+=g.right-y.right)},[]);v.useEffect(()=>{i&&c(l.current?.querySelector(".nav-rail__btn.is-active")??null)},[i,t,r,c]);const d=v.useCallback(I=>{if(I.settingsAction){r?(a(),history.replaceState(null,"",ki[t]||"#create")):(s(),history.replaceState(null,"","#settings"));return}I.mode&&(r&&a(),n(I.mode),history.replaceState(null,"",ki[I.mode]||"#create"))},[t,r,n,s,a]);v.useEffect(()=>{const I=()=>{const x=ES();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=TS.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 LS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Qdujpb4L.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 OS(){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"&&Zt?"agent":l==="node"&&Xt?"node":l==="home"?"home":l==="assets"?"assets":"classic",d=yt(),[u,p]=v.useState(!1),m=v.useRef(a),h=v.useRef(!1),b=v.useRef(null),I=v.useRef({}),x=v.useRef(!1),y=w=>{r(w),requestAnimationFrame(()=>I.current[w]?.focus())},g=(w,k)=>{const N=Ke.indexOf(k),O=w.key==="ArrowRight"?Ke[(N+1)%Ke.length]:w.key==="ArrowLeft"?Ke[(N-1+Ke.length)%Ke.length]:w.key==="Home"?Ke[0]:w.key==="End"?Ke[Ke.length-1]:null;O&&(w.preventDefault(),y(O))},_=He(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,SS())},[t,n]);const S=d&&!i&&c==="classic";return v.useEffect(()=>{S||(x.current=!1,f.getState().composeSheetOpen&&s(),Ni())},[S]),v.useEffect(()=>()=>Ni(),[]),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:k=>{I.current[w]=k},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:k=>g(k,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 k=document.getElementById(dr);h.current=k?.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(ed,{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(gd,{}):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(LS,{variant:"embedded",forceOpen:!0,onRequestClose:()=>r("prompt")})}):null})]})]})]}):null}const FS={ArrowLeft:"previous",ArrowRight:"next",Home:"first",End:"last",PageUp:"pagePrevious",PageDown:"pageNext"};function DS(){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=FS[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,xd="Image Gen";let na=xd,Zs=!1,ht=null,ra="",Qs=!1;function Id(){return navigator}function Sd(){if(typeof document>"u")return null;if(ht)return ht;const e=document.querySelector('link[rel~="icon"]');if(e)return ht=e,ra=e.href||e.getAttribute("href")||"",e;const t=document.createElement("link");return t.rel="icon",document.head.appendChild(t),ht=t,Qs=!0,t}function GS(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",zS(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 zS(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 qS(e){const t=Id();if(typeof t.setAppBadge=="function")try{await t.setAppBadge(e)}catch{}}async function $S(){const e=Id();if(typeof e.clearAppBadge=="function")try{await e.clearAppBadge()}catch{}}function US(e){document.title=`(${e}) ${na}`;const t=Sd();t&&(t.href=GS(e)),qS(e)}function Ci(){document.title=na,ht&&(Qs?(ht.remove(),ht=null,Qs=!1):ht.href=ra),$S()}function ji(){Zs||typeof document>"u"||(Zs=!0,na=document.title||xd,Sd())}function HS(e){v.useEffect(()=>(ji(),()=>{Zs&&Ci()}),[]),v.useEffect(()=>{ji(),e>0?US(e):Ci()},[e])}function VS(){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 KS=v.lazy(()=>Me(()=>import("./NodeCanvas-D2N3m-1s.js"),__vite__mapDeps([7,1,2,8])).then(e=>({default:e.NodeCanvas}))),BS=v.lazy(()=>Me(()=>import("./SettingsWorkspace-Dm4wezu_.js"),__vite__mapDeps([9,1,2,5])).then(e=>({default:e.SettingsWorkspace}))),WS=v.lazy(()=>Me(()=>import("./CardNewsWorkspace-CM5hwbRV.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.CardNewsWorkspace}))),JS=v.lazy(()=>Me(()=>import("./AgentWorkspace-DlLaTsPK.js"),__vite__mapDeps([11,1,2,12])).then(e=>({default:e.AgentWorkspace}))),YS=v.lazy(()=>Me(()=>import("./AssetsWorkspace-BcbAM8uC.js"),__vite__mapDeps([13,1,2,14,12,15])).then(e=>({default:e.AssetsWorkspace}))),XS=v.lazy(()=>Me(()=>import("./AssetGenWorkspace-C8eIs-bS.js").then(e=>e.A),__vite__mapDeps([16,1,2,14,12,17])).then(e=>({default:e.AssetGenWorkspace}))),ZS=v.lazy(()=>Me(()=>import("./HomeWorkspace-KGUtIZyG.js"),__vite__mapDeps([18,1,2])).then(e=>({default:e.HomeWorkspace}))),QS=v.lazy(()=>Me(()=>import("./PromptLibraryPanel-Qdujpb4L.js"),__vite__mapDeps([3,1,2])).then(e=>({default:e.PromptLibraryPanel})));function ew(){return o.jsx("main",{className:"canvas canvas--lazy-loading","aria-busy":"true"})}function tw(){DS(),VS();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"&&Zt?"agent":p==="node"&&Xt?"node":p==="home"?"home":p==="assets"?"assets":p==="asset-gen"?"asset-gen":"classic",h=m==="agent",b=m==="assets",I=m==="asset-gen",x=m==="home",y=yt(),g=Dn(u),_=!y&&m==="classic"&&g.composerPlacement==="bottom"&&g.multimodeHistoryGrouping==="sequence",S=!_&&!h&&!b&&!I&&!x;return HS(c),v.useEffect(()=>{document.documentElement.lang=e},[e]),v.useEffect(()=>{if(!de())return r(),t(),n(),a(),s(),At(),ua(()=>a()),ma(w=>{w==="failed"&&console.warn("[SSE] connection failed after multiple retries")}),()=>{En(),ua(()=>{}),ma(()=>{})}},[t,n,a,s,r]),v.useEffect(()=>{const w=k=>{const N=k.detail?.assetId;N&&f.getState().openAssetDetail(N)};return window.addEventListener("ima2:open-assets-detail",w),()=>window.removeEventListener("ima2:open-assets-detail",w)},[]),v.useEffect(()=>{const w=k=>{k.key&&(k.key==="ima2.inFlight"||k.key==="ima2.selectedFilename"||k.key===ho||k.key===fo||k.key===yo)&&i()};return window.addEventListener("storage",w),()=>window.removeEventListener("storage",w)},[i]),v.useEffect(()=>{const w=()=>{dp(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(MS,{}),x?null:o.jsx(yb,{}),o.jsx(wS,{}),S?o.jsx(xI,{}):null,o.jsx(v.Suspense,{fallback:o.jsx(ew,{}),children:l?o.jsx(BS,{}):m==="classic"?_?o.jsx(dx,{}):o.jsx(Ys,{}):m==="node"?o.jsx(KS,{}):m==="card-news"?o.jsx(WS,{}):m==="agent"?o.jsx(JS,{}):m==="assets"?o.jsx(YS,{}):m==="asset-gen"?o.jsx(XS,{}):m==="home"?o.jsx(ZS,{}):o.jsx(Ys,{})}),y||m==="agent"||m==="card-news"||m==="assets"||m==="asset-gen"||m==="home"?null:o.jsx(fI,{})]}),o.jsx(dS,{}),o.jsx(vS,{}),o.jsx(II,{}),o.jsx(SI,{}),o.jsx(lS,{}),o.jsx(uS,{}),o.jsx(gS,{}),o.jsx(yS,{}),o.jsx(OS,{}),o.jsx(xS,{}),m==="card-news"?o.jsx(v.Suspense,{fallback:null,children:o.jsx(QS,{})}):null]})}const Uw=Object.freeze(Object.defineProperty({__proto__:null,default:tw},Symbol.toStringTag,{value:"Module"}));export{_w as $,ju as A,Fe as B,zc as C,Rw as D,Tw as E,Mw as F,Cu as G,Lw as H,Qe as I,Gw as J,Qo as K,Ow as L,Fw as M,Dw as N,ku as O,Se as P,hI as Q,Ds as R,mv as S,Yu as T,Cw as U,Du as V,pv as W,st as X,By as Y,Aw as Z,Iu as _,f as a,Rp as a0,QI as a1,Jc as a2,zw as a3,$w as a4,qw as a5,kw as a6,Pw as a7,Qb as a8,so as a9,mw as aA,cw as aB,rw as aC,pw as aD,lw as aE,_b as aF,iw as aG,tx as aH,Pi as aI,L as aJ,sw as aK,aw as aL,ow as aM,gw as aN,fw as aO,yw as aP,vw as aQ,hw as aR,bw as aS,xw as aT,Iw as aU,Sw as aV,ww as aW,Uw as aX,sc as aa,NI as ab,Xo as ac,Nw as ad,jt as ae,Ew as af,es as ag,Wo as ah,Wc as ai,wv as aj,Pe as ak,md as al,NS as am,CS as an,Xt as ao,jS as ap,Zt as aq,PS as ar,ki as as,Ky as at,Jb as au,ex as av,Bs as aw,uw as ax,dw as ay,Ir as az,RI as b,bp as c,nt as d,Nt as e,Bu as f,Hi as g,jw as h,Xe as i,rc as j,He as k,Tp as l,bu as m,yp as n,q as o,yt as p,Ee as q,Oe as r,cd as s,dd as t,H as u,_x as v,tp as w,ud as x,Mu as y,ss as z};
|