@ensocode/server 0.3.3 → 0.3.4
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/README.md +10 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/CHANGELOG.md +117 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-MGNURJ72.js +6 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{azure-openai-responses-FSC6BAW3.js → azure-openai-responses-4WDOP7MF.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/bedrock-converse-stream.js +3 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-4KSTFUIK.js +19 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-4UNPP53I.js +55 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CCYGJPSU.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-4EYXVSA5.js → chunk-FF6XOTWB.js} +9 -9
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-FMPAMX2W.js +82 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-C2WU32PX.js → chunk-H4W2F2IO.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-EOO47QGR.js → chunk-JLFZH7C6.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-LCB5FO32.js +4 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-GN3QYODH.js → chunk-LQUBM7HF.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-MABPTPMF.js +30 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-MPEFJ3RP.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-EBFHJFEE.js → chunk-PYBKJQVF.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-VKJQ6CME.js +8 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-B46VJEHW.js → chunk-VUPOM3AH.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-3TGLJEWK.js → chunk-WL4TUXY7.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-V6KH5QG4.js → chunk-XM4MQFQV.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{chunk-YZKQS34S.js → chunk-Y55SJART.js} +5 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-ZKNSXGL5.js +1243 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{cli-MCOUW5WS.js → cli-35W4A75E.js} +7 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{cloudflare-workers-ai-system-one-WLAFJSP6.js → cloudflare-workers-ai-system-one-WKRH5HZA.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/codemode-worker.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{easter-egg-3d-WMBNSJ4M.js → easter-egg-3d-GEVPKQF6.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{execute-4CEBORGZ.js → execute-L2EEDV3L.js} +5 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/github-copilot.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-generative-ai-INGKNW72.js → google-generative-ai-VSMFCHJU.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{google-vertex-IBTX6MBF.js → google-vertex-35UTLZJN.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{llama-cpp-classify-V5U3QKXI.js → llama-cpp-classify-Z3SS4FP4.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{mistral-conversations-S4OWXIXQ.js → mistral-conversations-LWJTUFIM.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-codex-responses-YYIXDJWF.js +10 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-completions-EJNYB6IX.js → openai-completions-X2I4TQ2L.js} +3 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openai-decisions-IXI34BYG.js → openai-decisions-GG3FBAIF.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-responses-5CX3GG6R.js +4 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{openrouter-images-PISKSFMS.js → openrouter-images-WHNK2UQG.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{pi-messages-NORUKF4E.js → pi-messages-5CXWY5I7.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{runtime-FQB7RU7U.js → runtime-J5ZSBGTX.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/{typesafe-system-one-CHVC2UUI.js → typesafe-system-one-KA2SBSSD.js} +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/virtual-modules-7ZY53V4K.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/cli-runtime.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/index.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/rpc-entry.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/args.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-command.js +26 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-login.d.ts +15 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-login.js +232 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-logout.d.ts +14 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-logout.js +57 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-terminal.d.ts +17 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/auth-terminal.js +63 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/cli/config-selector.js +3 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session-runtime.d.ts +5 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session-runtime.js +7 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.d.ts +25 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/agent-session.js +139 -50
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/auth-storage.js +3 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/bash-executor.js +3 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/cache-warmer.d.ts +4 -37
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/cache-warmer.js +11 -89
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/compaction/utils.js +2 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/index.d.ts +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/loader.js +10 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.d.ts +1 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/runner.js +9 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/extensions/types.d.ts +28 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/keybindings.d.ts +2 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/keybindings.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/mcp-servers.d.ts +12 -37
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/mcp-servers.js +42 -121
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-config.d.ts +52 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-resolver.js +20 -19
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.d.ts +5 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/model-runtime.js +11 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/package-manager.d.ts +10 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/package-manager.js +50 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/pi-ai-schemas.d.ts +4 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/preferred-providers.d.ts +17 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/preferred-providers.js +24 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/prompt-templates.js +18 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-composer.js +3 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-matching.d.ts +6 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/provider-matching.js +8 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/radius-mcp.d.ts +13 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/radius-mcp.js +29 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/remote-catalog-provider.js +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/runtime-credentials.d.ts +8 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/runtime-credentials.js +15 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-defaults.d.ts +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/settings-defaults.js +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/bash.js +35 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit-diff.d.ts +23 -14
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit-diff.js +182 -41
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/edit.js +8 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/find.js +82 -36
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/grep.d.ts +5 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/grep.js +87 -75
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/ls.js +2 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/powershell.js +15 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/read.d.ts +8 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/read.js +141 -25
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.d.ts +4 -14
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/core/tools/truncate.js +23 -29
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/execute.js +4 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/codemode/tool.js +34 -12
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.d.ts +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/client.js +23 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/llama/ui.js +15 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/cli.d.ts +2 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/cli.js +49 -14
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/config.js +4 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/index.js +4 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.d.ts +11 -49
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/oauth.js +56 -319
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/resources.d.ts +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/resources.js +4 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.d.ts +4 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/runtime.js +7 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/tools.d.ts +2 -23
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/mcp/tools.js +6 -58
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/extensions/tool-search/tool.js +18 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/index.d.ts +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/main.js +46 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/branch-summary-message.d.ts +5 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/branch-summary-message.js +12 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/compaction-summary-message.d.ts +5 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/compaction-summary-message.js +12 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/custom-message.d.ts +5 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/custom-message.js +10 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/diff.js +11 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/extension-selector.js +9 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/login-dialog.js +1 -18
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/mermaid.d.ts +2 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/mermaid.js +25 -20
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/model-selector.js +14 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/oauth-selector.d.ts +10 -3
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/oauth-selector.js +32 -5
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/provider-brand.d.ts +14 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/provider-brand.js +66 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/radius-login-selector.d.ts +1 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/radius-login-selector.js +6 -37
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/skill-invocation-message.d.ts +5 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/skill-invocation-message.js +12 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/components/tree-selector.js +19 -10
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.d.ts +11 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/interactive-mode.js +110 -63
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/interactive/theme/theme.js +4 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/print-mode.js +19 -10
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/modes/rpc/rpc-mode.js +53 -23
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/package-manager-cli.js +39 -8
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/changelog.d.ts +2 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/changelog.js +12 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/image-resize.js +3 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/terminal-question.d.ts +8 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/terminal-question.js +24 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/web-url.d.ts +12 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/utils/web-url.js +20 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/cli.md +14 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/extensions.md +27 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/keybindings.md +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/llama-cpp.md +4 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/models-configuration.md +6 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/models.md +2 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/prompt-templates.md +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/providers.md +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/rpc.md +4 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/settings.md +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/docs/tui.md +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package-lock.json +2 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/gondolin/package.json +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/plan-mode/index.ts +23 -13
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/plan-mode/utils.ts +42 -16
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/README.md +14 -11
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/index.ts +392 -171
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package-lock.json +2 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/extensions/with-deps/package.json +1 -1
- package/out/node_modules/@earendil-works/pi-coding-agent/examples/tsconfig.json +63 -35
- package/out/node_modules/@earendil-works/pi-coding-agent/package.json +7 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/schemas/models.schema.json +29 -0
- package/out/node_modules/@earendil-works/pi-coding-agent/schemas/settings.schema.json +1 -1
- package/out/phone/assets/{abnfDiagram-VCTEODGH-CLgfII9z.js → abnfDiagram-VCTEODGH-6JYofuK8.js} +1 -1
- package/out/phone/assets/architecture-7GRP2DOG-D7mwyuxS.js +1 -0
- package/out/phone/assets/{architectureDiagram-5GKGNRK7-I2RDn32D.js → architectureDiagram-5GKGNRK7-BeLeAQB1.js} +1 -1
- package/out/phone/assets/{blockDiagram-I7D4REHJ-D5xNQZkS.js → blockDiagram-I7D4REHJ-uXn3vhT2.js} +1 -1
- package/out/phone/assets/{c4Diagram-7LVT6UL2-CRKpzdlA.js → c4Diagram-7LVT6UL2-CjzMFRll.js} +1 -1
- package/out/phone/assets/channel-BsGN1oT0.js +1 -0
- package/out/phone/assets/{chunk-4HAMMTFA-CcezrqKz.js → chunk-4HAMMTFA-BA8HaYy2.js} +1 -1
- package/out/phone/assets/{chunk-75Z2AOVW-DDCXp4y1.js → chunk-75Z2AOVW-BhIfO9es.js} +1 -1
- package/out/phone/assets/{chunk-DU6HZSFF-CjWveEkB.js → chunk-DU6HZSFF-BTLBHwj-.js} +1 -1
- package/out/phone/assets/{chunk-F27PBJKO-Bgl_xI02.js → chunk-F27PBJKO-CUw8NZk8.js} +1 -1
- package/out/phone/assets/{chunk-GMAD6QVW-EmL8nOme.js → chunk-GMAD6QVW-bZOKnRyM.js} +1 -1
- package/out/phone/assets/{chunk-GVQU2GXP-Dox_nphF.js → chunk-GVQU2GXP-B0WIm1dS.js} +1 -1
- package/out/phone/assets/{chunk-IMKFNOWR-BapGpI4S.js → chunk-IMKFNOWR-DWND4rEr.js} +1 -1
- package/out/phone/assets/{chunk-L3NEJ4N5-Cq_UZI8A.js → chunk-L3NEJ4N5-DgMknY3k.js} +1 -1
- package/out/phone/assets/{chunk-OSK3NFVY-2VVlErAd.js → chunk-OSK3NFVY-C5aEouov.js} +1 -1
- package/out/phone/assets/{chunk-P2QGCYS3-Cci-G-p1.js → chunk-P2QGCYS3-D2ID3RxV.js} +1 -1
- package/out/phone/assets/{chunk-POPQ4Y6H-CJ47EOfE.js → chunk-POPQ4Y6H-C1lOuNpV.js} +1 -1
- package/out/phone/assets/{chunk-PWAF6VOD-D9dLdFqC.js → chunk-PWAF6VOD-CfqWQZRE.js} +1 -1
- package/out/phone/assets/{chunk-SHT3W25Y-BlGSiWZn.js → chunk-SHT3W25Y-p37Dlvn4.js} +1 -1
- package/out/phone/assets/{chunk-SVP7TREG-C0zdsa_A.js → chunk-SVP7TREG-CSSqW-zb.js} +1 -1
- package/out/phone/assets/{chunk-TICWLB2K-DAQW8nQU.js → chunk-TICWLB2K-Bse5ne4b.js} +1 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-a1PUvjC2.js +1 -0
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-a1PUvjC2.js +1 -0
- package/out/phone/assets/{cynefin-OW5HDTMX-_zsx5mdV.js → cynefin-OW5HDTMX-BGQqPhYk.js} +1 -1
- package/out/phone/assets/{cynefinDiagram-5FMLGOSQ-Cww-w0ex.js → cynefinDiagram-5FMLGOSQ-Cz3XWaxY.js} +1 -1
- package/out/phone/assets/{dagre-GXQ25YYZ-C0i7DPqX.js → dagre-GXQ25YYZ-CjAF6lSz.js} +1 -1
- package/out/phone/assets/desk-1McWacjU.js +2 -0
- package/out/phone/assets/{diagram-S7CK7UJ4-Bx-G5hYz.js → diagram-S7CK7UJ4-B135cp5a.js} +1 -1
- package/out/phone/assets/{diagram-UQ7AKVKN-DaTblkjV.js → diagram-UQ7AKVKN-C4pCe0fQ.js} +1 -1
- package/out/phone/assets/{diagram-VSXAHHWV-gmN2e1b4.js → diagram-VSXAHHWV-CYkCrin2.js} +1 -1
- package/out/phone/assets/{diagram-VX7I27RA-WYtRtOo8.js → diagram-VX7I27RA-CT_vufh_.js} +1 -1
- package/out/phone/assets/{diagram-Z3DM3KII-Cr6uUB5B.js → diagram-Z3DM3KII-XEkkXu3P.js} +1 -1
- package/out/phone/assets/{ebnfDiagram-PWID7BFC-BCicfvpA.js → ebnfDiagram-PWID7BFC-DfLyeXjw.js} +1 -1
- package/out/phone/assets/{erDiagram-RLTQ6QDP-B3QlJvfQ.js → erDiagram-RLTQ6QDP-pKNbKkAP.js} +1 -1
- package/out/phone/assets/eventmodeling-NTZA5JFV-DcUsfQiW.js +1 -0
- package/out/phone/assets/flowDiagram-HODETNUW-sUobw8zi.js +1 -0
- package/out/phone/assets/{ganttDiagram-EL5Y4UJY-LYy2mfCh.js → ganttDiagram-EL5Y4UJY-Df4E50Mj.js} +1 -1
- package/out/phone/assets/{gitGraph-4MIJSDKK-dT22Z2jG.js → gitGraph-4MIJSDKK-CkjzZeFD.js} +1 -1
- package/out/phone/assets/{gitGraphDiagram-WWUBYQGX-DHNdY57l.js → gitGraphDiagram-WWUBYQGX-CBxfRAfy.js} +1 -1
- package/out/phone/assets/{info-A6RAGUB7-nIu8NSOs.js → info-A6RAGUB7-CHFXa2pw.js} +1 -1
- package/out/phone/assets/{infoDiagram-27XIBGKW-DGkWZIMT.js → infoDiagram-27XIBGKW-K0DnZhi4.js} +1 -1
- package/out/phone/assets/{ishikawaDiagram-5VMMS53U-C8EPXru-.js → ishikawaDiagram-5VMMS53U-DTQF2ZuR.js} +1 -1
- package/out/phone/assets/{journeyDiagram-3NMN7TZE-Dyd9L3l3.js → journeyDiagram-3NMN7TZE-wBltkU2i.js} +1 -1
- package/out/phone/assets/{kanban-definition-UXKFOSKX-DehTYcsL.js → kanban-definition-UXKFOSKX-BZpcOajP.js} +1 -1
- package/out/phone/assets/{line-Db4SulF4.js → line-BflnZFgp.js} +1 -1
- package/out/phone/assets/main-CnA1zWP8.css +1 -0
- package/out/phone/assets/main-Crtf_g8h.js +1643 -0
- package/out/phone/assets/{mermaid-parser.core-D7h_8WV8.js → mermaid-parser.core-BiCTmcqa.js} +3 -3
- package/out/phone/assets/{mermaid.core-Dw_E5kj4.js → mermaid.core-D3TwYaLF.js} +4 -4
- package/out/phone/assets/{mindmap-definition-YA3MSWOX-_5Mxqxsy.js → mindmap-definition-YA3MSWOX-Cz0aS_6Y.js} +1 -1
- package/out/phone/assets/{packet-AYTQ26CC-_cgeMDdN.js → packet-AYTQ26CC-DW-djbhd.js} +1 -1
- package/out/phone/assets/{pegDiagram-XKGWAZYB-BhBwaNEr.js → pegDiagram-XKGWAZYB-CE0sZZAE.js} +1 -1
- package/out/phone/assets/{pie-WAS4IAKB-BepY80_0.js → pie-WAS4IAKB-CKGFlXok.js} +1 -1
- package/out/phone/assets/{pieDiagram-E7YTZNPT-CQQgqmI8.js → pieDiagram-E7YTZNPT-BrnQ32_6.js} +1 -1
- package/out/phone/assets/{quadrantDiagram-AXDQQJYC-DEEatC1J.js → quadrantDiagram-AXDQQJYC-BrxDAygB.js} +1 -1
- package/out/phone/assets/{radar-RG4KPBEZ-BqsiI_qQ.js → radar-RG4KPBEZ-Bo2f5QyA.js} +1 -1
- package/out/phone/assets/{railroad-74A4TZTK-C_2pEUjD.js → railroad-74A4TZTK-BZEmm0Ha.js} +1 -1
- package/out/phone/assets/railroad-abnf-HS5TGJTU-CGiIT1ZV.js +1 -0
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-C85Q3c0J.js +1 -0
- package/out/phone/assets/railroad-peg-WCYAUIDC-8qPPCLgU.js +1 -0
- package/out/phone/assets/{railroadDiagram-O6MQD6OU-B7786u7W.js → railroadDiagram-O6MQD6OU-BvOyUNMC.js} +1 -1
- package/out/phone/assets/{requirementDiagram-BXWQKSXE-Ci3b5uwm.js → requirementDiagram-BXWQKSXE-T42N3TW5.js} +1 -1
- package/out/phone/assets/{sankeyDiagram-P5KCCOFB-PwT2gJjH.js → sankeyDiagram-P5KCCOFB-0us9ErVV.js} +1 -1
- package/out/phone/assets/{sequenceDiagram-WJ2MYXX4-H6sgB5RI.js → sequenceDiagram-WJ2MYXX4-BMcYh2ll.js} +1 -1
- package/out/phone/assets/{stateDiagram-D77RDMKH-BxyRe7OB.js → stateDiagram-D77RDMKH-CgP9dUc3.js} +1 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-WM4CNSf-.js +1 -0
- package/out/phone/assets/storage-CahQ0cyN.js +1 -0
- package/out/phone/assets/{swimlanes-42K2YHIH-DWT3f1Hk.js → swimlanes-42K2YHIH-VnE4ceCW.js} +1 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-65AiMWVp.js +8 -0
- package/out/phone/assets/{timeline-definition-24CTP7MA-D67esSVY.js → timeline-definition-24CTP7MA-tH3izgae.js} +1 -1
- package/out/phone/assets/{treeView-Q6P3EWNA-BTIfu3Qr.js → treeView-Q6P3EWNA-CVFDOC7i.js} +1 -1
- package/out/phone/assets/{treemap-WGGIJYW6-DkPf6LQc.js → treemap-WGGIJYW6-vmikHzt3.js} +1 -1
- package/out/phone/assets/{vennDiagram-4TSXK5OY-DRMRxJ4f.js → vennDiagram-4TSXK5OY-b8ttDCR-.js} +1 -1
- package/out/phone/assets/{wardley-WFR3VGLG-hOvC_8-W.js → wardley-WFR3VGLG-D32vKoC1.js} +1 -1
- package/out/phone/assets/{wardleyDiagram-VM6X3IG4-a5aYRgrw.js → wardleyDiagram-VM6X3IG4-CMkaIPVH.js} +1 -1
- package/out/phone/assets/{xychartDiagram-S5SC5T6Z-DXjoRFDL.js → xychartDiagram-S5SC5T6Z-pLYDcql3.js} +1 -1
- package/out/phone/desk.html +2 -2
- package/out/phone/index.html +3 -3
- package/out/renderer/assets/{abnfDiagram-VCTEODGH-DhskujJf.js → abnfDiagram-VCTEODGH-N6OiVFQx.js} +1 -1
- package/out/renderer/assets/{arc-BcW67t47.js → arc-CXVc3U0J.js} +1 -1
- package/out/renderer/assets/{architectureDiagram-5GKGNRK7-D-x057Ia.js → architectureDiagram-5GKGNRK7-BT5CXpcQ.js} +1 -1
- package/out/renderer/assets/{blockDiagram-I7D4REHJ-DR3sZkhW.js → blockDiagram-I7D4REHJ-C32Vqzip.js} +1 -1
- package/out/renderer/assets/{c4Diagram-7LVT6UL2-CQ4lScWs.js → c4Diagram-7LVT6UL2-qjwL2BP8.js} +1 -1
- package/out/renderer/assets/channel-B1Cv56hA.js +1 -0
- package/out/renderer/assets/{chunk-2Q5K7J3B-CtT0yqF3.js → chunk-2Q5K7J3B-YC6CQiyD.js} +1 -1
- package/out/renderer/assets/{chunk-5VM5RSS4-DlCfddrY.js → chunk-5VM5RSS4-E-kluPz3.js} +1 -1
- package/out/renderer/assets/{chunk-F27PBJKO-BAJ5dGzo.js → chunk-F27PBJKO-Bhx1_P75.js} +1 -1
- package/out/renderer/assets/{chunk-IMKFNOWR-Dlah_YbP.js → chunk-IMKFNOWR-Dgb_730B.js} +1 -1
- package/out/renderer/assets/{chunk-JWPE2WC7-BiXd3nUZ.js → chunk-JWPE2WC7-COQNHw4u.js} +1 -1
- package/out/renderer/assets/{chunk-POPQ4Y6H-Ch86i4EJ.js → chunk-POPQ4Y6H-CQz4hRgP.js} +1 -1
- package/out/renderer/assets/{chunk-SVP7TREG-z3inDV-H.js → chunk-SVP7TREG-DGp9XQFd.js} +1 -1
- package/out/renderer/assets/{chunk-TICWLB2K-B34A2AKD.js → chunk-TICWLB2K-CovR1uHr.js} +1 -1
- package/out/renderer/assets/{chunk-XXDRQBXY-Do_L0wRR.js → chunk-XXDRQBXY-gVmqSU5b.js} +1 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-CDWgELaf.js +1 -0
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-CDWgELaf.js +1 -0
- package/out/renderer/assets/{cose-bilkent-JH36ORCC-BQraKmgl.js → cose-bilkent-JH36ORCC-DD4PEqt_.js} +1 -1
- package/out/renderer/assets/{cynefin-OW5HDTMX-BwixoR4r.js → cynefin-OW5HDTMX-DNsYCrBx.js} +1 -1
- package/out/renderer/assets/{cynefinDiagram-5FMLGOSQ-BLTBma3J.js → cynefinDiagram-5FMLGOSQ-CoSzqs25.js} +1 -1
- package/out/renderer/assets/{cytoscape-fcose-BRpJ5tyq.js → cytoscape-fcose-CV0MpCmk.js} +1 -1
- package/out/renderer/assets/{dagre-GXQ25YYZ-aWsjA_wn.js → dagre-GXQ25YYZ-BxpTPeHN.js} +1 -1
- package/out/renderer/assets/{diagram-S7CK7UJ4-Cur2zK4q.js → diagram-S7CK7UJ4-Df_OM1vW.js} +1 -1
- package/out/renderer/assets/{diagram-UQ7AKVKN-DlrY8YcD.js → diagram-UQ7AKVKN-iovjmny_.js} +1 -1
- package/out/renderer/assets/{diagram-VSXAHHWV-BBdjreqR.js → diagram-VSXAHHWV-BMrwlcQx.js} +1 -1
- package/out/renderer/assets/{diagram-VX7I27RA-XiWMdc8S.js → diagram-VX7I27RA-DqLh449X.js} +1 -1
- package/out/renderer/assets/{diagram-Z3DM3KII-CBB5leat.js → diagram-Z3DM3KII-CH_W77UO.js} +1 -1
- package/out/renderer/assets/{ebnfDiagram-PWID7BFC-nl8RPo8j.js → ebnfDiagram-PWID7BFC-yjzodXoL.js} +1 -1
- package/out/renderer/assets/{erDiagram-RLTQ6QDP-C_oaG80x.js → erDiagram-RLTQ6QDP-DXxhvHYS.js} +1 -1
- package/out/renderer/assets/{flowDiagram-HODETNUW-nDoVZFS7.js → flowDiagram-HODETNUW-b2AWCAaB.js} +1 -1
- package/out/renderer/assets/{ganttDiagram-EL5Y4UJY-DOrcuM3Q.js → ganttDiagram-EL5Y4UJY-COkyXL3K.js} +1 -1
- package/out/renderer/assets/{gitGraphDiagram-WWUBYQGX-D_DB3jro.js → gitGraphDiagram-WWUBYQGX-BYPqy5fh.js} +1 -1
- package/out/renderer/assets/globals-DX-8GWfJ.css +1 -0
- package/out/renderer/assets/{globals-D1ocHHQV.js → globals-y5_C1IiJ.js} +182 -176
- package/out/renderer/assets/index-CHJ6mVl2.js +117 -0
- package/out/renderer/assets/{infoDiagram-27XIBGKW-BbBrANxo.js → infoDiagram-27XIBGKW-DNg-VxlH.js} +1 -1
- package/out/renderer/assets/{ishikawaDiagram-5VMMS53U-7UlfWlWV.js → ishikawaDiagram-5VMMS53U-DProTI6a.js} +1 -1
- package/out/renderer/assets/{journeyDiagram-3NMN7TZE-CJP9bosH.js → journeyDiagram-3NMN7TZE-BWhC4n3f.js} +1 -1
- package/out/renderer/assets/{kanban-definition-UXKFOSKX-D772kW7T.js → kanban-definition-UXKFOSKX-CHJRR0qi.js} +1 -1
- package/out/renderer/assets/{layout-BzVfJEvx.js → layout-D8t6q8k0.js} +1 -1
- package/out/renderer/assets/{linear-DBjhr05m.js → linear-Cxb1p4iF.js} +1 -1
- package/out/renderer/assets/{mermaid.core-CJpNSowm.js → mermaid.core-CFNOEUmc.js} +5 -5
- package/out/renderer/assets/{mindmap-definition-YA3MSWOX-C2oqlH5E.js → mindmap-definition-YA3MSWOX-Ba78cyY4.js} +1 -1
- package/out/renderer/assets/{pegDiagram-XKGWAZYB-CcZ8Hae-.js → pegDiagram-XKGWAZYB-C7zqoWMk.js} +1 -1
- package/out/renderer/assets/{pieDiagram-E7YTZNPT-DTw-_k2D.js → pieDiagram-E7YTZNPT-g304yFeX.js} +1 -1
- package/out/renderer/assets/{quadrantDiagram-AXDQQJYC-D5eX0DO7.js → quadrantDiagram-AXDQQJYC-Bwn3gGTO.js} +1 -1
- package/out/renderer/assets/{railroadDiagram-O6MQD6OU-DzpBB_Re.js → railroadDiagram-O6MQD6OU-DRetS8pv.js} +1 -1
- package/out/renderer/assets/{requirementDiagram-BXWQKSXE-UbOUXLgl.js → requirementDiagram-BXWQKSXE-CHz0FVZ7.js} +1 -1
- package/out/renderer/assets/{sankeyDiagram-P5KCCOFB-jRbXLLsa.js → sankeyDiagram-P5KCCOFB-BYGRDIG9.js} +1 -1
- package/out/renderer/assets/{sequenceDiagram-WJ2MYXX4-s0WBQQPf.js → sequenceDiagram-WJ2MYXX4-B60RuFFk.js} +1 -1
- package/out/renderer/assets/settings-Cd128yRb.js +34 -0
- package/out/renderer/assets/{sizeCapture-INFHLROL-DvUs5rDx.js → sizeCapture-INFHLROL-CB-i3Fmz.js} +1 -1
- package/out/renderer/assets/{stateDiagram-D77RDMKH-C1_V497y.js → stateDiagram-D77RDMKH-CJOcikAJ.js} +1 -1
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-BosPi5SR.js +1 -0
- package/out/renderer/assets/{swimlanes-42K2YHIH-BulPeZ6y.js → swimlanes-42K2YHIH-Buap2upT.js} +1 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-B7TQEEbL.js +8 -0
- package/out/renderer/assets/{timeline-definition-24CTP7MA-gQ5OygZn.js → timeline-definition-24CTP7MA-BdQta3QT.js} +1 -1
- package/out/renderer/assets/{vennDiagram-4TSXK5OY-A8QyA5Ix.js → vennDiagram-4TSXK5OY-BynM2l28.js} +1 -1
- package/out/renderer/assets/{wardleyDiagram-VM6X3IG4-CfP6E41T.js → wardleyDiagram-VM6X3IG4-FZjDO9FY.js} +1 -1
- package/out/renderer/assets/{xychartDiagram-S5SC5T6Z-DTG5UHh7.js → xychartDiagram-S5SC5T6Z-pJPSISxM.js} +1 -1
- package/out/renderer/index.html +3 -3
- package/out/renderer/plugin-view.html +39 -0
- package/out/renderer/settings.html +4 -4
- package/out/renderer/web-preload.js +1 -1
- package/out/server/agent.js +1502 -370
- package/out/server/chunks/{agent-BhQn6jGA.js → agent--Q7N17bY.js} +356 -165
- package/out/server/chunks/{gpuBackendInstall-CdExgjGi.js → gpuBackendInstall-P7COXJlD.js} +6 -5
- package/out/server/chunks/{loadProvider-BnkyjMSW.js → loadProvider-DvvFIF6F.js} +2 -2
- package/out/server/chunks/{manifest-2odvnxjZ.js → manifest-BvEa5QR3.js} +125 -5
- package/out/server/chunks/{workflowPresets-DqSsjOj6.js → workflowPresets-CuLnfQqa.js} +3444 -448
- package/out/server/index.js +2719 -308
- package/out/server/plugin-host.js +7 -3
- package/package.json +7 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/anthropic-messages-BWGCKOF4.js +0 -6
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-44DLKSKE.js +0 -1234
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-62VOPMLK.js +0 -65
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-7O7QKK6A.js +0 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-CHWNPHIS.js +0 -82
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-NL4X6LBY.js +0 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-NZY7EIPA.js +0 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-R2EGYMOO.js +0 -7
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-UKVNB6C4.js +0 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-USJZMAIR.js +0 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/chunk-VOLAXWGI.js +0 -2
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-codex-responses-QAWLOQSN.js +0 -10
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/openai-responses-MD3562FB.js +0 -4
- package/out/node_modules/@earendil-works/pi-coding-agent/dist/bundle/chunks/virtual-modules-O76XM3OB.js +0 -2
- package/out/phone/assets/architecture-7GRP2DOG-CQOPTv6S.js +0 -1
- package/out/phone/assets/channel-DdXebl9x.js +0 -1
- package/out/phone/assets/classDiagram-ZZMXUADV-BCctWEp1.js +0 -1
- package/out/phone/assets/classDiagram-v2-VYDZK3BY-BCctWEp1.js +0 -1
- package/out/phone/assets/desk-mfuEW2n4.js +0 -2
- package/out/phone/assets/eventmodeling-NTZA5JFV-BtfapP6M.js +0 -1
- package/out/phone/assets/flowDiagram-HODETNUW-BsyiyBtD.js +0 -1
- package/out/phone/assets/main-Dv9ve8mT.css +0 -1
- package/out/phone/assets/main-uMMbioCA.js +0 -1638
- package/out/phone/assets/railroad-abnf-HS5TGJTU-TmODpceI.js +0 -1
- package/out/phone/assets/railroad-ebnf-LZEXJU2U-BTCjNR9u.js +0 -1
- package/out/phone/assets/railroad-peg-WCYAUIDC-DjhKNo8j.js +0 -1
- package/out/phone/assets/stateDiagram-v2-MP3YSRHH-Cncmf_cL.js +0 -1
- package/out/phone/assets/storage-D9RW_4__.js +0 -1
- package/out/phone/assets/swimlanesDiagram-VR7AAH4N-DAahG4fH.js +0 -8
- package/out/renderer/assets/channel-CudRig7z.js +0 -1
- package/out/renderer/assets/classDiagram-ZZMXUADV-DL20WkD0.js +0 -1
- package/out/renderer/assets/classDiagram-v2-VYDZK3BY-DL20WkD0.js +0 -1
- package/out/renderer/assets/globals-Bkw7iiQG.css +0 -1
- package/out/renderer/assets/index-Cm5iq85v.js +0 -117
- package/out/renderer/assets/settings-DxYo7s4h.js +0 -34
- package/out/renderer/assets/stateDiagram-v2-MP3YSRHH-C9dfLXR8.js +0 -1
- package/out/renderer/assets/swimlanesDiagram-VR7AAH4N-LXwy6qGO.js +0 -8
|
@@ -1,117 +0,0 @@
|
|
|
1
|
-
import{r as m,eH as Ne,eI as Ws,j as i,c as nt,eJ as Av,eK as Mv,eL as mP,eM as ok,eN as gP,bi as rk,q as Ce,eO as gn,eP as Fh,eQ as uf,eR as xP,eS as vP,eT as bP,p as Q,dd as ak,au as sd,X as an,aQ as wP,cM as fi,e as q,c_ as lk,ci as Go,aB as ta,eU as yP,eV as SP,eW as dk,cl as CP,eX as ck,cm as ma,bQ as na,dp as Fi,cP as rg,eY as kP,ax as ag,eZ as jP,e_ as _P,e$ as NP,f0 as TP,f1 as Nl,f2 as ga,f3 as co,f4 as DP,f5 as IP,f6 as EP,f7 as ms,f8 as Cc,f9 as PP,fa as AP,fb as Tl,fc as Dl,fd as Ti,fe as Hh,ff as MP,fg as kc,fh as _r,fi as RP,fj as LP,fk as OP,fl as zP,fm as GP,fn as FP,fo as Bh,fp as Fr,fq as Rv,fr as uk,fs as Lv,ft as HP,fu as BP,fv as qr,fw as VP,fx as ri,fy as $P,fz as rr,fA as hk,fB as Ov,fC as sa,fD as WP,fE as Dd,fF as UP,fG as KP,fH as qP,fI as YP,fJ as zv,fK as pk,fL as hf,fM as XP,fN as ZP,fO as fk,fP as JP,fQ as Gv,fR as mk,fS as QP,fT as eA,fU as pf,fV as tA,fW as gk,fX as nA,fY as sA,fZ as iA,f_ as oA,f$ as rA,g0 as Fv,g1 as aA,g2 as lA,g3 as dA,g4 as Hv,g5 as Vh,g6 as cA,g7 as uA,g8 as hA,g9 as xk,ga as Lr,gb as qa,gc as or,gd as vk,ge as $h,gf as ff,gg as pA,gh as Hu,gi as fA,gj as mA,gk as gA,gl as Ia,gm as xA,gn as vA,go as bA,gp as bk,gq as wA,gr as yA,gs as SA,gt as CA,gu as kA,gv as wk,gw as yk,gx as so,gy as jA,gz as _A,gA as Bv,gB as NA,cS as ia,cQ as id,cR as xa,bu as oa,es as Hs,$ as od,gC as TA,gD as DA,gE as IA,gF as EA,gG as PA,gH as AA,gI as MA,gJ as RA,gK as LA,gL as OA,gM as zA,gN as GA,a5 as lg,ah as FA,gO as HA,gP as BA,gQ as VA,gR as $A,gS as WA,gT as UA,gU as KA,a6 as Sk,gV as qA,gW as YA,gX as XA,gY as ZA,b as rd,gZ as JA,g_ as QA,g$ as eM,h0 as tM,h1 as nM,h2 as sM,d as iM,h3 as oM,h4 as rM,h5 as aM,h6 as lM,dk as dM,cs as Ck,et as Bu,h7 as cM,cV as kk,h8 as gs,cy as Un,bN as Vu,dB as zs,h9 as js,ha as ss,hb as uM,bb as $u,ba as hM,dj as re,cn as jk,bZ as Vn,bd as bn,hc as _k,hd as uo,he as ho,hf as po,hg as Ut,Z as kn,J as Be,hh as pM,aC as gr,hi as fM,hj as mM,dc as dg,bk as Fo,hk as Vv,ch as gM,hl as xM,at as qt,hm as $v,hn as Nk,ho as Tk,hp as vM,hq as bM,hr as Dk,hs as wM,ht as yM,hu as SM,hv as CM,hw as kM,hx as jM,hy as _M,hz as NM,hA as TM,hB as DM,hC as IM,hD as Id,hE as Ri,hF as Li,hG as Oi,aR as fs,hH as EM,hI as PM,hJ as AM,hK as Wv,bP as MM,hL as RM,hM as Ik,hN as LM,co as cg,hO as OM,hP as Ek,hQ as zM,cF as bo,s as wn,hR as GM,v as yn,x as Sn,y as Cn,E as On,hS as Uv,hT as FM,hU as HM,ev as Pk,hV as BM,hW as VM,hX as $M,B as ge,eo as ui,b4 as mf,ee as Kv,bJ as ug,bf as Ea,bj as ni,hY as Ak,hZ as WM,h_ as Mk,h$ as UM,i0 as KM,i1 as qM,i2 as YM,i3 as gf,i4 as Rk,i5 as XM,i6 as ZM,bv as Gs,i7 as JM,i8 as QM,i9 as eR,ia as tR,ib as nR,ic as sR,id as iR,ie as Lk,ig as qv,ih as Yv,ii as oR,ij as Xv,ik as xf,il as vf,im as Hr,io as rR,ip as aR,iq as lR,ir as Zv,is as dR,it as cR,iu as uR,iv as Jv,iw as hR,ix as Wh,iy as Uh,iz as pR,ec as ad,ed as Ok,bt as ds,iA as ld,bM as Fs,iB as fR,iC as mR,iD as gR,iE as xR,iF as vR,iG as bR,iH as wR,ck as fo,iI as yR,iJ as zk,iK as ce,iL as SR,iM as Kc,iN as Gk,iO as qc,e9 as CR,iP as kR,eq as Fk,d9 as hr,cN as Il,iQ as jR,iR as Hk,iS as Qv,cH as Ai,iT as _R,iU as NR,iV as TR,iW as Bk,bI as tn,iX as Vk,iY as DR,iZ as IR,i_ as mo,i$ as ER,j0 as $k,j1 as Wk,j2 as Uk,j3 as El,j4 as PR,j5 as AR,j6 as MR,j7 as bf,j8 as RR,j9 as LR,ja as OR,jb as zR,jc as GR,jd as FR,je as HR,jf as BR,jg as VR,jh as $R,z as Bs,bh as WR,G as cs,ji as UR,bX as Kt,bg as hg,c2 as Kk,aS as Di,I as Xt,jj as e0,jk as t0,jl as n0,F as dd,jm as Pl,cd as Kh,e2 as qh,c3 as ei,jn as KR,jo as qk,jp as qR,jq as ys,jr as YR,eb as pg,O as xs,P as vs,Q as bs,R as ws,T as ns,bW as fg,js as wf,jt as yf,ju as Sf,bE as Wu,bF as Uu,bG as Ds,bH as oo,c1 as Yk,jv as Xk,jw as Zk,jx as sl,jy as Yc,jz as Jk,jA as XR,jB as ZR,jC as JR,jD as mg,jE as QR,jF as e2,jG as Qk,dS as Hi,dT as Bi,dV as Vi,dZ as pn,jH as ej,jI as tj,jJ as nj,dX as va,cq as gg,jK as sj,jL as Ku,jM as _s,b_ as ij,bT as t2,bU as n2,c4 as s2,jN as i2,c6 as o2,jO as r2,jP as oj,jQ as a2,jR as l2,jS as d2,jT as c2,jU as rj,jV as u2,jW as h2,jX as p2,jY as xr,jZ as xg,j_ as Ya,j$ as vg,k0 as bg,d3 as qu,d5 as Yu,cj as ti,d4 as Xu,ea as aj,eh as ba,k1 as f2,k2 as lj,k3 as dj,k4 as m2,k5 as il,av as wg,k6 as cj,k7 as yg,k8 as uj,ct as wa,k9 as hj,ka as g2,d7 as x2,d6 as v2,kb as b2,A as w2,kc as y2,kd as S2,n as C2,ke as k2,kf as j2,kg as _2,m as N2,kh as T2,ki as D2,C as I2,f as pj,h as E2,i as P2,k as A2,S as M2,l as R2,o as L2,kj as O2,kk as z2,kl as G2,km as F2,kn as H2,ko as B2,kp as fj,cL as ai,kq as V2,cp as ra,ex as Cf,kr as $2,ks as W2,kt as Sg,ku as mj,kv as gj,kw as xj,kx as Cg,ky as U2,kz as K2,kA as q2,bD as vj,bL as er,bC as Y2,kB as X2,kC as bj,kD as Nr,bK as s0,bS as Z2,kE as J2,b$ as i0,ek as Zu,kF as o0,cz as ts,kG as Q2,ew as eL,kH as wj,kI as tL,kJ as nL,kK as sL,dQ as iL,kL as yj,kM as kg,kN as oL,kO as rL,kP as jg,kQ as aL,kR as Sj,ep as lL,kS as dL,kT as cL,kU as uL,kV as Yh,kW as r0,kX as hL,el as Cj,kY as pL,kZ as _g,ef as fL,cC as Us,cD as Ks,k_ as kj,k$ as mL,l0 as gL,l1 as xL,l2 as vL,l3 as bL,er as Xc,l4 as wL,l5 as yL,l6 as SL,l7 as jj,l8 as CL,l9 as kL,cv as jL,la as _L,lb as _j,lc as Ng,ld as NL,df as Nj,le as TL,lf as a0,lg as DL,lh as IL,d1 as EL,d0 as PL,db as AL,eu as ML,li as Tj,lj as kf,aD as Dj,aE as Ij,aF as Ej,aG as Pj,aH as Aj,aI as Mj,lk as jc,ll as Rj,ej as RL,lm as jf,ln as LL,aK as Tg,lo as Zc,lp as Al,lq as aa,lr as _f,ls as OL,dD as Jc,lt as zL,aN as Ju,lu as Dg,e0 as l0,d$ as GL,lv as us,lw as Mn,lx as pr,ly as Lj,aO as FL,lz as Qc,lA as Po,ce as HL,lB as Oj,lC as ol,lD as Or,lE as BL,lF as zj,lG as VL,lH as $L,lI as WL,cx as d0,lJ as UL,lK as Gj,lL as c0,cr as u0,dU as Ig,lM as KL,cE as qL,lN as YL,lO as XL,lP as Nf,lQ as ZL,b3 as JL,cB as QL,lR as e5,eg as t5,dr as n5,lS as s5,dM as i5,dN as o5,cG as r5,lT as a5,ei as l5,e1 as d5,lU as c5,lV as u5,lW as Fj,lX as Eg,lY as Hj,lZ as h5,l_ as p5,l$ as f5,m0 as m5,m1 as g5,m2 as h0,m3 as Bj,m4 as Pg,de as x5,m5 as Qu,m6 as Ed,m7 as v5,m8 as b5,m9 as w5,ma as y5,mb as S5,mc as C5,md as k5,me as j5,mf as _5,mg as N5,mh as p0,mi as T5,mj as D5,mk as I5,ml as E5,cT as P5,bc as A5,mm as f0,bO as M5,cU as R5,cW as L5,mn as O5,mo as z5,mp as m0,mq as G5,mr as F5,ms as H5,mt as Tf,mu as Vj,mv as B5,mw as V5,mx as $5,my as W5,mz as $j,mA as U5,mB as K5,mC as q5,mD as Y5,mE as X5,mF as Z5,mG as Io,mH as J5,mI as Q5,mJ as eO,mK as tO,mL as nO,mM as sO,mN as iO,mO as g0,mP as oO,mQ as rO,mR as aO,mS as lO,mT as dO,ds as cO,mU as uO,mV as x0,mW as hO,mX as pO,mY as Wj,d_ as fO,mZ as mO,m_ as gO,m$ as xO,eF as vO,eB as bO,eG as v0,eC as wO,aJ as yO,n0 as SO,n1 as CO,n2 as kO,n3 as jO,n4 as _O,n5 as NO,n6 as TO,ey as DO,ez as IO,eA as EO}from"./globals-D1ocHHQV.js";function PO(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>s=>{t.forEach(o=>o(s))},t)}const eh=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ya(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function Ag(e){return"nodeType"in e}function Ns(e){var t,n;return e?ya(e)?e:Ag(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function Mg(e){const{Document:t}=Ns(e);return e instanceof t}function cd(e){return ya(e)?!1:e instanceof Ns(e).HTMLElement}function Uj(e){return e instanceof Ns(e).SVGElement}function Sa(e){return e?ya(e)?e.document:Ag(e)?Mg(e)?e:cd(e)||Uj(e)?e.ownerDocument:document:document:document}const mi=eh?m.useLayoutEffect:m.useEffect;function th(e){const t=m.useRef(e);return mi(()=>{t.current=e}),m.useCallback(function(){for(var n=arguments.length,s=new Array(n),o=0;o<n;o++)s[o]=arguments[o];return t.current==null?void 0:t.current(...s)},[])}function AO(){const e=m.useRef(null),t=m.useCallback((s,o)=>{e.current=setInterval(s,o)},[]),n=m.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Ml(e,t){t===void 0&&(t=[e]);const n=m.useRef(e);return mi(()=>{n.current!==e&&(n.current=e)},t),n}function ud(e,t){const n=m.useRef();return m.useMemo(()=>{const s=e(n.current);return n.current=s,s},[...t])}function eu(e){const t=th(e),n=m.useRef(null),s=m.useCallback(o=>{o!==n.current&&t?.(o,n.current),n.current=o},[]);return[n,s]}function tu(e){const t=m.useRef();return m.useEffect(()=>{t.current=e},[e]),t.current}let Xh={};function hd(e,t){return m.useMemo(()=>{if(t)return t;const n=Xh[e]==null?0:Xh[e]+1;return Xh[e]=n,e+"-"+n},[e,t])}function Kj(e){return function(t){for(var n=arguments.length,s=new Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];return s.reduce((r,a)=>{const l=Object.entries(a);for(const[d,c]of l){const u=r[d];u!=null&&(r[d]=u+e*c)}return r},{...t})}}const Yr=Kj(1),nu=Kj(-1);function MO(e){return"clientX"in e&&"clientY"in e}function nh(e){if(!e)return!1;const{KeyboardEvent:t}=Ns(e.target);return t&&e instanceof t}function RO(e){if(!e)return!1;const{TouchEvent:t}=Ns(e.target);return t&&e instanceof t}function su(e){if(RO(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return MO(e)?{x:e.clientX,y:e.clientY}:null}const zi=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[zi.Translate.toString(e),zi.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:s}=e;return t+" "+n+"ms "+s}}}),b0="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function LO(e){return e.matches(b0)?e:e.querySelector(b0)}const OO={display:"none"};function zO(e){let{id:t,value:n}=e;return Ne.createElement("div",{id:t,style:OO},n)}function GO(e){let{id:t,announcement:n,ariaLiveType:s="assertive"}=e;const o={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ne.createElement("div",{id:t,style:o,role:"status","aria-live":s,"aria-atomic":!0},n)}function FO(){const[e,t]=m.useState("");return{announce:m.useCallback(s=>{s!=null&&t(s)},[]),announcement:e}}const qj=m.createContext(null);function Yj(e){const t=m.useContext(qj);m.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of <DndContext>");return t(e)},[e,t])}function HO(){const[e]=m.useState(()=>new Set),t=m.useCallback(s=>(e.add(s),()=>e.delete(s)),[e]);return[m.useCallback(s=>{let{type:o,event:r}=s;e.forEach(a=>{var l;return(l=a[o])==null?void 0:l.call(a,r)})},[e]),t]}const BO={draggable:`
|
|
2
|
-
To pick up a draggable item, press the space bar.
|
|
3
|
-
While dragging, use the arrow keys to move the item.
|
|
4
|
-
Press space again to drop the item in its new position, or press escape to cancel.
|
|
5
|
-
`},VO={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function $O(e){let{announcements:t=VO,container:n,hiddenTextDescribedById:s,screenReaderInstructions:o=BO}=e;const{announce:r,announcement:a}=FO(),l=hd("DndLiveRegion"),[d,c]=m.useState(!1);if(m.useEffect(()=>{c(!0)},[]),Yj(m.useMemo(()=>({onDragStart(h){let{active:p}=h;r(t.onDragStart({active:p}))},onDragMove(h){let{active:p,over:f}=h;t.onDragMove&&r(t.onDragMove({active:p,over:f}))},onDragOver(h){let{active:p,over:f}=h;r(t.onDragOver({active:p,over:f}))},onDragEnd(h){let{active:p,over:f}=h;r(t.onDragEnd({active:p,over:f}))},onDragCancel(h){let{active:p,over:f}=h;r(t.onDragCancel({active:p,over:f}))}}),[r,t])),!d)return null;const u=Ne.createElement(Ne.Fragment,null,Ne.createElement(zO,{id:s,value:o.draggable}),Ne.createElement(GO,{id:l,announcement:a}));return n?Ws.createPortal(u,n):u}var Zn;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(Zn||(Zn={}));function iu(){}function WO(e,t){return m.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function UO(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return m.useMemo(()=>[...t].filter(s=>s!=null),[...t])}const gi=Object.freeze({x:0,y:0});function KO(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function qO(e,t){const n=su(e);if(!n)return"0 0";const s={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return s.x+"% "+s.y+"%"}function YO(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return n-s}function XO(e,t){let{data:{value:n}}=e,{data:{value:s}}=t;return s-n}function ZO(e){let{left:t,top:n,height:s,width:o}=e;return[{x:t,y:n},{x:t+o,y:n},{x:t,y:n+s},{x:t+o,y:n+s}]}function JO(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function QO(e,t){const n=Math.max(t.top,e.top),s=Math.max(t.left,e.left),o=Math.min(t.left+t.width,e.left+e.width),r=Math.min(t.top+t.height,e.top+e.height),a=o-s,l=r-n;if(s<o&&n<r){const d=t.width*t.height,c=e.width*e.height,u=a*l,h=u/(d+c-u);return Number(h.toFixed(4))}return 0}const Xj=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:s}=e;const o=[];for(const r of s){const{id:a}=r,l=n.get(a);if(l){const d=QO(l,t);d>0&&o.push({id:a,data:{droppableContainer:r,value:d}})}}return o.sort(XO)};function ez(e,t){const{top:n,left:s,bottom:o,right:r}=t;return n<=e.y&&e.y<=o&&s<=e.x&&e.x<=r}const tz=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:s}=e;if(!s)return[];const o=[];for(const r of t){const{id:a}=r,l=n.get(a);if(l&&ez(s,l)){const c=ZO(l).reduce((h,p)=>h+KO(s,p),0),u=Number((c/4).toFixed(4));o.push({id:a,data:{droppableContainer:r,value:u}})}}return o.sort(YO)};function nz(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Zj(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:gi}function sz(e){return function(n){for(var s=arguments.length,o=new Array(s>1?s-1:0),r=1;r<s;r++)o[r-1]=arguments[r];return o.reduce((a,l)=>({...a,top:a.top+e*l.y,bottom:a.bottom+e*l.y,left:a.left+e*l.x,right:a.right+e*l.x}),{...n})}}const iz=sz(1);function Jj(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function oz(e,t,n){const s=Jj(t);if(!s)return e;const{scaleX:o,scaleY:r,x:a,y:l}=s,d=e.left-a-(1-o)*parseFloat(n),c=e.top-l-(1-r)*parseFloat(n.slice(n.indexOf(" ")+1)),u=o?e.width/o:e.width,h=r?e.height/r:e.height;return{width:u,height:h,top:c,right:d+u,bottom:c+h,left:d}}const rz={ignoreTransform:!1};function Ca(e,t){t===void 0&&(t=rz);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:u}=Ns(e).getComputedStyle(e);c&&(n=oz(n,c,u))}const{top:s,left:o,width:r,height:a,bottom:l,right:d}=n;return{top:s,left:o,width:r,height:a,bottom:l,right:d}}function w0(e){return Ca(e,{ignoreTransform:!0})}function az(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function lz(e,t){return t===void 0&&(t=Ns(e).getComputedStyle(e)),t.position==="fixed"}function dz(e,t){t===void 0&&(t=Ns(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(o=>{const r=t[o];return typeof r=="string"?n.test(r):!1})}function Rg(e,t){const n=[];function s(o){if(t!=null&&n.length>=t||!o)return n;if(Mg(o)&&o.scrollingElement!=null&&!n.includes(o.scrollingElement))return n.push(o.scrollingElement),n;if(!cd(o)||Uj(o)||n.includes(o))return n;const r=Ns(e).getComputedStyle(o);return o!==e&&dz(o,r)&&n.push(o),lz(o,r)?n:s(o.parentNode)}return e?s(e):n}function Qj(e){const[t]=Rg(e,1);return t??null}function Zh(e){return!eh||!e?null:ya(e)?e:Ag(e)?Mg(e)||e===Sa(e).scrollingElement?window:cd(e)?e:null:null}function e_(e){return ya(e)?e.scrollX:e.scrollLeft}function t_(e){return ya(e)?e.scrollY:e.scrollTop}function Df(e){return{x:e_(e),y:t_(e)}}var es;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(es||(es={}));function n_(e){return!eh||!e?!1:e===document.scrollingElement}function s_(e){const t={x:0,y:0},n=n_(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},s={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},o=e.scrollTop<=t.y,r=e.scrollLeft<=t.x,a=e.scrollTop>=s.y,l=e.scrollLeft>=s.x;return{isTop:o,isLeft:r,isBottom:a,isRight:l,maxScroll:s,minScroll:t}}const cz={x:.2,y:.2};function uz(e,t,n,s,o){let{top:r,left:a,right:l,bottom:d}=n;s===void 0&&(s=10),o===void 0&&(o=cz);const{isTop:c,isBottom:u,isLeft:h,isRight:p}=s_(e),f={x:0,y:0},g={x:0,y:0},x={height:t.height*o.y,width:t.width*o.x};return!c&&r<=t.top+x.height?(f.y=es.Backward,g.y=s*Math.abs((t.top+x.height-r)/x.height)):!u&&d>=t.bottom-x.height&&(f.y=es.Forward,g.y=s*Math.abs((t.bottom-x.height-d)/x.height)),!p&&l>=t.right-x.width?(f.x=es.Forward,g.x=s*Math.abs((t.right-x.width-l)/x.width)):!h&&a<=t.left+x.width&&(f.x=es.Backward,g.x=s*Math.abs((t.left+x.width-a)/x.width)),{direction:f,speed:g}}function hz(e){if(e===document.scrollingElement){const{innerWidth:r,innerHeight:a}=window;return{top:0,left:0,right:r,bottom:a,width:r,height:a}}const{top:t,left:n,right:s,bottom:o}=e.getBoundingClientRect();return{top:t,left:n,right:s,bottom:o,width:e.clientWidth,height:e.clientHeight}}function i_(e){return e.reduce((t,n)=>Yr(t,Df(n)),gi)}function pz(e){return e.reduce((t,n)=>t+e_(n),0)}function fz(e){return e.reduce((t,n)=>t+t_(n),0)}function o_(e,t){if(t===void 0&&(t=Ca),!e)return;const{top:n,left:s,bottom:o,right:r}=t(e);Qj(e)&&(o<=0||r<=0||n>=window.innerHeight||s>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const mz=[["x",["left","right"],pz],["y",["top","bottom"],fz]];class Lg{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const s=Rg(n),o=i_(s);this.rect={...t},this.width=t.width,this.height=t.height;for(const[r,a,l]of mz)for(const d of a)Object.defineProperty(this,d,{get:()=>{const c=l(s),u=o[r]-c;return this.rect[d]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class rl{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var s;return(s=this.target)==null?void 0:s.removeEventListener(...n)})},this.target=t}add(t,n,s){var o;(o=this.target)==null||o.addEventListener(t,n,s),this.listeners.push([t,n,s])}}function gz(e){const{EventTarget:t}=Ns(e);return e instanceof t?e:Sa(e)}function Jh(e,t){const n=Math.abs(e.x),s=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+s**2)>t:"x"in t&&"y"in t?n>t.x&&s>t.y:"x"in t?n>t.x:"y"in t?s>t.y:!1}var $s;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})($s||($s={}));function y0(e){e.preventDefault()}function xz(e){e.stopPropagation()}var hn;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(hn||(hn={}));const r_={start:[hn.Space,hn.Enter],cancel:[hn.Esc],end:[hn.Space,hn.Enter,hn.Tab]},vz=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case hn.Right:return{...n,x:n.x+25};case hn.Left:return{...n,x:n.x-25};case hn.Down:return{...n,y:n.y+25};case hn.Up:return{...n,y:n.y-25}}};class a_{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new rl(Sa(n)),this.windowListeners=new rl(Ns(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add($s.Resize,this.handleCancel),this.windowListeners.add($s.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add($s.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,s=t.node.current;s&&o_(s),n(gi)}handleKeyDown(t){if(nh(t)){const{active:n,context:s,options:o}=this.props,{keyboardCodes:r=r_,coordinateGetter:a=vz,scrollBehavior:l="smooth"}=o,{code:d}=t;if(r.end.includes(d)){this.handleEnd(t);return}if(r.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:c}=s.current,u=c?{x:c.left,y:c.top}:gi;this.referenceCoordinates||(this.referenceCoordinates=u);const h=a(t,{active:n,context:s.current,currentCoordinates:u});if(h){const p=nu(h,u),f={x:0,y:0},{scrollableAncestors:g}=s.current;for(const x of g){const v=t.code,{isTop:y,isRight:w,isLeft:b,isBottom:_,maxScroll:j,minScroll:N}=s_(x),C=hz(x),S={x:Math.min(v===hn.Right?C.right-C.width/2:C.right,Math.max(v===hn.Right?C.left:C.left+C.width/2,h.x)),y:Math.min(v===hn.Down?C.bottom-C.height/2:C.bottom,Math.max(v===hn.Down?C.top:C.top+C.height/2,h.y))},A=v===hn.Right&&!w||v===hn.Left&&!b,E=v===hn.Down&&!_||v===hn.Up&&!y;if(A&&S.x!==h.x){const I=x.scrollLeft+p.x,D=v===hn.Right&&I<=j.x||v===hn.Left&&I>=N.x;if(D&&!p.y){x.scrollTo({left:I,behavior:l});return}D?f.x=x.scrollLeft-I:f.x=v===hn.Right?x.scrollLeft-j.x:x.scrollLeft-N.x,f.x&&x.scrollBy({left:-f.x,behavior:l});break}else if(E&&S.y!==h.y){const I=x.scrollTop+p.y,D=v===hn.Down&&I<=j.y||v===hn.Up&&I>=N.y;if(D&&!p.x){x.scrollTo({top:I,behavior:l});return}D?f.y=x.scrollTop-I:f.y=v===hn.Down?x.scrollTop-j.y:x.scrollTop-N.y,f.y&&x.scrollBy({top:-f.y,behavior:l});break}}this.handleMove(t,Yr(nu(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:s}=this.props;t.preventDefault(),s(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}a_.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:s=r_,onActivation:o}=t,{active:r}=n;const{code:a}=e.nativeEvent;if(s.start.includes(a)){const l=r.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),o?.({event:e.nativeEvent}),!0)}return!1}}];function S0(e){return!!(e&&"distance"in e)}function C0(e){return!!(e&&"delay"in e)}class Og{constructor(t,n,s){var o;s===void 0&&(s=gz(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:r}=t,{target:a}=r;this.props=t,this.events=n,this.document=Sa(a),this.documentListeners=new rl(this.document),this.listeners=new rl(s),this.windowListeners=new rl(Ns(a)),this.initialCoordinates=(o=su(r))!=null?o:gi,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:s}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add($s.Resize,this.handleCancel),this.windowListeners.add($s.DragStart,y0),this.windowListeners.add($s.VisibilityChange,this.handleCancel),this.windowListeners.add($s.ContextMenu,y0),this.documentListeners.add($s.Keydown,this.handleKeydown),n){if(s!=null&&s({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(C0(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(S0(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:s,onPending:o}=this.props;o(s,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add($s.Click,xz,{capture:!0}),this.removeTextSelection(),this.documentListeners.add($s.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:s,initialCoordinates:o,props:r}=this,{onMove:a,options:{activationConstraint:l}}=r;if(!o)return;const d=(n=su(t))!=null?n:gi,c=nu(o,d);if(!s&&l){if(S0(l)){if(l.tolerance!=null&&Jh(c,l.tolerance))return this.handleCancel();if(Jh(c,l.distance))return this.handleStart()}if(C0(l)&&Jh(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),a(d)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===hn.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const bz={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class zg extends Og{constructor(t){const{event:n}=t,s=Sa(n.target);super(t,bz,s)}}zg.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return!n.isPrimary||n.button!==0?!1:(s?.({event:n}),!0)}}];const wz={move:{name:"mousemove"},end:{name:"mouseup"}};var If;(function(e){e[e.RightClick=2]="RightClick"})(If||(If={}));class yz extends Og{constructor(t){super(t,wz,Sa(t.event.target))}}yz.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;return n.button===If.RightClick?!1:(s?.({event:n}),!0)}}];const Qh={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class Sz extends Og{constructor(t){super(t,Qh)}static setup(){return window.addEventListener(Qh.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(Qh.move.name,t)};function t(){}}}Sz.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:s}=t;const{touches:o}=n;return o.length>1?!1:(s?.({event:n}),!0)}}];var al;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(al||(al={}));var ou;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ou||(ou={}));function Cz(e){let{acceleration:t,activator:n=al.Pointer,canScroll:s,draggingRect:o,enabled:r,interval:a=5,order:l=ou.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:u,delta:h,threshold:p}=e;const f=jz({delta:h,disabled:!r}),[g,x]=AO(),v=m.useRef({x:0,y:0}),y=m.useRef({x:0,y:0}),w=m.useMemo(()=>{switch(n){case al.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case al.DraggableRect:return o}},[n,o,d]),b=m.useRef(null),_=m.useCallback(()=>{const N=b.current;if(!N)return;const C=v.current.x*y.current.x,S=v.current.y*y.current.y;N.scrollBy(C,S)},[]),j=m.useMemo(()=>l===ou.TreeOrder?[...c].reverse():c,[l,c]);m.useEffect(()=>{if(!r||!c.length||!w){x();return}for(const N of j){if(s?.(N)===!1)continue;const C=c.indexOf(N),S=u[C];if(!S)continue;const{direction:A,speed:E}=uz(N,S,w,t,p);for(const I of["x","y"])f[I][A[I]]||(E[I]=0,A[I]=0);if(E.x>0||E.y>0){x(),b.current=N,g(_,a),v.current=E,y.current=A;return}}v.current={x:0,y:0},y.current={x:0,y:0},x()},[t,_,s,x,r,a,JSON.stringify(w),JSON.stringify(f),g,c,j,u,JSON.stringify(p)])}const kz={x:{[es.Backward]:!1,[es.Forward]:!1},y:{[es.Backward]:!1,[es.Forward]:!1}};function jz(e){let{delta:t,disabled:n}=e;const s=tu(t);return ud(o=>{if(n||!s||!o)return kz;const r={x:Math.sign(t.x-s.x),y:Math.sign(t.y-s.y)};return{x:{[es.Backward]:o.x[es.Backward]||r.x===-1,[es.Forward]:o.x[es.Forward]||r.x===1},y:{[es.Backward]:o.y[es.Backward]||r.y===-1,[es.Forward]:o.y[es.Forward]||r.y===1}}},[n,t,s])}function _z(e,t){const n=t!=null?e.get(t):void 0,s=n?n.node.current:null;return ud(o=>{var r;return t==null?null:(r=s??o)!=null?r:null},[s,t])}function Nz(e,t){return m.useMemo(()=>e.reduce((n,s)=>{const{sensor:o}=s,r=o.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,s)}));return[...n,...r]},[]),[e,t])}var Rl;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Rl||(Rl={}));var Ef;(function(e){e.Optimized="optimized"})(Ef||(Ef={}));const k0=new Map;function Tz(e,t){let{dragging:n,dependencies:s,config:o}=t;const[r,a]=m.useState(null),{frequency:l,measure:d,strategy:c}=o,u=m.useRef(e),h=v(),p=Ml(h),f=m.useCallback(function(y){y===void 0&&(y=[]),!p.current&&a(w=>w===null?y:w.concat(y.filter(b=>!w.includes(b))))},[p]),g=m.useRef(null),x=ud(y=>{if(h&&!n)return k0;if(!y||y===k0||u.current!==e||r!=null){const w=new Map;for(let b of e){if(!b)continue;if(r&&r.length>0&&!r.includes(b.id)&&b.rect.current){w.set(b.id,b.rect.current);continue}const _=b.node.current,j=_?new Lg(d(_),_):null;b.rect.current=j,j&&w.set(b.id,j)}return w}return y},[e,r,n,h,d]);return m.useEffect(()=>{u.current=e},[e]),m.useEffect(()=>{h||f()},[n,h]),m.useEffect(()=>{r&&r.length>0&&a(null)},[JSON.stringify(r)]),m.useEffect(()=>{h||typeof l!="number"||g.current!==null||(g.current=setTimeout(()=>{f(),g.current=null},l))},[l,h,f,...s]),{droppableRects:x,measureDroppableContainers:f,measuringScheduled:r!=null};function v(){switch(c){case Rl.Always:return!1;case Rl.BeforeDragging:return n;default:return!n}}}function Gg(e,t){return ud(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function Dz(e,t){return Gg(e,t)}function Iz(e){let{callback:t,disabled:n}=e;const s=th(t),o=m.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:r}=window;return new r(s)},[s,n]);return m.useEffect(()=>()=>o?.disconnect(),[o]),o}function sh(e){let{callback:t,disabled:n}=e;const s=th(t),o=m.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:r}=window;return new r(s)},[n]);return m.useEffect(()=>()=>o?.disconnect(),[o]),o}function Ez(e){return new Lg(Ca(e),e)}function j0(e,t,n){t===void 0&&(t=Ez);const[s,o]=m.useState(null);function r(){o(d=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=d??n)!=null?c:null}const u=t(e);return JSON.stringify(d)===JSON.stringify(u)?d:u})}const a=Iz({callback(d){if(e)for(const c of d){const{type:u,target:h}=c;if(u==="childList"&&h instanceof HTMLElement&&h.contains(e)){r();break}}}}),l=sh({callback:r});return mi(()=>{r(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),s}function Pz(e){const t=Gg(e);return Zj(e,t)}const _0=[];function Az(e){const t=m.useRef(e),n=ud(s=>e?s&&s!==_0&&e&&t.current&&e.parentNode===t.current.parentNode?s:Rg(e):_0,[e]);return m.useEffect(()=>{t.current=e},[e]),n}function Mz(e){const[t,n]=m.useState(null),s=m.useRef(e),o=m.useCallback(r=>{const a=Zh(r.target);a&&n(l=>l?(l.set(a,Df(a)),new Map(l)):null)},[]);return m.useEffect(()=>{const r=s.current;if(e!==r){a(r);const l=e.map(d=>{const c=Zh(d);return c?(c.addEventListener("scroll",o,{passive:!0}),[c,Df(c)]):null}).filter(d=>d!=null);n(l.length?new Map(l):null),s.current=e}return()=>{a(e),a(r)};function a(l){l.forEach(d=>{const c=Zh(d);c?.removeEventListener("scroll",o)})}},[o,e]),m.useMemo(()=>e.length?t?Array.from(t.values()).reduce((r,a)=>Yr(r,a),gi):i_(e):gi,[e,t])}function N0(e,t){t===void 0&&(t=[]);const n=m.useRef(null);return m.useEffect(()=>{n.current=null},t),m.useEffect(()=>{const s=e!==gi;s&&!n.current&&(n.current=e),!s&&n.current&&(n.current=null)},[e]),n.current?nu(e,n.current):gi}function Rz(e){m.useEffect(()=>{if(!eh)return;const t=e.map(n=>{let{sensor:s}=n;return s.setup==null?void 0:s.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function Lz(e,t){return m.useMemo(()=>e.reduce((n,s)=>{let{eventName:o,handler:r}=s;return n[o]=a=>{r(a,t)},n},{}),[e,t])}function l_(e){return m.useMemo(()=>e?az(e):null,[e])}const T0=[];function Oz(e,t){t===void 0&&(t=Ca);const[n]=e,s=l_(n?Ns(n):null),[o,r]=m.useState(T0);function a(){r(()=>e.length?e.map(d=>n_(d)?s:new Lg(t(d),d)):T0)}const l=sh({callback:a});return mi(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),o}function d_(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return cd(t)?t:e}function zz(e){let{measure:t}=e;const[n,s]=m.useState(null),o=m.useCallback(c=>{for(const{target:u}of c)if(cd(u)){s(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),r=sh({callback:o}),a=m.useCallback(c=>{const u=d_(c);r?.disconnect(),u&&r?.observe(u),s(u?t(u):null)},[t,r]),[l,d]=eu(a);return m.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const Gz=[{sensor:zg,options:{}},{sensor:a_,options:{}}],Fz={current:{}},_c={draggable:{measure:w0},droppable:{measure:w0,strategy:Rl.WhileDragging,frequency:Ef.Optimized},dragOverlay:{measure:Ca}};class ll extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,s;return(n=(s=this.get(t))==null?void 0:s.node.current)!=null?n:void 0}}const Hz={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new ll,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:iu},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:_c,measureDroppableContainers:iu,windowRect:null,measuringScheduled:!1},c_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:iu,draggableNodes:new Map,over:null,measureDroppableContainers:iu},pd=m.createContext(c_),u_=m.createContext(Hz);function Bz(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new ll}}}function Vz(e,t){switch(t.type){case Zn.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Zn.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case Zn.DragEnd:case Zn.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Zn.RegisterDroppable:{const{element:n}=t,{id:s}=n,o=new ll(e.droppable.containers);return o.set(s,n),{...e,droppable:{...e.droppable,containers:o}}}case Zn.SetDroppableDisabled:{const{id:n,key:s,disabled:o}=t,r=e.droppable.containers.get(n);if(!r||s!==r.key)return e;const a=new ll(e.droppable.containers);return a.set(n,{...r,disabled:o}),{...e,droppable:{...e.droppable,containers:a}}}case Zn.UnregisterDroppable:{const{id:n,key:s}=t,o=e.droppable.containers.get(n);if(!o||s!==o.key)return e;const r=new ll(e.droppable.containers);return r.delete(n),{...e,droppable:{...e.droppable,containers:r}}}default:return e}}function $z(e){let{disabled:t}=e;const{active:n,activatorEvent:s,draggableNodes:o}=m.useContext(pd),r=tu(s),a=tu(n?.id);return m.useEffect(()=>{if(!t&&!s&&r&&a!=null){if(!nh(r)||document.activeElement===r.target)return;const l=o.get(a);if(!l)return;const{activatorNode:d,node:c}=l;if(!d.current&&!c.current)return;requestAnimationFrame(()=>{for(const u of[d.current,c.current]){if(!u)continue;const h=LO(u);if(h){h.focus();break}}})}},[s,t,o,a,r]),null}function h_(e,t){let{transform:n,...s}=t;return e!=null&&e.length?e.reduce((o,r)=>r({transform:o,...s}),n):n}function Wz(e){return m.useMemo(()=>({draggable:{..._c.draggable,...e?.draggable},droppable:{..._c.droppable,...e?.droppable},dragOverlay:{..._c.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function Uz(e){let{activeNode:t,measure:n,initialRect:s,config:o=!0}=e;const r=m.useRef(!1),{x:a,y:l}=typeof o=="boolean"?{x:o,y:o}:o;mi(()=>{if(!a&&!l||!t){r.current=!1;return}if(r.current||!s)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const u=n(c),h=Zj(u,s);if(a||(h.x=0),l||(h.y=0),r.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const p=Qj(c);p&&p.scrollBy({top:h.y,left:h.x})}},[t,a,l,s,n])}const ih=m.createContext({...gi,scaleX:1,scaleY:1});var No;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(No||(No={}));const Kz=m.memo(function(t){var n,s,o,r;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:u=Gz,collisionDetection:h=Xj,measuring:p,modifiers:f,...g}=t;const x=m.useReducer(Vz,void 0,Bz),[v,y]=x,[w,b]=HO(),[_,j]=m.useState(No.Uninitialized),N=_===No.Initialized,{draggable:{active:C,nodes:S,translate:A},droppable:{containers:E}}=v,I=C!=null?S.get(C):null,D=m.useRef({initial:null,translated:null}),T=m.useMemo(()=>{var bt;return C!=null?{id:C,data:(bt=I?.data)!=null?bt:Fz,rect:D}:null},[C,I]),z=m.useRef(null),[$,R]=m.useState(null),[B,H]=m.useState(null),oe=Ml(g,Object.values(g)),te=hd("DndDescribedBy",a),O=m.useMemo(()=>E.getEnabled(),[E]),V=Wz(p),{droppableRects:J,measureDroppableContainers:pe,measuringScheduled:fe}=Tz(O,{dragging:N,dependencies:[A.x,A.y],config:V.droppable}),_e=_z(S,C),Ee=m.useMemo(()=>B?su(B):null,[B]),me=tt(),W=Dz(_e,V.draggable.measure);Uz({activeNode:C!=null?S.get(C):null,config:me.layoutShiftCompensation,initialRect:W,measure:V.draggable.measure});const G=j0(_e,V.draggable.measure,W),de=j0(_e?_e.parentElement:null),X=m.useRef({activatorEvent:null,active:null,activeNode:_e,collisionRect:null,collisions:null,droppableRects:J,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ie=E.getNodeFor((n=X.current.over)==null?void 0:n.id),Z=zz({measure:V.dragOverlay.measure}),le=(s=Z.nodeRef.current)!=null?s:_e,be=N?(o=Z.rect)!=null?o:G:null,Fe=!!(Z.nodeRef.current&&Z.rect),Je=Pz(Fe?null:G),We=l_(le?Ns(le):null),et=Az(N?ie??_e:null),qe=Oz(et),Lt=h_(f,{transform:{x:A.x-Je.x,y:A.y-Je.y,scaleX:1,scaleY:1},activatorEvent:B,active:T,activeNodeRect:G,containerNodeRect:de,draggingNodeRect:be,over:X.current.over,overlayNodeRect:Z.rect,scrollableAncestors:et,scrollableAncestorRects:qe,windowRect:We}),Bt=Ee?Yr(Ee,A):null,Mt=Mz(et),ne=N0(Mt),se=N0(Mt,[G]),He=Yr(Lt,ne),kt=be?iz(be,Lt):null,st=T&&kt?h({active:T,collisionRect:kt,droppableRects:J,droppableContainers:O,pointerCoordinates:Bt}):null,ke=JO(st,"id"),[ut,ft]=m.useState(null),ze=Fe?Lt:Yr(Lt,se),wt=nz(ze,(r=ut?.rect)!=null?r:null,G),Y=m.useRef(null),U=m.useCallback((bt,Vt)=>{let{sensor:Jt,options:un}=Vt;if(z.current==null)return;const nn=S.get(z.current);if(!nn)return;const Ie=bt.nativeEvent,it=new Jt({active:z.current,activeNode:nn,event:Ie,options:un,context:X,onAbort(jt){if(!S.get(jt))return;const{onDragAbort:dn}=oe.current,P={id:jt};dn?.(P),w({type:"onDragAbort",event:P})},onPending(jt,Rt,dn,P){if(!S.get(jt))return;const{onDragPending:L}=oe.current,k={id:jt,constraint:Rt,initialCoordinates:dn,offset:P};L?.(k),w({type:"onDragPending",event:k})},onStart(jt){const Rt=z.current;if(Rt==null)return;const dn=S.get(Rt);if(!dn)return;const{onDragStart:P}=oe.current,M={activatorEvent:Ie,active:{id:Rt,data:dn.data,rect:D}};Ws.unstable_batchedUpdates(()=>{P?.(M),j(No.Initializing),y({type:Zn.DragStart,initialCoordinates:jt,active:Rt}),w({type:"onDragStart",event:M}),R(Y.current),H(Ie)})},onMove(jt){y({type:Zn.DragMove,coordinates:jt})},onEnd:dt(Zn.DragEnd),onCancel:dt(Zn.DragCancel)});Y.current=it;function dt(jt){return async function(){const{active:dn,collisions:P,over:M,scrollAdjustedTranslate:L}=X.current;let k=null;if(dn&&L){const{cancelDrop:F}=oe.current;k={activatorEvent:Ie,active:dn,collisions:P,delta:L,over:M},jt===Zn.DragEnd&&typeof F=="function"&&await Promise.resolve(F(k))&&(jt=Zn.DragCancel)}z.current=null,Ws.unstable_batchedUpdates(()=>{y({type:jt}),j(No.Uninitialized),ft(null),R(null),H(null),Y.current=null;const F=jt===Zn.DragEnd?"onDragEnd":"onDragCancel";if(k){const he=oe.current[F];he?.(k),w({type:F,event:k})}})}}},[S]),ue=m.useCallback((bt,Vt)=>(Jt,un)=>{const nn=Jt.nativeEvent,Ie=S.get(un);if(z.current!==null||!Ie||nn.dndKit||nn.defaultPrevented)return;const it={active:Ie};bt(Jt,Vt.options,it)===!0&&(nn.dndKit={capturedBy:Vt.sensor},z.current=un,U(Jt,Vt))},[S,U]),je=Nz(u,ue);Rz(u),mi(()=>{G&&_===No.Initializing&&j(No.Initialized)},[G,_]),m.useEffect(()=>{const{onDragMove:bt}=oe.current,{active:Vt,activatorEvent:Jt,collisions:un,over:nn}=X.current;if(!Vt||!Jt)return;const Ie={active:Vt,activatorEvent:Jt,collisions:un,delta:{x:He.x,y:He.y},over:nn};Ws.unstable_batchedUpdates(()=>{bt?.(Ie),w({type:"onDragMove",event:Ie})})},[He.x,He.y]),m.useEffect(()=>{const{active:bt,activatorEvent:Vt,collisions:Jt,droppableContainers:un,scrollAdjustedTranslate:nn}=X.current;if(!bt||z.current==null||!Vt||!nn)return;const{onDragOver:Ie}=oe.current,it=un.get(ke),dt=it&&it.rect.current?{id:it.id,rect:it.rect.current,data:it.data,disabled:it.disabled}:null,jt={active:bt,activatorEvent:Vt,collisions:Jt,delta:{x:nn.x,y:nn.y},over:dt};Ws.unstable_batchedUpdates(()=>{ft(dt),Ie?.(jt),w({type:"onDragOver",event:jt})})},[ke]),mi(()=>{X.current={activatorEvent:B,active:T,activeNode:_e,collisionRect:kt,collisions:st,droppableRects:J,draggableNodes:S,draggingNode:le,draggingNodeRect:be,droppableContainers:E,over:ut,scrollableAncestors:et,scrollAdjustedTranslate:He},D.current={initial:be,translated:kt}},[T,_e,st,kt,S,le,be,J,E,ut,et,He]),Cz({...me,delta:A,draggingRect:kt,pointerCoordinates:Bt,scrollableAncestors:et,scrollableAncestorRects:qe});const De=m.useMemo(()=>({active:T,activeNode:_e,activeNodeRect:G,activatorEvent:B,collisions:st,containerNodeRect:de,dragOverlay:Z,draggableNodes:S,droppableContainers:E,droppableRects:J,over:ut,measureDroppableContainers:pe,scrollableAncestors:et,scrollableAncestorRects:qe,measuringConfiguration:V,measuringScheduled:fe,windowRect:We}),[T,_e,G,B,st,de,Z,S,E,J,ut,pe,et,qe,V,fe,We]),Le=m.useMemo(()=>({activatorEvent:B,activators:je,active:T,activeNodeRect:G,ariaDescribedById:{draggable:te},dispatch:y,draggableNodes:S,over:ut,measureDroppableContainers:pe}),[B,je,T,G,y,te,S,ut,pe]);return Ne.createElement(qj.Provider,{value:b},Ne.createElement(pd.Provider,{value:Le},Ne.createElement(u_.Provider,{value:De},Ne.createElement(ih.Provider,{value:wt},c)),Ne.createElement($z,{disabled:l?.restoreFocus===!1})),Ne.createElement($O,{...l,hiddenTextDescribedById:te}));function tt(){const bt=$?.autoScrollEnabled===!1,Vt=typeof d=="object"?d.enabled===!1:d===!1,Jt=N&&!bt&&!Vt;return typeof d=="object"?{...d,enabled:Jt}:{enabled:Jt}}}),qz=m.createContext(null),D0="button",Yz="Draggable";function Fg(e){let{id:t,data:n,disabled:s=!1,attributes:o}=e;const r=hd(Yz),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:u,draggableNodes:h,over:p}=m.useContext(pd),{role:f=D0,roleDescription:g="draggable",tabIndex:x=0}=o??{},v=d?.id===t,y=m.useContext(v?ih:qz),[w,b]=eu(),[_,j]=eu(),N=Lz(a,t),C=Ml(n);mi(()=>(h.set(t,{id:t,key:r,node:w,activatorNode:_,data:C}),()=>{const A=h.get(t);A&&A.key===r&&h.delete(t)}),[h,t]);const S=m.useMemo(()=>({role:f,tabIndex:x,"aria-disabled":s,"aria-pressed":v&&f===D0?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[s,f,x,v,g,u.draggable]);return{active:d,activatorEvent:l,activeNodeRect:c,attributes:S,isDragging:v,listeners:s?void 0:N,node:w,over:p,setNodeRef:b,setActivatorNodeRef:j,transform:y}}function fd(){return m.useContext(u_)}const Xz="Droppable",Zz={timeout:25};function md(e){let{data:t,disabled:n=!1,id:s,resizeObserverConfig:o}=e;const r=hd(Xz),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=m.useContext(pd),u=m.useRef({disabled:n}),h=m.useRef(!1),p=m.useRef(null),f=m.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:v}={...Zz,...o},y=Ml(x??s),w=m.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),f.current=null},v)},[v]),b=sh({callback:w,disabled:g||!a}),_=m.useCallback((S,A)=>{b&&(A&&(b.unobserve(A),h.current=!1),S&&b.observe(S))},[b]),[j,N]=eu(_),C=Ml(t);return m.useEffect(()=>{!b||!j.current||(b.disconnect(),h.current=!1,b.observe(j.current))},[j,b]),m.useEffect(()=>(l({type:Zn.RegisterDroppable,element:{id:s,key:r,disabled:n,node:j,rect:p,data:C}}),()=>l({type:Zn.UnregisterDroppable,key:r,id:s})),[s]),m.useEffect(()=>{n!==u.current.disabled&&(l({type:Zn.SetDroppableDisabled,id:s,key:r,disabled:n}),u.current.disabled=n)},[s,r,n,l]),{active:a,rect:p,isOver:d?.id===s,node:j,over:d,setNodeRef:N}}function Jz(e){let{animation:t,children:n}=e;const[s,o]=m.useState(null),[r,a]=m.useState(null),l=tu(n);return!n&&!s&&l&&o(l),mi(()=>{if(!r)return;const d=s?.key,c=s?.props.id;if(d==null||c==null){o(null);return}Promise.resolve(t(c,r)).then(()=>{o(null)})},[t,s,r]),Ne.createElement(Ne.Fragment,null,n,s?m.cloneElement(s,{ref:a}):null)}const Qz={x:0,y:0,scaleX:1,scaleY:1};function eG(e){let{children:t}=e;return Ne.createElement(pd.Provider,{value:c_},Ne.createElement(ih.Provider,{value:Qz},t))}const tG={position:"fixed",touchAction:"none"},nG=e=>nh(e)?"transform 250ms ease":void 0,sG=m.forwardRef((e,t)=>{let{as:n,activatorEvent:s,adjustScale:o,children:r,className:a,rect:l,style:d,transform:c,transition:u=nG}=e;if(!l)return null;const h=o?c:{...c,scaleX:1,scaleY:1},p={...tG,width:l.width,height:l.height,top:l.top,left:l.left,transform:zi.Transform.toString(h),transformOrigin:o&&s?qO(s,l):void 0,transition:typeof u=="function"?u(s):u,...d};return Ne.createElement(n,{className:a,style:p,ref:t},r)}),iG=e=>t=>{let{active:n,dragOverlay:s}=t;const o={},{styles:r,className:a}=e;if(r!=null&&r.active)for(const[l,d]of Object.entries(r.active))d!==void 0&&(o[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,d));if(r!=null&&r.dragOverlay)for(const[l,d]of Object.entries(r.dragOverlay))d!==void 0&&s.node.style.setProperty(l,d);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&s.node.classList.add(a.dragOverlay),function(){for(const[d,c]of Object.entries(o))n.node.style.setProperty(d,c);a!=null&&a.active&&n.node.classList.remove(a.active)}},oG=e=>{let{transform:{initial:t,final:n}}=e;return[{transform:zi.Transform.toString(t)},{transform:zi.Transform.toString(n)}]},rG={duration:250,easing:"ease",keyframes:oG,sideEffects:iG({styles:{active:{opacity:"0"}}})};function aG(e){let{config:t,draggableNodes:n,droppableContainers:s,measuringConfiguration:o}=e;return th((r,a)=>{if(t===null)return;const l=n.get(r);if(!l)return;const d=l.node.current;if(!d)return;const c=d_(a);if(!c)return;const{transform:u}=Ns(a).getComputedStyle(a),h=Jj(u);if(!h)return;const p=typeof t=="function"?t:lG(t);return o_(d,o.draggable.measure),p({active:{id:r,data:l.data,node:d,rect:o.draggable.measure(d)},draggableNodes:n,dragOverlay:{node:a,rect:o.dragOverlay.measure(c)},droppableContainers:s,measuringConfiguration:o,transform:h})})}function lG(e){const{duration:t,easing:n,sideEffects:s,keyframes:o}={...rG,...e};return r=>{let{active:a,dragOverlay:l,transform:d,...c}=r;if(!t)return;const u={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},h={scaleX:d.scaleX!==1?a.rect.width*d.scaleX/l.rect.width:1,scaleY:d.scaleY!==1?a.rect.height*d.scaleY/l.rect.height:1},p={x:d.x-u.x,y:d.y-u.y,...h},f=o({...c,active:a,dragOverlay:l,transform:{initial:d,final:p}}),[g]=f,x=f[f.length-1];if(JSON.stringify(g)===JSON.stringify(x))return;const v=s?.({active:a,dragOverlay:l,...c}),y=l.node.animate(f,{duration:t,easing:n,fill:"forwards"});return new Promise(w=>{y.onfinish=()=>{v?.(),w()}})}}let I0=0;function dG(e){return m.useMemo(()=>{if(e!=null)return I0++,I0},[e])}const cG=Ne.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:s,style:o,transition:r,modifiers:a,wrapperElement:l="div",className:d,zIndex:c=999}=e;const{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggableNodes:g,droppableContainers:x,dragOverlay:v,over:y,measuringConfiguration:w,scrollableAncestors:b,scrollableAncestorRects:_,windowRect:j}=fd(),N=m.useContext(ih),C=dG(h?.id),S=h_(a,{activatorEvent:u,active:h,activeNodeRect:p,containerNodeRect:f,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:b,scrollableAncestorRects:_,transform:N,windowRect:j}),A=Gg(p),E=aG({config:s,draggableNodes:g,droppableContainers:x,measuringConfiguration:w}),I=A?v.setRef:void 0;return Ne.createElement(eG,null,Ne.createElement(Jz,{animation:E},h&&C?Ne.createElement(sG,{key:C,id:h.id,ref:I,as:l,activatorEvent:u,adjustScale:t,className:d,transition:r,rect:A,style:{zIndex:c,...o},transform:S},n):null))}),Hg=m.createContext({});function Bg(e){const t=m.useRef(null);return t.current===null&&(t.current=e()),t.current}const uG=typeof window<"u",ru=uG?m.useLayoutEffect:m.useEffect,oh=m.createContext(null);function Vg(e,t){e.indexOf(t)===-1&&e.push(t)}function au(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}const Gi=(e,t,n)=>n>t?t:n<e?e:n;let rh=()=>{};const Ao={},p_=e=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(e),f_=e=>typeof e=="object"&&e!==null,m_=e=>/^0[^.\s]+$/u.test(e);function g_(e){let t;return()=>(t===void 0&&(t=e()),t)}const Js=e=>e,gd=(...e)=>e.reduce((t,n)=>s=>n(t(s))),Ll=(e,t,n)=>{const s=t-e;return s?(n-e)/s:1};class $g{constructor(){this.subscriptions=[]}add(t){return Vg(this.subscriptions,t),()=>au(this.subscriptions,t)}notify(t,n,s){const o=this.subscriptions.length;if(o)if(o===1)this.subscriptions[0](t,n,s);else for(let r=0;r<o;r++){const a=this.subscriptions[r];a&&a(t,n,s)}}getSize(){return this.subscriptions.length}clear(){this.subscriptions.length=0}}const Ls=e=>e*1e3,qs=e=>e/1e3,x_=(e,t)=>t?e*(1e3/t):0,v_=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,hG=1e-7,pG=12;function fG(e,t,n,s,o){let r,a,l=0;do a=t+(n-t)/2,r=v_(a,s,o)-e,r>0?n=a:t=a;while(Math.abs(r)>hG&&++l<pG);return a}function xd(e,t,n,s){if(e===t&&n===s)return Js;const o=r=>fG(r,0,1,e,n);return r=>r===0||r===1?r:v_(o(r),t,s)}const b_=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,w_=e=>t=>1-e(1-t),y_=xd(.33,1.53,.69,.99),Wg=w_(y_),S_=b_(Wg),C_=e=>e>=1?1:(e*=2)<1?.5*Wg(e):.5*(2-Math.pow(2,-10*(e-1))),Ug=e=>1-Math.sin(Math.acos(e)),k_=w_(Ug),j_=b_(Ug),mG=xd(.42,0,1,1),gG=xd(0,0,.58,1),__=xd(.42,0,.58,1),xG=e=>Array.isArray(e)&&typeof e[0]!="number",N_=e=>Array.isArray(e)&&typeof e[0]=="number",vG={linear:Js,easeIn:mG,easeInOut:__,easeOut:gG,circIn:Ug,circInOut:j_,circOut:k_,backIn:Wg,backInOut:S_,backOut:y_,anticipate:C_},bG=e=>typeof e=="string",E0=e=>{if(N_(e)){rh(e.length===4);const[t,n,s,o]=e;return xd(t,n,s,o)}else if(bG(e))return vG[e];return e},Pd=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function wG(e){let t=new Set,n=new Set,s=!1,o=!1;const r=new WeakSet;let a={delta:0,timestamp:0,isProcessing:!1};function l(c){r.has(c)&&(d.schedule(c),e()),c(a)}const d={schedule:(c,u=!1,h=!1)=>{const f=h&&s?t:n;return u&&r.add(c),f.add(c),c},cancel:c=>{n.delete(c),r.delete(c)},process:c=>{if(a=c,s){o=!0;return}s=!0;const u=t;t=n,n=u,t.forEach(l),t.clear(),s=!1,o&&(o=!1,d.process(c))}};return d}const yG=40;function T_(e,t){let n=!1,s=!0;const o={delta:0,timestamp:0,isProcessing:!1},r=()=>n=!0,a=Pd.reduce((b,_)=>(b[_]=wG(r),b),{}),{setup:l,read:d,resolveKeyframes:c,preUpdate:u,update:h,preRender:p,render:f,postRender:g}=a,x=()=>{const b=Ao.useManualTiming,_=b?o.timestamp:performance.now();n=!1,b||(o.delta=s?1e3/60:Math.max(Math.min(_-o.timestamp,yG),1)),o.timestamp=_,o.isProcessing=!0,l.process(o),d.process(o),c.process(o),u.process(o),h.process(o),p.process(o),f.process(o),g.process(o),o.isProcessing=!1,n&&t&&(s=!1,e(x))},v=()=>{n=!0,s=!0,o.isProcessing||e(x)};return{schedule:Pd.reduce((b,_)=>{const j=a[_];return b[_]=(N,C=!1,S=!1)=>(n||v(),j.schedule(N,C,S)),b},{}),cancel:b=>{for(let _=0;_<Pd.length;_++)a[Pd[_]].cancel(b)},state:o,steps:a}}const{schedule:_n,cancel:Mo,state:as,steps:ep}=T_(typeof requestAnimationFrame<"u"?requestAnimationFrame:Js,!0);let Nc;function SG(){Nc=void 0}const Ss={now:()=>(Nc===void 0&&Ss.set(as.isProcessing||Ao.useManualTiming?as.timestamp:performance.now()),Nc),set:e=>{Nc=e,queueMicrotask(SG)}},D_=e=>t=>typeof t=="string"&&t.startsWith(e),I_=D_("--"),CG=D_("var(--"),Kg=e=>CG(e)?kG.test(e.split("/*")[0].trim()):!1,kG=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function P0(e){return typeof e!="string"?!1:e.split("/*")[0].includes("var(--")}const ka={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},Ol={...ka,transform:e=>Gi(0,1,e)},Ad={...ka,default:1},dl=e=>Math.round(e*1e5)/1e5,qg=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function jG(e){return e==null}const _G=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,Yg=(e,t)=>n=>!!(typeof n=="string"&&_G.test(n)&&n.startsWith(e)||t&&!jG(n)&&Object.prototype.hasOwnProperty.call(n,t)),E_=(e,t,n)=>s=>{if(typeof s!="string")return s;const[o,r,a,l]=s.match(qg);return{[e]:parseFloat(o),[t]:parseFloat(r),[n]:parseFloat(a),alpha:l!==void 0?parseFloat(l):1}},NG=e=>Gi(0,255,e),tp={...ka,transform:e=>Math.round(NG(e))},ar={test:Yg("rgb","red"),parse:E_("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:s=1})=>"rgba("+tp.transform(e)+", "+tp.transform(t)+", "+tp.transform(n)+", "+dl(Ol.transform(s))+")"};function TG(e){let t="",n="",s="",o="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),s=e.substring(5,7),o=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),s=e.substring(3,4),o=e.substring(4,5),t+=t,n+=n,s+=s,o+=o),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(s,16),alpha:o?parseInt(o,16)/255:1}}const Pf={test:Yg("#"),parse:TG,transform:ar.transform},vd=e=>({test:t=>typeof t=="string"&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),eo=vd("deg"),Mi=vd("%"),gt=vd("px"),DG=vd("vh"),IG=vd("vw"),A0={...Mi,parse:e=>Mi.parse(e)/100,transform:e=>Mi.transform(e*100)},Br={test:Yg("hsl","hue"),parse:E_("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:s=1})=>"hsla("+Math.round(e)+", "+Mi.transform(dl(t))+", "+Mi.transform(dl(n))+", "+dl(Ol.transform(s))+")"},$n={test:e=>ar.test(e)||Pf.test(e)||Br.test(e),parse:e=>ar.test(e)?ar.parse(e):Br.test(e)?Br.parse(e):Pf.parse(e),transform:e=>typeof e=="string"?e:e.hasOwnProperty("red")?ar.transform(e):Br.transform(e),getAnimatableNone:e=>{const t=$n.parse(e);return t.alpha=0,$n.transform(t)}},EG=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function PG(e){return isNaN(e)&&typeof e=="string"&&(e.match(qg)?.length||0)+(e.match(EG)?.length||0)>0}const P_="number",A_="color",AG="var",MG="var(",M0="${}",RG=/var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;function la(e){const t=e.toString(),n=[],s={color:[],number:[],var:[]},o=[];let r=0;const l=t.replace(RG,d=>($n.test(d)?(s.color.push(r),o.push(A_),n.push($n.parse(d))):d.startsWith(MG)?(s.var.push(r),o.push(AG),n.push(d)):(s.number.push(r),o.push(P_),n.push(parseFloat(d))),++r,M0)).split(M0);return{values:n,split:l,indexes:s,types:o}}function LG(e){return la(e).values}function M_({split:e,types:t}){const n=e.length;return s=>{let o="";for(let r=0;r<n;r++)if(o+=e[r],s[r]!==void 0){const a=t[r];a===P_?o+=dl(s[r]):a===A_?o+=$n.transform(s[r]):o+=s[r]}return o}}function OG(e){return M_(la(e))}const zG=e=>typeof e=="number"?0:$n.test(e)?$n.getAnimatableNone(e):e,GG=(e,t)=>typeof e=="number"?t?.trim().endsWith("/")?e:0:zG(e);function FG(e){const t=la(e);return M_(t)(t.values.map((s,o)=>GG(s,t.split[o])))}const hi={test:PG,parse:LG,createTransformer:OG,getAnimatableNone:FG};function np(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function HG({hue:e,saturation:t,lightness:n,alpha:s}){e/=360,t/=100,n/=100;let o=0,r=0,a=0;if(!t)o=r=a=n;else{const l=n<.5?n*(1+t):n+t-n*t,d=2*n-l;o=np(d,l,e+1/3),r=np(d,l,e),a=np(d,l,e-1/3)}return{red:Math.round(o*255),green:Math.round(r*255),blue:Math.round(a*255),alpha:s}}function lu(e,t){return n=>n>0?t:e}const jn=(e,t,n)=>e+(t-e)*n,sp=(e,t,n)=>{const s=e*e,o=n*(t*t-s)+s;return o<0?0:Math.sqrt(o)},BG=[Pf,ar,Br],VG=e=>BG.find(t=>t.test(e));function R0(e){const t=VG(e);if(!t)return!1;let n=t.parse(e);return t===Br&&(n=HG(n)),n}const L0=(e,t)=>{const n=R0(e),s=R0(t);if(!n||!s)return lu(e,t);const o={...n};return r=>(o.red=sp(n.red,s.red,r),o.green=sp(n.green,s.green,r),o.blue=sp(n.blue,s.blue,r),o.alpha=jn(n.alpha,s.alpha,r),ar.transform(o))},Af=new Set(["none","hidden"]);function $G(e,t){return Af.has(e)?n=>n<=0?e:t:n=>n>=1?t:e}function WG(e,t){return n=>jn(e,t,n)}function Xg(e){return typeof e=="number"?WG:typeof e=="string"?Kg(e)?lu:$n.test(e)?L0:qG:Array.isArray(e)?R_:typeof e=="object"?$n.test(e)?L0:UG:lu}function R_(e,t){const n=[...e],s=n.length,o=e.map((r,a)=>Xg(r)(r,t[a]));return r=>{for(let a=0;a<s;a++)n[a]=o[a](r);return n}}function UG(e,t){const n={...e,...t},s={};for(const o in n)e[o]!==void 0&&t[o]!==void 0&&(s[o]=Xg(e[o])(e[o],t[o]));return o=>{for(const r in s)n[r]=s[r](o);return n}}function KG(e,t){const n=[],s={color:0,var:0,number:0};for(let o=0;o<t.values.length;o++){const r=t.types[o],a=e.indexes[r][s[r]],l=e.values[a]??0;n[o]=l,s[r]++}return n}const qG=(e,t)=>{const n=hi.createTransformer(t),s=la(e),o=la(t);return s.indexes.var.length===o.indexes.var.length&&s.indexes.color.length===o.indexes.color.length&&s.indexes.number.length>=o.indexes.number.length?Af.has(e)&&!o.values.length||Af.has(t)&&!s.values.length?$G(e,t):gd(R_(KG(s,o),o.values),n):lu(e,t)};function L_(e,t,n){return typeof e=="number"&&typeof t=="number"&&typeof n=="number"?jn(e,t,n):Xg(e)(e,t)}const YG=e=>{const t=({timestamp:n})=>e(n);return{start:(n=!0)=>_n.update(t,n),stop:()=>Mo(t),now:()=>as.isProcessing?as.timestamp:Ss.now()}},O_=(e,t,n=10)=>{let s="";const o=Math.max(Math.round(t/n),2);for(let r=0;r<o;r++)s+=Math.round(e(r/(o-1))*1e4)/1e4+", ";return`linear(${s.substring(0,s.length-2)})`},du=2e4;function Zg(e){let t=0;const n=50;let s=e.next(t);for(;!s.done&&t<du;)t+=n,s=e.next(t);return t>=du?1/0:t}function XG(e,t=100,n){const s=n({...e,keyframes:[0,t]}),o=Math.min(Zg(s),du);return{type:"keyframes",ease:r=>s.next(o*r).value/t,duration:qs(o)}}const Gn={stiffness:100,damping:10,mass:1,velocity:0,duration:800,bounce:.3,visualDuration:.3,restSpeed:{granular:.01,default:2},restDelta:{granular:.005,default:.5},minDuration:.01,maxDuration:10,minDamping:.05,maxDamping:1};function Mf(e,t){return e*Math.sqrt(1-t*t)}const ZG=12;function JG(e,t,n){let s=n;for(let o=1;o<ZG;o++)s=s-e(s)/t(s);return s}const ip=.001;function QG({duration:e=Gn.duration,bounce:t=Gn.bounce,velocity:n=Gn.velocity,mass:s=Gn.mass}){let o,r,a=1-t;a=Gi(Gn.minDamping,Gn.maxDamping,a),e=Gi(Gn.minDuration,Gn.maxDuration,qs(e)),a<1?(o=c=>{const u=c*a,h=u*e,p=u-n,f=Mf(c,a),g=Math.exp(-h);return ip-p/f*g},r=c=>{const h=c*a*e,p=h*n+n,f=Math.pow(a,2)*Math.pow(c,2)*e,g=Math.exp(-h),x=Mf(Math.pow(c,2),a);return(-o(c)+ip>0?-1:1)*((p-f)*g)/x}):(o=c=>{const u=Math.exp(-c*e),h=(c-n)*e+1;return-ip+u*h},r=c=>{const u=Math.exp(-c*e),h=(n-c)*(e*e);return u*h});const l=5/e,d=JG(o,r,l);if(e=Ls(e),isNaN(d))return{stiffness:Gn.stiffness,damping:Gn.damping,duration:e};{const c=Math.pow(d,2)*s;return{stiffness:c,damping:a*2*Math.sqrt(s*c),duration:e}}}const e3=["duration","bounce"],t3=["stiffness","damping","mass"];function O0(e,t){return t.some(n=>e[n]!==void 0)}function n3(e){let t={velocity:Gn.velocity,stiffness:Gn.stiffness,damping:Gn.damping,mass:Gn.mass,isResolvedFromDuration:!1,...e};if(!O0(e,t3)&&O0(e,e3))if(t.velocity=0,e.visualDuration){const n=e.visualDuration,s=2*Math.PI/(n*1.2),o=s*s,r=2*Gi(.05,1,1-(e.bounce||0))*Math.sqrt(o);t={...t,mass:Gn.mass,stiffness:o,damping:r}}else{const n=QG({...e,velocity:0});t={...t,...n,mass:Gn.mass},t.isResolvedFromDuration=!0}return t}function cu(e=Gn.visualDuration,t=Gn.bounce){const n=typeof e!="object"?{visualDuration:e,keyframes:[0,1],bounce:t}:e;let{restSpeed:s,restDelta:o}=n;const r=n.keyframes[0],a=n.keyframes[n.keyframes.length-1],l={done:!1,value:r},{stiffness:d,damping:c,mass:u,duration:h,velocity:p,isResolvedFromDuration:f}=n3({...n,velocity:-qs(n.velocity||0)}),g=p||0,x=c/(2*Math.sqrt(d*u)),v=a-r,y=qs(Math.sqrt(d/u)),w=Math.abs(v)<5;s||(s=w?Gn.restSpeed.granular:Gn.restSpeed.default),o||(o=w?Gn.restDelta.granular:Gn.restDelta.default);let b,_,j,N,C,S;if(x<1)j=Mf(y,x),N=(g+x*y*v)/j,b=E=>{const I=Math.exp(-x*y*E);return a-I*(N*Math.sin(j*E)+v*Math.cos(j*E))},C=x*y*N+v*j,S=x*y*v-N*j,_=E=>Math.exp(-x*y*E)*(C*Math.sin(j*E)+S*Math.cos(j*E));else if(x===1){b=I=>a-Math.exp(-y*I)*(v+(g+y*v)*I);const E=g+y*v;_=I=>Math.exp(-y*I)*(y*E*I-g)}else{const E=y*Math.sqrt(x*x-1);b=z=>{const $=Math.exp(-x*y*z),R=Math.min(E*z,300);return a-$*((g+x*y*v)*Math.sinh(R)+E*v*Math.cosh(R))/E};const I=(g+x*y*v)/E,D=x*y*I-v*E,T=x*y*v-I*E;_=z=>{const $=Math.exp(-x*y*z),R=Math.min(E*z,300);return $*(D*Math.sinh(R)+T*Math.cosh(R))}}const A={calculatedDuration:f&&h||null,velocity:E=>Ls(_(E)),next:E=>{if(!f&&x<1){const D=Math.exp(-x*y*E),T=Math.sin(j*E),z=Math.cos(j*E),$=a-D*(N*T+v*z),R=Ls(D*(C*T+S*z));return l.done=Math.abs(R)<=s&&Math.abs(a-$)<=o,l.value=l.done?a:$,l}const I=b(E);if(f)l.done=E>=h;else{const D=Ls(_(E));l.done=Math.abs(D)<=s&&Math.abs(a-I)<=o}return l.value=l.done?a:I,l},toString:()=>{const E=Math.min(Zg(A),du),I=O_(D=>A.next(E*D).value,E,30);return E+"ms "+I},toTransition:()=>{}};return A}cu.applyToOptions=e=>{const t=XG(e,100,cu);return e.ease=t.ease,e.duration=Ls(t.duration),e.type="keyframes",e};const s3=5;function z_(e,t,n){const s=Math.max(t-s3,0);return x_(n-e(s),t-s)}function Rf({keyframes:e,velocity:t=0,power:n=.8,timeConstant:s=325,bounceDamping:o=10,bounceStiffness:r=500,modifyTarget:a,min:l,max:d,restDelta:c=.5,restSpeed:u}){const h=e[0],p={done:!1,value:h},f=S=>l!==void 0&&S<l||d!==void 0&&S>d,g=S=>l===void 0?d:d===void 0||Math.abs(l-S)<Math.abs(d-S)?l:d;let x=n*t;const v=h+x,y=a===void 0?v:a(v);y!==v&&(x=y-h);const w=S=>-x*Math.exp(-S/s),b=S=>y+w(S),_=S=>{const A=w(S),E=b(S);p.done=Math.abs(A)<=c,p.value=p.done?y:E};let j,N;const C=S=>{f(p.value)&&(j=S,N=cu({keyframes:[p.value,g(p.value)],velocity:z_(b,S,p.value),damping:o,stiffness:r,restDelta:c,restSpeed:u}))};return C(0),{calculatedDuration:null,next:S=>{let A=!1;return!N&&j===void 0&&(A=!0,_(S),C(S)),j!==void 0&&S>=j?N.next(S-j):(!A&&_(S),p)}}}function i3(e,t,n){const s=[],o=n||Ao.mix||L_,r=e.length-1;for(let a=0;a<r;a++){let l=o(e[a],e[a+1]);if(t){const d=Array.isArray(t)?t[a]||Js:t;l=gd(d,l)}s.push(l)}return s}function o3(e,t,{clamp:n=!0,ease:s,mixer:o}={}){const r=e.length;if(rh(r===t.length),r===1)return()=>t[0];if(r===2&&t[0]===t[1])return()=>t[1];const a=e[0]===e[1];e[0]>e[r-1]&&(e=[...e].reverse(),t=[...t].reverse());const l=i3(t,s,o),d=l.length,c=u=>{if(a&&u<e[0])return t[0];let h=0;if(d>1)for(;h<e.length-2&&!(u<e[h+1]);h++);const p=Ll(e[h],e[h+1],u);return l[h](p)};return n?u=>c(Gi(e[0],e[r-1],u)):c}function r3(e,t){const n=e[e.length-1];for(let s=1;s<=t;s++){const o=Ll(0,t,s);e.push(jn(n,1,o))}}function a3(e){const t=[0];return r3(t,e.length-1),t}function l3(e,t){return e.map(n=>n*t)}function d3(e,t){return e.map(()=>t||__).splice(0,e.length-1)}function cl({duration:e=300,keyframes:t,times:n,ease:s="easeInOut"}){const o=xG(s)?s.map(E0):E0(s),r={done:!1,value:t[0]},a=l3(n&&n.length===t.length?n:a3(t),e),l=o3(a,t,{ease:Array.isArray(o)?o:d3(t,o)});return{calculatedDuration:e,next:d=>(r.value=l(d),r.done=d>=e,r)}}const c3=e=>e!==null;function ah(e,{repeat:t,repeatType:n="loop"},s,o=1){const r=e.filter(c3),l=o<0||t&&n!=="loop"&&t%2===1?0:r.length-1;return!l||s===void 0?r[l]:s}const u3={decay:Rf,inertia:Rf,tween:cl,keyframes:cl,spring:cu};function G_(e){typeof e.type=="string"&&(e.type=u3[e.type])}class Jg{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const h3=e=>e/100;class uu extends Jg{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{const{motionValue:n}=this.options;n&&n.updatedAt!==Ss.now()&&this.tick(Ss.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),this.options.onStop?.())},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;G_(t);const{type:n=cl,repeat:s=0,repeatDelay:o=0,repeatType:r,velocity:a=0}=t;let{keyframes:l}=t;const d=n||cl;d!==cl&&typeof l[0]!="number"&&(this.mixKeyframes=gd(h3,L_(l[0],l[1])),l=[0,100]);const c=d({...t,keyframes:l});r==="mirror"&&(this.mirroredGenerator=d({...t,keyframes:[...l].reverse(),velocity:-a})),c.calculatedDuration===null&&(c.calculatedDuration=Zg(c));const{calculatedDuration:u}=c;this.calculatedDuration=u,this.resolvedDuration=u+o,this.totalDuration=this.resolvedDuration*(s+1)-o,this.generator=c}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:s,totalDuration:o,mixKeyframes:r,mirroredGenerator:a,resolvedDuration:l,calculatedDuration:d}=this;if(this.startTime===null)return s.next(0);const{delay:c=0,keyframes:u,repeat:h,repeatType:p,repeatDelay:f,type:g,onUpdate:x,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-o/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const y=this.currentTime-c*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?y<0:y>o;this.currentTime=Math.max(y,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=o);let b=this.currentTime,_=s;if(h){const S=Math.min(this.currentTime,o)/l;let A=Math.floor(S),E=S%1;!E&&S>=1&&(E=1),E===1&&A--,A=Math.min(A,h+1),A%2&&(p==="reverse"?(E=1-E,f&&(E-=f/l)):p==="mirror"&&(_=a)),b=Gi(0,1,E)*l}let j;w?(this.delayState.value=u[0],j=this.delayState):j=_.next(b),r&&!w&&(j.value=r(j.value));let{done:N}=j;!w&&d!==null&&(N=this.playbackSpeed>=0?this.currentTime>=o:this.currentTime<=0);const C=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&N);return C&&g!==Rf&&(j.value=ah(u,this.options,v,this.speed)),x&&x(j.value),C&&this.finish(),j}then(t,n){return this.finished.then(t,n)}get duration(){return qs(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+qs(t)}get time(){return qs(this.currentTime)}set time(t){t=Ls(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=t,this.tick(t))}getGeneratorVelocity(){const t=this.currentTime;if(t<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(t);const n=this.generator.next(t).value;return z_(s=>this.generator.next(s).value,t,n)}get speed(){return this.playbackSpeed}set speed(t){const n=this.playbackSpeed!==t;n&&this.driver&&this.updateTime(Ss.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=qs(this.currentTime))}play(){if(this.isStopped)return;const{driver:t=YG,startTime:n}=this.options;this.driver||(this.driver=t(o=>this.tick(o))),this.options.onPlay?.();const s=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=s):this.holdTime!==null?this.startTime=s-this.holdTime:this.startTime||(this.startTime=n??s),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Ss.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){this.notifyFinished(),this.teardown(),this.state="finished",this.options.onComplete?.()}cancel(){this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),this.options.onCancel?.()}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),this.driver?.stop(),t.observe(this)}}function p3(e){for(let t=1;t<e.length;t++)e[t]??(e[t]=e[t-1])}const lr=e=>e*180/Math.PI,Lf=e=>{const t=lr(Math.atan2(e[1],e[0]));return Of(t)},f3={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:e=>(Math.abs(e[0])+Math.abs(e[3]))/2,rotate:Lf,rotateZ:Lf,skewX:e=>lr(Math.atan(e[1])),skewY:e=>lr(Math.atan(e[2])),skew:e=>(Math.abs(e[1])+Math.abs(e[2]))/2},Of=e=>(e=e%360,e<0&&(e+=360),e),z0=Lf,G0=e=>Math.sqrt(e[0]*e[0]+e[1]*e[1]),F0=e=>Math.sqrt(e[4]*e[4]+e[5]*e[5]),m3={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:G0,scaleY:F0,scale:e=>(G0(e)+F0(e))/2,rotateX:e=>Of(lr(Math.atan2(e[6],e[5]))),rotateY:e=>Of(lr(Math.atan2(-e[2],e[0]))),rotateZ:z0,rotate:z0,skewX:e=>lr(Math.atan(e[4])),skewY:e=>lr(Math.atan(e[1])),skew:e=>(Math.abs(e[1])+Math.abs(e[4]))/2};function zf(e){return e.includes("scale")?1:0}function Gf(e,t){if(!e||e==="none")return zf(t);const n=e.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let s,o;if(n)s=m3,o=n;else{const l=e.match(/^matrix\(([-\d.e\s,]+)\)$/u);s=f3,o=l}if(!o)return zf(t);const r=s[t],a=o[1].split(",").map(x3);return typeof r=="function"?r(a):a[r]}const g3=(e,t)=>{const{transform:n="none"}=getComputedStyle(e);return Gf(n,t)};function x3(e){return parseFloat(e.trim())}const ja=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],_a=new Set([...ja,"pathRotation"]),H0=e=>e===ka||e===gt,v3=new Set(["x","y","z"]),b3=ja.filter(e=>!v3.has(e));function w3(e){const t=[];return b3.forEach(n=>{const s=e.getValue(n);s!==void 0&&(t.push([n,s.get()]),s.set(n.startsWith("scale")?1:0))}),t}const Eo={width:({x:e},{paddingLeft:t="0",paddingRight:n="0",boxSizing:s})=>{const o=e.max-e.min;return s==="border-box"?o:o-parseFloat(t)-parseFloat(n)},height:({y:e},{paddingTop:t="0",paddingBottom:n="0",boxSizing:s})=>{const o=e.max-e.min;return s==="border-box"?o:o-parseFloat(t)-parseFloat(n)},top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:(e,{transform:t})=>Gf(t,"x"),y:(e,{transform:t})=>Gf(t,"y")};Eo.translateX=Eo.x;Eo.translateY=Eo.y;const fr=new Set;let Ff=!1,Hf=!1,Bf=!1;function F_(){if(Hf){const e=Array.from(fr).filter(s=>s.needsMeasurement),t=new Set(e.map(s=>s.element)),n=new Map;t.forEach(s=>{const o=w3(s);o.length&&(n.set(s,o),s.render())}),e.forEach(s=>s.measureInitialState()),t.forEach(s=>{s.render();const o=n.get(s);o&&o.forEach(([r,a])=>{s.getValue(r)?.set(a)})}),e.forEach(s=>s.measureEndState()),e.forEach(s=>{s.suspendedScrollY!==void 0&&window.scrollTo(0,s.suspendedScrollY)})}Hf=!1,Ff=!1,fr.forEach(e=>e.complete(Bf)),fr.clear()}function H_(){fr.forEach(e=>{e.readKeyframes(),e.needsMeasurement&&(Hf=!0)})}function y3(){Bf=!0,H_(),F_(),Bf=!1}class Qg{constructor(t,n,s,o,r,a=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=s,this.motionValue=o,this.element=r,this.isAsync=a}scheduleResolve(){this.state="scheduled",this.isAsync?(fr.add(this),Ff||(Ff=!0,_n.read(H_),_n.resolveKeyframes(F_))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:s,motionValue:o}=this;if(t[0]===null){const r=o?.get(),a=t[t.length-1];if(r!==void 0)t[0]=r;else if(s&&n){const l=s.readValue(n,a);l!=null&&(t[0]=l)}t[0]===void 0&&(t[0]=a),o&&r===void 0&&o.set(t[0])}p3(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),fr.delete(this)}cancel(){this.state==="scheduled"&&(fr.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const S3=e=>e.startsWith("--");function B_(e,t,n){S3(t)?e.style.setProperty(t,n):e.style[t]=n}const C3={};function V_(e,t){const n=g_(e);return()=>C3[t]??n()}const k3=V_(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),$_=V_(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),Xa=([e,t,n,s])=>`cubic-bezier(${e}, ${t}, ${n}, ${s})`,B0={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:Xa([0,.65,.55,1]),circOut:Xa([.55,0,1,.45]),backIn:Xa([.31,.01,.66,-.59]),backOut:Xa([.33,1.53,.69,.99])};function W_(e,t){if(e)return typeof e=="function"?$_()?O_(e,t):"ease-out":N_(e)?Xa(e):Array.isArray(e)?e.map(n=>W_(n,t)||B0.easeOut):B0[e]}function j3(e,t,n,{delay:s=0,duration:o=300,repeat:r=0,repeatType:a="loop",ease:l="easeOut",times:d}={},c=void 0){const u={[t]:n};d&&(u.offset=d);const h=W_(l,o);Array.isArray(h)&&(u.easing=h);const p={delay:s,duration:o,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:r+1,direction:a==="reverse"?"alternate":"normal"};return c&&(p.pseudoElement=c),e.animate(u,p)}function U_(e){return typeof e=="function"&&"applyToOptions"in e}function _3({type:e,...t}){return U_(e)&&$_()?e.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class K_ extends Jg{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:s,keyframes:o,pseudoElement:r,allowFlatten:a=!1,finalKeyframe:l,onComplete:d}=t;this.isPseudoElement=!!r,this.allowFlatten=a,this.options=t,rh(typeof t.type!="string");const c=_3(t);this.animation=j3(n,s,o,c,r),c.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!r){const u=ah(o,this.options,l,this.speed);this.updateMotionValue&&this.updateMotionValue(u),B_(n,s,u),this.animation.cancel()}d?.(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){this.animation.finish?.()}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){const t=this.options?.element;!this.isPseudoElement&&t?.isConnected&&this.animation.commitStyles?.()}get duration(){const t=this.animation.effect?.getComputedTiming?.().duration||0;return qs(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+qs(t)}get time(){return qs(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Ls(t),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:n,rangeEnd:s,observe:o}){return this.allowFlatten&&this.animation.effect?.updateTiming({easing:"linear"}),this.animation.onfinish=null,t&&k3()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),s&&(this.animation.rangeEnd=s),Js):o(this)}}const q_={anticipate:C_,backInOut:S_,circInOut:j_};function N3(e){return e in q_}function T3(e){typeof e.ease=="string"&&N3(e.ease)&&(e.ease=q_[e.ease])}const op=10;class D3 extends K_{constructor(t){T3(t),G_(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:s,onComplete:o,element:r,...a}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const l=new uu({...a,autoplay:!1}),d=Math.max(op,Ss.now()-this.startTime),c=Gi(0,op,d-op),u=l.sample(d).value,{name:h}=this.options;r&&h&&B_(r,h,u),n.setWithVelocity(l.sample(Math.max(0,d-c)).value,u,c),l.stop()}}const V0=(e,t)=>t==="zIndex"?!1:!!(typeof e=="number"||Array.isArray(e)||typeof e=="string"&&(hi.test(e)||e==="0")&&!e.startsWith("url("));function I3(e){const t=e[0];if(e.length===1)return!0;for(let n=0;n<e.length;n++)if(e[n]!==t)return!0}function E3(e,t,n,s){const o=e[0];if(o===null)return!1;if(t==="display"||t==="visibility")return!0;const r=e[e.length-1],a=V0(o,t),l=V0(r,t);return!a||!l?!1:I3(e)||(n==="spring"||U_(n))&&s}function Vf(e){e.duration=0,e.type="keyframes"}const Y_=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),P3=/^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/;function A3(e){for(let t=0;t<e.length;t++)if(typeof e[t]=="string"&&P3.test(e[t]))return!0;return!1}const M3=new Set(["color","backgroundColor","outlineColor","fill","stroke","borderColor","borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"]),R3=g_(()=>Object.hasOwnProperty.call(Element.prototype,"animate"));function L3(e){const{motionValue:t,name:n,repeatDelay:s,repeatType:o,damping:r,type:a,keyframes:l}=e,d=t?.owner?.current;if(!(d instanceof HTMLElement)&&!(d instanceof SVGElement))return!1;const{onUpdate:c,transformTemplate:u}=t.owner.getProps();return R3()&&n&&(Y_.has(n)||M3.has(n)&&A3(l))&&(n!=="transform"||!u)&&!c&&!s&&o!=="mirror"&&r!==0&&a!=="inertia"}const O3=40;class z3 extends Jg{constructor({autoplay:t=!0,delay:n=0,type:s="keyframes",repeat:o=0,repeatDelay:r=0,repeatType:a="loop",keyframes:l,name:d,motionValue:c,element:u,...h}){super(),this.stop=()=>{this._animation&&(this._animation.stop(),this.stopTimeline?.()),this.keyframeResolver?.cancel()},this.createdAt=Ss.now();const p={autoplay:t,delay:n,type:s,repeat:o,repeatDelay:r,repeatType:a,name:d,motionValue:c,element:u,...h},f=u?.KeyframeResolver||Qg;this.keyframeResolver=new f(l,(g,x,v)=>this.onKeyframesResolved(g,x,p,!v),d,c,u),this.keyframeResolver?.scheduleResolve()}onKeyframesResolved(t,n,s,o){this.keyframeResolver=void 0;const{name:r,type:a,velocity:l,delay:d,isHandoff:c,onUpdate:u}=s;this.resolvedAt=Ss.now();let h=!0;E3(t,r,a,l)||(h=!1,(Ao.instantAnimations||!d)&&u?.(ah(t,s,n)),t[0]=t[t.length-1],Vf(s),s.repeat=0);const f={startTime:o?this.resolvedAt?this.resolvedAt-this.createdAt>O3?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...s,keyframes:t},g=h&&!c&&L3(f),x=f.motionValue?.owner?.current;let v;if(g)try{v=new D3({...f,element:x})}catch{v=new uu(f)}else v=new uu(f);v.finished.then(()=>{this.notifyFinished()}).catch(Js),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){return this._animation||(this.keyframeResolver?.resume(),y3()),this._animation}get duration(){return this.animation.duration}get iterationDuration(){return this.animation.iterationDuration}get time(){return this.animation.time}set time(t){this.animation.time=t}get speed(){return this.animation.speed}get state(){return this.animation.state}set speed(t){this.animation.speed=t}get startTime(){return this.animation.startTime}attachTimeline(t){return this._animation?this.stopTimeline=this.animation.attachTimeline(t):this.pendingTimeline=t,()=>this.stop()}play(){this.animation.play()}pause(){this.animation.pause()}complete(){this.animation.complete()}cancel(){this._animation&&this.animation.cancel(),this.keyframeResolver?.cancel()}}function X_(e,t,n,s=0,o=1){const r=Array.from(e).sort((c,u)=>c.sortNodePosition(u)).indexOf(t),a=e.size,l=(a-1)*s;return typeof n=="function"?n(r,a):o===1?r*s:l-r*s}const $0=30,G3=e=>!isNaN(parseFloat(e));class F3{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=s=>{const o=Ss.now();if(this.updatedAt!==o&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(s),this.current!==this.prev&&(this.events.change?.notify(this.current),this.dependents))for(const r of this.dependents)r.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Ss.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=G3(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new $g);const s=this.events[t].add(n);return t==="change"?()=>{s(),_n.read(()=>{this.events.change.getSize()||this.stop()})}:s}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,s){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-s}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){this.events.change?.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Ss.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>$0)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,$0);return x_(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.dependents?.clear(),this.events.destroy?.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function da(e,t){return new F3(e,t)}function Z_(e,t){if(e?.inherit&&t){const{inherit:n,...s}=e;return{...t,...s}}return e}function ex(e,t){const n=e?.[t]??e?.default??e;return n!==e?Z_(n,e):n}const H3={type:"spring",stiffness:500,damping:25,restSpeed:10},B3=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),V3={type:"keyframes",duration:.8},$3={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},W3=(e,{keyframes:t})=>t.length>2?V3:_a.has(e)?e.startsWith("scale")?B3(t[1]):H3:$3,U3=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function K3(e){for(const t in e)if(!U3.has(t))return!0;return!1}const tx=(e,t,n,s={},o,r)=>a=>{const l=ex(s,e)||{},d=l.delay||s.delay||0;let{elapsed:c=0}=s;c=c-Ls(d);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...l,delay:-c,onUpdate:p=>{t.set(p),l.onUpdate&&l.onUpdate(p)},onComplete:()=>{a(),l.onComplete&&l.onComplete()},name:e,motionValue:t,element:r?void 0:o};K3(l)||Object.assign(u,W3(e,u)),u.duration&&(u.duration=Ls(u.duration)),u.repeatDelay&&(u.repeatDelay=Ls(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(Vf(u),u.delay===0&&(h=!0)),(Ao.instantAnimations||Ao.skipAnimations||o?.shouldSkipAnimations||l.skipAnimations)&&(h=!0,Vf(u),u.delay=0),u.allowFlatten=!l.type&&!l.ease,h&&!r&&t.get()!==void 0){const p=ah(u.keyframes,l);if(p!==void 0){_n.update(()=>{u.onUpdate(p),u.onComplete()});return}}return l.isSync?new uu(u):new z3(u)},q3=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function Y3(e){const t=q3.exec(e);if(!t)return[,];const[,n,s,o]=t;return[`--${n??s}`,o]}function J_(e,t,n=1){const[s,o]=Y3(e);if(!s)return;const r=window.getComputedStyle(t).getPropertyValue(s);if(r){const a=r.trim();return p_(a)?parseFloat(a):a}return Kg(o)?J_(o,t,n+1):o}function W0(e){const t=[{},{}];return e?.values.forEach((n,s)=>{t[0][s]=n.get(),t[1][s]=n.getVelocity()}),t}function nx(e,t,n,s){if(typeof t=="function"){const[o,r]=W0(s);t=t(n!==void 0?n:e.custom,o,r)}if(typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"){const[o,r]=W0(s);t=t(n!==void 0?n:e.custom,o,r)}return t}function mr(e,t,n){const s=e.getProps();return nx(s,t,n!==void 0?n:s.custom,e)}const Q_=new Set(["width","height","top","left","right","bottom",...ja]),$f=e=>Array.isArray(e);function X3(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,da(n))}function Z3(e){return $f(e)?e[e.length-1]||0:e}function J3(e,t){const n=mr(e,t);let{transitionEnd:s={},transition:o={},...r}=n||{};r={...r,...s};for(const a in r){const l=Z3(r[a]);X3(e,a,l)}}const ls=e=>!!(e&&e.getVelocity);function Q3(e){return!!(ls(e)&&e.add)}function Wf(e,t){const n=e.getValue("willChange");if(Q3(n))return n.add(t);if(!n&&Ao.WillChange){const s=new Ao.WillChange("auto");e.addValue("willChange",s),s.add(t)}}function sx(e){return e.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const eF="framerAppearId",e1="data-"+sx(eF);function t1(e){return e.props[e1]}const tF=typeof window<"u";function nF({protectedKeys:e,needsAnimating:t},n){const s=e.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,s}function n1(e,t,{delay:n=0,transitionOverride:s,type:o}={}){let{transition:r,transitionEnd:a,...l}=t;const d=e.getDefaultTransition();r=r?Z_(r,d):d;const c=r?.reduceMotion,u=r?.skipAnimations;s&&(r=s);const h=[],p=o&&e.animationState&&e.animationState.getState()[o],f=r?.path;f&&f.animateVisualElement(e,l,r,n,h);for(const g in l){const x=e.getValue(g,e.latestValues[g]??null),v=l[g];if(v===void 0||p&&nF(p,g))continue;const y={delay:n,...ex(r||{},g)};u&&(y.skipAnimations=!0);const w=x.get();if(w!==void 0&&!x.isAnimating()&&!Array.isArray(v)&&v===w&&!y.velocity){_n.update(()=>x.set(v));continue}let b=!1;if(tF&&window.MotionHandoffAnimation){const N=t1(e);if(N){const C=window.MotionHandoffAnimation(N,g,_n);C!==null&&(y.startTime=C,b=!0)}}Wf(e,g);const _=c??e.shouldReduceMotion;x.start(tx(g,x,v,_&&Q_.has(g)?{type:!1}:y,e,b));const j=x.animation;j&&h.push(j)}if(a){const g=()=>_n.update(()=>{a&&J3(e,a)});h.length?Promise.all(h).then(g):g()}return h}function Uf(e,t,n={}){const s=mr(e,t,n.type==="exit"?e.presenceContext?.custom:void 0);let{transition:o=e.getDefaultTransition()||{}}=s||{};n.transitionOverride&&(o=n.transitionOverride);const r=s?()=>Promise.all(n1(e,s,n)):()=>Promise.resolve(),a=e.variantChildren&&e.variantChildren.size?(d=0)=>{const{delayChildren:c=0,staggerChildren:u,staggerDirection:h}=o;return sF(e,t,d,c,u,h,n)}:()=>Promise.resolve(),{when:l}=o;if(l){const[d,c]=l==="beforeChildren"?[r,a]:[a,r];return d().then(()=>c())}else return Promise.all([r(),a(n.delay)])}function sF(e,t,n=0,s=0,o=0,r=1,a){const l=[];for(const d of e.variantChildren)d.notify("AnimationStart",t),l.push(Uf(d,t,{...a,delay:n+(typeof s=="function"?0:s)+X_(e.variantChildren,d,s,o,r)}).then(()=>d.notify("AnimationComplete",t)));return Promise.all(l)}function iF(e,t,n={}){e.notify("AnimationStart",t);let s;if(Array.isArray(t)){const o=t.map(r=>Uf(e,r,n));s=Promise.all(o)}else if(typeof t=="string")s=Uf(e,t,n);else{const o=typeof t=="function"?mr(e,t,n.custom):t;s=Promise.all(n1(e,o,n))}return s.then(()=>{e.notify("AnimationComplete",t)})}const oF={test:e=>e==="auto",parse:e=>e},s1=e=>t=>t.test(e),i1=[ka,gt,Mi,eo,IG,DG,oF],U0=e=>i1.find(s1(e));function rF(e){return typeof e=="number"?e===0:e!==null?e==="none"||e==="0"||m_(e):!0}const aF=new Set(["brightness","contrast","saturate","opacity"]);function lF(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[s]=n.match(qg)||[];if(!s)return e;const o=n.replace(s,"");let r=aF.has(t)?1:0;return s!==n&&(r*=100),t+"("+r+o+")"}const dF=/\b([a-z-]*)\(.*?\)/gu,Kf={...hi,getAnimatableNone:e=>{const t=e.match(dF);return t?t.map(lF).join(" "):e}},qf={...hi,getAnimatableNone:e=>{const t=hi.parse(e);return hi.createTransformer(e)(t.map(s=>typeof s=="number"?0:typeof s=="object"?{...s,alpha:1}:s))}},K0={...ka,transform:Math.round},cF={rotate:eo,pathRotation:eo,rotateX:eo,rotateY:eo,rotateZ:eo,scale:Ad,scaleX:Ad,scaleY:Ad,scaleZ:Ad,skew:eo,skewX:eo,skewY:eo,distance:gt,translateX:gt,translateY:gt,translateZ:gt,x:gt,y:gt,z:gt,perspective:gt,transformPerspective:gt,opacity:Ol,originX:A0,originY:A0,originZ:gt},hu={borderWidth:gt,borderTopWidth:gt,borderRightWidth:gt,borderBottomWidth:gt,borderLeftWidth:gt,borderRadius:gt,borderTopLeftRadius:gt,borderTopRightRadius:gt,borderBottomRightRadius:gt,borderBottomLeftRadius:gt,width:gt,maxWidth:gt,height:gt,maxHeight:gt,top:gt,right:gt,bottom:gt,left:gt,inset:gt,insetBlock:gt,insetBlockStart:gt,insetBlockEnd:gt,insetInline:gt,insetInlineStart:gt,insetInlineEnd:gt,padding:gt,paddingTop:gt,paddingRight:gt,paddingBottom:gt,paddingLeft:gt,paddingBlock:gt,paddingBlockStart:gt,paddingBlockEnd:gt,paddingInline:gt,paddingInlineStart:gt,paddingInlineEnd:gt,margin:gt,marginTop:gt,marginRight:gt,marginBottom:gt,marginLeft:gt,marginBlock:gt,marginBlockStart:gt,marginBlockEnd:gt,marginInline:gt,marginInlineStart:gt,marginInlineEnd:gt,fontSize:gt,backgroundPositionX:gt,backgroundPositionY:gt,...cF,zIndex:K0,fillOpacity:Ol,strokeOpacity:Ol,numOctaves:K0},uF={...hu,color:$n,backgroundColor:$n,outlineColor:$n,fill:$n,stroke:$n,borderColor:$n,borderTopColor:$n,borderRightColor:$n,borderBottomColor:$n,borderLeftColor:$n,filter:Kf,WebkitFilter:Kf,mask:qf,WebkitMask:qf},o1=e=>uF[e],hF=new Set([Kf,qf]);function r1(e,t){let n=o1(e);return hF.has(n)||(n=hi),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const pF=new Set(["auto","none","0"]);function fF(e,t,n){let s=0,o;for(;s<e.length&&!o;){const r=e[s];typeof r=="string"&&!pF.has(r)&&la(r).values.length&&(o=e[s]),s++}if(o&&n)for(const r of t)e[r]=r1(n,o)}class mF extends Qg{constructor(t,n,s,o,r){super(t,n,s,o,r,!0)}readKeyframes(){const{unresolvedKeyframes:t,element:n,name:s}=this;if(!n||!n.current)return;super.readKeyframes();for(let u=0;u<t.length;u++){let h=t[u];if(typeof h=="string"&&(h=h.trim(),Kg(h))){const p=J_(h,n.current);p!==void 0&&(t[u]=p),u===t.length-1&&(this.finalKeyframe=h)}}if(this.resolveNoneKeyframes(),!Q_.has(s)||t.length!==2)return;const[o,r]=t,a=U0(o),l=U0(r),d=P0(o),c=P0(r);if(d!==c&&Eo[s]){this.needsMeasurement=!0;return}if(a!==l)if(H0(a)&&H0(l))for(let u=0;u<t.length;u++){const h=t[u];typeof h=="string"&&(t[u]=parseFloat(h))}else Eo[s]&&(this.needsMeasurement=!0)}resolveNoneKeyframes(){const{unresolvedKeyframes:t,name:n}=this,s=[];for(let o=0;o<t.length;o++)(t[o]===null||rF(t[o]))&&s.push(o);s.length&&fF(t,s,n)}measureInitialState(){const{element:t,unresolvedKeyframes:n,name:s}=this;if(!t||!t.current)return;s==="height"&&(this.suspendedScrollY=window.pageYOffset),this.measuredOrigin=Eo[s](t.measureViewportBox(),window.getComputedStyle(t.current)),n[0]=this.measuredOrigin;const o=n[n.length-1];o!==void 0&&t.getValue(s,o).jump(o,!1)}measureEndState(){const{element:t,name:n,unresolvedKeyframes:s}=this;if(!t||!t.current)return;const o=t.getValue(n);o&&o.jump(this.measuredOrigin,!1);const r=s.length-1,a=s[r];s[r]=Eo[n](t.measureViewportBox(),window.getComputedStyle(t.current)),a!==null&&this.finalKeyframe===void 0&&(this.finalKeyframe=a),this.removedTransforms?.length&&this.removedTransforms.forEach(([l,d])=>{t.getValue(l).set(d)}),this.resolveNoneKeyframes()}}const ix=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function a1(e,t,n){if(e==null)return[];if(e instanceof EventTarget)return[e];if(typeof e=="string"){let s=document;const o=n?.[e]??s.querySelectorAll(e);return o?Array.from(o):[]}return Array.from(e).filter(s=>s!=null)}const Yf=(e,t)=>t&&typeof e=="number"?t.transform(e):e;function Tc(e){return f_(e)&&"offsetHeight"in e&&!("ownerSVGElement"in e)}const{schedule:ox}=T_(queueMicrotask,!1),oi={x:!1,y:!1};function l1(){return oi.x||oi.y}function gF(e){return e==="x"||e==="y"?oi[e]?null:(oi[e]=!0,()=>{oi[e]=!1}):oi.x||oi.y?null:(oi.x=oi.y=!0,()=>{oi.x=oi.y=!1})}function d1(e,t){const n=a1(e),s=new AbortController,o={passive:!0,...t,signal:s.signal};return[n,o,()=>s.abort()]}function xF(e){return!(e.pointerType==="touch"||l1())}function vF(e,t,n={}){const[s,o,r]=d1(e,n);return s.forEach(a=>{let l=!1,d=!1,c;const u=()=>{a.removeEventListener("pointerleave",g)},h=v=>{c&&(c(v),c=void 0),u()},p=v=>{l=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),d&&(d=!1,h(v))},f=()=>{l=!0,window.addEventListener("pointerup",p,o),window.addEventListener("pointercancel",p,o)},g=v=>{if(v.pointerType!=="touch"){if(l){d=!0;return}h(v)}},x=v=>{if(!xF(v))return;d=!1;const y=t(a,v);typeof y=="function"&&(c=y,a.addEventListener("pointerleave",g,o))};a.addEventListener("pointerenter",x,o),a.addEventListener("pointerdown",f,o)}),r}const c1=(e,t)=>t?e===t?!0:c1(e,t.parentElement):!1,rx=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1,bF=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function wF(e){return bF.has(e.tagName)||e.isContentEditable===!0}const yF=new Set(["INPUT","SELECT","TEXTAREA"]);function SF(e){return yF.has(e.tagName)||e.isContentEditable===!0}const Dc=new WeakSet;function q0(e){return t=>{t.key==="Enter"&&e(t)}}function rp(e,t){e.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const CF=(e,t)=>{const n=e.currentTarget;if(!n)return;const s=q0(()=>{if(Dc.has(n))return;rp(n,"down");const o=q0(()=>{rp(n,"up")}),r=()=>rp(n,"cancel");n.addEventListener("keyup",o,t),n.addEventListener("blur",r,t)});n.addEventListener("keydown",s,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",s),t)};function Y0(e){return rx(e)&&!l1()}const X0=new WeakSet;function kF(e,t,n={}){const[s,o,r]=d1(e,n),a=l=>{const d=l.currentTarget;if(!Y0(l)||X0.has(l))return;Dc.add(d),n.stopPropagation&&X0.add(l);const c=t(d,l),u={...o,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",p,u),window.removeEventListener("pointercancel",f,u),Dc.has(d)&&Dc.delete(d),Y0(g)&&typeof c=="function"&&c(g,{success:x})},p=g=>{h(g,d===window||d===document||n.useGlobalTarget||c1(d,g.target))},f=g=>{h(g,!1)};window.addEventListener("pointerup",p,u),window.addEventListener("pointercancel",f,u)};return s.forEach(l=>{(n.useGlobalTarget?window:l).addEventListener("pointerdown",a,o),Tc(l)&&(l.addEventListener("focus",c=>CF(c,o)),!wF(l)&&!l.hasAttribute("tabindex")&&(l.tabIndex=0))}),r}function ax(e){return f_(e)&&"ownerSVGElement"in e}const Ic=new WeakMap;let Ec;const u1=(e,t,n)=>(s,o)=>o&&o[0]?o[0][e+"Size"]:ax(s)&&"getBBox"in s?s.getBBox()[t]:s[n],jF=u1("inline","width","offsetWidth"),_F=u1("block","height","offsetHeight");function NF({target:e,borderBoxSize:t}){Ic.get(e)?.forEach(n=>{n(e,{get width(){return jF(e,t)},get height(){return _F(e,t)}})})}function TF(e){e.forEach(NF)}function DF(){typeof ResizeObserver>"u"||(Ec=new ResizeObserver(TF))}function IF(e,t){Ec||DF();const n=a1(e);return n.forEach(s=>{let o=Ic.get(s);o||(o=new Set,Ic.set(s,o)),o.add(t),Ec?.observe(s)}),()=>{n.forEach(s=>{const o=Ic.get(s);o?.delete(t),o?.size||Ec?.unobserve(s)})}}const Pc=new Set;let Vr;function EF(){Vr=()=>{const e={get width(){return window.innerWidth},get height(){return window.innerHeight}};Pc.forEach(t=>t(e))},window.addEventListener("resize",Vr)}function PF(e){return Pc.add(e),Vr||EF(),()=>{Pc.delete(e),!Pc.size&&typeof Vr=="function"&&(window.removeEventListener("resize",Vr),Vr=void 0)}}function Z0(e,t){return typeof e=="function"?PF(e):IF(e,t)}function AF(e){return ax(e)&&e.tagName==="svg"}const MF=[...i1,$n,hi],RF=e=>MF.find(s1(e)),J0=()=>({translate:0,scale:1,origin:0,originPoint:0}),$r=()=>({x:J0(),y:J0()}),Q0=()=>({min:0,max:0}),qn=()=>({x:Q0(),y:Q0()}),LF=new WeakMap;function lh(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}function zl(e){return typeof e=="string"||Array.isArray(e)}const lx=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],dx=["initial",...lx];function dh(e){return lh(e.animate)||dx.some(t=>zl(e[t]))}function h1(e){return!!(dh(e)||e.variants)}function OF(e,t,n){for(const s in t){const o=t[s],r=n[s];if(ls(o))e.addValue(s,o);else if(ls(r))e.addValue(s,da(o,{owner:e}));else if(r!==o)if(e.hasValue(s)){const a=e.getValue(s);a.liveStyle===!0?a.jump(o):a.hasAnimated||a.set(o)}else{const a=e.getStaticValue(s);e.addValue(s,da(a!==void 0?a:o,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const pu={current:null},cx={current:!1},zF=typeof window<"u";function p1(){if(cx.current=!0,!!zF)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>pu.current=e.matches;e.addEventListener("change",t),t()}else pu.current=!1}const eb=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let fu={};function f1(e){fu=e}function GF(){return fu}class FF{scrapeMotionValuesFromProps(t,n,s){return{}}constructor({parent:t,props:n,presenceContext:s,reducedMotionConfig:o,skipAnimations:r,blockInitialAnimation:a,visualState:l},d={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=Qg,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Ss.now();this.renderScheduledAt<f&&(this.renderScheduledAt=f,_n.render(this.render,!1,!0))};const{latestValues:c,renderState:u}=l;this.latestValues=c,this.baseTarget={...c},this.initialValues=n.initial?{...c}:{},this.renderState=u,this.parent=t,this.props=n,this.presenceContext=s,this.depth=t?t.depth+1:0,this.reducedMotionConfig=o,this.skipAnimationsConfig=r,this.options=d,this.blockInitialAnimation=!!a,this.isControllingVariants=dh(n),this.isVariantNode=h1(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:h,...p}=this.scrapeMotionValuesFromProps(n,{},this);for(const f in p){const g=p[f];c[f]!==void 0&&ls(g)&&g.set(c[f])}}mount(t){if(this.hasBeenMounted)for(const n in this.initialValues)this.values.get(n)?.jump(this.initialValues[n]),this.latestValues[n]=this.initialValues[n];this.current=t,LF.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,s)=>this.bindToMotionValue(s,n)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(cx.current||p1(),this.shouldReduceMotion=pu.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,this.parent?.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){this.projection&&this.projection.unmount(),Mo(this.notifyUpdate),Mo(this.render),this.valueSubscriptions.forEach(t=>t()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent?.removeChild(this);for(const t in this.events)this.events[t].clear();for(const t in this.features){const n=this.features[t];n&&(n.unmount(),n.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),n.accelerate&&Y_.has(t)&&this.current instanceof HTMLElement){const{factory:a,keyframes:l,times:d,ease:c,duration:u}=n.accelerate,h=new K_({element:this.current,name:t,keyframes:l,times:d,ease:c,duration:Ls(u)}),p=a(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const s=_a.has(t);s&&this.onBindTransform&&this.onBindTransform();const o=n.on("change",a=>{this.latestValues[t]=a,this.props.onUpdate&&_n.preRender(this.notifyUpdate),s&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let r;typeof window<"u"&&window.MotionCheckAppearSync&&(r=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{o(),r&&r()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in fu){const n=fu[t];if(!n)continue;const{isEnabled:s,Feature:o}=n;if(!this.features[t]&&o&&s(this.props)&&(this.features[t]=new o(this)),this.features[t]){const r=this.features[t];r.isMounted?r.update():(r.mount(),r.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):qn()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let s=0;s<eb.length;s++){const o=eb[s];this.propEventSubscriptions[o]&&(this.propEventSubscriptions[o](),delete this.propEventSubscriptions[o]);const r="on"+o,a=t[r];a&&(this.propEventSubscriptions[o]=this.on(o,a))}this.prevMotionValues=OF(this,this.scrapeMotionValuesFromProps(t,this.prevProps||{},this),this.prevMotionValues),this.handleChildMotionValue&&this.handleChildMotionValue()}getProps(){return this.props}getVariant(t){return this.props.variants?this.props.variants[t]:void 0}getDefaultTransition(){return this.props.transition}getTransformPagePoint(){return this.props.transformPagePoint}getClosestVariantNode(){return this.isVariantNode?this:this.parent?this.parent.getClosestVariantNode():void 0}addVariantChild(t){const n=this.getClosestVariantNode();if(n)return n.variantChildren&&n.variantChildren.add(t),()=>n.variantChildren.delete(t)}addValue(t,n){const s=this.values.get(t);n!==s&&(s&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let s=this.values.get(t);return s===void 0&&n!==void 0&&(s=da(n===null?void 0:n,{owner:this}),this.addValue(t,s)),s}readValue(t,n){let s=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return s!=null&&(typeof s=="string"&&(p_(s)||m_(s))?s=parseFloat(s):!RF(s)&&hi.test(n)&&(s=r1(t,n)),this.setBaseTarget(t,ls(s)?s.get():s)),ls(s)?s.get():s}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){const{initial:n}=this.props;let s;if(typeof n=="string"||typeof n=="object"){const r=nx(this.props,n,this.presenceContext?.custom);r&&(s=r[t])}if(n&&s!==void 0)return s;const o=this.getBaseTargetFromProps(this.props,t);return o!==void 0&&!ls(o)?o:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new $g),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){ox.render(this.render)}}class m1 extends FF{constructor(){super(...arguments),this.KeyframeResolver=mF}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){const s=t.style;return s?s[n]:void 0}removeValueFromRenderState(t,{vars:n,style:s}){delete n[t],delete s[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;ls(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class Ho{constructor(t){this.isMounted=!1,this.node=t}update(){}}function g1({top:e,left:t,right:n,bottom:s}){return{x:{min:t,max:n},y:{min:e,max:s}}}function HF({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function BF(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),s=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:s.y,right:s.x}}function ap(e){return e===void 0||e===1}function Xf({scale:e,scaleX:t,scaleY:n}){return!ap(e)||!ap(t)||!ap(n)}function tr(e){return Xf(e)||x1(e)||e.z||e.rotate||e.rotateX||e.rotateY||e.skewX||e.skewY}function x1(e){return tb(e.x)||tb(e.y)}function tb(e){return e&&e!=="0%"}function mu(e,t,n){const s=e-n,o=t*s;return n+o}function nb(e,t,n,s,o){return o!==void 0&&(e=mu(e,o,s)),mu(e,n,s)+t}function Zf(e,t=0,n=1,s,o){e.min=nb(e.min,t,n,s,o),e.max=nb(e.max,t,n,s,o)}function v1(e,{x:t,y:n}){Zf(e.x,t.translate,t.scale,t.originPoint),Zf(e.y,n.translate,n.scale,n.originPoint)}const sb=.999999999999,ib=1.0000000000001;function VF(e,t,n,s=!1){const o=n.length;if(!o)return;t.x=t.y=1;let r,a;for(let l=0;l<o;l++){r=n[l],a=r.projectionDelta;const{visualElement:d}=r.options;d&&d.props.style&&d.props.style.display==="contents"||(s&&r.options.layoutScroll&&r.scroll&&r!==r.root&&(ji(e.x,-r.scroll.offset.x),ji(e.y,-r.scroll.offset.y)),a&&(t.x*=a.x.scale,t.y*=a.y.scale,v1(e,a)),s&&tr(r.latestValues)&&Ac(e,r.latestValues,r.layout?.layoutBox))}t.x<ib&&t.x>sb&&(t.x=1),t.y<ib&&t.y>sb&&(t.y=1)}function ji(e,t){e.min+=t,e.max+=t}function ob(e,t,n,s,o=.5){const r=jn(e.min,e.max,o);Zf(e,t,n,r,s)}function rb(e,t){return typeof e=="string"?parseFloat(e)/100*(t.max-t.min):e}function Ac(e,t,n){const s=n??e;ob(e.x,rb(t.x,s.x),t.scaleX,t.scale,t.originX),ob(e.y,rb(t.y,s.y),t.scaleY,t.scale,t.originY)}function b1(e,t){return g1(BF(e.getBoundingClientRect(),t))}function $F(e,t,n){const s=b1(e,n),{scroll:o}=t;return o&&(ji(s.x,o.offset.x),ji(s.y,o.offset.y)),s}const WF={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},UF=ja.length;function KF(e,t,n){let s="",o=!0;for(let a=0;a<UF;a++){const l=ja[a],d=e[l];if(d===void 0)continue;let c=!0;if(typeof d=="number")c=d===(l.startsWith("scale")?1:0);else{const u=parseFloat(d);c=l.startsWith("scale")?u===1:u===0}if(!c||n){const u=Yf(d,hu[l]);if(!c){o=!1;const h=WF[l]||l;s+=`${h}(${u}) `}n&&(t[l]=u)}}const r=e.pathRotation;return r&&(o=!1,s+=`rotate(${Yf(r,hu.pathRotation)}) `),s=s.trim(),n?s=n(t,o?"":s):o&&(s="none"),s}function ux(e,t,n){const{style:s,vars:o,transformOrigin:r}=e;let a=!1,l=!1;for(const d in t){const c=t[d];if(_a.has(d)){a=!0;continue}else if(I_(d)){o[d]=c;continue}else{const u=Yf(c,hu[d]);d.startsWith("origin")?(l=!0,r[d]=u):s[d]=u}}if(t.transform||(a||n?s.transform=KF(t,e.transform,n):s.transform&&(s.transform="none")),l){const{originX:d="50%",originY:c="50%",originZ:u=0}=r;s.transformOrigin=`${d} ${c} ${u}`}}function w1(e,{style:t,vars:n},s,o){const r=e.style;let a;for(a in t)r[a]=t[a];o?.applyProjectionStyles(r,s);for(a in n)r.setProperty(a,n[a])}function ab(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Pa={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(gt.test(e))e=parseFloat(e);else return e;const n=ab(e,t.target.x),s=ab(e,t.target.y);return`${n}% ${s}%`}},qF={correct:(e,{treeScale:t,projectionDelta:n})=>{const s=e,o=hi.parse(e);if(o.length>5)return s;const r=hi.createTransformer(e),a=typeof o[0]!="number"?1:0,l=n.x.scale*t.x,d=n.y.scale*t.y;o[0+a]/=l,o[1+a]/=d;const c=jn(l,d,.5);return typeof o[2+a]=="number"&&(o[2+a]/=c),typeof o[3+a]=="number"&&(o[3+a]/=c),r(o)}},Jf={borderRadius:{...Pa,applyTo:[...ix]},borderTopLeftRadius:Pa,borderTopRightRadius:Pa,borderBottomLeftRadius:Pa,borderBottomRightRadius:Pa,boxShadow:qF};function y1(e,{layout:t,layoutId:n}){return _a.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!Jf[e]||e==="opacity")}function hx(e,t,n){const s=e.style,o=t?.style,r={};if(!s)return r;for(const a in s)(ls(s[a])||o&&ls(o[a])||y1(a,e)||n?.getValue(a)?.liveStyle!==void 0)&&(r[a]=s[a]);return r}function YF(e){return window.getComputedStyle(e)}class XF extends m1{constructor(){super(...arguments),this.type="html",this.renderInstance=w1}mount(t){rh(!!t.style),super.mount(t)}readValueFromInstance(t,n){if(_a.has(n))return this.projection?.isProjecting?zf(n):g3(t,n);{const s=YF(t),o=(I_(n)?s.getPropertyValue(n):s[n])||0;return typeof o=="string"?o.trim():o}}measureInstanceViewportBox(t,{transformPagePoint:n}){return b1(t,n)}build(t,n,s){ux(t,n,s.transformTemplate)}scrapeMotionValuesFromProps(t,n,s){return hx(t,n,s)}}const ZF={offset:"stroke-dashoffset",array:"stroke-dasharray"},JF={offset:"strokeDashoffset",array:"strokeDasharray"};function QF(e,t,n=1,s=0,o=!0){e.pathLength=1;const r=o?ZF:JF;e[r.offset]=`${-s}`,e[r.array]=`${t} ${n}`}const S1=["transform","opacity","offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function C1(e,{attrX:t,attrY:n,attrScale:s,pathLength:o,pathSpacing:r=1,pathOffset:a=0,...l},d,c,u){if(ux(e,l,c),d){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:p}=e;for(const f of S1)h[f]!==void 0&&(p[f]=h[f],delete h[f]);(p.transform||h.transformOrigin)&&(p.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),p.transform&&(p.transformBox=u?.transformBox??"fill-box",delete h.transformBox),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),s!==void 0&&(h.scale=s),o!==void 0&&QF(h,o,r,a,!1)}const k1=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]),j1=e=>typeof e=="string"&&e.toLowerCase()==="svg";function eH(e,t,n,s){w1(e,t,void 0,s);for(const o in t.attrs)e.setAttribute(k1.has(o)?o:sx(o),t.attrs[o])}function _1(e,t,n){const s=hx(e,t,n);for(const o in e)if(ls(e[o])||ls(t[o])){const r=ja.indexOf(o)!==-1?"attr"+o.charAt(0).toUpperCase()+o.substring(1):o;s[r]=e[o]}return s}class tH extends m1{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=qn}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(_a.has(n)){const s=o1(n);return s&&s.default||0}if(S1.includes(n)){const o=getComputedStyle(t)[n];if(typeof o=="string"&&o)return o.trim()}return n=k1.has(n)?n:sx(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,s){return _1(t,n,s)}build(t,n,s){C1(t,n,this.isSVGTag,s.transformTemplate,s.style)}renderInstance(t,n,s,o){eH(t,n,s,o)}mount(t){this.isSVGTag=j1(t.tagName),super.mount(t)}}const nH=dx.length;function N1(e){if(!e)return;if(!e.isControllingVariants){const n=e.parent?N1(e.parent)||{}:{};return e.props.initial!==void 0&&(n.initial=e.props.initial),n}const t={};for(let n=0;n<nH;n++){const s=dx[n],o=e.props[s];(zl(o)||o===!1)&&(t[s]=o)}return t}function T1(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let s=0;s<n;s++)if(t[s]!==e[s])return!1;return!0}const sH=[...lx].reverse(),iH=lx.length;function oH(e){return t=>Promise.all(t.map(({animation:n,options:s})=>iF(e,n,s)))}function rH(e){let t=oH(e),n=lb(),s=!0,o=!1;const r=c=>(u,h)=>{const p=mr(e,h,c==="exit"?e.presenceContext?.custom:void 0);if(p){const{transition:f,transitionEnd:g,...x}=p;u={...u,...x,...g}}return u};function a(c){t=c(e)}function l(c){const{props:u}=e,h=N1(e.parent)||{},p=[],f=new Set;let g={},x=1/0;for(let y=0;y<iH;y++){const w=sH[y],b=n[w],_=u[w]!==void 0?u[w]:h[w],j=zl(_),N=w===c?b.isActive:null;N===!1&&(x=y);let C=_===h[w]&&_!==u[w]&&j;if(C&&(s||o)&&e.manuallyAnimateOnMount&&(C=!1),b.protectedKeys={...g},!b.isActive&&N===null||!_&&!b.prevProp||lh(_)||typeof _=="boolean")continue;if(w==="exit"&&b.isActive&&N!==!0){b.prevResolvedValues&&(g={...g,...b.prevResolvedValues});continue}const S=aH(b.prevProp,_);let A=S||w===c&&b.isActive&&!C&&j||y>x&&j,E=!1;const I=Array.isArray(_)?_:[_];let D=I.reduce(r(w),{});N===!1&&(D={});const{prevResolvedValues:T={}}=b,z={...T,...D},$=H=>{A=!0,f.has(H)&&(E=!0,f.delete(H)),b.needsAnimating[H]=!0;const oe=e.getValue(H);oe&&(oe.liveStyle=!1)};for(const H in z){const oe=D[H],te=T[H];if(g.hasOwnProperty(H))continue;let O=!1;$f(oe)&&$f(te)?O=!T1(oe,te)||S:O=oe!==te,O?oe!=null?$(H):f.add(H):oe!==void 0&&f.has(H)?$(H):b.protectedKeys[H]=!0}b.prevProp=_,b.prevResolvedValues=D,b.isActive&&(g={...g,...D}),(s||o)&&e.blockInitialAnimation&&(A=!1);const R=C&&S;A&&(!R||E)&&p.push(...I.map(H=>{const oe={type:w};if(typeof H=="string"&&(s||o)&&!R&&e.manuallyAnimateOnMount&&e.parent){const{parent:te}=e,O=mr(te,H);if(te.enteringChildren&&O){const{delayChildren:V}=O.transition||{};oe.delay=X_(te.enteringChildren,e,V)}}return{animation:H,options:oe}}))}if(f.size){const y={};if(typeof u.initial!="boolean"){const w=mr(e,Array.isArray(u.initial)?u.initial[0]:u.initial);w&&w.transition&&(y.transition=w.transition)}f.forEach(w=>{const b=e.getBaseTarget(w),_=e.getValue(w);_&&(_.liveStyle=!0),y[w]=b??null}),p.push({animation:y})}let v=!!p.length;return s&&(u.initial===!1||u.initial===u.animate)&&!e.manuallyAnimateOnMount&&(v=!1),s=!1,o=!1,v?t(p):Promise.resolve()}function d(c,u){if(n[c].isActive===u)return Promise.resolve();e.variantChildren?.forEach(p=>p.animationState?.setActive(c,u)),n[c].isActive=u;const h=l(c);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:l,setActive:d,setAnimateFunction:a,getState:()=>n,reset:()=>{n=lb(),o=!0}}}function aH(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!T1(t,e):!1}function Yo(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function lb(){return{animate:Yo(!0),whileInView:Yo(),whileHover:Yo(),whileTap:Yo(),whileDrag:Yo(),whileFocus:Yo(),exit:Yo()}}function Qf(e,t){e.min=t.min,e.max=t.max}function si(e,t){Qf(e.x,t.x),Qf(e.y,t.y)}function db(e,t){e.translate=t.translate,e.scale=t.scale,e.originPoint=t.originPoint,e.origin=t.origin}const D1=1e-4,lH=1-D1,dH=1+D1,I1=.01,cH=0-I1,uH=0+I1;function Cs(e){return e.max-e.min}function hH(e,t,n){return Math.abs(e-t)<=n}function cb(e,t,n,s=.5){e.origin=s,e.originPoint=jn(t.min,t.max,e.origin),e.scale=Cs(n)/Cs(t),e.translate=jn(n.min,n.max,e.origin)-e.originPoint,(e.scale>=lH&&e.scale<=dH||isNaN(e.scale))&&(e.scale=1),(e.translate>=cH&&e.translate<=uH||isNaN(e.translate))&&(e.translate=0)}function ul(e,t,n,s){cb(e.x,t.x,n.x,s?s.originX:void 0),cb(e.y,t.y,n.y,s?s.originY:void 0)}function ub(e,t,n,s=0){const o=s?jn(n.min,n.max,s):n.min;e.min=o+t.min,e.max=e.min+Cs(t)}function pH(e,t,n,s){ub(e.x,t.x,n.x,s?.x),ub(e.y,t.y,n.y,s?.y)}function hb(e,t,n,s=0){const o=s?jn(n.min,n.max,s):n.min;e.min=t.min-o,e.max=e.min+Cs(t)}function gu(e,t,n,s){hb(e.x,t.x,n.x,s?.x),hb(e.y,t.y,n.y,s?.y)}function pb(e,t,n,s,o){return e-=t,e=mu(e,1/n,s),o!==void 0&&(e=mu(e,1/o,s)),e}function fH(e,t=0,n=1,s=.5,o,r=e,a=e){if(Mi.test(t)&&(t=parseFloat(t),t=jn(a.min,a.max,t/100)-a.min),typeof t!="number")return;let l=jn(r.min,r.max,s);e===r&&(l-=t),e.min=pb(e.min,t,n,l,o),e.max=pb(e.max,t,n,l,o)}function fb(e,t,[n,s,o],r,a){fH(e,t[n],t[s],t[o],t.scale,r,a)}const mH=["x","scaleX","originX"],gH=["y","scaleY","originY"];function mb(e,t,n,s){fb(e.x,t,mH,n?n.x:void 0,s?s.x:void 0),fb(e.y,t,gH,n?n.y:void 0,s?s.y:void 0)}function gb(e){return e.translate===0&&e.scale===1}function E1(e){return gb(e.x)&&gb(e.y)}function xb(e,t){return e.min===t.min&&e.max===t.max}function xH(e,t){return xb(e.x,t.x)&&xb(e.y,t.y)}function vb(e,t){return Math.round(e.min)===Math.round(t.min)&&Math.round(e.max)===Math.round(t.max)}function P1(e,t){return vb(e.x,t.x)&&vb(e.y,t.y)}function bb(e){return Cs(e.x)/Cs(e.y)}function wb(e,t){return e.translate===t.translate&&e.scale===t.scale&&e.originPoint===t.originPoint}function ki(e){return[e("x"),e("y")]}function vH(e,t,n){let s="";const o=e.x.translate/t.x,r=e.y.translate/t.y,a=n?.z||0;if((o||r||a)&&(s=`translate3d(${o}px, ${r}px, ${a}px) `),(t.x!==1||t.y!==1)&&(s+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:c,rotate:u,pathRotation:h,rotateX:p,rotateY:f,skewX:g,skewY:x}=n;c&&(s=`perspective(${c}px) ${s}`),u&&(s+=`rotate(${u}deg) `),h&&(s+=`rotate(${h}deg) `),p&&(s+=`rotateX(${p}deg) `),f&&(s+=`rotateY(${f}deg) `),g&&(s+=`skewX(${g}deg) `),x&&(s+=`skewY(${x}deg) `)}const l=e.x.scale*t.x,d=e.y.scale*t.y;return(l!==1||d!==1)&&(s+=`scale(${l}, ${d})`),s||"none"}const bH=ix.length,yb=e=>typeof e=="string"?parseFloat(e):e,Sb=e=>typeof e=="number"||gt.test(e);function wH(e,t,n,s,o,r){o?(e.opacity=jn(0,n.opacity??1,yH(s)),e.opacityExit=jn(t.opacity??1,0,SH(s))):r&&(e.opacity=jn(t.opacity??1,n.opacity??1,s));for(let a=0;a<bH;a++){const l=ix[a];let d=Cb(t,l),c=Cb(n,l);if(d===void 0&&c===void 0)continue;d||(d=0),c||(c=0),d===0||c===0||Sb(d)===Sb(c)?(e[l]=Math.max(jn(yb(d),yb(c),s),0),(Mi.test(c)||Mi.test(d))&&(e[l]+="%")):e[l]=c}(t.rotate||n.rotate)&&(e.rotate=jn(t.rotate||0,n.rotate||0,s))}function Cb(e,t){return e[t]!==void 0?e[t]:e.borderRadius}const yH=A1(0,.5,k_),SH=A1(.5,.95,Js);function A1(e,t,n){return s=>s<e?0:s>t?1:n(Ll(e,t,s))}function CH(e,t,n){const s=ls(e)?e:da(e);return s.start(tx("",s,t,n)),s.animation}function Gl(e,t,n,s={passive:!0}){return e.addEventListener(t,n,s),()=>e.removeEventListener(t,n,s)}const kH=(e,t)=>e.depth-t.depth;class jH{constructor(){this.children=[],this.isDirty=!1}add(t){Vg(this.children,t),this.isDirty=!0}remove(t){au(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(kH),this.isDirty=!1,this.children.forEach(t)}}function _H(e,t){const n=Ss.now(),s=({timestamp:o})=>{const r=o-n;r>=t&&(Mo(s),e(r-t))};return _n.setup(s,!0),()=>Mo(s)}function Mc(e){return ls(e)?e.get():e}class NH{constructor(){this.members=[]}add(t){Vg(this.members,t);for(let n=this.members.length-1;n>=0;n--){const s=this.members[n];if(s===t||s===this.lead||s===this.prevLead)continue;const o=s.instance;(!o||o.isConnected===!1)&&!s.snapshot&&(au(this.members,s),s.unmount())}t.scheduleRender()}remove(t){if(au(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){for(let n=this.members.indexOf(t)-1;n>=0;n--){const s=this.members[n];if(s.isPresent!==!1&&s.instance?.isConnected!==!1)return this.promote(s),!0}return!1}promote(t,n){const s=this.lead;if(t!==s&&(this.prevLead=s,this.lead=t,t.show(),s)){s.updateSnapshot(),t.scheduleRender();const{layoutDependency:o}=s.options,{layoutDependency:r}=t.options;(o===void 0||o!==r)&&(t.resumeFrom=s,n&&(s.preserveOpacity=!0),s.snapshot&&(t.snapshot=s.snapshot,t.snapshot.latestValues=s.animationValues||s.latestValues),t.root?.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&s.hide()}}exitAnimationComplete(){this.members.forEach(t=>{t.options.onExitComplete?.(),t.resumingFrom?.options.onExitComplete?.()})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){this.lead?.snapshot&&(this.lead.snapshot=void 0)}}const Rc={hasAnimatedSinceResize:!0,hasEverUpdated:!1},lp=["","X","Y","Z"],TH=1e3;let DH=0;function dp(e,t,n,s){const{latestValues:o}=t;o[e]&&(n[e]=o[e],t.setStaticValue(e,0),s&&(s[e]=0))}function M1(e){if(e.hasCheckedOptimisedAppear=!0,e.root===e)return;const{visualElement:t}=e.options;if(!t)return;const n=t1(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:o,layoutId:r}=e.options;window.MotionCancelOptimisedAnimation(n,"transform",_n,!(o||r))}const{parent:s}=e;s&&!s.hasCheckedOptimisedAppear&&M1(s)}function R1({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:s,resetTransform:o}){return class{constructor(a={},l=t?.()){this.id=DH++,this.animationId=0,this.animationCommitId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.hasCheckedOptimisedAppear=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.layoutVersion=0,this.updateScheduled=!1,this.scheduleUpdate=()=>this.update(),this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,this.nodes.forEach(PH),this.nodes.forEach(zH),this.nodes.forEach(GH),this.nodes.forEach(AH)},this.resolvedRelativeTargetAt=0,this.linkedParentVersion=0,this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=a,this.root=l?l.root||l:this,this.path=l?[...l.path,l]:[],this.parent=l,this.depth=l?l.depth+1:0;for(let d=0;d<this.path.length;d++)this.path[d].shouldResetTransform=!0;this.root===this&&(this.nodes=new jH)}addEventListener(a,l){return this.eventHandlers.has(a)||this.eventHandlers.set(a,new $g),this.eventHandlers.get(a).add(l)}notifyListeners(a,...l){const d=this.eventHandlers.get(a);d&&d.notify(...l)}hasListeners(a){return this.eventHandlers.has(a)}mount(a){if(this.instance)return;this.isSVG=ax(a)&&!AF(a),this.instance=a;const{layoutId:l,layout:d,visualElement:c}=this.options;if(c&&!c.current&&c.mount(a),this.root.nodes.add(this),this.parent&&this.parent.children.add(this),this.root.hasTreeAnimated&&(d||l)&&(this.isLayoutDirty=!0),e){let u,h=0;const p=()=>this.root.updateBlockedByResize=!1;_n.read(()=>{h=window.innerWidth}),e(a,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=_H(p,250),Rc.hasAnimatedSinceResize&&(Rc.hasAnimatedSinceResize=!1,this.nodes.forEach(_b)))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&c&&(l||d)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:p,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||c.getDefaultTransition()||$H,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=c.getProps(),y=!this.targetLayout||!P1(this.targetLayout,f),w=!h&&p;if(this.options.layoutRoot||this.resumeFrom||w||h&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const b={...ex(g,"layout"),onPlay:x,onComplete:v};(c.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b),this.setAnimationOrigin(u,w,b.path)}else h||_b(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const a=this.getStack();a&&a.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),Mo(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(FH),this.animationId++)}getTransformTemplate(){const{visualElement:a}=this.options;return a&&a.getProps().transformTemplate}willUpdate(a=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(window.MotionCancelOptimisedAnimation&&!this.hasCheckedOptimisedAppear&&M1(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u<this.path.length;u++){const h=this.path[u];h.shouldResetTransform=!0,(typeof h.latestValues.x=="string"||typeof h.latestValues.y=="string")&&(h.isLayoutDirty=!0),h.updateScroll("snapshot"),h.options.layoutRoot&&h.willUpdate(!1)}const{layoutId:l,layout:d}=this.options;if(l===void 0&&!d)return;const c=this.getTransformTemplate();this.prevTransformTemplateValue=c?c(this.latestValues,""):void 0,this.updateSnapshot(),a&&this.notifyListeners("willUpdate")}update(){if(this.updateScheduled=!1,this.isUpdateBlocked()){const d=this.updateBlockedByResize;this.unblockUpdate(),this.updateBlockedByResize=!1,this.clearAllSnapshots(),d&&this.nodes.forEach(RH),this.nodes.forEach(kb);return}if(this.animationId<=this.animationCommitId){this.nodes.forEach(jb);return}this.animationCommitId=this.animationId,this.isUpdating?(this.isUpdating=!1,this.nodes.forEach(LH),this.nodes.forEach(OH),this.nodes.forEach(IH),this.nodes.forEach(EH)):this.nodes.forEach(jb),this.clearAllSnapshots();const l=Ss.now();as.delta=Gi(0,1e3/60,l-as.timestamp),as.timestamp=l,as.isProcessing=!0,ep.update.process(as),ep.preRender.process(as),ep.render.process(as),as.isProcessing=!1}didUpdate(){this.updateScheduled||(this.updateScheduled=!0,ox.read(this.scheduleUpdate))}clearAllSnapshots(){this.nodes.forEach(MH),this.sharedNodes.forEach(HH)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,_n.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){_n.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Cs(this.snapshot.measuredBox.x)&&!Cs(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let d=0;d<this.path.length;d++)this.path[d].updateScroll();const a=this.layout;this.layout=this.measure(!1),this.layoutVersion++,this.layoutCorrected||(this.layoutCorrected=qn()),this.isLayoutDirty=!1,this.projectionDelta=void 0,this.notifyListeners("measure",this.layout.layoutBox);const{visualElement:l}=this.options;l&&l.notify("LayoutMeasure",this.layout.layoutBox,a?a.layoutBox:void 0)}updateScroll(a="measure"){let l=!!(this.options.layoutScroll&&this.instance);if(this.scroll&&this.scroll.animationId===this.root.animationId&&this.scroll.phase===a&&(l=!1),l&&this.instance){const d=s(this.instance);this.scroll={animationId:this.root.animationId,phase:a,isRoot:d,offset:n(this.instance),wasRoot:this.scroll?this.scroll.isRoot:d}}}resetTransform(){if(!o)return;const a=this.isLayoutDirty||this.shouldResetTransform||this.options.alwaysMeasureLayout,l=this.projectionDelta&&!E1(this.projectionDelta),d=this.getTransformTemplate(),c=d?d(this.latestValues,""):void 0,u=c!==this.prevTransformTemplateValue;a&&this.instance&&(l||tr(this.latestValues)||u)&&(o(this.instance,c),this.shouldResetTransform=!1,this.scheduleRender())}measure(a=!0){const l=this.measurePageBox();let d=this.removeElementScroll(l);return a&&(d=this.removeTransform(d)),WH(d),{animationId:this.root.animationId,measuredBox:l,layoutBox:d,latestValues:{},source:this.id}}measurePageBox(){const{visualElement:a}=this.options;if(!a)return qn();const l=a.measureViewportBox();if(!(this.scroll?.wasRoot||this.path.some(UH))){const{scroll:c}=this.root;c&&(ji(l.x,c.offset.x),ji(l.y,c.offset.y))}return l}removeElementScroll(a){const l=qn();if(si(l,a),this.scroll?.wasRoot)return l;for(let d=0;d<this.path.length;d++){const c=this.path[d],{scroll:u,options:h}=c;c!==this.root&&u&&h.layoutScroll&&(u.wasRoot&&si(l,a),ji(l.x,u.offset.x),ji(l.y,u.offset.y))}return l}applyTransform(a,l=!1,d){const c=d||qn();si(c,a);for(let u=0;u<this.path.length;u++){const h=this.path[u];!l&&h.options.layoutScroll&&h.scroll&&h!==h.root&&(ji(c.x,-h.scroll.offset.x),ji(c.y,-h.scroll.offset.y)),tr(h.latestValues)&&Ac(c,h.latestValues,h.layout?.layoutBox)}return tr(this.latestValues)&&Ac(c,this.latestValues,this.layout?.layoutBox),c}removeTransform(a){const l=qn();si(l,a);for(let d=0;d<this.path.length;d++){const c=this.path[d];if(!tr(c.latestValues))continue;let u;c.instance&&(Xf(c.latestValues)&&c.updateSnapshot(),u=qn(),si(u,c.measurePageBox())),mb(l,c.latestValues,c.snapshot?.layoutBox,u)}return tr(this.latestValues)&&mb(l,this.latestValues),l}setTargetDelta(a){this.targetDelta=a,this.root.scheduleUpdateProjection(),this.isProjectionDirty=!0}setOptions(a){this.options={...this.options,...a,crossfade:a.crossfade!==void 0?a.crossfade:!0}}clearMeasurements(){this.scroll=void 0,this.layout=void 0,this.snapshot=void 0,this.prevTransformTemplateValue=void 0,this.targetDelta=void 0,this.target=void 0,this.isLayoutDirty=!1}forceRelativeParentToResolveTarget(){this.relativeParent&&this.relativeParent.resolvedRelativeTargetAt!==as.timestamp&&this.relativeParent.resolveTargetDelta(!0)}resolveTargetDelta(a=!1){const l=this.getLead();this.isProjectionDirty||(this.isProjectionDirty=l.isProjectionDirty),this.isTransformDirty||(this.isTransformDirty=l.isTransformDirty),this.isSharedProjectionDirty||(this.isSharedProjectionDirty=l.isSharedProjectionDirty);const d=!!this.resumingFrom||this!==l;if(!(a||d&&this.isSharedProjectionDirty||this.isProjectionDirty||this.parent?.isProjectionDirty||this.attemptToResolveRelativeTarget||this.root.updateBlockedByResize))return;const{layout:u,layoutId:h}=this.options;if(!this.layout||!(u||h))return;this.resolvedRelativeTargetAt=as.timestamp;const p=this.getClosestProjectingParent();p&&this.linkedParentVersion!==p.layoutVersion&&!p.options.layoutRoot&&this.removeRelativeTarget(),!this.targetDelta&&!this.relativeTarget&&(this.options.layoutAnchor!==!1&&p&&p.layout?this.createRelativeTarget(p,this.layout.layoutBox,p.layout.layoutBox):this.removeRelativeTarget()),!(!this.relativeTarget&&!this.targetDelta)&&(this.target||(this.target=qn(),this.targetWithTransforms=qn()),this.relativeTarget&&this.relativeTargetOrigin&&this.relativeParent&&this.relativeParent.target?(this.forceRelativeParentToResolveTarget(),pH(this.target,this.relativeTarget,this.relativeParent.target,this.options.layoutAnchor||void 0)):this.targetDelta?(this.resumingFrom?this.applyTransform(this.layout.layoutBox,!1,this.target):si(this.target,this.layout.layoutBox),v1(this.target,this.targetDelta)):si(this.target,this.layout.layoutBox),this.attemptToResolveRelativeTarget&&(this.attemptToResolveRelativeTarget=!1,this.options.layoutAnchor!==!1&&p&&!!p.resumingFrom==!!this.resumingFrom&&!p.options.layoutScroll&&p.target&&this.animationProgress!==1?this.createRelativeTarget(p,this.target,p.target):this.relativeParent=this.relativeTarget=void 0))}getClosestProjectingParent(){if(!(!this.parent||Xf(this.parent.latestValues)||x1(this.parent.latestValues)))return this.parent.isProjecting()?this.parent:this.parent.getClosestProjectingParent()}isProjecting(){return!!((this.relativeTarget||this.targetDelta||this.options.layoutRoot)&&this.layout)}createRelativeTarget(a,l,d){this.relativeParent=a,this.linkedParentVersion=a.layoutVersion,this.forceRelativeParentToResolveTarget(),this.relativeTarget=qn(),this.relativeTargetOrigin=qn(),gu(this.relativeTargetOrigin,l,d,this.options.layoutAnchor||void 0),si(this.relativeTarget,this.relativeTargetOrigin)}removeRelativeTarget(){this.relativeParent=this.relativeTarget=void 0}calcProjection(){const a=this.getLead(),l=!!this.resumingFrom||this!==a;let d=!0;if((this.isProjectionDirty||this.parent?.isProjectionDirty)&&(d=!1),l&&(this.isSharedProjectionDirty||this.isTransformDirty)&&(d=!1),this.resolvedRelativeTargetAt===as.timestamp&&(d=!1),d)return;const{layout:c,layoutId:u}=this.options;if(this.isTreeAnimating=!!(this.parent&&this.parent.isTreeAnimating||this.currentAnimation||this.pendingAnimation),this.isTreeAnimating||(this.targetDelta=this.relativeTarget=void 0),!this.layout||!(c||u))return;si(this.layoutCorrected,this.layout.layoutBox);const h=this.treeScale.x,p=this.treeScale.y;VF(this.layoutCorrected,this.treeScale,this.path,l),a.layout&&!a.target&&(this.treeScale.x!==1||this.treeScale.y!==1)&&(a.target=a.layout.layoutBox,a.targetWithTransforms=qn());const{target:f}=a;if(!f){this.prevProjectionDelta&&(this.createProjectionDeltas(),this.scheduleRender());return}!this.projectionDelta||!this.prevProjectionDelta?this.createProjectionDeltas():(db(this.prevProjectionDelta.x,this.projectionDelta.x),db(this.prevProjectionDelta.y,this.projectionDelta.y)),ul(this.projectionDelta,this.layoutCorrected,f,this.latestValues),(this.treeScale.x!==h||this.treeScale.y!==p||!wb(this.projectionDelta.x,this.prevProjectionDelta.x)||!wb(this.projectionDelta.y,this.prevProjectionDelta.y))&&(this.hasProjected=!0,this.scheduleRender(),this.notifyListeners("projectionUpdate",f))}hide(){this.isVisible=!1}show(){this.isVisible=!0}scheduleRender(a=!0){if(this.options.visualElement?.scheduleRender(),a){const l=this.getStack();l&&l.scheduleRender()}this.resumingFrom&&!this.resumingFrom.instance&&(this.resumingFrom=void 0)}createProjectionDeltas(){this.prevProjectionDelta=$r(),this.projectionDelta=$r(),this.projectionDeltaWithTransform=$r()}setAnimationOrigin(a,l=!1,d){const c=this.snapshot,u=c?c.latestValues:{},h={...this.latestValues},p=$r();(!this.relativeParent||!this.relativeParent.options.layoutRoot)&&(this.relativeTarget=this.relativeTargetOrigin=void 0),this.attemptToResolveRelativeTarget=!l;const f=qn(),g=c?c.source:void 0,x=this.layout?this.layout.source:void 0,v=g!==x,y=this.getStack(),w=!y||y.members.length<=1,b=!!(v&&!w&&this.options.crossfade===!0&&!this.path.some(VH));this.animationProgress=0;let _;const j=d?.interpolateProjection(a);this.mixTargetDelta=N=>{const C=N/1e3,S=j?.(C);S?(p.x.translate=S.x,p.x.scale=jn(a.x.scale,1,C),p.x.origin=a.x.origin,p.x.originPoint=a.x.originPoint,p.y.translate=S.y,p.y.scale=jn(a.y.scale,1,C),p.y.origin=a.y.origin,p.y.originPoint=a.y.originPoint):(Nb(p.x,a.x,C),Nb(p.y,a.y,C)),this.setTargetDelta(p),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(gu(f,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),BH(this.relativeTarget,this.relativeTargetOrigin,f,C),_&&xH(this.relativeTarget,_)&&(this.isProjectionDirty=!1),_||(_=qn()),si(_,this.relativeTarget)),v&&(this.animationValues=h,wH(h,u,this.latestValues,C,b,w)),S&&S.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=S.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=C},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(a){this.notifyListeners("animationStart"),this.currentAnimation?.stop(),this.resumingFrom?.currentAnimation?.stop(),this.pendingAnimation&&(Mo(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=_n.update(()=>{Rc.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=da(0)),this.motionValue.jump(0,!1),this.currentAnimation=CH(this.motionValue,[0,1e3],{...a,velocity:0,isSync:!0,onUpdate:l=>{this.mixTargetDelta(l),a.onUpdate&&a.onUpdate(l)},onComplete:()=>{a.onComplete&&a.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const a=this.getStack();a&&a.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(TH),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const a=this.getLead();let{targetWithTransforms:l,target:d,layout:c,latestValues:u}=a;if(!(!l||!d||!c)){if(this!==a&&this.layout&&c&&L1(this.options.animationType,this.layout.layoutBox,c.layoutBox)){d=this.target||qn();const h=Cs(this.layout.layoutBox.x);d.x.min=a.target.x.min,d.x.max=d.x.min+h;const p=Cs(this.layout.layoutBox.y);d.y.min=a.target.y.min,d.y.max=d.y.min+p}si(l,d),Ac(l,u),ul(this.projectionDeltaWithTransform,this.layoutCorrected,l,u)}}registerSharedNode(a,l){this.sharedNodes.has(a)||this.sharedNodes.set(a,new NH),this.sharedNodes.get(a).add(l);const c=l.options.initialPromotionConfig;l.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(l):void 0})}isLead(){const a=this.getStack();return a?a.lead===this:!0}getLead(){const{layoutId:a}=this.options;return a?this.getStack()?.lead||this:this}getPrevLead(){const{layoutId:a}=this.options;return a?this.getStack()?.prevLead:void 0}getStack(){const{layoutId:a}=this.options;if(a)return this.root.sharedNodes.get(a)}promote({needsReset:a,transition:l,preserveFollowOpacity:d}={}){const c=this.getStack();c&&c.promote(this,d),a&&(this.projectionDelta=void 0,this.needsReset=!0),l&&this.setOptions({transition:l})}relegate(){const a=this.getStack();return a?a.relegate(this):!1}resetSkewAndRotation(){const{visualElement:a}=this.options;if(!a)return;let l=!1;const{latestValues:d}=a;if((d.z||d.rotate||d.rotateX||d.rotateY||d.rotateZ||d.skewX||d.skewY)&&(l=!0),!l)return;const c={};d.z&&dp("z",a,c,this.animationValues);for(let u=0;u<lp.length;u++)dp(`rotate${lp[u]}`,a,c,this.animationValues),dp(`skew${lp[u]}`,a,c,this.animationValues);a.render();for(const u in c)a.setStaticValue(u,c[u]),this.animationValues&&(this.animationValues[u]=c[u]);a.scheduleRender()}applyProjectionStyles(a,l){if(!this.instance||this.isSVG)return;if(!this.isVisible){a.visibility="hidden";return}const d=this.getTransformTemplate();if(this.needsReset){this.needsReset=!1,a.visibility="",a.opacity="",a.pointerEvents=Mc(l?.pointerEvents)||"",a.transform=d?d(this.latestValues,""):"none";return}const c=this.getLead();if(!this.projectionDelta||!this.layout||!c.target){this.options.layoutId&&(a.opacity=this.latestValues.opacity!==void 0?this.latestValues.opacity:1,a.pointerEvents=Mc(l?.pointerEvents)||""),this.hasProjected&&!tr(this.latestValues)&&(a.transform=d?d({},""):"none",this.hasProjected=!1);return}a.visibility="";const u=c.animationValues||c.latestValues;this.applyTransformsToTarget();let h=vH(this.projectionDeltaWithTransform,this.treeScale,u);d&&(h=d(u,h)),a.transform=h;const{x:p,y:f}=this.projectionDelta;a.transformOrigin=`${p.origin*100}% ${f.origin*100}% 0`,c.animationValues?a.opacity=c===this?u.opacity??this.latestValues.opacity??1:this.preserveOpacity?this.latestValues.opacity:u.opacityExit:a.opacity=c===this?u.opacity!==void 0?u.opacity:"":u.opacityExit!==void 0?u.opacityExit:0;for(const g in Jf){if(u[g]===void 0)continue;const{correct:x,applyTo:v,isCSSVariable:y}=Jf[g],w=h==="none"?u[g]:x(u[g],c);if(v){const b=v.length;for(let _=0;_<b;_++)a[v[_]]=w}else y?this.options.visualElement.renderState.vars[g]=w:a[g]=w}this.options.layoutId&&(a.pointerEvents=c===this?Mc(l?.pointerEvents)||"":"none")}clearSnapshot(){this.resumeFrom=this.snapshot=void 0}resetTree(){this.root.nodes.forEach(a=>a.currentAnimation?.stop()),this.root.nodes.forEach(kb),this.root.sharedNodes.clear()}}}function IH(e){e.updateLayout()}function EH(e){const t=e.resumeFrom?.snapshot||e.snapshot;if(e.isLead()&&e.layout&&t&&e.hasListeners("didUpdate")){const{layoutBox:n,measuredBox:s}=e.layout,{animationType:o}=e.options,r=t.source!==e.layout.source;if(o==="size")ki(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=Cs(h);h.min=n[u].min,h.max=h.min+p});else if(o==="x"||o==="y"){const u=o==="x"?"y":"x";Qf(r?t.measuredBox[u]:t.layoutBox[u],n[u])}else L1(o,t.layoutBox,n)&&ki(u=>{const h=r?t.measuredBox[u]:t.layoutBox[u],p=Cs(n[u]);h.max=h.min+p,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[u].max=e.relativeTarget[u].min+p)});const a=$r();ul(a,n,t.layoutBox);const l=$r();r?ul(l,e.applyTransform(s,!0),t.measuredBox):ul(l,n,t.layoutBox);const d=!E1(a);let c=!1;if(!e.resumeFrom){const u=e.getClosestProjectingParent();if(u&&!u.resumeFrom){const{snapshot:h,layout:p}=u;if(h&&p){const f=e.options.layoutAnchor||void 0,g=qn();gu(g,t.layoutBox,h.layoutBox,f);const x=qn();gu(x,n,p.layoutBox,f),P1(g,x)||(c=!0),u.options.layoutRoot&&(e.relativeTarget=x,e.relativeTargetOrigin=g,e.relativeParent=u)}}}e.notifyListeners("didUpdate",{layout:n,snapshot:t,delta:l,layoutDelta:a,hasLayoutChanged:d,hasRelativeLayoutChanged:c})}else if(e.isLead()){const{onExitComplete:n}=e.options;n&&n()}e.options.transition=void 0}function PH(e){e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function AH(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function MH(e){e.clearSnapshot()}function kb(e){e.clearMeasurements()}function RH(e){e.isLayoutDirty=!0,e.updateLayout()}function jb(e){e.isLayoutDirty=!1}function LH(e){e.isAnimationBlocked&&e.layout&&!e.isLayoutDirty&&(e.snapshot=e.layout,e.isLayoutDirty=!0)}function OH(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function _b(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function zH(e){e.resolveTargetDelta()}function GH(e){e.calcProjection()}function FH(e){e.resetSkewAndRotation()}function HH(e){e.removeLeadSnapshot()}function Nb(e,t,n){e.translate=jn(t.translate,0,n),e.scale=jn(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Tb(e,t,n,s){e.min=jn(t.min,n.min,s),e.max=jn(t.max,n.max,s)}function BH(e,t,n,s){Tb(e.x,t.x,n.x,s),Tb(e.y,t.y,n.y,s)}function VH(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const $H={duration:.45,ease:[.4,0,.1,1]},Db=e=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(e),Ib=Db("applewebkit/")&&!Db("chrome/")?Math.round:Js;function Eb(e){e.min=Ib(e.min),e.max=Ib(e.max)}function WH(e){Eb(e.x),Eb(e.y)}function L1(e,t,n){return e==="position"||e==="preserve-aspect"&&!hH(bb(t),bb(n),.2)}function UH(e){return e!==e.root&&e.scroll?.wasRoot}const KH=R1({attachResizeListener:(e,t)=>Gl(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body?.scrollLeft||0,y:document.documentElement.scrollTop||document.body?.scrollTop||0}),checkIsScrollRoot:()=>!0}),cp={current:void 0},O1=R1({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!cp.current){const e=new KH({});e.mount(window),e.setOptions({layoutScroll:!0}),cp.current=e}return cp.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),px=m.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"});function Pb(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function qH(...e){return t=>{let n=!1;const s=e.map(o=>{const r=Pb(o,t);return!n&&typeof r=="function"&&(n=!0),r});if(n)return()=>{for(let o=0;o<s.length;o++){const r=s[o];typeof r=="function"?r():Pb(e[o],null)}}}}function YH(...e){return m.useCallback(qH(...e),e)}class XH extends m.Component{getSnapshotBeforeUpdate(t){const n=this.props.childRef.current;if(Tc(n)&&t.isPresent&&!this.props.isPresent&&this.props.pop!==!1){const s=n.offsetParent,o=Tc(s)&&s.offsetWidth||0,r=Tc(s)&&s.offsetHeight||0,a=getComputedStyle(n),l=this.props.sizeRef.current;l.height=parseFloat(a.height),l.width=parseFloat(a.width),l.top=n.offsetTop,l.left=n.offsetLeft,l.right=o-l.width-l.left,l.bottom=r-l.height-l.top,l.direction=a.direction}return null}componentDidUpdate(){}render(){return this.props.children}}function ZH({children:e,isPresent:t,anchorX:n,anchorY:s,root:o,pop:r}){const a=m.useId(),l=m.useRef(null),d=m.useRef({width:0,height:0,top:0,left:0,right:0,bottom:0,direction:"ltr"}),{nonce:c}=m.useContext(px),u=r!==!1?e.props?.ref??e?.ref:void 0,h=YH(l,u);return m.useInsertionEffect(()=>{const{width:p,height:f,top:g,left:x,right:v,bottom:y,direction:w}=d.current;if(t||r===!1||!l.current||!p||!f)return;const b=w==="rtl",_=n==="left"?b?`right: ${v}`:`left: ${x}`:b?`left: ${x}`:`right: ${v}`,j=s==="bottom"?`bottom: ${y}`:`top: ${g}`;l.current.dataset.motionPopId=a;const N=document.createElement("style");c&&(N.nonce=c);const C=o??document.head;return C.appendChild(N),N.sheet&&N.sheet.insertRule(`
|
|
6
|
-
[data-motion-pop-id="${a}"] {
|
|
7
|
-
position: absolute !important;
|
|
8
|
-
width: ${p}px !important;
|
|
9
|
-
height: ${f}px !important;
|
|
10
|
-
${_}px !important;
|
|
11
|
-
${j}px !important;
|
|
12
|
-
}
|
|
13
|
-
`),()=>{l.current?.removeAttribute("data-motion-pop-id"),C.contains(N)&&C.removeChild(N)}},[t]),i.jsx(XH,{isPresent:t,childRef:l,sizeRef:d,pop:r,children:r===!1?e:m.cloneElement(e,{ref:h})})}const JH=({children:e,initial:t,isPresent:n,onExitComplete:s,custom:o,presenceAffectsLayout:r,mode:a,anchorX:l,anchorY:d,root:c})=>{const u=Bg(QH),h=m.useId(),p=m.useRef(n),f=m.useRef(s);ru(()=>{p.current=n,f.current=s});let g=!0,x=m.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:o,onExitComplete:v=>{u.set(v,!0);for(const y of u.values())if(!y)return;s&&s()},register:v=>(u.set(v,!1),()=>{u.delete(v),!p.current&&!u.size&&f.current?.()})}),[n,u,s]);return r&&g&&(x={...x}),m.useMemo(()=>{u.forEach((v,y)=>u.set(y,!1))},[n]),m.useEffect(()=>{!n&&!u.size&&s&&s()},[n]),e=i.jsx(ZH,{pop:a==="popLayout",isPresent:n,anchorX:l,anchorY:d,root:c,children:e}),i.jsx(oh.Provider,{value:x,children:e})};function QH(){return new Map}function z1(e=!0){const t=m.useContext(oh);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:s,register:o}=t,r=m.useId();m.useEffect(()=>{if(e)return o(r)},[e]);const a=m.useCallback(()=>e&&s&&s(r),[r,s,e]);return!n&&s?[!1,a]:[!0]}const Md=e=>e.key||"";function Ab(e){const t=[];return m.Children.forEach(e,n=>{m.isValidElement(n)&&t.push(n)}),t}const hl=({children:e,custom:t,initial:n=!0,onExitComplete:s,presenceAffectsLayout:o=!0,mode:r="sync",propagate:a=!1,anchorX:l="left",anchorY:d="top",root:c})=>{const[u,h]=z1(a),p=m.useMemo(()=>Ab(e),[e]),f=a&&!u?[]:p.map(Md),g=m.useRef(!0),x=m.useRef(p),v=Bg(()=>new Map),y=m.useRef(new Set),[w,b]=m.useState(p),[_,j]=m.useState(p);ru(()=>{a&&!u&&!_.length&&h?.()},[u,a,_.length,h]),ru(()=>{g.current=!1,x.current=p;for(let S=0;S<_.length;S++){const A=Md(_[S]);f.includes(A)?(v.delete(A),y.current.delete(A)):v.get(A)!==!0&&v.set(A,!1)}},[_,f.length,f.join("-")]);const N=[];if(p!==w){let S=[...p],A=0;for(const E of _){const I=f.indexOf(Md(E));I===-1?(S.splice(A++,0,E),N.push(E)):A=I+N.length+1}return r==="wait"&&N.length&&(S=N),j(Ab(S)),b(p),null}const{forceRender:C}=m.useContext(Hg);return i.jsx(i.Fragment,{children:_.map(S=>{const A=Md(S),E=a&&!u?!1:p===_||f.includes(A),I=()=>{if(y.current.has(A))return;if(v.has(A))y.current.add(A),v.set(A,!0);else return;let D=!0;v.forEach(T=>{T||(D=!1)}),D&&(C?.(),j(x.current),a&&h?.(),s&&s())};return i.jsx(JH,{isPresent:E,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:o,mode:r,root:c,onExitComplete:E?void 0:I,anchorX:l,anchorY:d,children:S},A)})})},G1=m.createContext({strict:!1}),Mb={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let Rb=!1;function eB(){if(Rb)return;const e={};for(const t in Mb)e[t]={isEnabled:n=>Mb[t].some(s=>!!n[s])};f1(e),Rb=!0}function F1(){return eB(),GF()}function tB(e){const t=F1();for(const n in e)t[n]={...t[n],...e[n]};f1(t)}const ch=m.createContext({});function nB(e,t){if(dh(e)){const{initial:n,animate:s}=e;return{initial:n===!1||zl(n)?n:void 0,animate:zl(s)?s:void 0}}return e.inherit!==!1?t:{}}function sB(e){const{initial:t,animate:n}=nB(e,m.useContext(ch));return m.useMemo(()=>({initial:t,animate:n}),[Lb(t),Lb(n)])}function Lb(e){return Array.isArray(e)?e.join(" "):e}const fx=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function H1(e,t,n){for(const s in t)!ls(t[s])&&!y1(s,n)&&(e[s]=t[s])}function iB({transformTemplate:e},t){return m.useMemo(()=>{const n=fx();return ux(n,t,e),Object.assign({},n.vars,n.style)},[t])}function oB(e,t){const n=e.style||{},s={};return H1(s,n,e),Object.assign(s,iB(e,t)),s}function rB(e,t){const n={},s=oB(e,t);return e.drag&&e.dragListener!==!1&&(n.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(n.tabIndex=0),n.style=s,n}const B1=()=>({...fx(),attrs:{}});function aB(e,t,n,s){const o=m.useMemo(()=>{const r=B1();return C1(r,t,j1(s),e.transformTemplate,e.style),{...r.attrs,style:{...r.style}}},[t]);if(e.style){const r={};H1(r,e.style,e),o.style={...r,...o.style}}return o}const lB=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","propagate","ignoreStrict","viewport"]);function xu(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||lB.has(e)}function dB(e,t){return e.startsWith("on")?!xu(e):t?.(e)??!xu(e)}function cB(e,t,n,s){const o={};for(const r in e)r==="values"&&typeof e.values=="object"||ls(e[r])||(dB(r,s)||n===!0&&xu(r)||!t&&!xu(r)||e.draggable&&r.startsWith("onDrag"))&&(o[r]=e[r]);return o}const uB=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function mx(e){return typeof e!="string"||e.includes("-")?!1:!!(uB.indexOf(e)>-1||/[A-Z]/u.test(e))}function hB(e,t,n,{latestValues:s},o,r=!1,a,l){const c=(a??mx(e)?aB:rB)(t,s,o,e),u=cB(t,typeof e=="string",r,l),h=e!==m.Fragment?{...u,...c,ref:n}:{},{children:p}=t,f=m.useMemo(()=>ls(p)?p.get():p,[p]);return m.createElement(e,{...h,children:f})}function pB({scrapeMotionValuesFromProps:e,createRenderState:t},n,s,o){return{latestValues:fB(n,s,o,e),renderState:t()}}function fB(e,t,n,s){const o={},r=s(e,{});for(const p in r)o[p]=Mc(r[p]);let{initial:a,animate:l}=e;const d=dh(e),c=h1(e);t&&c&&!d&&e.inherit!==!1&&(a===void 0&&(a=t.initial),l===void 0&&(l=t.animate));let u=n?n.initial===!1:!1;u=u||a===!1;const h=u?l:a;if(h&&typeof h!="boolean"&&!lh(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f<p.length;f++){const g=nx(e,p[f]);if(g){const{transitionEnd:x,transition:v,...y}=g;for(const w in y){let b=y[w];if(Array.isArray(b)){const _=u?b.length-1:0;b=b[_]}b!==null&&(o[w]=b)}for(const w in x)o[w]=x[w]}}}return o}const V1=e=>(t,n)=>{const s=m.useContext(ch),o=m.useContext(oh),r=()=>pB(e,t,s,o);return n?r():Bg(r)},mB=V1({scrapeMotionValuesFromProps:hx,createRenderState:fx}),gB=V1({scrapeMotionValuesFromProps:_1,createRenderState:B1}),xB=Symbol.for("motionComponentSymbol");function vB(e,t,n){const s=m.useRef(n);m.useInsertionEffect(()=>{s.current=n});const o=m.useRef(null);return m.useCallback(r=>{r&&e.onMount?.(r),t&&(r?t.mount(r):t.unmount());const a=s.current;if(typeof a=="function")if(r){const l=a(r);typeof l=="function"&&(o.current=l)}else o.current?(o.current(),o.current=null):a(r);else a&&(a.current=r)},[t])}const $1=m.createContext({});function zr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function bB(e,t,n,s,o,r){const{visualElement:a}=m.useContext(ch),l=m.useContext(G1),d=m.useContext(oh),c=m.useContext(px),u=c.reducedMotion,h=c.skipAnimations,p=m.useRef(null),f=m.useRef(!1);s=s||l.renderer,!p.current&&s&&(p.current=s(e,{visualState:t,parent:a,props:n,presenceContext:d,blockInitialAnimation:d?d.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:r}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const g=p.current,x=m.useContext($1);g&&!g.projection&&o&&(g.type==="html"||g.type==="svg")&&wB(p.current,n,o,x);const v=m.useRef(!1);m.useInsertionEffect(()=>{g&&v.current&&g.update(n,d)});const y=n[e1],w=m.useRef(!!y&&typeof window<"u"&&!window.MotionHandoffIsComplete?.(y)&&window.MotionHasOptimisedAnimation?.(y));return ru(()=>{f.current=!0,g&&(v.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),w.current&&g.animationState&&g.animationState.animateChanges())}),m.useEffect(()=>{g&&(!w.current&&g.animationState&&g.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{window.MotionHandoffMarkAsComplete?.(y)}),w.current=!1),g.enteringChildren=void 0)}),g}function wB(e,t,n,s){const{layoutId:o,layout:r,drag:a,dragConstraints:l,layoutScroll:d,layoutRoot:c,layoutAnchor:u,layoutCrossfade:h}=t;e.projection=new n(e.latestValues,t["data-framer-portal-id"]?void 0:W1(e.parent)),e.projection.setOptions({layoutId:o,layout:r,alwaysMeasureLayout:!!a||l&&zr(l),visualElement:e,animationType:typeof r=="string"?r:"both",initialPromotionConfig:s,crossfade:h,layoutScroll:d,layoutRoot:c,layoutAnchor:u})}function W1(e){if(e)return e.options.allowProjection!==!1?e.projection:W1(e.parent)}function up(e,{forwardMotionProps:t=!1,type:n}={},s,o){s&&tB(s);const r=n?n==="svg":mx(e),a=r?gB:mB;function l(c,u){let h;const p={...m.useContext(px),...c,layoutId:yB(c)},{isStatic:f,isValidProp:g}=p,x=sB(c),v=a(c,f);if(!f&&typeof window<"u"){SB();const y=CB(p);h=y.MeasureLayout,x.visualElement=bB(e,v,p,o,y.ProjectionNode,r)}return i.jsxs(ch.Provider,{value:x,children:[h&&x.visualElement?i.jsx(h,{visualElement:x.visualElement,...p}):null,hB(e,c,vB(v,x.visualElement,u),v,f,t,r,g)]})}l.displayName=`motion.${typeof e=="string"?e:`create(${e.displayName??e.name??""})`}`;const d=m.forwardRef(l);return d[xB]=e,d}function yB({layoutId:e}){const t=m.useContext(Hg).id;return t&&e!==void 0?t+"-"+e:e}function SB(e,t){m.useContext(G1).strict}function CB(e){const t=F1(),{drag:n,layout:s}=t;if(!n&&!s)return{};const o={...n,...s};return{MeasureLayout:n?.isEnabled(e)||s?.isEnabled(e)?o.MeasureLayout:void 0,ProjectionNode:o.ProjectionNode}}function kB(e,t){if(typeof Proxy>"u")return up;const n=new Map,s=(r,a)=>up(r,a,e,t),o=(r,a)=>s(r,a);return new Proxy(o,{get:(r,a)=>a==="create"?s:(n.has(a)||n.set(a,up(a,void 0,e,t)),n.get(a))})}const jB=(e,t)=>t.isSVG??mx(e)?new tH(t):new XF(t,{allowProjection:e!==m.Fragment});class _B extends Ho{constructor(t){super(t),t.animationState||(t.animationState=rH(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();lh(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){this.node.animationState.reset(),this.unmountControls?.()}}let NB=0;class TB extends Ho{constructor(){super(...arguments),this.id=NB++,this.isExitComplete=!1}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;if(t&&s===!1){if(this.isExitComplete){const{initial:r,custom:a}=this.node.getProps();if(typeof r=="string"||typeof r=="object"&&r!==null&&!Array.isArray(r)){const l=mr(this.node,r,a);if(l){const{transition:d,transitionEnd:c,...u}=l;for(const h in u)this.node.getValue(h)?.jump(u[h])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const o=this.node.animationState.setActive("exit",!t);n&&!t&&o.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const DB={animation:{Feature:_B},exit:{Feature:TB}};function bd(e){return{point:{x:e.pageX,y:e.pageY}}}const IB=e=>t=>rx(t)&&e(t,bd(t));function pl(e,t,n,s){return Gl(e,t,IB(n),s)}const U1=({current:e})=>e?e.ownerDocument.defaultView:null,Ob=(e,t)=>Math.abs(e-t);function EB(e,t){const n=Ob(e.x,t.x),s=Ob(e.y,t.y);return Math.sqrt(n**2+s**2)}const zb=new Set(["auto","scroll"]);class K1{constructor(t,n,{transformPagePoint:s,contextWindow:o=window,dragSnapToOrigin:r=!1,distanceThreshold:a=3,element:l}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=g=>{this.handleScroll(g.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=Rd(this.lastRawMoveEventInfo,this.transformPagePoint));const g=hp(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,v=EB(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!v)return;const{point:y}=g,{timestamp:w}=as;this.history.push({...y,timestamp:w});const{onStart:b,onMove:_}=this.handlers;x||(b&&b(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),_&&_(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=Rd(x,this.transformPagePoint),_n.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:v,onSessionEnd:y,resumeAnimation:w}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&w&&w(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const b=hp(g.type==="pointercancel"?this.lastMoveEventInfo:Rd(x,this.transformPagePoint),this.history);this.startEvent&&v&&v(g,b),y&&y(g,b)},!rx(t))return;this.dragSnapToOrigin=r,this.handlers=n,this.transformPagePoint=s,this.distanceThreshold=a,this.contextWindow=o||window;const d=bd(t),c=Rd(d,this.transformPagePoint),{point:u}=c,{timestamp:h}=as;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,hp(c,this.history));const f={passive:!0,capture:!0};this.removeListeners=gd(pl(this.contextWindow,"pointermove",this.handlePointerMove,f),pl(this.contextWindow,"pointerup",this.handlePointerUp,f),pl(this.contextWindow,"pointercancel",this.handlePointerUp,f)),l&&this.startScrollTracking(l)}startScrollTracking(t){let n=t.parentElement;for(;n;){const s=getComputedStyle(n);(zb.has(s.overflowX)||zb.has(s.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const s=t===window,o=s?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},r={x:o.x-n.x,y:o.y-n.y};r.x===0&&r.y===0||(s?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=r.x,this.lastMoveEventInfo.point.y+=r.y):this.history.length>0&&(this.history[0].x-=r.x,this.history[0].y-=r.y),this.scrollPositions.set(t,o),_n.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),Mo(this.updatePoint)}}function Rd(e,t){return t?{point:t(e.point)}:e}function Gb(e,t){return{x:e.x-t.x,y:e.y-t.y}}function hp({point:e},t){return{point:e,delta:Gb(e,q1(t)),offset:Gb(e,PB(t)),velocity:AB(t,.1)}}function PB(e){return e[0]}function q1(e){return e[e.length-1]}function AB(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,s=null;const o=q1(e);for(;n>=0&&(s=e[n],!(o.timestamp-s.timestamp>Ls(t)));)n--;if(!s)return{x:0,y:0};s===e[0]&&e.length>2&&o.timestamp-s.timestamp>Ls(t)*2&&(s=e[1]);const r=qs(o.timestamp-s.timestamp);if(r===0)return{x:0,y:0};const a={x:(o.x-s.x)/r,y:(o.y-s.y)/r};return a.x===1/0&&(a.x=0),a.y===1/0&&(a.y=0),a}function MB(e,{min:t,max:n},s){return t!==void 0&&e<t?e=s?jn(t,e,s.min):Math.max(e,t):n!==void 0&&e>n&&(e=s?jn(n,e,s.max):Math.min(e,n)),e}function Fb(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function RB(e,{top:t,left:n,bottom:s,right:o}){return{x:Fb(e.x,n,o),y:Fb(e.y,t,s)}}function Hb(e,t){let n=t.min-e.min,s=t.max-e.max;return t.max-t.min<e.max-e.min&&([n,s]=[s,n]),{min:n,max:s}}function LB(e,t){return{x:Hb(e.x,t.x),y:Hb(e.y,t.y)}}function OB(e,t){let n=.5;const s=Cs(e),o=Cs(t);return o>s?n=Ll(t.min,t.max-s,e.min):s>o&&(n=Ll(e.min,e.max-o,t.min)),Gi(0,1,n)}function zB(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const em=.35;function GB(e=em){return e===!1?e=0:e===!0&&(e=em),{x:Bb(e,"left","right"),y:Bb(e,"top","bottom")}}function Bb(e,t,n){return{min:Vb(e,t),max:Vb(e,n)}}function Vb(e,t){return typeof e=="number"?e:e[t]||0}const FB=new WeakMap;class HB{constructor(t){this.openDragLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=qn(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:s}={}){const{presenceContext:o}=this.visualElement;if(o&&o.isPresent===!1)return;const r=h=>{n&&this.snapToCursor(bd(h).point),this.stopAnimation()},a=(h,p)=>{const{drag:f,dragPropagation:g,onDragStart:x}=this.getProps();if(f&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=gF(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),ki(y=>{let w=this.getAxisMotionValue(y).get()||0;if(Mi.test(w)){const{projection:b}=this.visualElement;if(b&&b.layout){const _=b.layout.layoutBox[y];_&&(w=Cs(_)*(parseFloat(w)/100))}}this.originPoint[y]=w}),x&&_n.update(()=>x(h,p),!1,!0),Wf(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},l=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p;const{dragPropagation:f,dragDirectionLock:g,onDirectionLock:x,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:y}=p;if(g&&this.currentDirection===null){this.currentDirection=VB(y),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",p.point,y),this.updateAxis("y",p.point,y),this.visualElement.render(),v&&_n.update(()=>v(h,p),!1,!0)},d=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p,this.stop(h,p),this.latestPointerEvent=null,this.latestPanInfo=null},c=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new K1(t,{onSessionStart:r,onStart:a,onMove:l,onSessionEnd:d,resumeAnimation:c},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:s,contextWindow:U1(this.visualElement),element:this.visualElement.current})}stop(t,n){const s=t||this.latestPointerEvent,o=n||this.latestPanInfo,r=this.isDragging;if(this.cancel(),!r||!o||!s)return;const{velocity:a}=o;this.startAnimation(a);const{onDragEnd:l}=this.getProps();l&&_n.postRender(()=>l(s,o))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:s}=this.getProps();!s&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,s){const{drag:o}=this.getProps();if(!s||!Ld(t,o,this.currentDirection))return;const r=this.getAxisMotionValue(t);let a=this.originPoint[t]+s[t];this.constraints&&this.constraints[t]&&(a=MB(a,this.constraints[t],this.elastic[t])),r.set(a)}resolveConstraints(){const{dragConstraints:t,dragElastic:n}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):this.visualElement.projection?.layout,o=this.constraints;t&&zr(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&s?this.constraints=RB(s.layoutBox,t):this.constraints=!1,this.elastic=GB(n),o!==this.constraints&&!zr(t)&&s&&this.constraints&&!this.hasMutatedConstraints&&ki(r=>{this.constraints!==!1&&this.getAxisMotionValue(r)&&(this.constraints[r]=zB(s.layoutBox[r],this.constraints[r]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!zr(t))return!1;const s=t.current,{projection:o}=this.visualElement;if(!o||!o.layout)return!1;o.root&&(o.root.scroll=void 0,o.root.updateScroll());const r=$F(s,o.root,this.visualElement.getTransformPagePoint());let a=LB(o.layout.layoutBox,r);if(n){const l=n(HF(a));this.hasMutatedConstraints=!!l,l&&(a=g1(l))}return a}startAnimation(t){const{drag:n,dragMomentum:s,dragElastic:o,dragTransition:r,dragSnapToOrigin:a,onDragTransitionEnd:l}=this.getProps(),d=this.constraints||{},c=ki(u=>{if(!Ld(u,n,this.currentDirection))return;let h=d&&d[u]||{};(a===!0||a===u)&&(h={min:0,max:0});const p=o?200:1e6,f=o?40:1e7,g={type:"inertia",velocity:s?t[u]:0,bounceStiffness:p,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...r,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(c).then(l)}startAxisValueAnimation(t,n){const s=this.getAxisMotionValue(t);return Wf(this.visualElement,t),s.start(tx(t,s,0,n,this.visualElement,!1))}stopAnimation(){ki(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,o=this.visualElement.getProps()[n];return o||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){ki(n=>{const{drag:s}=this.getProps();if(!Ld(n,s,this.currentDirection))return;const{projection:o}=this.visualElement,r=this.getAxisMotionValue(n);if(o&&o.layout){const{min:a,max:l}=o.layout.layoutBox[n],d=r.get()||0;r.set(t[n]-jn(a,l,.5)+d)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:s}=this.visualElement;if(!zr(n)||!s||!this.constraints)return;this.stopAnimation();const o={x:0,y:0};ki(a=>{const l=this.getAxisMotionValue(a);if(l&&this.constraints!==!1){const d=l.get();o[a]=OB({min:d,max:d},this.constraints[a])}});const{transformTemplate:r}=this.visualElement.getProps();this.visualElement.current.style.transform=r?r({},""):"none",s.root&&s.root.updateScroll(),s.updateLayout(),this.constraints=!1,this.resolveConstraints(),ki(a=>{if(!Ld(a,t,null))return;const l=this.getAxisMotionValue(a),{min:d,max:c}=this.constraints[a];l.set(jn(d,c,o[a]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;FB.set(this.visualElement,this);const t=this.visualElement.current,n=pl(t,"pointerdown",c=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=c.target,f=p!==t&&SF(p);u&&h&&!f&&this.start(c)});let s;const o=()=>{const{dragConstraints:c}=this.getProps();zr(c)&&c.current&&(this.constraints=this.resolveRefConstraints(),s||(s=BB(t,c.current,()=>this.scalePositionWithinConstraints())))},{projection:r}=this.visualElement,a=r.addEventListener("measure",o);r&&!r.layout&&(r.root&&r.root.updateScroll(),r.updateLayout()),_n.read(o);const l=Gl(window,"resize",()=>this.scalePositionWithinConstraints()),d=r.addEventListener("didUpdate",(({delta:c,hasLayoutChanged:u})=>{this.isDragging&&u&&(ki(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=c[h].translate,p.set(p.get()+c[h].translate))}),this.visualElement.render())}));return()=>{l(),n(),a(),d&&d(),s&&s()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:s=!1,dragPropagation:o=!1,dragConstraints:r=!1,dragElastic:a=em,dragMomentum:l=!0}=t;return{...t,drag:n,dragDirectionLock:s,dragPropagation:o,dragConstraints:r,dragElastic:a,dragMomentum:l}}}function $b(e){let t=!0;return()=>{if(t){t=!1;return}e()}}function BB(e,t,n){const s=Z0(e,$b(n)),o=Z0(t,$b(n));return()=>{s(),o()}}function Ld(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function VB(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class $B extends Ho{constructor(t){super(t),this.removeGroupControls=Js,this.removeListeners=Js,this.controls=new HB(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Js}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const pp=e=>(t,n)=>{e&&_n.update(()=>e(t,n),!1,!0)};class WB extends Ho{constructor(){super(...arguments),this.removePointerDownListener=Js}onPointerDown(t){this.session=new K1(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:U1(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:s,onPanEnd:o}=this.node.getProps();return{onSessionStart:pp(t),onStart:pp(n),onMove:pp(s),onEnd:(r,a)=>{delete this.session,o&&_n.postRender(()=>o(r,a))}}}mount(){this.removePointerDownListener=pl(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}let fp=!1;class UB extends m.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s,layoutId:o}=this.props,{projection:r}=t;r&&(n.group&&n.group.add(r),s&&s.register&&o&&s.register(r),fp&&r.root.didUpdate(),r.addEventListener("animationComplete",()=>{this.safeToRemove()}),r.setOptions({...r.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Rc.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:s,drag:o,isPresent:r}=this.props,{projection:a}=s;return a&&(a.isPresent=r,t.layoutDependency!==n&&a.setOptions({...a.options,layoutDependency:n}),fp=!0,o||t.layoutDependency!==n||n===void 0||t.isPresent!==r?a.willUpdate():this.safeToRemove(),t.isPresent!==r&&(r?a.promote():a.relegate()||_n.postRender(()=>{const l=a.getStack();(!l||!l.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:s}=t;s&&(s.options.layoutAnchor=n,s.root.didUpdate(),ox.postRender(()=>{!s.currentAnimation&&s.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:s}=this.props,{projection:o}=t;fp=!0,o&&(o.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(o),s&&s.deregister&&s.deregister(o))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function Y1(e){const[t,n]=z1(),s=m.useContext(Hg);return i.jsx(UB,{...e,layoutGroup:s,switchLayoutGroup:m.useContext($1),isPresent:t,safeToRemove:n})}const KB={pan:{Feature:WB},drag:{Feature:$B,ProjectionNode:O1,MeasureLayout:Y1}};function Wb(e,t,n){const{props:s}=e;e.animationState&&s.whileHover&&e.animationState.setActive("whileHover",n==="Start");const o="onHover"+n,r=s[o];r&&_n.postRender(()=>r(t,bd(t)))}class qB extends Ho{mount(){const{current:t}=this.node;t&&(this.unmount=vF(t,(n,s)=>(Wb(this.node,s,"Start"),o=>Wb(this.node,o,"End"))))}unmount(){}}class YB extends Ho{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=gd(Gl(this.node.current,"focus",()=>this.onFocus()),Gl(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function Ub(e,t,n){const{props:s}=e;if(e.current instanceof HTMLButtonElement&&e.current.disabled)return;e.animationState&&s.whileTap&&e.animationState.setActive("whileTap",n==="Start");const o="onTap"+(n==="End"?"":n),r=s[o];r&&_n.postRender(()=>r(t,bd(t)))}class XB extends Ho{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:s}=this.node.props;this.unmount=kF(t,(o,r)=>(Ub(this.node,r,"Start"),(a,{success:l})=>Ub(this.node,a,l?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:s?.tap===!1})}unmount(){}}const tm=new WeakMap,mp=new WeakMap,ZB=e=>{const t=tm.get(e.target);t&&t(e)},JB=e=>{e.forEach(ZB)};function QB({root:e,...t}){const n=e||document;mp.has(n)||mp.set(n,{});const s=mp.get(n),o=JSON.stringify(t);return s[o]||(s[o]=new IntersectionObserver(JB,{root:e,...t})),s[o]}function eV(e,t,n){const s=QB(t);return tm.set(e,n),s.observe(e),()=>{tm.delete(e),s.unobserve(e)}}const tV={some:0,all:1};class nV extends Ho{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.stopObserver?.();const{viewport:t={}}=this.node.getProps(),{root:n,margin:s,amount:o="some",once:r}=t,a={root:n?n.current:void 0,rootMargin:s,threshold:typeof o=="number"?o:tV[o]},l=d=>{const{isIntersecting:c}=d;if(this.isInView===c||(this.isInView=c,r&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:u,onViewportLeave:h}=this.node.getProps(),p=c?u:h;p&&p(d)};this.stopObserver=eV(this.node.current,a,l)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(sV(t,n))&&this.startObserver()}unmount(){this.stopObserver?.(),this.hasEnteredView=!1,this.isInView=!1}}function sV({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const iV={inView:{Feature:nV},tap:{Feature:XB},focus:{Feature:YB},hover:{Feature:qB}},oV={layout:{ProjectionNode:O1,MeasureLayout:Y1}},rV={...DB,...iV,...KB,...oV},Ms=kB(rV,jB);function aV(){!cx.current&&p1();const[e]=m.useState(pu.current);return e}const lV=[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]],dV=nt("alarm-clock",lV);const cV=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],Fl=nt("archive-restore",cV);const uV=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Ii=nt("archive",uV);const hV=[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]],pV=nt("arrow-down-to-line",hV);const fV=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],uh=nt("arrow-down",fV);const mV=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],gV=nt("arrow-up-right",mV);const xV=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],wd=nt("arrow-up",xV);const vV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M4.929 4.929 19.07 19.071",key:"196cmz"}]],bV=nt("ban",vV);const wV=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M17 17H4a1 1 0 0 1-.74-1.673C4.59 13.956 6 12.499 6 8a6 6 0 0 1 .258-1.742",key:"178tsu"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.668 3.01A6 6 0 0 1 18 8c0 2.687.77 4.653 1.707 6.05",key:"1hqiys"}]],Kb=nt("bell-off",wV);const yV=[["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M15 10H9",key:"o6yqo3"}],["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z",key:"oz39mx"}]],SV=nt("bookmark-plus",yV);const CV=[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]],X1=nt("bug",CV);const kV=[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]],jV=nt("chevrons-down-up",kV);const _V=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],NV=nt("circle-dot",_V);const TV=[["path",{d:"M9 9.003a1 1 0 0 1 1.517-.859l4.997 2.997a1 1 0 0 1 0 1.718l-4.997 2.997A1 1 0 0 1 9 14.996z",key:"kmsa83"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],DV=nt("circle-play",TV);const IV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],EV=nt("circle-question-mark",IV);const PV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],AV=nt("circle-stop",PV);const MV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],gx=nt("circle",MV);const RV=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]],Z1=nt("clipboard-check",RV);const LV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],J1=nt("clock",LV);const OV=[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]],Q1=nt("code-xml",OV);const zV=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],GV=nt("code",zV);const FV=[["path",{d:"M13.744 17.736a6 6 0 1 1-7.48-7.48",key:"bq4yh3"}],["path",{d:"M15 6h1v4",key:"11y1tn"}],["path",{d:"m6.134 14.768.866-.5 2 3.464",key:"17snzx"}],["circle",{cx:"16",cy:"8",r:"6",key:"14bfc9"}]],HV=nt("coins",FV);const BV=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}]],VV=nt("compass",BV);const $V=[["path",{d:"m15 10 5 5-5 5",key:"qqa56n"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]],WV=nt("corner-down-right",$V);const UV=[["path",{d:"M14 9 9 4 4 9",key:"1af5af"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]],KV=nt("corner-left-up",UV);const qV=[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]],YV=nt("cpu",qV);const XV=[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]],ZV=nt("database",XV);const JV=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],hh=nt("ellipsis",JV);const QV=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],e$=nt("file-diff",QV);const t$=[["path",{d:"M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34",key:"o6klzx"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z",key:"zhnas1"}]],n$=nt("file-pen",t$);const s$=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],i$=nt("file-plus",s$);const o$=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],r$=nt("file",o$);const a$=[["path",{d:"M2 12h6",key:"1wqiqv"}],["path",{d:"M22 12h-6",key:"1eg9hc"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 9-3 3 3 3",key:"12ol22"}],["path",{d:"m5 15 3-3-3-3",key:"1kdhjc"}]],l$=nt("fold-horizontal",a$);const d$=[["path",{d:"M18 19a5 5 0 0 1-5-5v8",key:"sz5oeg"}],["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]],c$=nt("folder-git-2",d$);const u$=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["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",key:"1kt360"}]],qb=nt("folder-plus",u$);const h$=[["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",key:"1kt360"}]],yd=nt("folder",h$);const p$=[["path",{d:"M20 5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5a1.5 1.5 0 0 1 1.2.6l.6.8a1.5 1.5 0 0 0 1.2.6z",key:"a4852j"}],["path",{d:"M3 8.268a2 2 0 0 0-1 1.738V19a2 2 0 0 0 2 2h11a2 2 0 0 0 1.732-1",key:"yxbcw3"}]],f$=nt("folders",p$);const m$=[["path",{d:"M6 3v12",key:"qpgusn"}],["path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"1d02ji"}],["path",{d:"M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"chk6ph"}],["path",{d:"M15 6a9 9 0 0 0-9 9",key:"or332x"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]],g$=nt("git-branch-plus",m$);const x$=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],Ei=nt("git-branch",x$);const v$=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],b$=nt("git-commit-horizontal",v$);const w$=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]],xx=nt("git-compare",w$);const y$=[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]],Yb=nt("hand",y$);const S$=[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]],C$=nt("hourglass",S$);const k$=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]],Xb=nt("house",k$);const j$=[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]],eN=nt("image-off",j$);const _$=[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]],ph=nt("image-plus",_$);const N$=[["path",{d:"m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16",key:"9kzy35"}],["path",{d:"M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2",key:"1t0f0t"}],["circle",{cx:"13",cy:"7",r:"1",fill:"currentColor",key:"1obus6"}],["rect",{x:"8",y:"2",width:"14",height:"14",rx:"2",key:"1gvhby"}]],T$=nt("images",N$);const D$=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],vx=nt("inbox",D$);const I$=[["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"M3 10a2 2 0 0 0 2 2h3",key:"1npucw"}],["path",{d:"M3 5v12a2 2 0 0 0 2 2h3",key:"x1gjn2"}]],E$=nt("list-tree",I$);const P$=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],bx=nt("list",P$);const A$=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]],M$=nt("mail",A$);const R$=[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]],L$=nt("menu",R$);const O$=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]],vr=nt("message-circle",O$);const z$=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],Ro=nt("message-square-plus",z$);const G$=[["path",{d:"M16 10a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 14.286V4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z",key:"1n2ejm"}],["path",{d:"M20 9a2 2 0 0 1 2 2v10.286a.71.71 0 0 1-1.212.502l-2.202-2.202A2 2 0 0 0 17.172 19H10a2 2 0 0 1-2-2v-1",key:"1qfcsi"}]],ca=nt("messages-square",G$);const F$=[["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"M16 17h6",key:"1ook5g"}],["path",{d:"M21 13V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.729l7 4a2 2 0 0 0 2 .001l1.675-.955",key:"zu9avd"}],["path",{d:"M3.29 7 12 12l8.71-5",key:"19ckod"}],["path",{d:"m7.5 4.27 8.997 5.148",key:"9yrvtv"}]],H$=nt("package-minus",F$);const B$=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]],wx=nt("panel-left-close",B$);const V$=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],tN=nt("panel-left",V$);const $$=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],nN=nt("panel-right",$$);const W$=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],U$=nt("pause",W$);const K$=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]],vu=nt("pin-off",K$);const q$=[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]],di=nt("pin",q$);const Y$=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],X$=nt("repeat",Y$);const Z$=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],Bo=nt("rotate-ccw-clock",Z$);const J$=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],yx=nt("send",J$);const Q$=[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]],e6=nt("skip-forward",Q$);const t6=[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]],n6=nt("sliders-horizontal",t6);const s6=[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]],i6=nt("square-dashed",s6);const o6=[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]],sN=nt("square-pen",o6);const r6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]],iN=nt("square-slash",r6);const a6=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],l6=nt("square-x",a6);const d6=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],c6=nt("tag",d6);const u6=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Na=nt("target",u6);const h6=[["path",{d:"M21 5H3",key:"1fi0y6"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 19H3",key:"108z41"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]],oN=nt("text-search",h6);const p6=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],ua=nt("undo-2",p6);const f6=[["path",{d:"M16 12h6",key:"15xry1"}],["path",{d:"M8 12H2",key:"1jqql6"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 15 3-3-3-3",key:"wjy7rq"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}]],m6=nt("unfold-horizontal",f6);const g6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],x6=nt("user-minus",g6);const v6=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]],Hl=nt("user-plus",v6);const b6=[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]],w6=nt("user-round",b6);const y6=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]],S6=nt("wallet",y6),gp=(e,t)=>e.length>t?`${e.slice(0,t)}…`:e;function C6(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,{status:n,originalCommand:s,rewrittenCommand:o,inputTokens:r,outputTokens:a,reason:l}=t;if(n!=="compressed"&&n!=="unchanged"&&n!=="pending"&&n!=="bypassed"&&n!=="unavailable"||typeof s!="string"||o!==void 0&&typeof o!="string"||l!==void 0&&typeof l!="string")return;const d={status:n,originalCommand:gp(s,16e3)};if(o!==void 0&&(d.rewrittenCommand=gp(o,16e3)),l!==void 0&&(d.reason=gp(l,1e3)),r!==void 0||a!==void 0){if(typeof r!="number"||!Number.isSafeInteger(r)||r<0||typeof a!="number"||!Number.isSafeInteger(a)||a<0)return;d.inputTokens=r,d.outputTokens=a}return d}const k6=15e3;function j6(e){const t=[];for(const n of e){const s=t.at(-1);if(s&&s.batch===n.batch&&s.phase===n.phase){s.members.push(n);continue}t.push({batch:n.batch,members:[n],...n.phase?{phase:n.phase}:{}})}return t}function rN(e){if(e.length===0)return;const t="0 0, 100% 0, 100% 100%, 0 100%, 0 0",n=e.map(s=>`${_6(s).map(([o,r])=>`${Jb(o)}px ${Jb(r)}px`).join(", ")}, 0 0`);return`polygon(evenodd, ${[t,...n].join(", ")})`}const Zb=6,Jb=e=>Math.round(e*100)/100;function _6({x:e,y:t,width:n,height:s,radius:o=0}){const r=e+n,a=t+s,l=Math.min(o,n/2,s/2);if(l<=0)return[[e,t],[r,t],[r,a],[e,a],[e,t]];const c=[[r-l,t+l,-90],[r-l,a-l,0],[e+l,a-l,90],[e+l,t+l,180]].flatMap(([u,h,p])=>Array.from({length:Zb+1},(f,g)=>{const x=(p+90*g/Zb)*Math.PI/180;return[u+l*Math.cos(x),h+l*Math.sin(x)]}));return[...c,c[0]]}function Qb(e,t){for(let n=t-1;n>=0;n--){const s=e[n];if(s==="@"){const o=n>0?e[n-1]:" ";return o===" "||o===`
|
|
14
|
-
`?e.slice(n+1,t):null}if(s===" "||s===`
|
|
15
|
-
`)return null}return null}function N6(e){const t=Math.max(0,e.containerWidth-e.popupWidth),n=Math.min(Math.max(0,e.anchorLeft),t),s=e.containerWidth-n-e.popupWidth-e.flyoutGap;return{left:n,flyoutSide:s>=e.flyoutWidth?"right":"left"}}function T6(e){if(e.isComposing||e.itemCount===0)return{type:"none"};const t=e.key==="Enter"&&!e.shiftKey||e.key==="Tab";if(e.folderOpen){if(e.key==="Escape"||e.key==="ArrowLeft")return{type:"close-folder"};const n=e.folderItemCount??0;if(n===0)return{type:"none"};const s=e.folderIndex??0;return e.key==="ArrowDown"?{type:"move-folder",index:(s+1)%n}:e.key==="ArrowUp"?{type:"move-folder",index:(s-1+n)%n}:t?{type:"pick"}:{type:"none"}}return e.activeIsFolder&&(e.key==="ArrowRight"||t)?{type:"open-folder"}:e.key==="ArrowDown"?{type:"move",index:(e.activeIndex+1)%e.itemCount}:e.key==="ArrowUp"?{type:"move",index:(e.activeIndex-1+e.itemCount)%e.itemCount}:t?{type:"pick"}:e.key==="Escape"?{type:"close"}:{type:"none"}}function D6(e,t){return`[Referenced past chat "${e.replace(/["[\]\n]/g," ").replace(/\s+/g," ").trim()||"untitled"}" — transcript file: ${t} (pi session jsonl; read it if relevant)]`}const I6=/^\[Referenced past chat "(.+)" — transcript file: (.+) \(pi session jsonl; read it if relevant\)\]$/,E6=/^@(\S.*)$/;function P6(e){return e.map(t=>t.type==="text"?t.text:t.type==="file"?/\s/.test(t.path)&&!t.path.includes('"')?`@"${t.path}"`:`@${t.path}`:t.type==="chat"?D6(t.label,t.sessionFile):gP(t)).join("")}function ew(e,t){Av.lastIndex=t,Mv.lastIndex=t;const n=Av.exec(e),s=Mv.exec(e),o=n?{index:n.index,length:n[0].length,segment:{type:"chat",label:n[1],sessionFile:n[2]}}:null,r=s?mP(s[0]):null,a=s&&r?{index:s.index,length:s[0].length,segment:{type:"ui-element",id:"",...r,imageId:""}}:null;return o&&a?o.index<=a.index?o:a:o??a}function A6(e){const t=[];let n=0,s=ew(e,0);for(;s;){const r=e.slice(n,s.index);for(const a of tw(r))a.type==="text"&&a.text===""||t.push(a);t.push(s.segment),n=s.index+s.length,s=ew(e,n)}const o=e.slice(n);if(o||t.length===0)for(const r of tw(o))r.type==="text"&&r.text===""&&t.length>0||t.push(r);return t}const M6=/^(?:[A-Za-z]:[\\/])?(?:[\p{L}\p{N}_./\\-]*\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\p{L}\p{N}_./\\-]+[\\/])$/u,R6=/^"([^"\n]*(?:\.[\w-]{1,16}(?:#L\d+(?:-L\d+)?)?|[\\/]))"/,L6=/#L\d+(?:-L\d+)?$/;function O6(e){return e.replace(L6,"")}function fh(e){return e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).at(-1)||e}function tw(e){return ok(e).flatMap(t=>t.type==="file"?[t]:z6(t.text))}function z6(e){const t=[];let n="",s=0;for(;s<e.length;){const o=e.indexOf("@",s);if(o===-1){n+=e.slice(s);break}const r=o>0?e[o-1]:" ",a=r===" "||r===`
|
|
16
|
-
`?R6.exec(e.slice(o+1)):null;if(a){n+=e.slice(s,o),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:a[1]}),s=o+1+a[0].length;continue}const d=(/^\S*/.exec(e.slice(o+1))?.[0]??"").replace(/[),.;!?]+$/,"");(r===" "||r===`
|
|
17
|
-
`)&&d&&M6.test(d)?(n+=e.slice(s,o),n&&(t.push({type:"text",text:n}),n=""),t.push({type:"file",path:d}),s=o+1+d.length):(n+=e.slice(s,o+1),s=o+1)}return n&&t.push({type:"text",text:n}),t.length>0?t:[{type:"text",text:e}]}function G6(e){const t={body:e,files:[],chats:[]},n=e.split(`
|
|
18
|
-
`),s=[],o=[];let r=n.length-1;for(;r>=0;r--){const a=n[r],l=I6.exec(a);if(l){o.unshift({label:l[1],sessionFile:l[2]});continue}if(E6.test(a)){s.unshift(a.slice(1));continue}break}return s.length+o.length===0||r<0||n[r].trim()!==""?t:{body:n.slice(0,r).join(`
|
|
19
|
-
`).trimEnd(),files:s,chats:o}}function nw(e){const t=P6(e.segments).trim(),n=e.segments.filter(o=>o.type!=="text").map(o=>o.type==="file"?{kind:"file",id:o.path,label:fh(o.path),relativePath:O6(o.path)}:o.type==="chat"?{kind:"chat",id:o.sessionFile,label:o.label,sessionFile:o.sessionFile}:{kind:"ui-element",id:o.id,label:o.label,path:o.path,text:o.text,imageId:o.imageId});e.recipient&&n.push(e.recipient);const s=e.slashes.join(" ");return{text:s?t?`${s} ${t}`:s:t,images:e.images.map(({data:o,mimeType:r})=>({data:o,mimeType:r})),mentions:n,...e.recipient?{recipient:e.recipient}:{}}}const F6={cover:{backgroundSize:"cover",backgroundRepeat:"no-repeat",backgroundPosition:"center"},contain:{backgroundSize:"contain",backgroundRepeat:"no-repeat",backgroundPosition:"center"},repeat:{backgroundSize:"auto",backgroundRepeat:"repeat",backgroundPosition:"top left"},center:{backgroundSize:"auto",backgroundRepeat:"no-repeat",backgroundPosition:"center"}};function H6(){const e=rk(),t=Ce(x=>x.backgroundImageEnabled),n=Ce(x=>x.backgroundSourceType),s=Ce(x=>x.backgroundImagePath),o=Ce(x=>x.backgroundFolderPath),r=Ce(x=>x.backgroundUrlPath),a=Ce(x=>x.backgroundRandomEnabled),l=Ce(x=>x.backgroundRandomInterval),d=Ce(x=>x.backgroundRefreshNonce),[c,u]=m.useState(0);m.useEffect(()=>{d>0&&u(x=>x+1)},[d]),m.useEffect(()=>{if(!t||!a||n==="file")return;const x=Math.max(5,l)*1e3,v=window.setInterval(()=>u(y=>y+1),x);return()=>window.clearInterval(v)},[t,a,l,n]);const[h,p]=m.useState([]);m.useEffect(()=>{if(!t||n!=="folder"||!o){p([]);return}let x=!1;return window.electronAPI.files.listMedia(o).then(v=>{x||p(v)}),()=>{x=!0}},[t,n,o,c]);const[f,g]=m.useState("");return m.useEffect(()=>{if(h.length===0){g("");return}g(x=>{if(h.length===1)return h[0];const v=h.filter(y=>y!==x);return v[Math.floor(Math.random()*v.length)]})},[h]),i.jsxs(B6,{children:[e?.source==="user"&&i.jsx(V6,{state:{sourceType:n,imagePath:s,folderPick:f,urlPath:r,tick:c},look:e}),e?.source==="theme"&&i.jsxs(dN,{look:e,children:[i.jsx(cN,{image:"var(--enso-asset-background)",look:e}),i.jsx(uN,{mask:e.mask})]})]})}function B6({children:e}){const t=gn(s=>s.browserHoles),n=rN(Object.values(t));return m.useLayoutEffect(()=>{const s=document.documentElement;return n?s.style.setProperty("--enso-browser-holes-clip",n):s.style.removeProperty("--enso-browser-holes-clip"),()=>{s.style.removeProperty("--enso-browser-holes-clip")}},[n]),i.jsx("div",{"aria-hidden":!0,"data-slot":"background-layer",className:"pointer-events-none absolute inset-0 -z-10 overflow-hidden",style:{clipPath:n,backgroundColor:"var(--canvas)"},children:e})}const aN=({blur:e,brightness:t,saturation:n})=>`blur(${e}px) brightness(${t}) saturate(${n})`,lN=({blur:e})=>e>0?`-${e*2}px`:"0";function V6({state:e,look:t}){const{sourceType:n,imagePath:s,folderPick:o,urlPath:r,tick:a}=e,l=m.useMemo(()=>{if(n==="file"&&s)return{src:uf(s),video:Fh(s)};if(n==="folder"&&o)return{src:uf(o),video:Fh(o)};if(n==="url"){const p=r.trim();if(/^https?:\/\//i.test(p))return{src:xP(p,a),video:Fh(p)}}return null},[n,s,o,r,a]),[d,c]=m.useState(null);if(m.useEffect(()=>{if(!l){c(null);return}if(l.video){c(l);return}let p=!1;const f=new Image;return f.onload=()=>{p||c(l)},f.src=l.src,()=>{p=!0}},[l]),!d)return null;const{src:u,video:h}=d;return i.jsxs(dN,{look:t,children:[h?i.jsx("video",{src:u,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"absolute",style:{inset:lN(t),width:"auto",height:"auto",minWidth:"100%",minHeight:"100%",objectFit:t.size==="contain"?"contain":"cover",filter:aN(t),transition:"filter 0.3s ease"}},u):i.jsx(cN,{image:`url("${u}")`,look:t},u),i.jsx(uN,{mask:t.mask})]})}function dN({look:e,children:t}){return i.jsx("div",{"data-slot":"background-media",className:"absolute inset-0",style:{opacity:vP(e.opacity).wallpaperOpacity},children:t})}function cN({image:e,look:t}){return i.jsx("div",{className:"absolute",style:{inset:lN(t),backgroundImage:e,...F6[t.size],filter:aN(t),transition:"filter 0.3s ease"}})}function uN({mask:e}){return e<=0?null:i.jsx("div",{"aria-hidden":!0,className:"absolute inset-0",style:{backgroundColor:`color-mix(in oklab, var(--canvas, var(--background)) ${Math.round(Math.min(1,Math.max(0,e))*100)}%, transparent)`}})}function bu(e,t,n,s){return{left:e,top:t,right:n,bottom:s,x:e,y:t,width:n-e,height:s-t}}function $6(e){return{left:e.left,top:e.top,right:e.right,bottom:e.bottom,width:e.width,height:e.height}}function hN(e){const t=[];let n,s=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const l of Array.from(e).sort((d,c)=>d.top-c.top)){if(s=Math.min(s,l.left),o=Math.min(o,l.top),r=Math.max(r,l.right),a=Math.max(a,l.bottom),!n||l.top-n.top>n.height/2)t.push($6(l));else{const d=t[t.length-1];d.left=Math.min(d.left,l.left),d.right=Math.max(d.right,l.right),d.bottom=Math.max(d.bottom,l.bottom),d.width=d.right-d.left,d.height=d.bottom-d.top}n=l}return{lines:t,fallback:bu(s,o,r,a)}}function pN(e,t,n){return e.findIndex(s=>t>s.left-2&&t<s.right+2&&n>s.top-2&&n<s.bottom+2)}function sw(e){return bu(e.left,e.top,e.right,e.bottom)}function W6(e,t,n){const{lines:s}=hN(e.getClientRects());if(s.length<2)return;const o=pN(s,t,n);return{x:t,y:n,lineIndex:o===-1?void 0:o,element:e}}function U6(e,t,n){const{lines:s,fallback:o}=hN(e.getClientRects());if(s.length<2)return null;const r=n?.x,a=n?.y,l=t[0];if(n?.lineIndex!=null&&s[n.lineIndex])return sw(s[n.lineIndex]);if(r!=null&&a!=null){const g=pN(s,r,a);if(g!==-1)return sw(s[g])}if(s.length===2&&s[0].left>s[1].right&&r!=null&&a!=null)return o;if(l==="t"||l==="b"){const g=s[0],x=s[s.length-1],v=l==="t"?g:x;return bu(v.left,g.top,v.right,x.bottom)}const d=l==="l";let c=s[0].left,u=s[0].right,h=d?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY,p=s[0],f=s[0];for(const g of s){c=Math.min(c,g.left),u=Math.max(u,g.right);const x=d?g.left:g.right;d&&x<h||!d&&x>h?(h=x,p=g,f=g):x===h&&(f=g)}return bu(c,p.top,u,f.bottom)}function K6(e){return"contextElement"in e&&e.contextElement?e.contextElement:bP(e)?e:void 0}function q6(e,t){function n(o){fN(e,o.currentTarget,o.clientX,o.clientY)}function s(o){t||n(o)}return{onFocus(){e.current=void 0},onMouseEnter:s,onMouseMove:s}}function fN(e,t,n,s){const o=W6(t,n,s);return e.current=o,o}function Y6(e){return{name:"inline",async fn(t){const n=t.elements.reference;if(typeof n?.getClientRects!="function")return{};const s=K6(n),o=e.current,r=o?.element===n||o?.element===s?o:void 0,a=U6(n,t.placement,r);if(!a||typeof t.platform.getElementRects!="function")return{};const l=await t.platform.getElementRects({reference:{contextElement:s,getBoundingClientRect(){return a}},floating:t.elements.floating,strategy:t.strategy});return t.rects.reference.x===l.reference.x&&t.rects.reference.y===l.reference.y&&t.rects.reference.width===l.reference.width&&t.rects.reference.height===l.reference.height?{}:{reset:{rects:l}}}}}function iw(){const{t:e}=Q(),[t,n]=m.useState(null),[s,o]=m.useState(!1),[r,a]=m.useState(!1),[l,d]=m.useState(!1);if(m.useEffect(()=>{let f=!0;window.electronAPI.updater.getState().then(x=>f&&a(x.host==="desktop")).catch(()=>{});const g=window.electronAPI.updater.onStatus(x=>{n(x),x.status!=="checking"&&x.status!=="not-available"&&o(!1)});return()=>{f=!1,g()}},[]),s||!t)return null;const c=t.status==="available"&&r;if(t.status!=="downloaded"&&t.status!=="downloading"&&!c)return null;const u=t.info?.version,h=t.status==="downloaded",p=h&&t.restartPending===!0;return i.jsxs("div",{className:"border-b border-blue-500/20 bg-background",children:[i.jsxs("div",{className:"flex items-center gap-2 bg-blue-500/8 px-4 py-1.5 text-xs",children:[h?i.jsx(ak,{className:"h-3.5 w-3.5 shrink-0 text-blue-500"}):i.jsx(sd,{className:"h-3.5 w-3.5 shrink-0 animate-pulse text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1",children:p?e("Will restart to update {{version}} when the running turns finish.",{version:u??""}):h?e("New version {{version}} is ready — restart to update.",{version:u??""}):c?e("New version {{version}} found",{version:u??""}):e("Downloading update… {{percent}}%",{percent:Math.round(t.progress?.percent??0)})}),(h||c)&&i.jsx("button",{type:"button",onClick:()=>d(!0),className:"shrink-0 rounded-md px-2 py-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:e("Release notes")}),c&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.downloadUpdate()},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e("Download update")}),p&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.cancelRestart()},className:"shrink-0 rounded-md px-2 py-1 text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",children:e("Cancel")}),h&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.updater.quitAndInstall({now:p})},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e(p?"Restart now":"Restart to update")}),i.jsx("button",{type:"button",onClick:()=>o(!0),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",title:e("Close"),children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}),i.jsx(wP,{open:l,onOpenChange:d,status:t})]})}const xp="enso.zoomBanner.dismissedPercent";function X6(e,t){return e!==100&&e!==t}function Z6(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function vp(){return window.electronAPI.window.getZoomPercent()}function ow(){const{t:e}=Q(),[t,n]=m.useState(vp),[s,o]=m.useState(()=>Z6(localStorage.getItem(xp)));return m.useEffect(()=>{const r=()=>n(vp());return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),X6(t,s)?i.jsx("div",{className:"border-b border-blue-500/20 bg-background",children:i.jsxs("div",{className:"flex items-center gap-2 bg-blue-500/8 px-4 py-1.5 text-xs",children:[i.jsx("span",{className:"min-w-0 flex-1",children:e("Interface is zoomed to {{percent}}% · {{shortcut}}",{percent:t,shortcut:fi("mod+0")})}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.window.resetZoom(),localStorage.removeItem(xp),o(null),n(vp())},className:"shrink-0 rounded-md bg-primary px-2.5 py-1 text-primary-foreground transition-colors hover:bg-primary/90",children:e("Restore 100%")}),i.jsx("button",{type:"button",onClick:()=>{localStorage.setItem(xp,String(t)),o(t)},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",title:e("Close"),"aria-label":e("Close"),children:i.jsx(an,{className:"h-3.5 w-3.5"})})]})}):null}function J6(e,t){return[t,...e.filter(n=>n.parentId===t.id).sort((n,s)=>n.createdAt-s.createdAt)]}function Q6(e,t){return(t.activeThreadId?e.find(s=>s.id===t.activeThreadId&&s.parentId===t.id):void 0)??t}const e4=10,mN=e=>[...e].sort((t,n)=>n.activityAt-t.activityAt);function gN(e,t,n=e4){const s=mN(e),o=a=>a.id===t.currentId||a.id===t.rootId?0:a.unread||a.running?1:2,r=new Set([...s].sort((a,l)=>o(a)-o(l)).slice(0,n).map(a=>a.id));return s.filter(a=>r.has(a.id)).sort((a,l)=>+(l.id===t.rootId)-+(a.id===t.rootId))}function rw(e,t,n){const s=t.trim().toLowerCase();return mN(e).filter(o=>(n==="all"||(n==="unread"?o.unread:o.running))&&(!s||`${o.title}
|
|
20
|
-
${o.preview??""}`.toLowerCase().includes(s)))}function wu({onResize:e,onResizingChange:t,gap:n=!1,edge:s=!1}){const[o,r]=m.useState(!1),a=m.useRef(0),l=m.useCallback(d=>{d.preventDefault(),r(!0),t?.(!0),a.current=d.clientX;const c=h=>{e(h.clientX-a.current),a.current=h.clientX},u=()=>{r(!1),t?.(!1),document.removeEventListener("mousemove",c),document.removeEventListener("mouseup",u)};document.addEventListener("mousemove",c),document.addEventListener("mouseup",u)},[e,t]);return i.jsxs("div",{className:q("relative z-20 shrink-0",s?"w-0":n?"w-[8px]":"w-px bg-border"),children:[i.jsx("div",{onMouseDown:l,className:q("absolute inset-y-0 z-10 cursor-col-resize","after:absolute after:inset-y-0 after:w-px after:transition-colors hover:after:bg-ring",s?"left-0 w-3 after:left-0":n?"inset-x-0 after:left-1/2":"-left-1 -right-1 after:left-1",o&&"after:bg-ring")}),o&&i.jsx("div",{className:"fixed inset-0 z-50 cursor-col-resize"})]})}const t4={"external-send":"Protected: external send",delete:"Protected: delete",payment:"Protected: payment",deploy:"Protected: deploy / production",secret:"Protected: secrets",destructive:"Protected: destructive command"};function xN(e,t){return t(t4[e])}const vN={exec:"Isolated sandbox",codemode:"Isolated sandbox",tool_search:"Tool search",apply_patch:"Apply patch",explore_mark:"Explore mark",explore_fold:"Explore fold",subagent:"Subagent",workflow:"Workflow",ask_user:"Ask user",task_output:"Task output",task_stop:"Task stop",message_coworker:"Message coworker",message_main_agent:"Message main agent",enso_app:"Enso app",enso_capabilities:"Enso capabilities",recall:"Recall memory",memory_search:"Memory search",memory_capture:"Memory capture",memory_crystallize:"Memory crystallize",memory_delete:"Memory delete",browser_navigate:"Browser navigate",browser_snapshot:"Browser snapshot",browser_click:"Browser click",browser_type:"Browser type",browser_tabs:"Browser tabs",browser_lock:"Browser lock",browser_fill:"Browser fill",browser_press_key:"Browser press key",browser_scroll:"Browser scroll",browser_select_option:"Browser select option",browser_mouse_click_xy:"Browser click xy",browser_drag:"Browser drag",browser_highlight:"Browser highlight",browser_get_bounding_box:"Browser bounding box",browser_screenshot:"Browser screenshot",browser_cdp:"Browser CDP",web_search:"Web search",web_fetch:"Web fetch"};function ha(e,t){const n=vN[e];return n?t(n):e}const n4={report:"Read report",wait:"Wait",stop:"Stop",dismiss:"Dismiss agent",list:"List agents"};function bN(e,t=0){const[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{if(e===void 0)return;s(Date.now());const o=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(o)},[e]),e===void 0?void 0:e+t-n}function wN({remainingMs:e,expiredLabel:t}){const{t:n}=Q();if(e===void 0)return null;if(e<=0)return i.jsx("span",{className:"shrink-0 text-[10px] text-warning",children:n(t)});const s=Math.ceil(e/1e3),o=`${Math.floor(s/60)}:${String(s%60).padStart(2,"0")}`;return i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:n("{{time}} left",{time:o})})}const s4={command:Go,"file-edit":n$,"file-write":i$,mcp:lk};function i4({kind:e,summary:t}){const[n,s]=m.useState(null);m.useEffect(()=>{if(e!=="command")return;let r=!0;return SP(t,"shellscript").then(a=>{r&&s(a)}),()=>{r=!1}},[e,t]);const o=i.jsx(dk,{text:t,className:"absolute top-1 right-1 z-10 rounded-md bg-background/80 p-1 text-muted-foreground backdrop-blur"});return e==="command"&&n!=null?i.jsxs("div",{className:"relative mt-1.5",children:[i.jsx("div",{className:"max-h-24 overflow-auto rounded-md text-xs leading-relaxed [&_pre]:m-0 [&_pre]:py-1.5 [&_pre]:pr-7 [&_pre]:pl-2 [&_pre]:font-mono [&_pre]:whitespace-pre-wrap",dangerouslySetInnerHTML:{__html:n}}),o]}):i.jsxs("div",{className:"relative mt-1.5",children:[i.jsx("pre",{className:"max-h-24 overflow-auto rounded-md bg-muted/50 py-1.5 pr-7 pl-2 font-mono text-xs whitespace-pre-wrap",children:t}),o]})}const o4={timeout:"Auto-managed review timed out. Please decide.",error:"Auto-managed review failed. Please decide.",invalid:"Auto-managed review returned no valid decision. Please decide."};function Bl({approvals:e,onRespond:t,allowSession:n=!0,handoff:s=!0,clockOffset:o}){const{t:r}=Q(),[a,l]=m.useState(null),d=e[0],c=bN(d?.phase==="reviewing"?void 0:d?.expiresAt,o);if(!d)return null;const u=s4[d.kind]??ta,h=d.phase==="reviewing",p=a===d.requestId||c!==void 0&&c<=0,f=g=>{g!=="review"&&l(d.requestId),t(d.requestId,g)};return i.jsxs("div",{className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[i.jsx(ta,{className:"h-3.5 w-3.5 shrink-0 text-amber-500"}),i.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:r(h?"Assistant reviewing…":"Approval required")}),i.jsxs("span",{className:"flex min-w-0 items-center gap-1 text-muted-foreground",children:[i.jsx(u,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate font-mono",children:d.toolCallId&&yP(d.toolCallId)?`${r("Isolated sandbox")} › ${ha(d.tool,r)}`:ha(d.tool,r)})]}),d.protected&&i.jsx("span",{className:"shrink-0 rounded bg-destructive/15 px-1.5 text-[10px] text-destructive",children:xN(d.protected,r)}),i.jsxs("span",{className:"ml-auto flex shrink-0 items-center gap-2",children:[i.jsx(wN,{remainingMs:c,expiredLabel:"Timed out · denied"}),e.length>1&&i.jsxs("span",{className:"text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]})]}),d.reviewFallback&&i.jsx("p",{className:"mt-1 text-[11px] text-amber-600 dark:text-amber-400",children:r(o4[d.reviewFallback])}),d.guard&&i.jsx("p",{className:"mt-1 text-[11px] text-destructive",title:d.guard.ruleId,children:r("dcg: {{reason}}",{reason:d.guard.reason})}),d.summary&&i.jsx(i4,{kind:d.kind,summary:d.summary}),!h&&i.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[s&&d.kind==="command"&&i.jsx("button",{type:"button",disabled:p,title:r("Send back for a safer command"),onClick:()=>f("revise"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Adjust")}),s&&i.jsx("button",{type:"button",disabled:p,title:r("Let the assistant decide"),onClick:()=>f("review"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Assistant review")}),i.jsx("button",{type:"button",disabled:p,onClick:()=>f("deny"),className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:r("Deny")}),n&&!d.protected&&i.jsx("button",{type:"button",disabled:p,onClick:()=>f("allowSession"),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:r("Always allow this session")}),i.jsx("button",{type:"button",disabled:p,onClick:()=>f("allow"),className:"rounded-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:r("Allow")})]})]})}function mh({asks:e,onAnswer:t,clockOffset:n,autoFocus:s=!0}){const{t:o}=Q(),r=m.useRef(null),[a,l]=m.useState(""),[d,c]=m.useState(null),u=e[0],h=u?.requestId,p=bN(u?.expiresAt,n);if(m.useEffect(()=>{!s||!h||r.current?.focus()},[s,h]),!u)return null;const f=d===u.requestId||p!==void 0&&p<=0,g=x=>{x.trim()&&(c(u.requestId),l(""),t(u.requestId,x.trim()))};return i.jsxs("div",{className:"mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2",children:[i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx(CP,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-blue-500"}),i.jsx("span",{className:"min-w-0 flex-1 text-xs leading-relaxed whitespace-pre-wrap",children:u.question}),i.jsx(wN,{remainingMs:p,expiredLabel:"Timed out · no answer"}),e.length>1&&i.jsxs("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:["1/",e.length]})]}),u.options&&u.options.length>0&&i.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:u.options.map(x=>i.jsx("button",{type:"button",disabled:f,onClick:()=>g(x),className:"rounded-md border border-border/60 px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:x},x))}),i.jsxs("div",{className:"mt-2 flex items-center gap-1.5",children:[i.jsx("input",{ref:r,value:a,onChange:x=>l(x.target.value),onKeyDown:x=>{x.nativeEvent.isComposing||x.key==="Enter"&&g(a)},disabled:f,placeholder:o("Type an answer…"),className:"h-7 min-w-0 flex-1 rounded-md border bg-transparent px-2 text-xs outline-none focus:ring-1 focus:ring-ring disabled:opacity-50"}),i.jsx("button",{type:"button",disabled:f||!a.trim(),onClick:()=>g(a),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",children:i.jsx(yx,{className:"h-3.5 w-3.5"})})]})]})}const gh=0,Vo=1,Ta=2,yN=4;function aw(e){return()=>e}function r4(e){e()}function SN(e,t){return n=>e(t(n))}function lw(e,t){return()=>e(t)}function a4(e,t){return n=>e(t,n)}function Sx(e){return e!==void 0}function l4(...e){return()=>{e.map(r4)}}function Da(){}function xh(e,t){return t(e),e}function d4(e,t){return t(e)}function An(...e){return e}function fn(e,t){return e(Vo,t)}function Ht(e,t){e(gh,t)}function Cx(e){e(Ta)}function Rn(e){return e(yN)}function vt(e,t){return fn(e,a4(t,gh))}function pi(e,t){const n=e(Vo,s=>{n(),t(s)});return n}function dw(e){let t,n;return s=>o=>{t=o,n&&clearTimeout(n),n=setTimeout(()=>{s(t)},e)}}function CN(e,t){return e===t}function Pn(e=CN){let t;return n=>s=>{e(t,s)||(t=s,n(s))}}function Pt(e){return t=>n=>{e(n)&&t(n)}}function ht(e){return t=>SN(t,e)}function _i(e){return t=>()=>{t(e)}}function $e(e,...t){const n=c4(...t);return((s,o)=>{switch(s){case Ta:Cx(e);return;case Vo:return fn(e,n(o))}})}function Pi(e,t){return n=>s=>{n(t=e(t,s))}}function br(e){return t=>n=>{e>0?e--:t(n)}}function ro(e){let t=null,n;return s=>o=>{t=o,!n&&(n=setTimeout(()=>{n=void 0,s(t)},e))}}function Yt(...e){const t=Array.from({length:e.length});let n=0,s=null;const o=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;fn(r,d=>{const c=n;n|=l,t[a]=d,c!==o&&n===o&&s&&(s(),s=null)})}),r=>a=>{const l=()=>{r([a].concat(t))};n===o?l():s=l}}function c4(...e){return t=>e.reduceRight(d4,t)}function u4(e){let t,n;const s=()=>t?.();return function(o,r){switch(o){case Vo:return r?n===r?void 0:(s(),n=r,t=fn(e,r),t):(s(),Da);case Ta:s(),n=null;return}}}function Ke(e){let t=e;const n=on();return((s,o)=>{switch(s){case gh:t=o;break;case Vo:{o(t);break}case yN:return t}return n(s,o)})}function ps(e,t){return xh(Ke(t),n=>vt(e,n))}function on(){const e=[];return((t,n)=>{switch(t){case gh:e.slice().forEach(s=>{s(n)});return;case Ta:e.splice(0);return;case Vo:return e.push(n),()=>{const s=e.indexOf(n);s>-1&&e.splice(s,1)}}})}function Os(e){return xh(on(),t=>vt(e,t))}const h4={singleton:!0};function cn(e,t=[],n=h4){const{singleton:s}=n;return{constructor:e,dependencies:t,id:p4(),singleton:s}}const p4=()=>Symbol("id");function f4(e){const t=new Map,n=({constructor:s,dependencies:o,id:r,singleton:a})=>{if(a&&t.has(r))return t.get(r);const l=s(o.map(d=>n(d)));return a&&t.set(r,l),l};return n(e)}function Bn(...e){const t=on(),n=Array.from({length:e.length});let s=0;const o=2**e.length-1;return e.forEach((r,a)=>{const l=2**a;fn(r,d=>{n[a]=d,s|=l,s===o&&Ht(t,n)})}),function(r,a){switch(r){case Ta:{Cx(t);return}case Vo:return s===o&&a(n),fn(t,a)}}}function Et(e,t=CN){return $e(e,Pn(t))}function nm(...e){return function(t,n){switch(t){case Ta:return;case Vo:return l4(...e.map(s=>fn(s,n)))}}}const Jn={DEBUG:0,INFO:1,WARN:2,ERROR:3},m4={[Jn.DEBUG]:"debug",[Jn.ERROR]:"error",[Jn.INFO]:"log",[Jn.WARN]:"warn"},g4=()=>typeof globalThis>"u"?window:globalThis,$o=cn(()=>{const e=Ke(Jn.ERROR);return{log:Ke((t,n,s=Jn.INFO)=>{const o=g4().VIRTUOSO_LOG_LEVEL??Rn(e);s>=o&&console[m4[s]]("%creact-virtuoso: %c%s %o","color: #0253b3; font-weight: bold","color: initial",t,n)}),logLevel:e}},[],{singleton:!0});function x4(e){return"self"in e?e.document.documentElement:e}function kN(e){const t=x4(e);return t.ownerDocument.defaultView.getComputedStyle(t).direction==="rtl"}function dr(e,t){return kN(e)?-t:t}function cw(e,t){return kN(e)?-t:t}function Sr(e,t,n){return kx(e,t,n).callbackRef}function kx(e,t,n){const s=Ne.useRef(null);let o=a=>{};const r=Ne.useMemo(()=>typeof ResizeObserver<"u"?new ResizeObserver(a=>{const l=()=>{const d=a[0].target;d.offsetParent!==null&&e(d)};n?l():requestAnimationFrame(l)}):null,[e,n]);return o=a=>{a&&t?(r?.observe(a),s.current=a):(s.current&&r?.unobserve(s.current),s.current=null)},{callbackRef:o,ref:s}}function v4(e,t,n,s,o,r,a,l,d){const c=Ne.useCallback(u=>{const h=b4(u.children,t,l?"offsetWidth":"offsetHeight",o);let p=u.parentElement;for(;p.dataset.virtuosoScroller===void 0;)p=p.parentElement;const f=p.lastElementChild?.dataset.viewportType==="window";let g;f&&(g=p.ownerDocument.defaultView);const x=a?l?a.scrollWidth:a.scrollHeight:f?l?g.document.documentElement.scrollWidth:g.document.documentElement.scrollHeight:l?p.scrollWidth:p.scrollHeight,v=a?l?a.offsetWidth:a.offsetHeight:f?l?g.innerWidth:g.innerHeight:l?p.offsetWidth:p.offsetHeight,y=a?l?dr(a,a.scrollLeft):a.scrollTop:f?l?dr(g,g.scrollX||g.document.documentElement.scrollLeft):g.scrollY||g.document.documentElement.scrollTop:l?dr(p,p.scrollLeft):p.scrollTop;s({scrollHeight:x,scrollTop:Math.max(y,0),viewportHeight:v}),r?.(l?uw("column-gap",getComputedStyle(u).columnGap,o):uw("row-gap",getComputedStyle(u).rowGap,o)),h!==null&&e(h)},[e,t,o,r,a,s,l]);return kx(c,n,d)}function b4(e,t,n,s){const o=e.length;if(o===0)return null;const r=[];for(let a=0;a<o;a++){const l=e.item(a);if(l.dataset.index===void 0)continue;const d=parseInt(l.dataset.index,10),c=parseFloat(l.dataset.knownSize),u=t(l,n);if(u===0&&s("Zero-sized element, this should not happen",{child:l},Jn.ERROR),u===c)continue;const h=r[r.length-1];r.length===0||h.size!==u||h.endIndex!==d-1?r.push({endIndex:d,size:u,startIndex:d}):r[r.length-1].endIndex++}return r}function uw(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,Jn.WARN),t==="normal"?0:parseInt(t??"0",10)}function jN(e,t,n){const s=Ne.useRef(null),o=Ne.useCallback(d=>{if(!d?.offsetParent)return;const c=d.getBoundingClientRect(),u=c.width;let h,p;if(t){const f=t.getBoundingClientRect(),g=c.top-f.top;p=f.height-Math.max(0,g),h=g+t.scrollTop}else{const f=a.current.ownerDocument.defaultView;p=f.innerHeight-Math.max(0,c.top),h=c.top+f.scrollY}s.current={listHeight:c.height,offsetTop:h,visibleHeight:p,visibleWidth:u},e(s.current)},[e,t]),{callbackRef:r,ref:a}=kx(o,!0,n),l=Ne.useCallback(()=>{o(a.current)},[o,a]);return Ne.useEffect(()=>{if(t){t.addEventListener("scroll",l);const c=new ResizeObserver(()=>{requestAnimationFrame(l)});return c.observe(t),()=>{t.removeEventListener("scroll",l),c.unobserve(t)}}const d=a.current?.ownerDocument.defaultView;return d?.addEventListener("scroll",l),d?.addEventListener("resize",l),()=>{d?.removeEventListener("scroll",l),d?.removeEventListener("resize",l)}},[l,t,a]),r}const Ts=cn(()=>{const e=on(),t=on(),n=Ke(0),s=on(),o=Ke(0),r=on(),a=on(),l=Ke(0),d=Ke(0),c=Ke(0),u=Ke(0),h=on(),p=on(),f=Ke(!1),g=Ke(!1),x=Ke(!1);return vt($e(e,ht(({scrollTop:v})=>v)),t),vt($e(e,ht(({scrollHeight:v})=>v)),a),vt(t,o),{deviation:n,fixedFooterHeight:c,fixedHeaderHeight:d,footerHeight:u,headerHeight:l,horizontalDirection:g,scrollBy:p,scrollContainerState:e,scrollHeight:a,scrollingInProgress:f,scrollTo:h,scrollTop:t,skipAnimationFrameInResizeObserver:x,smoothScrollTargetReached:s,statefulScrollTop:o,viewportHeight:r}},[],{singleton:!0}),Vl={lvl:0};function _N(e,t){const n=e.length;if(n===0)return[];let{index:s,value:o}=t(e[0]);const r=[];for(let a=1;a<n;a++){const{index:l,value:d}=t(e[a]);r.push({end:l-1,start:s,value:o}),s=l,o=d}return r.push({end:1/0,start:s,value:o}),r}function vn(e){return e===Vl}function $l(e,t){if(!vn(e))return t===e.k?e.v:t<e.k?$l(e.l,t):$l(e.r,t)}function xi(e,t,n="k"){if(vn(e))return[-1/0,void 0];if(Number(e[n])===t)return[e.k,e.v];if(Number(e[n])<t){const s=xi(e.r,t,n);return s[0]===-1/0?[e.k,e.v]:s}return xi(e.l,t,n)}function Rs(e,t,n){return vn(e)?DN(t,n,1):t===e.k?Xn(e,{k:t,v:n}):t<e.k?hw(Xn(e,{l:Rs(e.l,t,n)})):hw(Xn(e,{r:Rs(e.r,t,n)}))}function Xr(){return Vl}function Zr(e,t,n){if(vn(e))return[];const s=xi(e,t)[0];return w4(im(e,s,n))}function sm(e,t){if(vn(e))return Vl;const{k:n,l:s,r:o}=e;if(t===n){if(vn(s))return o;if(vn(o))return s;const[r,a]=TN(s);return Lc(Xn(e,{k:r,l:NN(s),v:a}))}return t<n?Lc(Xn(e,{l:sm(s,t)})):Lc(Xn(e,{r:sm(o,t)}))}function cr(e){return vn(e)?[]:[...cr(e.l),{k:e.k,v:e.v},...cr(e.r)]}function im(e,t,n){if(vn(e))return[];const{k:s,l:o,r,v:a}=e;let l=[];return s>t&&(l=l.concat(im(o,t,n))),s>=t&&s<=n&&l.push({k:s,v:a}),s<=n&&(l=l.concat(im(r,t,n))),l}function Lc(e){const{l:t,lvl:n,r:s}=e;if(s.lvl>=n-1&&t.lvl>=n-1)return e;if(n>s.lvl+1){if(bp(t))return IN(Xn(e,{lvl:n-1}));if(!vn(t)&&!vn(t.r))return Xn(t.r,{l:Xn(t,{r:t.r.l}),lvl:n,r:Xn(e,{l:t.r.r,lvl:n-1})});throw new Error("Unexpected empty nodes")}if(bp(e))return om(Xn(e,{lvl:n-1}));if(!vn(s)&&!vn(s.l)){const o=s.l,r=bp(o)?s.lvl-1:s.lvl;return Xn(o,{l:Xn(e,{lvl:n-1,r:o.l}),lvl:o.lvl+1,r:om(Xn(s,{l:o.r,lvl:r}))})}throw new Error("Unexpected empty nodes")}function Xn(e,t){return DN(t.k===void 0?e.k:t.k,t.v===void 0?e.v:t.v,t.lvl===void 0?e.lvl:t.lvl,t.l===void 0?e.l:t.l,t.r===void 0?e.r:t.r)}function NN(e){return vn(e.r)?e.l:Lc(Xn(e,{r:NN(e.r)}))}function bp(e){return vn(e)||e.lvl>e.r.lvl}function TN(e){return vn(e.r)?[e.k,e.v]:TN(e.r)}function DN(e,t,n,s=Vl,o=Vl){return{k:e,l:s,lvl:n,r:o,v:t}}function hw(e){return om(IN(e))}function IN(e){const{l:t}=e;return!vn(t)&&t.lvl===e.lvl?Xn(t,{r:Xn(e,{l:t.r})}):e}function om(e){const{lvl:t,r:n}=e;return!vn(n)&&!vn(n.r)&&n.lvl===t&&n.r.lvl===t?Xn(n,{l:Xn(e,{r:n.l}),lvl:t+1}):e}function w4(e){return _N(e,({k:t,v:n})=>({index:t,value:n}))}function EN(e,t){return!!(e&&e.startIndex===t.startIndex&&e.endIndex===t.endIndex)}function Wl(e,t){return!!(e&&e[0]===t[0]&&e[1]===t[1])}const jx=cn(()=>({recalcInProgress:Ke(!1)}),[],{singleton:!0});function PN(e,t,n){return e[yu(e,t,n)]}function yu(e,t,n,s=0){let o=e.length-1;for(;s<=o;){const r=Math.floor((s+o)/2),a=e[r],l=n(a,t);if(l===0)return r;if(l===-1){if(o-s<2)return r-1;o=r-1}else{if(o===s)return r;s=r+1}}throw new Error(`Failed binary finding record in array - ${e.join(",")}, searched for ${t}`)}function y4(e,t,n,s){const o=yu(e,t,s),r=yu(e,n,s,o);return e.slice(o,r+1)}function Lo(e,t){return Math.round(e.getBoundingClientRect()[t])}function vh(e){return!vn(e.groupOffsetTree)}function _x({index:e},t){return t===e?0:t<e?-1:1}function S4(){return{groupIndices:[],groupOffsetTree:Xr(),lastIndex:0,lastOffset:0,lastSize:0,offsetTree:[],sizeTree:Xr()}}function C4(e,t){let n=vn(e)?0:1/0;for(const s of t){const{endIndex:o,size:r,startIndex:a}=s;if(n=Math.min(n,a),vn(e)){e=Rs(e,0,r);continue}const l=Zr(e,a-1,o+1);if(l.some(I4(s)))continue;let d=!1,c=!1;for(const{end:u,start:h,value:p}of l)d?(o>=h||r===p)&&(e=sm(e,h)):(c=p!==r,d=!0),u>o&&o>=h&&p!==r&&(e=Rs(e,o+1,p));c&&(e=Rs(e,a,r))}return[e,n]}function k4(e){return e.groupIndex!==void 0}function j4({offset:e},t){return t===e?0:t<e?-1:1}function Ul(e,t,n){if(t.length===0)return 0;const{index:s,offset:o,size:r}=PN(t,e,_x),a=e-s,l=r*a+(a-1)*n+o;return l>0?l+n:l}function AN(e,t){if(!vh(t))return e;let n=0;for(;t.groupIndices[n]<=e+n;)n++;return e+n}function MN(e,t,n){if(k4(e))return t.groupIndices[e.groupIndex]+1;const s=e.index==="LAST"?n:e.index;let o=AN(s,t);return o=Math.max(0,Math.min(n,o)),o}function _4(e,t,n,s=0){return s>0&&(t=Math.max(t,PN(e,s,_x).offset)),_N(y4(e,t,n,j4),D4)}function N4(e,[t,n,s,o]){t.length>0&&s("received item sizes",t,Jn.DEBUG);const r=e.sizeTree;let a=r,l=0;if(n.length>0&&vn(r)&&t.length===2){const p=t[0].size,f=t[1].size;a=n.reduce((g,x)=>Rs(Rs(g,x,p),x+1,f),a)}else[a,l]=C4(a,t);if(a===r)return e;const{lastIndex:d,lastOffset:c,lastSize:u,offsetTree:h}=rm(e.offsetTree,l,a,o);return{groupIndices:n,groupOffsetTree:n.reduce((p,f)=>Rs(p,f,Ul(f,h,o)),Xr()),lastIndex:d,lastOffset:c,lastSize:u,offsetTree:h,sizeTree:a}}function T4(e){return cr(e).map(({k:t,v:n},s,o)=>{const r=o[s+1];return{endIndex:r===void 0?1/0:r.k-1,size:n,startIndex:t}})}function pw(e,t){let n=0,s=0;for(;n<e;)n+=t[s+1]-t[s]-1,s++;return s-(n===e?0:1)}function rm(e,t,n,s){let o=e,r=0,a=0,l=0,d=0;if(t===0)o=[];else{d=yu(o,t-1,_x),l=o[d].offset;const c=xi(n,t-1);r=c[0],a=c[1],o.length&&o[d].size===xi(n,t)[1]&&(d-=1),o=o.slice(0,d+1)}for(const{start:c,value:u}of Zr(n,t,1/0)){const h=c-r,p=h*a+l+h*s;o.push({index:c,offset:p,size:u}),r=c,l=p,a=u}return{lastIndex:r,lastOffset:l,lastSize:a,offsetTree:o}}function D4(e){return{index:e.index,value:e}}function I4(e){const{endIndex:t,size:n,startIndex:s}=e;return o=>o.start===s&&(o.end===t||o.end===1/0)&&o.value===n}const E4={offsetHeight:"height",offsetWidth:"width"},$i=cn(([{log:e},{recalcInProgress:t}])=>{const n=on(),s=on(),o=ps(s,0),r=on(),a=on(),l=Ke(0),d=Ke([]),c=Ke(void 0),u=Ke(void 0),h=Ke(void 0),p=Ke(void 0),f=Ke((C,S)=>Lo(C,E4[S])),g=Ke(void 0),x=Ke(0),v=S4(),y=ps($e(n,Yt(d,e,x),Pi(N4,v),Pn()),v),w=ps($e(d,Pn(),Pi((C,S)=>({current:S,prev:C.current}),{current:[],prev:[]}),ht(({prev:C})=>C)),[]);vt($e(d,Pt(C=>C.length>0),Yt(y,x),ht(([C,S,A])=>{const E=C.reduce((I,D,T)=>Rs(I,D,Ul(D,S.offsetTree,A)||T),Xr());return{...S,groupIndices:C,groupOffsetTree:E}})),y),vt($e(s,Yt(y),Pt(([C,{lastIndex:S}])=>C<S),ht(([C,{lastIndex:S,lastSize:A}])=>[{endIndex:S,size:A,startIndex:C}])),n),vt(c,u);const b=ps($e(c,ht(C=>C===void 0)),!0);vt($e(u,Pt(C=>C!==void 0&&vn(Rn(y).sizeTree)),ht(C=>{const S=Rn(h),A=Rn(d).length>0;return S!==void 0&&S!==0?A?[{endIndex:0,size:S,startIndex:0},{endIndex:1,size:C,startIndex:1}]:[]:[{endIndex:0,size:C,startIndex:0}]})),n),vt($e(p,Pt(C=>C!==void 0&&C.length>0&&vn(Rn(y).sizeTree)),ht(C=>{const S=[];let A=C[0],E=0;for(let I=1;I<C.length;I++){const D=C[I];D!==A&&(S.push({endIndex:I-1,size:A,startIndex:E}),A=D,E=I)}return S.push({endIndex:C.length-1,size:A,startIndex:E}),S})),n),vt($e(d,Yt(h,u),Pt(([,C,S])=>C!==void 0&&S!==void 0),ht(([C,S,A])=>{const E=[];for(let I=0;I<C.length;I++){const D=C[I],T=C[I+1];E.push({startIndex:D,endIndex:D,size:S}),T!==void 0&&E.push({startIndex:D+1,endIndex:T-1,size:A})}return E})),n);const _=Os($e(n,Yt(y),Pi(({sizes:C},[S,A])=>({changed:A!==C,sizes:A}),{changed:!1,sizes:v}),ht(C=>C.changed)));fn($e(l,Pi((C,S)=>({diff:C.prev-S,prev:S}),{diff:0,prev:0}),ht(C=>C.diff)),C=>{const{groupIndices:S}=Rn(y);if(C>0)Ht(t,!0),Ht(r,C+pw(C,S));else if(C<0){const A=Rn(w);A.length>0&&(C-=pw(-C,A)),Ht(a,C)}}),fn($e(l,Yt(e)),([C,S])=>{C<0&&S("`firstItemIndex` prop should not be set to less than zero. If you don't know the total count, just use a very high value",{firstItemIndex:l},Jn.ERROR)});const j=Os(r);vt($e(r,Yt(y),ht(([C,S])=>{const A=S.groupIndices.length>0,E=[],I=S.lastSize;if(A){const D=$l(S.sizeTree,0);let T=0,z=0;for(;T<C;){const R=S.groupIndices[z],B=S.groupIndices.length===z+1?1/0:S.groupIndices[z+1]-R-1;E.push({endIndex:R,size:D,startIndex:R}),E.push({endIndex:R+1+B-1,size:I,startIndex:R+1}),z++,T+=B+1}const $=cr(S.sizeTree);return T!==C&&$.shift(),$.reduce((R,{k:B,v:H})=>{let oe=R.ranges;return R.prevSize!==0&&(oe=[...R.ranges,{endIndex:B+C-1,size:R.prevSize,startIndex:R.prevIndex}]),{prevIndex:B+C,prevSize:H,ranges:oe}},{prevIndex:C,prevSize:0,ranges:E}).ranges}return cr(S.sizeTree).reduce((D,{k:T,v:z})=>({prevIndex:T+C,prevSize:z,ranges:[...D.ranges,{endIndex:T+C-1,size:D.prevSize,startIndex:D.prevIndex}]}),{prevIndex:0,prevSize:I,ranges:[]}).ranges})),n);const N=Os($e(a,Yt(y,x),ht(([C,{offsetTree:S},A])=>{const E=-C;return Ul(E,S,A)})));return vt($e(a,Yt(y,x),ht(([C,S,A])=>{if(S.groupIndices.length>0){if(vn(S.sizeTree))return S;let I=Xr();const D=Rn(w);let T=0,z=0,$=0;for(;T<-C;){$=D[z];const R=D[z+1]-$-1;z++,T+=R+1}if(I=cr(S.sizeTree).reduce((R,{k:B,v:H})=>Rs(R,Math.max(0,B+C),H),I),T!==-C){const R=$l(S.sizeTree,$);I=Rs(I,0,R);const B=xi(S.sizeTree,-C+1)[1];I=Rs(I,1,B)}return{...S,sizeTree:I,...rm(S.offsetTree,0,I,A)}}const E=cr(S.sizeTree).reduce((I,{k:D,v:T})=>Rs(I,Math.max(0,D+C),T),Xr());return{...S,sizeTree:E,...rm(S.offsetTree,0,E,A)}})),y),{beforeUnshiftWith:j,data:g,defaultItemSize:u,firstItemIndex:l,fixedItemSize:c,fixedGroupSize:h,gap:x,groupIndices:d,heightEstimates:p,itemSize:f,listRefresh:_,shiftWith:a,shiftWithOffset:N,sizeRanges:n,sizes:y,statefulTotalCount:o,totalCount:s,trackItemSizes:b,unshiftWith:r}},An($o,jx),{singleton:!0});function P4(e){return e.reduce((t,n)=>(t.groupIndices.push(t.totalCount),t.totalCount+=n+1,t),{groupIndices:[],totalCount:0})}const RN=cn(([{groupIndices:e,sizes:t,totalCount:n},{headerHeight:s,scrollTop:o}])=>{const r=on(),a=on(),l=Os($e(r,ht(P4)));return vt($e(l,ht(d=>d.totalCount)),n),vt($e(l,ht(d=>d.groupIndices)),e),vt($e(Bn(o,t,s),Pt(([d,c])=>vh(c)),ht(([d,c,u])=>xi(c.groupOffsetTree,Math.max(d-u,0),"v")[0]),Pn(),ht(d=>[d])),a),{groupCounts:r,topItemsIndexes:a}},An($i,Ts)),Wo=cn(([{log:e}])=>{const t=Ke(!1),n=Os($e(t,Pt(s=>s),Pn()));return fn(t,s=>{s&&Rn(e)("props updated",{},Jn.DEBUG)}),{didMount:n,propsReady:t}},An($o),{singleton:!0}),A4=typeof document<"u"&&"scrollBehavior"in document.documentElement.style;function LN(e){const t=typeof e=="number"?{index:e}:{...e};return t.align||(t.align="start"),(!t.behavior||!A4)&&(t.behavior="auto"),t.offset===void 0&&(t.offset=0),t}const Sd=cn(([{gap:e,listRefresh:t,sizes:n,totalCount:s},{fixedFooterHeight:o,fixedHeaderHeight:r,footerHeight:a,headerHeight:l,scrollingInProgress:d,scrollTo:c,smoothScrollTargetReached:u,viewportHeight:h},{log:p}])=>{const f=on(),g=on(),x=Ke(0);let v=null,y=null,w=null;function b(){v!==null&&(v(),v=null),w!==null&&(w(),w=null),y&&(clearTimeout(y),y=null),Ht(d,!1)}return vt($e(f,Yt(n,h,s,x,l,a,p),Yt(e,r,o),ht(([[_,j,N,C,S,A,E,I],D,T,z])=>{const $=LN(_),{align:R,behavior:B,offset:H}=$,oe=C-1,te=MN($,j,oe);let O=Ul(te,j.offsetTree,D)+A;R==="end"?(O+=T+xi(j.sizeTree,te)[1]-N+z,te===oe&&(O+=E)):R==="center"?O+=(T+xi(j.sizeTree,te)[1]-N+z)/2:O-=S,H!==void 0&&H!==0&&(O+=H);const V=J=>{b(),J?(I("retrying to scroll to",{location:_},Jn.DEBUG),Ht(f,_)):(Ht(g,!0),I("list did not change, scroll successful",{},Jn.DEBUG))};if(b(),B==="smooth"){let J=!1;w=fn(t,pe=>{J=J||pe}),v=pi(u,()=>{V(J)})}else v=pi($e(t,M4(150)),V);return y=setTimeout(()=>{b()},1200),Ht(d,!0),I("scrolling from index to",{behavior:B,index:te,top:O},Jn.DEBUG),{behavior:B,top:O}})),c),{scrollTargetReached:g,scrollToIndex:f,topListHeight:x}},An($i,Ts,$o),{singleton:!0});function M4(e){return t=>{const n=setTimeout(()=>{t(!1)},e);return s=>{s&&(t(!0),clearTimeout(n))}}}function Nx(e,t){e===0?t():requestAnimationFrame(()=>{Nx(e-1,t)})}function Tx(e,t){if(e===void 0)return 0;const n=t-1,s=typeof e=="number"?e:e.index==="LAST"?n:e.index;return Math.max(0,Math.min(s,n))}function am(e){return e===void 0?!0:typeof e=="number"?e===0:e.index===0&&(e.align===void 0||e.align==="start")&&(e.offset===void 0||e.offset===0)}const Cd=cn(([{defaultItemSize:e,listRefresh:t,sizes:n},{scrollTop:s},{scrollTargetReached:o,scrollToIndex:r},{didMount:a}])=>{const l=Ke(!0),d=Ke(0),c=Ke(!0);return vt($e(a,Yt(d),Pt(([u,h])=>!am(h)),_i(!1)),l),vt($e(a,Yt(d),Pt(([u,h])=>!am(h)),_i(!1)),c),fn($e(Bn(t,a),Yt(l,n,e,c),Pt(([[,u],h,{sizeTree:p},f,g])=>u&&(!vn(p)||Sx(f))&&!h&&!g),Yt(d)),([,u])=>{if(u===void 0){Ht(l,!0),Ht(c,!0);return}pi(o,()=>{Ht(c,!0)}),Nx(4,()=>{pi(s,()=>{Ht(l,!0)}),Ht(r,u)})}),{initialItemFinalLocationReached:c,initialTopMostItemIndex:d,scrolledToInitialItem:l}},An($i,Ts,Sd,Wo),{singleton:!0});function ON(e,t){return Math.abs(e-t)<1.01}const Kl="up",fl="down",R4="none",L4={atBottom:!1,notAtBottomBecause:"NOT_SHOWING_LAST_ITEM",state:{offsetBottom:0,scrollHeight:0,scrollTop:0,viewportHeight:0}},O4=0,kd=cn(([{footerHeight:e,headerHeight:t,scrollBy:n,scrollContainerState:s,scrollTop:o,viewportHeight:r}])=>{const a=Ke(!1),l=Ke(!0),d=on(),c=on(),u=Ke(4),h=Ke(O4),p=ps($e(nm($e(Et(o),br(1),_i(!0)),$e(Et(o),br(1),_i(!1),dw(100))),Pn()),!1),f=ps($e(nm($e(n,_i(!0)),$e(n,_i(!1),dw(200))),Pn()),!1);vt($e(Bn(Et(o),Et(h)),ht(([w,b])=>w<=b),Pn()),l),vt($e(l,ro(50)),c);const g=Os($e(Bn(s,Et(r),Et(t),Et(e),Et(u)),Pi((w,[{scrollHeight:b,scrollTop:_},j,N,C,S])=>{const A=_+j-b>-S,E={scrollHeight:b,scrollTop:_,viewportHeight:j};if(A){let D,T;return _>w.state.scrollTop?(D="SCROLLED_DOWN",T=w.state.scrollTop-_):(D="SIZE_DECREASED",T=w.state.scrollTop-_||w.scrollTopDelta),{atBottom:!0,atBottomBecause:D,scrollTopDelta:T,state:E}}let I;return E.scrollHeight>w.state.scrollHeight?I="SIZE_INCREASED":j<w.state.viewportHeight?I="VIEWPORT_HEIGHT_DECREASING":_<w.state.scrollTop?I="SCROLLING_UPWARDS":I="NOT_FULLY_SCROLLED_TO_LAST_ITEM_BOTTOM",{atBottom:!1,notAtBottomBecause:I,state:E}},L4),Pn((w,b)=>w!==void 0&&w.atBottom===b.atBottom))),x=ps($e(s,Pi((w,{scrollHeight:b,scrollTop:_,viewportHeight:j})=>{if(!ON(w.scrollHeight,b)){const N=b-(_+j)<1;return w.scrollTop!==_&&N?{changed:!0,jump:w.scrollTop-_,scrollHeight:b,scrollTop:_}:{changed:!0,jump:0,scrollHeight:b,scrollTop:_}}return{changed:!1,jump:0,scrollHeight:b,scrollTop:_}},{changed:!1,jump:0,scrollHeight:0,scrollTop:0}),Pt(w=>w.changed),ht(w=>w.jump)),0);vt($e(g,ht(w=>w.atBottom)),a),vt($e(a,ro(50)),d);const v=Ke(fl);vt($e(s,ht(({scrollTop:w})=>w),Pn(),Pi((w,b)=>Rn(f)?{direction:w.direction,prevScrollTop:b}:{direction:b<w.prevScrollTop?Kl:fl,prevScrollTop:b},{direction:fl,prevScrollTop:0}),ht(w=>w.direction)),v),vt($e(s,ro(50),_i(R4)),v);const y=Ke(0);return vt($e(p,Pt(w=>!w),_i(0)),y),vt($e(o,ro(100),Yt(p),Pt(([w,b])=>b),Pi(([w,b],[_])=>[b,_],[0,0]),ht(([w,b])=>b-w)),y),{atBottomState:g,atBottomStateChange:d,atBottomThreshold:u,atTopStateChange:c,atTopThreshold:h,isAtBottom:a,isAtTop:l,isScrolling:p,lastJumpDueToItemResize:x,scrollDirection:v,scrollVelocity:y}},An(Ts)),ql="top",Yl="bottom",fw="none";function mw(e,t,n){return typeof e=="number"?n===Kl&&t===ql||n===fl&&t===Yl?e:0:n===Kl?t===ql?e.main:e.reverse:t===Yl?e.main:e.reverse}function gw(e,t){return typeof e=="number"?e:e[t]??0}const Dx=cn(([{deviation:e,fixedHeaderHeight:t,headerHeight:n,scrollTop:s,viewportHeight:o}])=>{const r=on(),a=Ke(0),l=Ke(0),d=Ke(0),c=ps($e(Bn(Et(s),Et(o),Et(n),Et(r,Wl),Et(d),Et(a),Et(t),Et(e),Et(l)),ht(([u,h,p,[f,g],x,v,y,w,b])=>{const _=u-w,j=v+y,N=Math.max(p-_,0);let C=fw;const S=gw(b,ql),A=gw(b,Yl);return f-=w,f+=p+y,g+=p+y,g-=w,f>u+j-S&&(C=Kl),g<u-N+h+A&&(C=fl),C!==fw?[Math.max(_-p-mw(x,ql,C)-S,0),_-N-y+h+mw(x,Yl,C)+A]:null}),Pt(u=>u!==null),Pn(Wl)),[0,0]);return{increaseViewportBy:l,listBoundary:r,overscan:d,topListHeight:a,visibleRange:c}},An(Ts),{singleton:!0});function z4(e,t,n){if(vh(t)){const s=AN(e,t);return[{index:xi(t.groupOffsetTree,s)[0],offset:0,size:0},{data:n?.[0],index:s,offset:0,size:0}]}return[{data:n?.[0],index:e,offset:0,size:0}]}const wp={bottom:0,firstItemIndex:0,items:[],offsetBottom:0,offsetTop:0,top:0,topItems:[],topListHeight:0,totalCount:0};function Oc(e,t,n,s,o,r){const{lastIndex:a,lastOffset:l,lastSize:d}=o;let c=0,u=0;if(e.length>0){c=e[0].offset;const x=e[e.length-1];u=x.offset+x.size}const h=n-a,p=l+h*d+(h-1)*s,f=c,g=p-u;return{bottom:u,firstItemIndex:r,items:xw(e,o,r),offsetBottom:g,offsetTop:c,top:f,topItems:xw(t,o,r),topListHeight:t.reduce((x,v)=>v.size+x,0),totalCount:n}}function zN(e,t,n,s,o,r){let a=0;if(n.groupIndices.length>0)for(const u of n.groupIndices){if(u-a>=e)break;a++}const l=e+a,d=Tx(t,l),c=Array.from({length:l}).map((u,h)=>({data:r[h+d],index:h+d,offset:0,size:0}));return Oc(c,[],l,o,n,s)}function xw(e,t,n){if(e.length===0)return[];if(!vh(t))return e.map(c=>({...c,index:c.index+n,originalIndex:c.index}));const s=e[0].index,o=e[e.length-1].index,r=[],a=Zr(t.groupOffsetTree,s,o);let l,d=0;for(const c of e){(!l||l.end<c.index)&&(l=a.shift(),d=t.groupIndices.indexOf(l.start));let u;c.index===l.start?u={index:d,type:"group"}:u={groupIndex:d,index:c.index-(d+1)+n},r.push({...u,data:c.data,offset:c.offset,originalIndex:c.index,size:c.size})}return r}function vw(e,t){return e===void 0?0:typeof e=="number"?e:e[t]??0}const Cr=cn(([{data:e,firstItemIndex:t,gap:n,sizes:s,totalCount:o},r,{listBoundary:a,topListHeight:l,visibleRange:d},{initialTopMostItemIndex:c,scrolledToInitialItem:u},{topListHeight:h},p,{didMount:f},{recalcInProgress:g}])=>{const x=Ke([]),v=Ke(0),y=on(),w=Ke(0);vt(r.topItemsIndexes,x);const b=ps($e(Bn(f,g,Et(d,Wl),Et(o),Et(s),Et(c),u,Et(x),Et(t),Et(n),Et(w),e),Pt(([C,S,,A,,,,,,,,E])=>{const I=E!==void 0&&E.length!==A;return C&&!S&&!I}),ht(([,,[C,S],A,E,I,D,T,z,$,R,B])=>{const H=E,{offsetTree:oe,sizeTree:te}=H,O=Rn(v);if(A===0)return{...wp,totalCount:A};if(C===0&&S===0)return O===0?{...wp,totalCount:A}:zN(O,I,E,z,$,B||[]);if(vn(te))return O>0?null:Oc(z4(Tx(I,A),H,B),[],A,$,H,z);const V=[];if(T.length>0){const W=T[0],G=T[T.length-1];let de=0;for(const X of Zr(te,W,G)){const ie=X.value,Z=Math.max(X.start,W),le=Math.min(X.end,G);for(let be=Z;be<=le;be++)V.push({data:B?.[be],index:be,offset:de,size:ie}),de+=ie}}if(!D)return Oc([],V,A,$,H,z);const J=T.length>0?T[T.length-1]+1:0,pe=_4(oe,C,S,J);if(pe.length===0)return null;const fe=A-1,_e=xh([],W=>{for(const G of pe){const de=G.value;let X=de.offset,ie=G.start;const Z=de.size;if(de.offset<C){ie+=Math.floor((C-de.offset+$)/(Z+$));const be=ie-G.start;X+=be*Z+be*$}ie<J&&(X+=(J-ie)*Z,ie=J);const le=Math.min(G.end,fe);for(let be=ie;be<=le&&!(X>=S);be++)W.push({data:B?.[be],index:be,offset:X,size:Z}),X+=Z+$}}),Ee=vw(R,ql),me=vw(R,Yl);if(_e.length>0&&(Ee>0||me>0)){const W=_e[0],G=_e[_e.length-1];if(Ee>0&&W.index>J){const de=Math.min(Ee,W.index-J),X=[];let ie=W.offset;for(let Z=W.index-1;Z>=W.index-de;Z--){const le=Zr(te,Z,Z)[0]?.value??W.size;ie-=le+$,X.unshift({data:B?.[Z],index:Z,offset:ie,size:le})}_e.unshift(...X)}if(me>0&&G.index<fe){const de=Math.min(me,fe-G.index);let X=G.offset+G.size+$;for(let ie=G.index+1;ie<=G.index+de;ie++){const Z=Zr(te,ie,ie)[0]?.value??G.size;_e.push({data:B?.[ie],index:ie,offset:X,size:Z}),X+=Z+$}}}return Oc(_e,V,A,$,H,z)}),Pt(C=>C!==null),Pn()),wp);vt($e(e,Pt(Sx),ht(C=>C?.length)),o),vt($e(b,ht(C=>C.topListHeight)),h),vt(h,l),vt($e(b,ht(C=>[C.top,C.bottom])),a),vt($e(b,ht(C=>C.items)),y);const _=Os($e(b,Pt(({items:C})=>C.length>0),Yt(o,e),Pt(([{items:C},S])=>C[C.length-1].originalIndex===S-1),ht(([,C,S])=>[C-1,S]),Pn(Wl),ht(([C])=>C))),j=Os($e(b,ro(200),Pt(({items:C,topItems:S})=>C.length>0&&C[0].originalIndex===S.length),ht(({items:C})=>C[0].index),Pn())),N=Os($e(b,Pt(({items:C})=>C.length>0),ht(({items:C})=>{let S=0,A=C.length-1;for(;C[S].type==="group"&&S<A;)S++;for(;C[A].type==="group"&&A>S;)A--;return{endIndex:C[A].index,startIndex:C[S].index}}),Pn(EN)));return{endReached:_,initialItemCount:v,itemsRendered:y,listState:b,minOverscanItemCount:w,rangeChanged:N,startReached:j,topItemsIndexes:x,...p}},An($i,RN,Dx,Cd,Sd,kd,Wo,jx),{singleton:!0}),GN=cn(([{fixedFooterHeight:e,fixedHeaderHeight:t,footerHeight:n,headerHeight:s},{listState:o}])=>{const r=on(),a=ps($e(Bn(n,e,s,t,o),ht(([l,d,c,u,h])=>l+d+c+u+h.offsetBottom+h.bottom)),0);return vt(Et(a),r),{totalListHeight:a,totalListHeightChanged:r}},An(Ts,Cr),{singleton:!0}),G4=cn(([{viewportHeight:e},{totalListHeight:t}])=>{const n=Ke(!1),s=ps($e(Bn(n,e,t),Pt(([o])=>o),ht(([,o,r])=>Math.max(0,o-r)),ro(0),Pn()),0);return{alignToBottom:n,paddingTopAddition:s}},An(Ts,GN),{singleton:!0}),FN=cn(()=>({context:Ke(null)})),F4=({itemBottom:e,itemTop:t,locationParams:{align:n,behavior:s,...o},viewportBottom:r,viewportTop:a})=>t<a?{...o,align:n??"start",...s===void 0?{}:{behavior:s}}:e>r?{...o,align:n??"end",...s===void 0?{}:{behavior:s}}:null,HN=cn(([{gap:e,sizes:t,totalCount:n},{fixedFooterHeight:s,fixedHeaderHeight:o,headerHeight:r,scrollingInProgress:a,scrollTop:l,viewportHeight:d},{scrollToIndex:c}])=>{const u=on();return vt($e(u,Yt(t,d,n,r,o,s,l),Yt(e),ht(([[h,p,f,g,x,v,y,w],b])=>{const{calculateViewLocation:_=F4,done:j,...N}=h,C=MN(h,p,g-1),S=Ul(C,p.offsetTree,b)+x+v,A=S+xi(p.sizeTree,C)[1],E=w+v,I=w+f-y,D=_({itemBottom:A,itemTop:S,locationParams:N,viewportBottom:I,viewportTop:E});return D===null?j?.():j&&pi($e(a,Pt(T=>!T),br(Rn(a)?1:2)),j),D}),Pt(h=>h!==null)),c),{scrollIntoView:u}},An($i,Ts,Sd,Cr,$o),{singleton:!0});function bw(e){return e===!1?!1:e==="smooth"?"smooth":"auto"}const H4=(e,t)=>typeof e=="function"?bw(e(t)):t&&bw(e),B4=cn(([{listRefresh:e,totalCount:t,fixedItemSize:n,data:s},{atBottomState:o,isAtBottom:r},{scrollToIndex:a},{scrolledToInitialItem:l},{didMount:d,propsReady:c},{log:u},{scrollingInProgress:h},{context:p},{scrollIntoView:f}])=>{const g=Ke(!1),x=on();let v=null;function y(j){Ht(a,{align:"end",behavior:j,index:"LAST"})}fn($e(Bn($e(Et(t),br(1)),d),Yt(Et(g),r,l,h),ht(([[j,N],C,S,A,E])=>{let I=N&&A,D="auto";return I&&(D=H4(C,S||E),I=I&&D!==!1),{followOutputBehavior:D,shouldFollow:I,totalCount:j}}),Pt(({shouldFollow:j})=>j)),({followOutputBehavior:j,totalCount:N})=>{v!==null&&(v(),v=null),Rn(n)===void 0?v=pi(e,()=>{Rn(u)("following output to ",{totalCount:N},Jn.DEBUG),y(j),v=null}):requestAnimationFrame(()=>{Rn(u)("following output to ",{totalCount:N},Jn.DEBUG),y(j)})});function w(j){const N=pi(o,C=>{j&&!C.atBottom&&C.notAtBottomBecause==="SIZE_INCREASED"&&v===null&&(Rn(u)("scrolling to bottom due to increased size",{},Jn.DEBUG),y("auto"))});setTimeout(N,100)}fn($e(Bn(Et(g),t,c),Pt(([j,,N])=>j!==!1&&N),Pi(({value:j},[,N])=>({refreshed:j===N,value:N}),{refreshed:!1,value:0}),Pt(({refreshed:j})=>j),Yt(g,t)),([,j])=>{Rn(l)&&w(j!==!1)}),fn(x,()=>{w(Rn(g)!==!1)}),fn(Bn(Et(g),o),([j,N])=>{j!==!1&&!N.atBottom&&N.notAtBottomBecause==="VIEWPORT_HEIGHT_DECREASING"&&y("auto")});const b=Ke(null),_=on();return vt(nm($e(Et(s),ht(j=>j?.length??0)),$e(Et(t))),_),fn($e(Bn($e(_,br(1)),d),Yt(Et(b),l,h,p),ht(([[j,N],C,S,A,E])=>N&&S&&C?.({context:E,totalCount:j,scrollingInProgress:A})),Pt(j=>!!j),ro(0)),j=>{v!==null&&(v(),v=null),Rn(n)===void 0?v=pi(e,()=>{Rn(u)("scrolling into view",{}),Ht(f,j),v=null}):requestAnimationFrame(()=>{Rn(u)("scrolling into view",{}),Ht(f,j)})}),{autoscrollToBottom:x,followOutput:g,scrollIntoViewOnChange:b}},An($i,kd,Sd,Cd,Wo,$o,Ts,FN,HN)),V4=cn(([{data:e,firstItemIndex:t,gap:n,sizes:s},{initialTopMostItemIndex:o},{initialItemCount:r,listState:a},{didMount:l}])=>(vt($e(l,Yt(r),Pt(([,d])=>d!==0),Yt(o,s,t,n,e),ht(([[,d],c,u,h,p,f=[]])=>zN(d,c,u,h,p,f))),a),{}),An($i,Cd,Cr,Wo),{singleton:!0}),$4=cn(([{didMount:e},{scrollTo:t},{listState:n}])=>{const s=Ke(0);return fn($e(e,Yt(s),Pt(([,o])=>o!==0),ht(([,o])=>({top:o}))),o=>{pi($e(n,br(1),Pt(r=>r.items.length>1)),()=>{requestAnimationFrame(()=>{Ht(t,o)})})}),{initialScrollTop:s}},An(Wo,Ts,Cr),{singleton:!0}),BN=cn(([{scrollVelocity:e}])=>{const t=Ke(!1),n=on(),s=Ke(!1);return vt($e(e,Yt(s,t,n),Pt(([o,r])=>r!==!1&&r!==void 0),ht(([o,r,a,l])=>{const{enter:d,exit:c}=r;if(a){if(c(o,l))return!1}else if(d(o,l))return!0;return a}),Pn()),t),fn($e(Bn(t,e,n),Yt(s)),([[o,r,a],l])=>{o&&l!==!1&&l!==void 0&&l.change&&l.change(r,a)}),{isSeeking:t,scrollSeekConfiguration:s,scrollSeekRangeChanged:n,scrollVelocity:e}},An(kd),{singleton:!0}),Ix=cn(([{scrollContainerState:e,scrollTo:t}])=>{const n=on(),s=on(),o=on(),r=Ke(!1),a=Ke(void 0);return vt($e(Bn(n,s),ht(([{scrollTop:l,viewportHeight:d},{offsetTop:c,listHeight:u}])=>({scrollHeight:u,scrollTop:Math.max(0,l-c),viewportHeight:d}))),e),vt($e(t,Yt(s),ht(([l,{offsetTop:d}])=>({...l,top:l.top+d}))),o),{customScrollParent:a,useWindowScroll:r,windowScrollContainerState:n,windowScrollTo:o,windowViewportRect:s}},An(Ts)),W4=cn(([{sizeRanges:e,sizes:t},{headerHeight:n,scrollTop:s},{initialTopMostItemIndex:o},{didMount:r},{useWindowScroll:a,windowScrollContainerState:l,windowViewportRect:d}])=>{const c=on(),u=Ke(void 0),h=Ke(null),p=Ke(null);return vt(l,h),vt(d,p),fn($e(c,Yt(t,s,a,h,p,n)),([f,g,x,v,y,w,b])=>{const _=T4(g.sizeTree);v&&y!==null&&w!==null&&(x=y.scrollTop-w.offsetTop),x-=b,f({ranges:_,scrollTop:x})}),vt($e(u,Pt(Sx),ht(U4)),o),vt($e(r,Yt(u),Pt(([,f])=>f!==void 0),Pn(),ht(([,f])=>f.ranges)),e),{getState:c,restoreStateFrom:u}},An($i,Ts,Cd,Wo,Ix));function U4(e){return{align:"start",index:0,offset:e.scrollTop}}const K4=cn(([{topItemsIndexes:e}])=>{const t=Ke(0);return vt($e(t,Pt(n=>n>=0),ht(n=>Array.from({length:n}).map((s,o)=>o))),e),{topItemCount:t}},An(Cr));function VN(e){let t=!1,n;return(()=>(t||(t=!0,n=e()),n))}const q4=VN(()=>/iP(ad|od|hone)/i.test(navigator.userAgent)&&/WebKit/i.test(navigator.userAgent)),Y4=cn(([{deviation:e,scrollBy:t,scrollingInProgress:n,scrollTop:s},{isAtBottom:o,isScrolling:r,lastJumpDueToItemResize:a,scrollDirection:l},{listState:d},{beforeUnshiftWith:c,gap:u,shiftWithOffset:h,sizes:p},{log:f},{recalcInProgress:g}])=>{const x=Os($e(d,Yt(a),Pi(([,y,w,b],[{bottom:_,items:j,offsetBottom:N,totalCount:C},S])=>{const A=_+N;let E=0;return w===C&&y.length>0&&j.length>0&&(j[0].originalIndex===0&&y[0].originalIndex===0||(E=A-b,E!==0&&(E+=S))),[E,j,C,A]},[0,[],0,0]),Pt(([y])=>y!==0),Yt(s,l,n,o,f,g),Pt(([,y,w,b,,,_])=>!_&&!b&&y!==0&&w===Kl),ht(([[y],,,,,w])=>(w("Upward scrolling compensation",{amount:y},Jn.DEBUG),y))));function v(y){y>0?(Ht(t,{behavior:"auto",top:-y}),Ht(e,0)):(Ht(e,0),Ht(t,{behavior:"auto",top:-y}))}return fn($e(x,Yt(e,r)),([y,w,b])=>{b&&q4()?Ht(e,w-y):v(-y)}),fn($e(Bn(ps(r,!1),e,g),Pt(([y,w,b])=>!y&&!b&&w!==0),ht(([y,w])=>w),ro(1)),v),vt($e(h,ht(y=>({top:-y}))),t),fn($e(c,Yt(p,u),ht(([y,{groupIndices:w,lastSize:b,sizeTree:_},j])=>{function N(I){return I*(b+j)}if(w.length===0)return N(y);let C=0;const S=$l(_,0);let A=0,E=0;for(;A<y;){A++,C+=S;let I=w.length===E+1?1/0:w[E+1]-w[E]-1;A+I>y&&(C-=S,I=y-A+1),A+=I,C+=N(I),E++}return C})),y=>{Ht(e,y),requestAnimationFrame(()=>{Ht(t,{top:y}),requestAnimationFrame(()=>{Ht(e,0),Ht(g,!1)})})}),{deviation:e}},An(Ts,kd,Cr,$i,$o,jx)),X4=cn(([e,t,n,s,o,r,a,l,d,c,u])=>({...e,...t,...n,...s,...o,...r,...a,...l,...d,...c,...u}),An(Dx,V4,Wo,BN,GN,$4,G4,Ix,HN,$o,FN)),$N=cn(([{data:e,defaultItemSize:t,firstItemIndex:n,fixedItemSize:s,fixedGroupSize:o,gap:r,groupIndices:a,heightEstimates:l,itemSize:d,sizeRanges:c,sizes:u,statefulTotalCount:h,totalCount:p,trackItemSizes:f},{initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v},y,w,b,_,{scrollToIndex:j},N,{topItemCount:C},{groupCounts:S},A])=>{const{listState:E,minOverscanItemCount:I,topItemsIndexes:D,rangeChanged:T,...z}=_;return vt(T,A.scrollSeekRangeChanged),vt($e(Bn(A.windowViewportRect,y.headerHeight,y.fixedHeaderHeight),ht(([$,R,B])=>Math.max(R+B+1,$.visibleHeight))),y.viewportHeight),{data:e,defaultItemHeight:t,firstItemIndex:n,fixedItemHeight:s,fixedGroupHeight:o,gap:r,groupCounts:S,heightEstimates:l,initialItemFinalLocationReached:g,initialTopMostItemIndex:x,scrolledToInitialItem:v,sizeRanges:c,topItemCount:C,topItemsIndexes:D,totalCount:p,...b,groupIndices:a,itemSize:d,listState:E,minOverscanItemCount:I,scrollToIndex:j,statefulTotalCount:h,trackItemSizes:f,rangeChanged:T,...z,...A,...y,sizes:u,...w}},An($i,Cd,Ts,W4,B4,Cr,Sd,Y4,K4,RN,X4));function Z4(e,t){const n={},s={};let o=0;const r=e.length;for(;o<r;)s[e[o]]=1,o+=1;for(const a in t)Object.hasOwn(s,a)||(n[a]=t[a]);return n}const Od=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function WN(e,t,n){const s=Object.keys(t.required||{}),o=Object.keys(t.optional||{}),r=Object.keys(t.methods||{}),a=Object.keys(t.events||{}),l=Ne.createContext({});function d(v,y){v.propsReady!==void 0&&Ht(v.propsReady,!1);for(const w of s){const b=v[t.required[w]];Ht(b,y[w])}for(const w of o)if(w in y){const b=v[t.optional[w]];Ht(b,y[w])}v.propsReady!==void 0&&Ht(v.propsReady,!0)}function c(v){return r.reduce((y,w)=>(y[w]=b=>{const _=v[t.methods[w]];Ht(_,b)},y),{})}function u(v){return a.reduce((y,w)=>(y[w]=u4(v[t.events[w]]),y),{})}const h=Ne.forwardRef(function(v,y){const{children:w,...b}=v,[_]=Ne.useState(()=>xh(f4(e),C=>{d(C,b)})),[j]=Ne.useState(lw(u,_));Od(()=>{for(const C of a)C in b&&fn(j[C],b[C]);return()=>{Object.values(j).map(Cx)}},[b,j,_]),Od(()=>{d(_,b)}),Ne.useImperativeHandle(y,aw(c(_)));const N=n;return i.jsx(l.Provider,{value:_,children:n===void 0?w:i.jsx(N,{...Z4([...s,...o,...a],b),children:w})})}),p=v=>{const y=Ne.useContext(l);return Ne.useCallback(w=>{Ht(y[v],w)},[y,v])},f=v=>{const y=Ne.useContext(l)[v],w=Ne.useCallback(b=>fn(y,b),[y]);return Ne.useSyncExternalStore(w,()=>Rn(y),()=>Rn(y))},g=v=>{const y=Ne.useContext(l)[v],[w,b]=Ne.useState(lw(Rn,y));return Od(()=>fn(y,_=>{_!==w&&b(aw(_))}),[y,w]),w},x=parseInt(Ne.version,10)>=18?f:g;return{Component:h,useEmitter:(v,y)=>{const w=Ne.useContext(l)[v];Od(()=>fn(w,y),[y,w])},useEmitterValue:x,usePublisher:p}}const UN=Ne.createContext(void 0),KN=Ne.createContext(void 0),yp="-webkit-sticky",ww="sticky",Ex=VN(()=>{if(typeof document>"u")return ww;const e=document.createElement("div");return e.style.position=yp,e.style.position===yp?yp:ww}),qN=typeof document>"u"?Ne.useEffect:Ne.useLayoutEffect;function Sp(e){return"self"in e}function J4(e){return"body"in e}function YN(e,t,n,s=Da,o,r){const a=Ne.useRef(null),l=Ne.useRef(null),d=Ne.useRef(null),c=Ne.useCallback(p=>{let f,g,x;const v=p.target;if(J4(v)||Sp(v)){const w=Sp(v)?v:v.defaultView;x=r===!0?dr(w,w.scrollX):w.scrollY,f=r===!0?w.document.documentElement.scrollWidth:w.document.documentElement.scrollHeight,g=r===!0?w.innerWidth:w.innerHeight}else x=r===!0?dr(v,v.scrollLeft):v.scrollTop,f=r===!0?v.scrollWidth:v.scrollHeight,g=r===!0?v.offsetWidth:v.offsetHeight;const y=()=>{e({scrollHeight:f,scrollTop:Math.max(x,0),viewportHeight:g})};p.suppressFlushSync===!0?y():ck.flushSync(y),l.current!==null&&(x===l.current||x<=0||x===f-g)&&(l.current=null,t(!0),d.current&&(clearTimeout(d.current),d.current=null))},[e,t,r]);Ne.useEffect(()=>{const p=o??a.current;return s(o??a.current),c({suppressFlushSync:!0,target:p}),p.addEventListener("scroll",c,{passive:!0}),()=>{s(null),p.removeEventListener("scroll",c)}},[a,c,n,s,o]);function u(p){const f=a.current;if(!f||(r===!0?"offsetWidth"in f&&f.offsetWidth===0:"offsetHeight"in f&&f.offsetHeight===0))return;const g=p.behavior==="smooth";let x,v,y;Sp(f)?(v=Math.max(Lo(f.document.documentElement,r===!0?"width":"height"),r===!0?f.document.documentElement.scrollWidth:f.document.documentElement.scrollHeight),x=r===!0?f.innerWidth:f.innerHeight,y=r===!0?dr(f,f.scrollX):f.scrollY):(v=f[r===!0?"scrollWidth":"scrollHeight"],x=Lo(f,r===!0?"width":"height"),y=r===!0?dr(f,f.scrollLeft):f.scrollTop);const w=v-x;if(p.top===void 0){f.scrollTo(p);return}const b=Math.ceil(Math.max(Math.min(w,p.top),0));if(p.top=b,ON(x,v)||b===y){e({scrollHeight:v,scrollTop:y,viewportHeight:x}),g&&t(!0);return}g?(l.current=b,d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{d.current=null,l.current=null,t(!0)},1e3)):l.current=null,r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},left:cw(f,b)}),f.scrollTo(p)}function h(p){r===!0&&(p={...p.behavior===void 0?{}:{behavior:p.behavior},...p.top===void 0?{}:{left:cw(a.current,p.top)}}),a.current.scrollBy(p)}return{scrollByCallback:h,scrollerRef:a,scrollToCallback:u}}function Px(e){return e}const Q4=cn(()=>{const e=Ke(l=>`Item ${l}`),t=Ke(l=>`Group ${l}`),n=Ke({}),s=Ke(Px),o=Ke("div"),r=Ke(Da),a=(l,d=null)=>ps($e(n,ht(c=>c[l]),Pn()),d);return{components:n,computeItemKey:s,EmptyPlaceholder:a("EmptyPlaceholder"),FooterComponent:a("Footer"),GroupComponent:a("Group","div"),groupContent:t,HeaderComponent:a("Header"),HeaderFooterTag:o,ItemComponent:a("Item","div"),itemContent:e,ListComponent:a("List","div"),ScrollerComponent:a("Scroller","div"),scrollerRef:r,ScrollSeekPlaceholder:a("ScrollSeekPlaceholder"),TopItemListComponent:a("TopItemList")}}),eW=cn(([e,t])=>({...e,...t}),An($N,Q4)),tW=({height:e})=>i.jsx("div",{style:{height:e}}),nW={overflowAnchor:"none",position:Ex(),zIndex:1},XN={overflowAnchor:"none"},sW={...XN,display:"inline-block",height:"100%"},yw=Ne.memo(function({showTopList:e=!1}){const t=Ot("listState"),n=Ys("sizeRanges"),s=Ot("useWindowScroll"),o=Ot("customScrollParent"),r=Ys("windowScrollContainerState"),a=Ys("scrollContainerState"),l=o||s?r:a,d=Ot("itemContent"),c=Ot("context"),u=Ot("groupContent"),h=Ot("trackItemSizes"),p=Ot("itemSize"),f=Ot("log"),g=Ys("gap"),x=Ot("horizontalDirection"),{callbackRef:v}=v4(n,p,h,e?Da:l,f,g,o,x,Ot("skipAnimationFrameInResizeObserver")),[y,w]=Ne.useState(0);Mx("deviation",z=>{y!==z&&w(z)});const b=Ot("EmptyPlaceholder"),_=Ot("ScrollSeekPlaceholder")??tW,j=Ot("ListComponent"),N=Ot("ItemComponent"),C=Ot("GroupComponent"),S=Ot("computeItemKey"),A=Ot("isSeeking"),E=Ot("groupIndices").length>0,I=Ot("alignToBottom"),D=Ot("initialItemFinalLocationReached"),T=e?{}:{boxSizing:"border-box",...x?{display:"inline-block",height:"100%",marginInlineStart:y===0?I?"auto":0:y,paddingInlineEnd:t.offsetBottom,paddingInlineStart:t.offsetTop,whiteSpace:"nowrap"}:{marginTop:y===0?I?"auto":0:y,paddingBottom:t.offsetBottom,paddingTop:t.offsetTop},...D?{}:{visibility:"hidden"}};return!e&&t.totalCount===0&&b!==null&&b!==void 0?i.jsx(b,{...hs(b,c)}):i.jsx(j,{...hs(j,c),"data-testid":e?"virtuoso-top-item-list":"virtuoso-item-list",ref:v,style:T,children:(e?t.topItems:t.items).map(z=>{const $=z.originalIndex,R=S($+t.firstItemIndex,z.data,c);return A?m.createElement(_,{...hs(_,c),height:z.size,index:z.index,key:R,type:z.type||"item",...z.type==="group"?{}:{groupIndex:z.groupIndex}}):z.type==="group"?m.createElement(C,{...hs(C,c),"data-index":$,"data-item-index":z.index,"data-known-size":z.size,key:R,style:nW},u(z.index,c)):m.createElement(N,{...hs(N,c),...aW(N,z.data),"data-index":$,"data-item-group-index":z.groupIndex,"data-item-index":z.index,"data-known-size":z.size,key:R,style:x?sW:XN},E?d(z.index,z.groupIndex,z.data,c):d(z.index,z.data,c))})})}),iW={height:"100%",outline:"none",overflowY:"auto",position:"relative",WebkitOverflowScrolling:"touch"},oW={outline:"none",overflowX:"auto",position:"relative"},Ax=e=>({height:"100%",position:"absolute",top:0,width:"100%",...e?{display:"flex",flexDirection:"column"}:void 0}),ZN=(e,t,n=0)=>({...Ax(e),position:t?"relative":"absolute",top:t?-n:0}),rW={position:Ex(),top:0,width:"100%",zIndex:1};function hs(e,t){if(typeof e!="string")return{context:t}}function aW(e,t){return{item:typeof e=="string"?void 0:t}}const lW=Ne.memo(function(){const e=Ot("HeaderComponent"),t=Ys("headerHeight"),n=Ot("HeaderFooterTag"),s=Sr(Ne.useMemo(()=>r=>{t(Lo(r,"height"))},[t]),!0,Ot("skipAnimationFrameInResizeObserver")),o=Ot("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...hs(e,o)})}):null}),dW=Ne.memo(function(){const e=Ot("FooterComponent"),t=Ys("footerHeight"),n=Ot("HeaderFooterTag"),s=Sr(Ne.useMemo(()=>r=>{t(Lo(r,"height"))},[t]),!0,Ot("skipAnimationFrameInResizeObserver")),o=Ot("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...hs(e,o)})}):null});function JN({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ne.memo(function({children:s,style:o,context:r,...a}){const l=n("scrollContainerState"),d=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),u=t("scrollerRef"),h=t("horizontalDirection")||!1,{scrollByCallback:p,scrollerRef:f,scrollToCallback:g}=YN(l,c,d,u,void 0,h);return e("scrollTo",g),e("scrollBy",p),i.jsx(d,{"data-testid":"virtuoso-scroller","data-virtuoso-scroller":!0,ref:f,style:{...h?oW:iW,...o},tabIndex:0,...a,...hs(d,r),children:s})})}function QN({useEmitter:e,useEmitterValue:t,usePublisher:n}){return Ne.memo(function({children:s,style:o,context:r,...a}){const l=n("windowScrollContainerState"),d=t("ScrollerComponent"),c=n("smoothScrollTargetReached"),u=t("totalListHeight"),h=t("deviation"),p=t("customScrollParent"),f=Ne.useRef(null),g=t("scrollerRef"),{scrollByCallback:x,scrollerRef:v,scrollToCallback:y}=YN(l,c,d,g,p);return qN(()=>(v.current=p??f.current?.ownerDocument.defaultView,()=>{v.current=null}),[v,p]),e("windowScrollTo",y),e("scrollBy",x),i.jsx(d,{ref:f,"data-virtuoso-scroller":!0,style:{position:"relative",...o,...u===0?void 0:{height:u+h}},...a,...hs(d,r),children:s})})}const cW=({children:e})=>{const t=Ne.useContext(UN),n=Ys("viewportHeight"),s=Ys("fixedItemHeight"),o=Ot("alignToBottom"),r=Ot("horizontalDirection"),a=Ne.useMemo(()=>SN(n,d=>Lo(d,r?"width":"height")),[n,r]),l=Sr(a,!0,Ot("skipAnimationFrameInResizeObserver"));return Ne.useEffect(()=>{t&&(n(t.viewportHeight),s(t.itemHeight))},[t,n,s]),i.jsx("div",{"data-viewport-type":"element",ref:l,style:Ax(o),children:e})},uW=({children:e})=>{const t=Ne.useContext(UN),n=Ys("windowViewportRect"),s=Ys("fixedItemHeight"),o=Ot("customScrollParent"),r=Ot("useWindowScroll"),a=Ot("topListHeight"),l=jN(n,o,Ot("skipAnimationFrameInResizeObserver")),d=Ot("alignToBottom");return Ne.useEffect(()=>{t&&(s(t.itemHeight),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:100}))},[t,n,s]),i.jsx("div",{"data-viewport-type":"window",ref:l,style:ZN(d,r,a),children:e})},hW=({children:e})=>{const t=Ot("TopItemListComponent")??"div",n=Ot("headerHeight"),s={...rW,marginTop:`${n}px`},o=Ot("context");return i.jsx(t,{style:s,...hs(t,o),children:e})},pW=Ne.memo(function(e){const t=Ot("useWindowScroll"),n=Ot("topItemsIndexes").length>0,s=Ot("customScrollParent"),o=Ot("context");return i.jsxs(s||t?gW:mW,{...e,context:o,children:[n&&i.jsx(hW,{children:i.jsx(yw,{showTopList:!0})}),i.jsxs(s||t?uW:cW,{children:[i.jsx(lW,{}),i.jsx(yw,{}),i.jsx(dW,{})]})]})}),{Component:fW,useEmitter:Mx,useEmitterValue:Ot,usePublisher:Ys}=WN(eW,{optional:{restoreStateFrom:"restoreStateFrom",context:"context",followOutput:"followOutput",scrollIntoViewOnChange:"scrollIntoViewOnChange",itemContent:"itemContent",groupContent:"groupContent",overscan:"overscan",increaseViewportBy:"increaseViewportBy",minOverscanItemCount:"minOverscanItemCount",totalCount:"totalCount",groupCounts:"groupCounts",topItemCount:"topItemCount",firstItemIndex:"firstItemIndex",initialTopMostItemIndex:"initialTopMostItemIndex",components:"components",atBottomThreshold:"atBottomThreshold",atTopThreshold:"atTopThreshold",computeItemKey:"computeItemKey",defaultItemHeight:"defaultItemHeight",fixedGroupHeight:"fixedGroupHeight",fixedItemHeight:"fixedItemHeight",heightEstimates:"heightEstimates",itemSize:"itemSize",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"HeaderFooterTag",data:"data",initialItemCount:"initialItemCount",initialScrollTop:"initialScrollTop",alignToBottom:"alignToBottom",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",horizontalDirection:"horizontalDirection",skipAnimationFrameInResizeObserver:"skipAnimationFrameInResizeObserver"},methods:{scrollToIndex:"scrollToIndex",scrollIntoView:"scrollIntoView",scrollTo:"scrollTo",scrollBy:"scrollBy",autoscrollToBottom:"autoscrollToBottom",getState:"getState"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",totalListHeightChanged:"totalListHeightChanged",itemsRendered:"itemsRendered",groupIndices:"groupIndices"}},pW),mW=JN({useEmitter:Mx,useEmitterValue:Ot,usePublisher:Ys}),gW=QN({useEmitter:Mx,useEmitterValue:Ot,usePublisher:Ys}),xW=fW,vW=cn(()=>{const e=Ke(c=>i.jsxs("td",{children:["Item $",c]})),t=Ke(null),n=Ke(c=>i.jsxs("td",{colSpan:1e3,children:["Group ",c]})),s=Ke(null),o=Ke(null),r=Ke({}),a=Ke(Px),l=Ke(Da),d=(c,u=null)=>ps($e(r,ht(h=>h[c]),Pn()),u);return{components:r,computeItemKey:a,context:t,EmptyPlaceholder:d("EmptyPlaceholder"),FillerRow:d("FillerRow"),fixedFooterContent:o,fixedHeaderContent:s,itemContent:e,groupContent:n,ScrollerComponent:d("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:d("ScrollSeekPlaceholder"),TableBodyComponent:d("TableBody","tbody"),TableComponent:d("Table","table"),TableFooterComponent:d("TableFoot","tfoot"),TableHeadComponent:d("TableHead","thead"),TableRowComponent:d("TableRow","tr"),GroupComponent:d("Group","tr")}});An($N,vW);Ex();const Sw={bottom:0,itemHeight:0,items:[],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},bW={bottom:0,itemHeight:0,items:[{index:0}],itemWidth:0,offsetBottom:0,offsetTop:0,top:0},{ceil:Cw,floor:Su,max:ml,min:Cp,round:kw}=Math;function jw(e,t,n){return Array.from({length:t-e+1}).map((s,o)=>({data:n===null?null:n[o+e],index:o+e}))}function wW(e){return{...bW,items:e}}function zd(e,t){return e!==void 0&&e.width===t.width&&e.height===t.height}function yW(e,t){return e!==void 0&&e.column===t.column&&e.row===t.row}const SW=cn(([{increaseViewportBy:e,listBoundary:t,overscan:n,visibleRange:s},{footerHeight:o,headerHeight:r,scrollBy:a,scrollContainerState:l,scrollTo:d,scrollTop:c,smoothScrollTargetReached:u,viewportHeight:h},p,f,{didMount:g,propsReady:x},{customScrollParent:v,useWindowScroll:y,windowScrollContainerState:w,windowScrollTo:b,windowViewportRect:_},j])=>{const N=Ke(0),C=Ke(0),S=Ke(Sw),A=Ke({height:0,width:0}),E=Ke({height:0,width:0}),I=on(),D=on(),T=Ke(0),z=Ke(null),$=Ke({column:0,row:0}),R=on(),B=on(),H=Ke(!1),oe=Ke(0),te=Ke(!0),O=Ke(!1),V=Ke(!1);fn($e(g,Yt(oe),Pt(([me,W])=>!am(W))),()=>{Ht(te,!1)}),fn($e(Bn(g,te,E,A,oe,O),Pt(([me,W,G,de,,X])=>me&&!W&&G.height!==0&&de.height!==0&&!X)),([,,,,me])=>{if(me===void 0){Ht(te,!0);return}Ht(O,!0),Nx(1,()=>{Ht(I,me)}),pi($e(c),()=>{Ht(t,[0,0]),Ht(te,!0)})}),vt($e(B,Pt(me=>me!=null&&me.scrollTop>0),_i(0)),C),fn($e(g,Yt(B),Pt(([,me])=>me!=null)),([,me])=>{me&&(Ht(A,me.viewport),Ht(E,me.item),Ht($,me.gap),me.scrollTop>0&&(Ht(H,!0),pi($e(c,br(1)),W=>{Ht(H,!1)}),Ht(d,{top:me.scrollTop})))}),vt($e(A,ht(({height:me})=>me)),h),vt($e(Bn(Et(A,zd),Et(E,zd),Et($,(me,W)=>me!==void 0&&me.column===W.column&&me.row===W.row),Et(c)),ht(([me,W,G,de])=>({gap:G,item:W,scrollTop:de,viewport:me}))),R),vt($e(Bn(Et(N),s,Et($,yW),Et(E,zd),Et(A,zd),Et(z),Et(C),Et(H),Et(te),Et(oe)),Pt(([,,,,,,,me])=>!me),ht(([me,[W,G],de,X,ie,Z,le,,be,Fe])=>{const{column:Je,row:We}=de,{height:et,width:qe}=X,{width:Lt}=ie;if(le===0&&(me===0||Lt===0))return Sw;if(qe===0){const ut=Tx(Fe,me),ft=ut+Math.max(le-1,0);return wW(jw(ut,ft,Z))}const Bt=eT(Lt,qe,Je);let Mt,ne;be?W===0&&G===0&&le>0?(Mt=0,ne=le-1):(Mt=Bt*Su((W+We)/(et+We)),ne=Bt*Cw((G+We)/(et+We))-1,ne=Cp(me-1,ml(ne,Bt-1)),Mt=Cp(ne,ml(0,Mt))):(Mt=0,ne=-1);const se=jw(Mt,ne,Z),{bottom:He,top:kt}=_w(ie,de,X,se),st=Cw(me/Bt),ke=st*et+(st-1)*We-He;return{bottom:He,itemHeight:et,items:se,itemWidth:qe,offsetBottom:ke,offsetTop:kt,top:kt}})),S),vt($e(z,Pt(me=>me!==null),ht(me=>me.length)),N),vt($e(Bn(A,E,S,$),Pt(([me,W,{items:G}])=>G.length>0&&W.height!==0&&me.height!==0),ht(([me,W,{items:G},de])=>{const{bottom:X,top:ie}=_w(me,de,W,G);return[ie,X]}),Pn(Wl)),t);const J=Ke(!1);vt($e(c,Yt(J),ht(([me,W])=>W||me!==0)),J);const pe=Os($e(Bn(S,N),Pt(([{items:me}])=>me.length>0),Yt(J),Pt(([[me,W],G])=>{const de=me.items[me.items.length-1].index===W-1;return(G||me.bottom>0&&me.itemHeight>0&&me.offsetBottom===0&&me.items.length===W)&&de}),ht(([[,me]])=>me-1),Pn())),fe=Os($e(Et(S),Pt(({items:me})=>me.length>0&&me[0].index===0),_i(0),Pn())),_e=Os($e(Et(S),Yt(H),Pt(([{items:me},W])=>me.length>0&&!W),ht(([{items:me}])=>({endIndex:me[me.length-1].index,startIndex:me[0].index})),Pn(EN),ro(0)));vt(_e,f.scrollSeekRangeChanged),vt($e(I,Yt(A,E,N,$),ht(([me,W,G,de,X])=>{const ie=LN(me),{align:Z,behavior:le,offset:be}=ie;let Fe=ie.index;Fe==="LAST"&&(Fe=de-1),Fe=ml(0,Fe,Cp(de-1,Fe));let Je=lm(W,X,G,Fe);return Z==="end"?Je=kw(Je-W.height+G.height):Z==="center"&&(Je=kw(Je-W.height/2+G.height/2)),be!==void 0&&be!==0&&(Je+=be),{behavior:le,top:Je}})),d);const Ee=ps($e(S,ht(me=>me.offsetBottom+me.bottom)),0);return vt($e(_,ht(me=>({height:me.visibleHeight,width:me.visibleWidth}))),A),{customScrollParent:v,data:z,deviation:T,footerHeight:o,gap:$,headerHeight:r,increaseViewportBy:e,initialItemCount:C,itemDimensions:E,overscan:n,restoreStateFrom:B,scrollBy:a,scrollContainerState:l,scrollHeight:D,scrollTo:d,scrollToIndex:I,scrollTop:c,smoothScrollTargetReached:u,totalCount:N,useWindowScroll:y,viewportDimensions:A,windowScrollContainerState:w,windowScrollTo:b,windowViewportRect:_,...f,gridState:S,horizontalDirection:V,initialTopMostItemIndex:oe,totalListHeight:Ee,...p,endReached:pe,propsReady:x,rangeChanged:_e,startReached:fe,stateChanged:R,stateRestoreInProgress:H,...j}},An(Dx,Ts,kd,BN,Wo,Ix,$o));function eT(e,t,n){return ml(1,Su((e+n)/(Su(t)+n)))}function _w(e,t,n,s){const{height:o}=n;if(o===void 0||s.length===0)return{bottom:0,top:0};const r=lm(e,t,n,s[0].index);return{bottom:lm(e,t,n,s[s.length-1].index)+o,top:r}}function lm(e,t,n,s){const o=eT(e.width,n.width,t.column),r=Su(s/o),a=r*n.height+ml(0,r-1)*t.row;return a>0?a+t.row:a}const CW=cn(()=>{const e=Ke(h=>`Item ${h}`),t=Ke({}),n=Ke(null),s=Ke("virtuoso-grid-item"),o=Ke("virtuoso-grid-list"),r=Ke(Px),a=Ke("div"),l=Ke(Da),d=(h,p=null)=>ps($e(t,ht(f=>f[h]),Pn()),p),c=Ke(!1),u=Ke(!1);return vt(Et(u),c),{components:t,computeItemKey:r,context:n,FooterComponent:d("Footer"),HeaderComponent:d("Header"),headerFooterTag:a,itemClassName:s,ItemComponent:d("Item","div"),itemContent:e,listClassName:o,ListComponent:d("List","div"),readyStateChanged:c,reportReadyState:u,ScrollerComponent:d("Scroller","div"),scrollerRef:l,ScrollSeekPlaceholder:d("ScrollSeekPlaceholder","div")}}),kW=cn(([e,t])=>({...e,...t}),An(SW,CW)),jW=Ne.memo(function(){const e=In("gridState"),t=In("listClassName"),n=In("itemClassName"),s=In("itemContent"),o=In("computeItemKey"),r=In("isSeeking"),a=Xs("scrollHeight"),l=In("ItemComponent"),d=In("ListComponent"),c=In("ScrollSeekPlaceholder"),u=In("context"),h=Xs("itemDimensions"),p=Xs("gap"),f=In("log"),g=In("stateRestoreInProgress"),x=Xs("reportReadyState"),v=Sr(Ne.useMemo(()=>y=>{const w=y.parentElement.parentElement.scrollHeight;a(w);const b=y.firstChild;if(b!==null){const{height:_,width:j}=b.getBoundingClientRect();h({height:_,width:j})}p({column:Nw("column-gap",getComputedStyle(y).columnGap,f),row:Nw("row-gap",getComputedStyle(y).rowGap,f)})},[a,h,p,f]),!0,!1);return qN(()=>{e.itemHeight>0&&e.itemWidth>0&&x(!0)},[e]),g?null:i.jsx(d,{className:t,ref:v,...hs(d,u),"data-testid":"virtuoso-item-list",style:{paddingBottom:e.offsetBottom,paddingTop:e.offsetTop},children:e.items.map(y=>{const w=o(y.index,y.data,u);return r?i.jsx(c,{...hs(c,u),height:e.itemHeight,index:y.index,width:e.itemWidth},w):m.createElement(l,{...hs(l,u),className:n,"data-index":y.index,key:w},s(y.index,y.data,u))})})}),_W=Ne.memo(function(){const e=In("HeaderComponent"),t=Xs("headerHeight"),n=In("headerFooterTag"),s=Sr(Ne.useMemo(()=>r=>{t(Lo(r,"height"))},[t]),!0,!1),o=In("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...hs(e,o)})}):null}),NW=Ne.memo(function(){const e=In("FooterComponent"),t=Xs("footerHeight"),n=In("headerFooterTag"),s=Sr(Ne.useMemo(()=>r=>{t(Lo(r,"height"))},[t]),!0,!1),o=In("context");return e!=null?i.jsx(n,{ref:s,children:i.jsx(e,{...hs(e,o)})}):null}),TW=({children:e})=>{const t=Ne.useContext(KN),n=Xs("itemDimensions"),s=Xs("viewportDimensions"),o=Sr(Ne.useMemo(()=>r=>{s(r.getBoundingClientRect())},[s]),!0,!1);return Ne.useEffect(()=>{t&&(s({height:t.viewportHeight,width:t.viewportWidth}),n({height:t.itemHeight,width:t.itemWidth}))},[t,s,n]),i.jsx("div",{ref:o,style:Ax(!1),children:e})},DW=({children:e})=>{const t=Ne.useContext(KN),n=Xs("windowViewportRect"),s=Xs("itemDimensions"),o=In("customScrollParent"),r=In("useWindowScroll"),a=jN(n,o,!1);return Ne.useEffect(()=>{t&&(s({height:t.itemHeight,width:t.itemWidth}),n({listHeight:0,offsetTop:0,visibleHeight:t.viewportHeight,visibleWidth:t.viewportWidth}))},[t,n,s]),i.jsx("div",{ref:a,style:ZN(!1,r),children:e})},IW=Ne.memo(function({...e}){const t=In("useWindowScroll"),n=In("customScrollParent"),s=n||t?PW:EW,o=n||t?DW:TW,r=In("context");return i.jsx(s,{...e,...hs(s,r),children:i.jsxs(o,{children:[i.jsx(_W,{}),i.jsx(jW,{}),i.jsx(NW,{})]})})}),{useEmitter:tT,useEmitterValue:In,usePublisher:Xs}=WN(kW,{optional:{context:"context",totalCount:"totalCount",overscan:"overscan",itemContent:"itemContent",components:"components",computeItemKey:"computeItemKey",data:"data",initialItemCount:"initialItemCount",scrollSeekConfiguration:"scrollSeekConfiguration",headerFooterTag:"headerFooterTag",listClassName:"listClassName",itemClassName:"itemClassName",useWindowScroll:"useWindowScroll",customScrollParent:"customScrollParent",scrollerRef:"scrollerRef",logLevel:"logLevel",restoreStateFrom:"restoreStateFrom",initialTopMostItemIndex:"initialTopMostItemIndex",increaseViewportBy:"increaseViewportBy"},methods:{scrollTo:"scrollTo",scrollBy:"scrollBy",scrollToIndex:"scrollToIndex"},events:{isScrolling:"isScrolling",endReached:"endReached",startReached:"startReached",rangeChanged:"rangeChanged",atBottomStateChange:"atBottomStateChange",atTopStateChange:"atTopStateChange",stateChanged:"stateChanged",readyStateChanged:"readyStateChanged"}},IW),EW=JN({useEmitter:tT,useEmitterValue:In,usePublisher:Xs}),PW=QN({useEmitter:tT,useEmitterValue:In,usePublisher:Xs});function Nw(e,t,n){return t!=="normal"&&t?.endsWith("px")!==!0&&n(`${e} was not resolved to pixel value correctly`,t,Jn.WARN),t==="normal"?0:parseInt(t??"0",10)}function AW({className:e}){return i.jsx("svg",{viewBox:"0 0 64 64",fill:"none","aria-hidden":"true",className:q("size-4",e),children:i.jsx("path",{d:"M 38.96 48.86 A 18.24 18.24 0 1 1 48.19 40.4",stroke:"currentColor",strokeWidth:"8.32",strokeLinecap:"round"})})}const MW={rows:new Set,expanded:new Set};function RW(e,t,n){const s=[],o=[],r=new Map,a=new Set;for(const l of t){if(l.kind!=="tool-group"||!l.explore)continue;const d=e.rows.has(l.key);if(l.explore.steps){a.add(l.key),d&&!e.expanded.has(l.key)&&o.push(l.key),l.children.forEach((f,g)=>{r.set(f.key,{group:l.key,index:g})});continue}const c=l.children[0]?.key??"",u=l.children.at(-1)?.key??"",h=!d&&e.rows.has(c)&&e.rows.has(u);if(!h&&!e.expanded.has(l.key))continue;const p=n(h?c:l.key,u);p>0&&s.push({key:l.key,height:p,pair:h})}return{collapses:s,expands:o,children:r,next:{rows:new Set(t.map(l=>l.key)),expanded:a}}}function LW(e){return e==="right"||e==="off"?e:"left"}function OW(e,t,n){return e!=="off"&&!t&&n>=2}const Gd=40;function zW({items:e,activeKey:t,onJump:n}){const s=Ce(g=>g.chatWide),o=LW(Ce(g=>g.navRailSide)),[r,a]=m.useState(null);if(!OW(o,s,e.length))return null;const l=o==="right",d=Math.max(0,e.findIndex(g=>g.key===t)),c=Math.min(Math.max(0,d-Math.floor(Gd/2)),Math.max(0,e.length-Gd)),u=e.slice(c,c+Gd),h=c>0,p=c+Gd<e.length,f=(g,x)=>{const v=x?24:12;if(r===null)return v;const y=Math.abs(g-r),w=Math.max(0,16-y*6);return v+w};return i.jsx("div",{className:q("group/rail absolute top-0 z-10 hidden h-full w-14 @min-[52rem]:block",l?"right-0":"left-0"),children:i.jsx("div",{className:q("absolute top-1/2 -translate-y-1/2 opacity-0 transition-opacity duration-200 group-hover/rail:opacity-100",l?"right-2":"left-2"),onMouseLeave:()=>a(null),children:i.jsxs("div",{className:"relative flex flex-col justify-center gap-[5px]",style:{maskImage:h||p?`linear-gradient(to bottom, ${h?"transparent, black 24px":"black"}, ${p?"black calc(100% - 24px), transparent":"black"})`:void 0},children:[u.map((g,x)=>{const v=g.key===t,y=x===r;return i.jsx("button",{type:"button",onClick:()=>n(g.key),onMouseEnter:()=>a(x),className:q("flex h-[7px] w-10 items-center",l&&"justify-end"),children:i.jsx("span",{className:q("rounded-full transition-all duration-150",v||y?"h-[3px] bg-foreground":"h-[2px] bg-muted-foreground/40"),style:{width:f(x,v)}})},g.key)}),r!==null&&u[r]&&i.jsxs("div",{className:q("pointer-events-none absolute w-72 -translate-y-1/2 rounded-xl border bg-popover p-3 shadow-lg",l?"right-10":"left-10"),style:{top:`${(r+.5)/u.length*100}%`},children:[i.jsx("p",{className:"line-clamp-2 text-xs font-semibold",children:u[r].question}),u[r].answer&&i.jsx("p",{className:"mt-1 line-clamp-3 text-xs text-muted-foreground",children:u[r].answer})]})]})})})}const zc="You are a side conversation attached to a coding session. The main agent cannot see this thread. Do not continue the main task unless the user asks you to. Follow the same tool and skill constraints as the main session. Do not spawn subagents, coworkers, or workflows. Answer the user directly.";function nT(e){return e.content.filter(t=>t.type==="text").map(t=>t.text??"").join("").trim()}function GW(e){const t=[];for(const n of e){if(n.role!=="user"&&n.role!=="assistant")continue;const s=nT(n);s&&t.push(`${n.role==="user"?"User":"Assistant"}: ${s}`)}return t.slice(-40).join(`
|
|
21
|
-
`)}function FW(e){for(const t of[...e].reverse()){if(t.role!=="assistant")continue;const n=nT(t);if(n)return n}return""}function Tw(e,t){if(e!=="contextual")return zc;const n=t.trim();return n?`${zc}
|
|
22
|
-
|
|
23
|
-
# Main conversation (background only)
|
|
24
|
-
${n}`:zc}function HW(e){return e.startsWith(zc)}function BW(e){const t=e.trim();return t?`Treat the following as discussion context from a side conversation, not as work already completed.
|
|
25
|
-
|
|
26
|
-
`+t:""}function VW({message:e}){const{t}=Q(),n={queued:t("Queued"),running:t("In progress"),completed:t("Completed"),failed:t("Failed"),canceled:t("Canceled")},s=e.kind==="routine"?J1:e.kind==="group"?ca:e.kind==="delegation-task"?ma:e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?na:WV,o=e.kind==="routine"?`${e.dryRun?t("Routine dry run"):t("Routine task")} · ${e.title}`:e.kind==="group"?t("Group messages"):e.kind==="delegation-task"?t("Task from {{name}}",{name:e.from}):e.kind==="delegation-results"?t("Delegation results"):e.kind==="delegation-retry"?t("Continue delegated task"):e.kind==="delegation-check-failed"?t("Acceptance check not passed"):t("Result from {{name}}",{name:e.from});return i.jsxs("div",{"data-bot-injection":e.kind,className:"w-full rounded-lg border border-border/60 bg-muted/20 px-3 py-2 text-sm",children:[i.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs font-medium text-muted-foreground",children:[i.jsx(s,{className:"size-3.5 shrink-0"}),i.jsx("span",{children:o}),e.kind==="delegation-result"&&e.status&&i.jsxs("span",{children:["· ",n[e.status]??e.status]})]}),i.jsx("div",{className:"whitespace-pre-wrap break-words",children:e.kind==="routine"?e.prompt:e.kind==="delegation-task"?e.task:e.kind==="delegation-result"||e.kind==="delegation-retry"||e.kind==="delegation-check-failed"?e.text:e.kind==="delegation-results"?e.results.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,r.status&&` · ${n[r.status]??r.status}`,":"]}),r.text]},`${a}:${r.from}`)):e.messages.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))}),e.kind==="delegation-task"&&e.context&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer",children:t("Context")}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.context})]}),e.kind==="group"&&e.instruction&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer",children:t("Instructions")}),i.jsx("p",{className:"mt-1 whitespace-pre-wrap break-words",children:e.instruction})]}),e.kind==="group"&&!!e.refs?.length&&i.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:e.refs.map(r=>i.jsxs("span",{title:t("Referenced chat"),className:"inline-flex h-6 max-w-56 items-center gap-1 rounded-md bg-muted px-1.5 text-xs",children:[i.jsx(ca,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:r.title})]},r.id))}),e.kind==="group"&&e.note&&i.jsx("p",{className:"mt-1.5 text-xs text-muted-foreground",children:t("Dispatch hint: {{note}}",{note:e.note})}),e.kind!=="group"&&!!e.group?.length&&i.jsxs("details",{className:"mt-1.5 text-xs text-muted-foreground",children:[i.jsxs("summary",{className:"cursor-pointer",children:[t("Group messages")," · ",e.group.length]}),i.jsx("div",{className:"mt-1 whitespace-pre-wrap break-words",children:e.group.map((r,a)=>i.jsxs("p",{children:[i.jsxs("span",{className:"font-medium",children:[r.from,":"]}),r.text]},`${a}:${r.from}`))})]})]})}const sT=new Map;let Wr;function $W(e){if(Wr?.revision===e)return Wr.request;const t=window.electronAPI.providers.listOauth().then(s=>{const o=new Map;for(const r of s)for(const a of r.accounts){if(typeof a.email!="string")continue;let l="";for(const d of a.email){const c=d.codePointAt(0)??0;c>=32&&c!==127&&(l+=d)}l=l.trim(),l&&o.set(a.key,l)}return{revision:e,emails:o}}).catch(s=>(console.error("Failed to load OAuth account metadata",s),{revision:e,emails:sT})),n={revision:e,request:t,data:void 0};return Wr=n,t.then(s=>{Wr===n&&(n.data=s)}),t}function WW(){const e=Fi(s=>s.snapshot.revision),[t,n]=m.useState(()=>Wr?.revision===e?Wr.data:void 0);return m.useEffect(()=>{let s=!1;return $W(e).then(o=>{s||n(o)}),()=>{s=!0}},[e]),t?.revision===e?t.emails:sT}function Dw(e,t=0){let n=3735928559^t,s=1103547991^t;for(let o=0;o<e.length;o++){const r=e.charCodeAt(o);n=Math.imul(n^r,2654435761),s=Math.imul(s^r,1597334677)}return n=Math.imul(n^n>>>16,2246822507)^Math.imul(s^s>>>13,3266489909),s=Math.imul(s^s>>>16,2246822507)^Math.imul(n^n>>>13,3266489909),(4294967296*(2097151&s)+(n>>>0)).toString(36)}function Rx(e,t,n){return`${e}:${Dw(t)}:${Dw(n,1)}`}const UW=/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c|$)/g,KW=/(?:\x1b\[|\x9b)[0-?]*[ -/]*(?:[@-~]|$)/g;function vi(e){return e.replace(UW,"").replace(KW,"")}function qW(e){if(typeof e.ttft=="number"&&e.ttft>0)return e.ttft;const t=e.timing;if(!(!t||t.firstTokenMs===void 0))return Math.max(0,t.firstTokenMs-t.stepStartMs)}function YW(e){if(typeof e.duration=="number"&&e.duration>0)return e.duration;const t=e.timing;if(!(!t||t.completedMs===void 0))return Math.max(0,t.completedMs-t.stepStartMs)}function XW(e){let t=0,n=0,s=0,o=0,r=0,a=0,l=0,d=0,c=0,u=0,h=0,p=0,f=null;for(const x of e){if(x.role==="user"&&(t+=1,f=null),x.role!=="assistant")continue;n+=1,x.usage&&(s+=x.usage.input,o+=x.usage.output,r+=x.usage.cacheRead,a+=x.usage.cacheWrite);const v=x.timing,y=YW(x);y!==void 0&&(l+=y);const w=qW(x);w!==void 0&&(c+=w,u+=1);const b=x.usage?.output??0;y!==void 0&&y>0&&b>0&&(h+=y,p+=b),v&&(f!==null&&(d+=Math.max(0,v.stepStartMs-f)),f=v.completedMs??null)}const g=s+r+a;return{turns:t,steps:n,llmMs:l,toolMs:d,inputTokens:g,outputTokens:o,cacheHitPercent:g===0?null:Math.round(r/g*100),ttftAvgMs:u>0?c/u:null,tokensPerSecond:h>0&&p>0?Math.round(p/(h/1e3)*10)/10:null}}function ZW(e){return{inputTokens:e.inputTokens,outputTokens:e.outputTokens,...e.cacheHitPercent!==null?{cacheHitPercent:e.cacheHitPercent}:{},...e.ttftAvgMs!==null?{ttftAvgMs:e.ttftAvgMs}:{},...e.tokensPerSecond!==null?{tokensPerSecond:e.tokensPerSecond}:{}}}const Iw=rg(e=>({byConversation:{},replace:(t,n)=>e(s=>{const o={...s.byConversation};if(n.length>0)o[t]=n;else if(o[t])delete o[t];else return s;return{byConversation:o}})})),JW={read_only:"Read-only",regenerable:"Regenerable output",reversible_workspace_change:"Reversible workspace change",data_loss:"Possible data loss",system_state:"Changes system state",exfiltration:"Sends data externally",unclear_target:"Unclear target or intent"};function QW({value:e}){const t=kP(e),{t:n}=Q();if(!t)return null;const s=`allow ${t.allow.toFixed(2)} · ask ${t.ask.toFixed(2)} · block ${t.block.toFixed(2)}`;return i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 border-border/60 border-t px-3 py-1 text-[10px] text-muted-foreground","data-approval-review":t.verdict,children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:t.verdict==="allow"?n("Auto-managed · allowed"):n("Auto-managed · denied")}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{className:"font-mono",children:t.model}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{className:"font-mono",children:s}),t.reason&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsxs("span",{children:[n("Reason"),": ",n(JW[t.reason])]})]})]})}function eU({ask:e,waiting:t}){const{t:n}=Q(),s=e.answer!==null&&!e.options.includes(e.answer)?e.answer:null;return i.jsxs("div",{className:"space-y-1.5 px-3 py-2 text-xs",children:[i.jsx("p",{className:"whitespace-pre-wrap break-words leading-relaxed text-foreground",children:e.question}),(e.options.length>0||s!==null)&&i.jsxs("ul",{className:"space-y-0.5",children:[e.options.map(o=>i.jsx(Ew,{selected:o===e.answer,text:o},o)),s!==null&&i.jsx(Ew,{selected:!0,text:s,label:e.options.length>0&&!e.autoSelected?n("Custom answer"):void 0})]}),e.autoSelected&&i.jsx("p",{className:"text-muted-foreground",children:n("No answer in time; the default was selected")}),t&&e.answer===null&&i.jsx("p",{className:"text-muted-foreground",children:n("Waiting for your answer")})]})}function Ew({selected:e,text:t,label:n}){const{t:s}=Q(),o=e?ag:gx;return i.jsxs("li",{"data-selected":e||void 0,className:q("flex items-start gap-1.5 rounded-md px-2 py-1 leading-relaxed",e?"bg-primary/10 text-foreground":"text-muted-foreground"),children:[i.jsx(o,{className:q("mt-0.5 h-3.5 w-3.5 shrink-0",e?"text-primary":"opacity-40")}),i.jsxs("span",{className:"min-w-0 whitespace-pre-wrap break-words",children:[n&&i.jsx("span",{className:"mr-1.5 text-muted-foreground",children:n}),t]}),e&&i.jsx("span",{className:"sr-only",children:s("Selected")})]})}const tU=/^Subagent ".*" \(agentId [^,\s]+, runId [^)\s]+\) \S+ after .+\.$/gm,nU=/^The following is the subagent's report: .*$\n?/m,sU=/<usage>([\s\S]*?)<\/usage>/,kp=(e,t)=>{const n=new RegExp(`^${t}: (\\d+)$`,"m").exec(e);return n?Number(n[1]):null};function iU(e){const t=e.indexOf(`
|
|
27
|
-
`),n=t<0?e:e.slice(0,t);let s=t<0?"":e.slice(t+1),o=null;const r=sU.exec(s);if(r){s=s.slice(0,r.index);const a=kp(r[1],"subagent_tokens"),l=kp(r[1],"tool_uses"),d=kp(r[1],"duration_ms");a!==null&&l!==null&&d!==null&&(o={tokens:a,toolUses:l,durationMs:d})}return{header:n,report:s.replace(nU,"").trim(),usage:o}}function oU(e){const t=e.trim(),n=[...t.matchAll(tU)].map(s=>s.index);return n[0]!==0?null:n.map((s,o)=>iU(t.slice(s,n[o+1]).replace(/\n+---\s*$/,"").trim()))}const bh=m.createContext(null);function Wi(){return m.useContext(bh)}const rU=new TextEncoder,aU=new TextDecoder("utf-8",{ignoreBOM:!0}),lU=/[\uD800-\uDFFF]/,dm=1024;let Ur=new Uint8Array(dm);function dU(){Ur.length!==dm&&(Ur=new Uint8Array(dm))}function os(e){if(e.length===0)return e;if(lU.test(e))return JSON.parse(JSON.stringify(e));const t=e.length*3;Ur.length<t&&(Ur=new Uint8Array(t));const{written:n}=rU.encodeInto(e,Ur);return aU.decode(Ur.subarray(0,n))}const cU=4096,uU=.5;function hU(e){for(const t of e.hunks){for(let n=0;n<t.hunkContent.length;n++){const s=t.hunkContent[n];if(s.type!=="change")continue;const o=fU(e,s);o!=null&&(t.hunkContent.splice(n,1,...o),n+=o.length-1)}pU(t,e)}}function pU(e,t){const{hunkContent:n}=e;for(let s=1;s<n.length;s++){const o=n[s],r=n[s-1];if(o.type!=="change"||o.additions>0&&o.deletions>0||r.type!=="context")continue;const a=o.additions>0,l=a?t.additionLines:t.deletionLines,d=a?o.additionLineIndex:o.deletionLineIndex,c=a?o.additions:o.deletions,u=l[d]??"";if(u.trim()!=="")continue;let h=!0;for(let v=1;v<c;v++)if(l[d+v]!==u){h=!1;break}if(!h)continue;let p=0;for(;p<r.lines&&t.additionLines[r.additionLineIndex+r.lines-1-p]===u;)p++;if(p===0||s===1&&p===r.lines)continue;o.additionLineIndex-=p,o.deletionLineIndex-=p;const f=o.additionLineIndex+o.additions,g=o.deletionLineIndex+o.deletions,x=n[s+1];x?.type==="context"?(x.lines+=p,x.additionLineIndex=f,x.deletionLineIndex=g):n.splice(s+1,0,{type:"context",lines:p,additionLineIndex:f,deletionLineIndex:g}),r.lines-=p,r.lines===0&&(n.splice(s-1,1),s--)}}function fU(e,t){const{deletions:n,additions:s,deletionLineIndex:o,additionLineIndex:r}=t,a=Math.min(n,s),l=Math.abs(s-n);if(a===0||l===0||a*(l+1)>cU)return null;const d=[];for(let x=0;x<n;x++)d.push(Pw(e.deletionLines[o+x]??""));const c=[];for(let x=0;x<s;x++)c.push(Pw(e.additionLines[r+x]??""));const u=s>n;let h=0,p=-1;for(let x=0;x<=l;x++){let v=0;for(let y=0;y<a;y++)v+=gU(d[y+(u?0:x)],c[y+(u?x:0)]);x===0?p=v+a*uU:v>p&&(p=v,h=x)}if(h===0)return null;const f=[],g=(x,v,y,w)=>{(x>0||v>0)&&f.push({type:"change",deletions:x,additions:v,deletionLineIndex:y,additionLineIndex:w})};return u?(g(0,h,o,r),g(a,a,o,r+h),g(0,s-a-h,o+a,r+h+a)):(g(h,0,o,r),g(a,a,o+h,r),g(n-a-h,0,o+h+a,r+a)),f}const mU=/\s+/g;function Pw(e){return e.replace(mU,"")}function gU(e,t){if(e===t)return 1;const n=Math.max(e.length,t.length),s=Math.min(e.length,t.length);if(s===0)return 0;let o=0;for(;o<s&&e[o]===t[o];)o++;let r=0;for(;r<s-o&&e[e.length-1-r]===t[t.length-1-r];)r++;return(o+r)/n}function xU(e,t){try{return vU(e,t)}finally{dU()}}function vU(e,{cacheKey:t,isGitDiff:n=DP.test(e),oldFile:s,newFile:o,throwOnError:r=!1}={}){let a=0;const l=CU(e,"@@ ");let d;const c=s==null||o==null;let u=0,h=0;for(const p of l){const f=iT(p),g=f[0];if(g==null){if(r)throw Error("parsePatchContent: invalid hunk");console.error("parsePatchContent: invalid hunk",p);continue}const x=yU(g);let v=0,y=0;if(x==null||d==null){if(d!=null){if(r)throw Error("parsePatchContent: Invalid hunk");console.error("parsePatchContent: Invalid hunk",p);continue}d={name:"",type:"change",hunks:[],splitLineCount:0,unifiedLineCount:0,isPartial:c,additionLines:!c&&s!=null&&o!=null?Aw(o.contents):[],deletionLines:!c&&s!=null&&o!=null?Aw(s.contents):[],cacheKey:Rw(t)},d.additionLines.length===1&&o?.contents===""&&(d.additionLines.length=0),d.deletionLines.length===1&&s?.contents===""&&(d.deletionLines.length=0);for(const A of f){if(A.startsWith("diff --git")){const I=A.trim().match(jP),D=I?.[1]??I?.[2],T=I?.[3]??I?.[4];if(D==null||T==null){if(r)throw Error("parsePatchContent: invalid git diff header");console.error("parsePatchContent: invalid git diff header",A);continue}d.name=os(T.trim()),D!==T&&(d.prevName=os(D.trim()));continue}const E=A.startsWith("---")||A.startsWith("+++")?A.match(n?_P:NP):null;if(E!=null){const[,I,D]=E;if(I==="---"&&D!=="/dev/null"){const T=os(D.trim());d.prevName=T,d.name=T}else I==="+++"&&D!=="/dev/null"&&(d.name=os(D.trim()))}else if(n){if(A.startsWith("new mode ")&&(d.mode=os(A.slice(8).trim())),A.startsWith("old mode ")&&(d.prevMode=os(A.slice(8).trim())),A.startsWith("new file mode")&&(d.type="new",d.mode=os(A.slice(13).trim())),A.startsWith("deleted file mode")&&(d.type="deleted",d.mode=os(A.slice(17).trim())),A.startsWith("similarity index")&&(A.startsWith("similarity index 100%")?d.type="rename-pure":d.type="rename-changed"),A.startsWith("index ")){const[,I,D,T]=A.trim().match(TP)??[];I!=null&&(d.prevObjectId=os(I)),D!=null&&(d.newObjectId=os(D)),T!=null&&(d.mode=os(T))}A.startsWith("rename from ")&&(d.prevName=os(A.slice(12).trim())),A.startsWith("rename to ")&&(d.name=os(A.slice(10).trim()))}}continue}let w,b;for(;f.length>0&&(f[f.length-1]===`
|
|
28
|
-
`||f[f.length-1]==="\r"||f[f.length-1]===`\r
|
|
29
|
-
`||f[f.length-1]==="");)f.pop();const{additionStart:_,deletionStart:j}=x;u=c?u:j-1,h=c?h:_-1;const N={collapsedBefore:0,splitLineCount:0,splitLineStart:0,unifiedLineCount:0,unifiedLineStart:0,additionCount:x.additionCount,additionStart:_,additionLines:v,deletionCount:x.deletionCount,deletionStart:j,deletionLines:y,deletionLineIndex:u,additionLineIndex:h,hunkContent:[],hunkContext:Rw(x.hunkContext),hunkSpecs:os(g),noEOFCRAdditions:!1,noEOFCRDeletions:!1};let C=0,S=0;for(let A=1;A<f.length;A++){const E=f[A];if(C>=N.additionCount&&S>=N.deletionCount&&!E.startsWith("\\")){if(r&&bU(E)&&!wU(E))throw Error("parsePatchContent: hunk has more lines than expected");break}const I=E[0];if(I!=="+"&&I!=="-"&&I!==" "&&I!=="\\"){if(r)throw Error("parsePatchContent: invalid hunk line");console.error(`parseLineType: Invalid firstChar: "${I}", full line: "${E}"`),console.error("processFile: invalid rawLine:",E);continue}const D=kU(I);if(D==="addition"){if(r&&C>=N.additionCount)throw Error("parsePatchContent: hunk has too many addition lines");const T=jp(E);(w==null||w.type!=="change")&&(w=_p("change",u,h),N.hunkContent.push(w)),h++,C++,c&&d.additionLines.push(T),w.additions++,v++,b="addition"}else if(D==="deletion"){if(r&&S>=N.deletionCount)throw Error("parsePatchContent: hunk has too many deletion lines");const T=jp(E);(w==null||w.type!=="change")&&(w=_p("change",u,h),N.hunkContent.push(w)),u++,S++,c&&d.deletionLines.push(T),w.deletions++,y++,b="deletion"}else if(D==="context"){if(r&&(S>=N.deletionCount||C>=N.additionCount))throw Error("parsePatchContent: hunk has too many context lines");const T=jp(E);(w==null||w.type!=="context")&&(w=_p("context",u,h),N.hunkContent.push(w)),h++,u++,C++,S++,c&&(d.deletionLines.push(T),d.additionLines.push(T)),w.lines++,b="context"}else if(D==="metadata"&&w!=null){if(w.type==="context"?(N.noEOFCRAdditions=!0,N.noEOFCRDeletions=!0):b==="deletion"?N.noEOFCRDeletions=!0:b==="addition"&&(N.noEOFCRAdditions=!0),c&&(b==="addition"||b==="context")){const T=d.additionLines.length-1;T>=0&&(d.additionLines[T]=Nl(d.additionLines[T]))}if(c&&(b==="deletion"||b==="context")){const T=d.deletionLines.length-1;T>=0&&(d.deletionLines[T]=Nl(d.deletionLines[T]))}}}if(r&&(C!==N.additionCount||S!==N.deletionCount))throw Error("parsePatchContent: hunk line count mismatch");N.additionLines=v,N.deletionLines=y,N.collapsedBefore=Math.max(ga(N.additionStart,N.additionCount)-a,0),d.hunks.push(N),a=co(N.additionStart,N.additionCount);for(const A of N.hunkContent)A.type==="context"?(N.splitLineCount+=A.lines,N.unifiedLineCount+=A.lines):(N.splitLineCount+=Math.max(A.additions,A.deletions),N.unifiedLineCount+=A.deletions+A.additions);N.splitLineStart=d.splitLineCount+N.collapsedBefore,N.unifiedLineStart=d.unifiedLineCount+N.collapsedBefore,d.splitLineCount+=N.collapsedBefore+N.splitLineCount,d.unifiedLineCount+=N.collapsedBefore+N.unifiedLineCount}if(d!=null){if(r&&c&&!n&&d.hunks.length===0)throw Error("parsePatchContent: unified file has no hunks");if(d.hunks.length>0&&!c&&d.additionLines.length>0&&d.deletionLines.length>0){const p=d.hunks[d.hunks.length-1],f=co(p.additionStart,p.additionCount),g=d.additionLines.length,x=Math.max(g-f,0);d.splitLineCount+=x,d.unifiedLineCount+=x}return n||(d.prevName!=null&&d.name!==d.prevName?d.hunks.length>0?d.type="rename-changed":d.type="rename-pure":(s==null||s.contents==="")&&o!=null&&o.contents!==""?d.type="new":s!=null&&s.contents!==""&&(o==null||o.contents==="")&&(d.type="deleted")),d.type!=="rename-pure"&&d.type!=="rename-changed"&&(d.prevName=void 0),hU(d),d}}function Aw(e){const t=iT(e);for(let n=0;n<t.length;n++)t[n]=os(t[n]);return t}function iT(e){if(e.length===0)return[""];const t=[];let n=0;for(;;){const s=e.indexOf(`
|
|
30
|
-
`,n);if(s===-1)break;t.push(e.slice(n,s+1)),n=s+1}return n<e.length&&t.push(e.slice(n)),t}function bU(e){const t=e[0];return t==="+"||t==="-"||t===" "}function wU(e){if(!e.startsWith("--"))return!1;for(let t=2;t<e.length;t++){const n=e[t];if(n!==" "&&n!==" "&&n!==`
|
|
31
|
-
`&&n!=="\r")return!1}return!0}function yU(e){if(!e.startsWith("@@ -"))return;let t=4;const n=Fd(e,t);if(n==null)return;const s=n.value;t=n.endIndex;let o=1;if(e[t]===","){const u=Fd(e,t+1);if(u==null)return;o=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="+")return;t+=2;const r=Fd(e,t);if(r==null)return;const a=r.value;t=r.endIndex;let l=1;if(e[t]===","){const u=Fd(e,t+1);if(u==null)return;l=u.value,t=u.endIndex}if(e[t]!==" "||e[t+1]!=="@"||e[t+2]!=="@")return;let d;const c=t+3;return e[c]===" "&&(d=SU(e.slice(c+1))),{additionCount:l,additionStart:a,deletionCount:o,deletionStart:s,hunkContext:d}}function Fd(e,t){let n=t,s=0;for(;n<e.length;n++){const o=e.charCodeAt(n)-48;if(o<0||o>9)break;s=s*10+o}if(n!==t)return{value:s,endIndex:n}}function SU(e){return e.endsWith(`\r
|
|
32
|
-
`)?e.slice(0,-2):e.endsWith(`
|
|
33
|
-
`)?e.slice(0,-1):e}function CU(e,t){if(e.length===0)return[""];const n=`
|
|
34
|
-
${t}`,s=e.startsWith(t)?0:Mw(e,n,0);if(s===-1)return[e];const o=[];s>0&&o.push(e.slice(0,s));let r=s;for(;;){const a=Mw(e,n,r+1);if(a===-1)break;o.push(e.slice(r,a)),r=a}return o.push(e.slice(r)),o}function Mw(e,t,n){const s=e.indexOf(t,n);return s===-1?-1:s+1}function Rw(e){return e==null?e:os(e)}function kU(e){return e===" "?"context":e==="\\"?"metadata":e==="+"?"addition":"deletion"}function jp(e){const t=e.slice(1);return os(t===""?`
|
|
35
|
-
`:t)}function _p(e,t,n){return e==="change"?{type:"change",additions:0,deletions:0,additionLineIndex:n,deletionLineIndex:t}:{type:"context",lines:0,additionLineIndex:n,deletionLineIndex:t}}class jU extends IP{constructor(){super(...arguments),this.tokenize=NU}equals(t,n,s){return s.ignoreWhitespace?((!s.newlineIsToken||!t.includes(`
|
|
36
|
-
`))&&(t=t.trim()),(!s.newlineIsToken||!n.includes(`
|
|
37
|
-
`))&&(n=n.trim())):s.ignoreNewlineAtEof&&!s.newlineIsToken&&(t.endsWith(`
|
|
38
|
-
`)&&(t=t.slice(0,-1)),n.endsWith(`
|
|
39
|
-
`)&&(n=n.slice(0,-1))),super.equals(t,n,s)}}const _U=new jU;function Lw(e,t,n){return _U.diff(e,t,n)}function NU(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
40
|
-
`));const n=[],s=e.split(/(\n|\r\n)/);s[s.length-1]||s.pop();for(let o=0;o<s.length;o++){const r=s[o];o%2&&!t.newlineIsToken?n[n.length-1]+=r:n.push(r)}return n}function TU(e){for(let t=0;t<e.length;t++)if(e[t]<" "||e[t]>"~"||e[t]==='"'||e[t]==="\\")return!0;return!1}function Co(e){if(!TU(e))return e;let t='"';const n=new TextEncoder().encode(e);let s=0;for(;s<n.length;){const o=n[s];o===7?t+="\\a":o===8?t+="\\b":o===9?t+="\\t":o===10?t+="\\n":o===11?t+="\\v":o===12?t+="\\f":o===13?t+="\\r":o===34?t+='\\"':o===92?t+="\\\\":o>=32&&o<=126?t+=String.fromCharCode(o):t+="\\"+o.toString(8).padStart(3,"0"),s++}return t+='"',t}const Ow={includeIndex:!0,includeUnderline:!0,includeFileHeaders:!0};function zw(e,t,n,s,o,r,a){let l;a?typeof a=="function"?l={callback:a}:l=a:l={},typeof l.context>"u"&&(l.context=4);const d=l.context;if(l.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(l.callback){const{callback:u}=l;Lw(n,s,Object.assign(Object.assign({},l),{callback:h=>{const p=c(h);u(p)}}))}else return c(Lw(n,s,l));function c(u){if(!u)return;u.push({value:"",lines:[]});function h(w){return w.map(function(b){return" "+b})}const p=[];let f=0,g=0,x=[],v=1,y=1;for(let w=0;w<u.length;w++){const b=u[w],_=b.lines||IU(b.value);if(b.lines=_,b.added||b.removed){if(!f){const j=u[w-1];f=v,g=y,j&&(x=d>0?h(j.lines.slice(-d)):[],f-=x.length,g-=x.length)}for(const j of _)x.push((b.added?"+":"-")+j);b.added?y+=_.length:v+=_.length}else{if(f)if(_.length<=d*2&&w<u.length-2)for(const j of h(_))x.push(j);else{const j=Math.min(_.length,d);for(const C of h(_.slice(0,j)))x.push(C);const N={oldStart:f,oldLines:v-f+j,newStart:g,newLines:y-g+j,lines:x};p.push(N),f=0,g=0,x=[]}v+=_.length,y+=_.length}}for(const w of p)for(let b=0;b<w.lines.length;b++)w.lines[b].endsWith(`
|
|
41
|
-
`)?w.lines[b]=w.lines[b].slice(0,-1):(w.lines.splice(b+1,0,"\"),b++);return{oldFileName:e,newFileName:t,oldHeader:o,newHeader:r,hunks:p}}}function cm(e,t){var n,s,o,r,a,l;if(t||(t=Ow),Array.isArray(e)){if(e.length>1&&!t.includeFileHeaders&&!e.every(u=>u.isGit))throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return e.map(u=>cm(u,t)).join(`
|
|
42
|
-
`)}const d=[];if(e.isGit){if(t=Ow,!e.oldFileName)throw new Error("oldFileName must be specified for Git patches");if(!e.newFileName)throw new Error("newFileName must be specified for Git patches");let u=e.oldFileName,h=e.newFileName;e.isCreate&&u==="/dev/null"?u=h.replace(/^b\//,"a/"):e.isDelete&&h==="/dev/null"&&(h=u.replace(/^a\//,"b/")),d.push("diff --git "+Co(u)+" "+Co(h)),e.isDelete&&d.push("deleted file mode "+((n=e.oldMode)!==null&&n!==void 0?n:"100644")),e.isCreate&&d.push("new file mode "+((s=e.newMode)!==null&&s!==void 0?s:"100644")),e.oldMode&&e.newMode&&!e.isDelete&&!e.isCreate&&(d.push("old mode "+e.oldMode),d.push("new mode "+e.newMode)),e.isRename&&(d.push("rename from "+Co(((o=e.oldFileName)!==null&&o!==void 0?o:"").replace(/^a\//,""))),d.push("rename to "+Co(((r=e.newFileName)!==null&&r!==void 0?r:"").replace(/^b\//,"")))),e.isCopy&&(d.push("copy from "+Co(((a=e.oldFileName)!==null&&a!==void 0?a:"").replace(/^a\//,""))),d.push("copy to "+Co(((l=e.newFileName)!==null&&l!==void 0?l:"").replace(/^b\//,""))))}else t.includeIndex&&e.oldFileName==e.newFileName&&e.oldFileName!==void 0&&d.push("Index: "+e.oldFileName),t.includeUnderline&&d.push("===================================================================");const c=e.hunks.length>0;t.includeFileHeaders&&e.oldFileName!==void 0&&e.newFileName!==void 0&&(!e.isGit||c)&&(d.push("--- "+Co(e.oldFileName)+(e.oldHeader?" "+e.oldHeader:"")),d.push("+++ "+Co(e.newFileName)+(e.newHeader?" "+e.newHeader:"")));for(let u=0;u<e.hunks.length;u++){const h=e.hunks[u],p=h.oldLines===0?h.oldStart-1:h.oldStart,f=h.newLines===0?h.newStart-1:h.newStart;d.push("@@ -"+p+","+h.oldLines+" +"+f+","+h.newLines+" @@");for(const g of h.lines)d.push(g)}return d.join(`
|
|
43
|
-
`)+`
|
|
44
|
-
`}function DU(e,t,n,s,o,r,a){if(typeof a=="function"&&(a={callback:a}),a?.callback){const{callback:l}=a;zw(e,t,n,s,o,r,Object.assign(Object.assign({},a),{callback:d=>{l(d?cm(d,a.headerOptions):void 0)}}))}else{const l=zw(e,t,n,s,o,r,a);return l?cm(l,a?.headerOptions):void 0}}function IU(e){const t=e.endsWith(`
|
|
45
|
-
`),n=e.split(`
|
|
46
|
-
`).map(s=>s+`
|
|
47
|
-
`);return t?n.pop():n.push(n.pop().slice(0,-1)),n}const EU="/dev/null";function go(e,t,n,s=!1){if(e===null&&t===null)throw new Error("parseDiffFromFile: You must pass oldFile, newFile, or both");const o=e??Gw(),r=t??Gw(),a=xU(DU(o.name,r.name,o.contents,r.contents,o.header,r.header,n),{cacheKey:(()=>{const d=e?.cacheKey??e?.name,c=t?.cacheKey??t?.name;return d!=null&&c!=null?d+":"+c:d??c})(),oldFile:o,newFile:r,throwOnError:s});if(a==null)throw new Error("parseDiffFrom: FileInvalid diff -- probably need to fix something -- if the files are the same maybe?");e===null?(a.type="new",a.prevName=void 0):t===null&&(a.type="deleted",a.prevName=void 0);const l=t?.lang??(t===null?e?.lang:void 0);return l!=null&&(a.lang=l),a}function Gw(){return{name:EU,contents:""}}function PU(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function AU(e){return{...e,hunks:e.hunks.map(t=>({...t,hunkContent:t.hunkContent.map(n=>({...n}))})),deletionLines:[...e.deletionLines],additionLines:[...e.additionLines]}}function um(e){return e!==""?e.split(EP):[]}function hm(e,t,n){const s=e==="clone"?AU(t):t;if(!s.isPartial)throw new Error("hydratePartialDiff: fileDiff must be partial");switch(s.type){case"change":case"rename-changed":return MU(s,LU(s,n),Fw(s,n));case"rename-pure":{const o=Fw(s,n);OU(s,n);const r=um(o.contents);return s.isPartial=!1,s.deletionLines=r,s.additionLines=r,oT(s,null,o),s}}throw new Error(`hydratePartialDiff: ${s.type} diffs cannot be hydrated from loaded files`)}function MU(e,t,n){const s=um(t.contents),o=um(n.contents),{hunks:r,splitLineCount:a,unifiedLineCount:l}=RU(e.hunks,o.length);return e.hunks=r,e.splitLineCount=a,e.unifiedLineCount=l,e.isPartial=!1,e.deletionLines=s,e.additionLines=o,oT(e,t,n),e}function RU(e,t){let n=0,s=0,o=0;const r=[];for(const a of e){const l=Math.max(a.additionStart-1,0),d=Math.max(a.deletionStart-1,0);let c=l,u=d,h=0,p=0,f=0,g=0;const x=[];for(const y of a.hunkContent){if(y.type==="context"){x.push({...y,additionLineIndex:c,deletionLineIndex:u}),c+=y.lines,u+=y.lines,f+=y.lines,g+=y.lines;continue}x.push({...y,additionLineIndex:c,deletionLineIndex:u}),c+=y.additions,u+=y.deletions,h+=y.additions,p+=y.deletions,f+=Math.max(y.additions,y.deletions),g+=y.additions+y.deletions}const v=Math.max(ga(a.additionStart,a.additionCount)-o,0);r.push({...a,collapsedBefore:v,additionLineIndex:l,deletionLineIndex:d,additionLines:h,deletionLines:p,hunkContent:x,splitLineStart:n+v,unifiedLineStart:s+v,splitLineCount:f,unifiedLineCount:g}),n+=v+f,s+=v+g,o=co(a.additionStart,a.additionCount)}if(r.length>0){const a=r[r.length-1],l=co(a.additionStart,a.additionCount),d=Math.max(t-l,0);n+=d,s+=d}return{hunks:r,splitLineCount:n,unifiedLineCount:s}}function LU(e,t){if(t.oldFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile`);return t.oldFile}function Fw(e,t){if(t.newFile==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires newFile`);return t.newFile}function OU(e,t){if(t.oldFile!==null)throw new Error(`hydratePartialDiff: ${e.type} diff for ${e.name} requires oldFile to be null`)}function zU(e,t,n){return e.cacheKey!=null?`${e.cacheKey}:hydrated`:GU(t,n)}function oT(e,t,n){const s=zU(e,t,n);if(s==null){delete e.cacheKey;return}e.cacheKey=s}function GU(e,t){return e!=null&&t!=null?e.cacheKey!=null&&t.cacheKey!=null?`${e.cacheKey}:${t.cacheKey}`:void 0:e?.cacheKey??t?.cacheKey}var FU=class{isDeletionsScrolling=!1;isAdditionsScrolling=!1;timeoutId=-1;codeDeletions;codeAdditions;enabled=!1;cleanUp(){this.enabled&&(this.codeDeletions?.removeEventListener("scroll",this.handleDeletionsScroll),this.codeAdditions?.removeEventListener("scroll",this.handleAdditionsScroll),clearTimeout(this.timeoutId),this.codeDeletions=void 0,this.codeAdditions=void 0,this.enabled=!1)}setup(e,t,n){if(t==null||n==null)for(const s of e.children??[])s instanceof HTMLElement&&("deletions"in s.dataset?t=s:"additions"in s.dataset&&(n=s));if(n==null||t==null){this.cleanUp();return}this.codeDeletions!==t&&(this.codeDeletions?.removeEventListener("scroll",this.handleDeletionsScroll),this.codeDeletions=t,t.addEventListener("scroll",this.handleDeletionsScroll,{passive:!0})),this.codeAdditions!==n&&(this.codeAdditions?.removeEventListener("scroll",this.handleAdditionsScroll),this.codeAdditions=n,n.addEventListener("scroll",this.handleAdditionsScroll,{passive:!0})),this.enabled=!0}handleDeletionsScroll=()=>{this.isAdditionsScrolling||(this.isDeletionsScrolling=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isDeletionsScrolling=!1},300),this.codeAdditions?.scrollTo({left:this.codeDeletions?.scrollLeft}))};handleAdditionsScroll=()=>{this.isDeletionsScrolling||(this.isAdditionsScrolling=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout(()=>{this.isAdditionsScrolling=!1},300),this.codeDeletions?.scrollTo({left:this.codeAdditions?.scrollLeft}))}};function Hd(e){return ms({tagName:"div",properties:{"data-content-buffer":"","data-buffer-size":e,style:`grid-row: span ${e};min-height:calc(${e} * 1lh)`}})}function Bd(e){return ms({tagName:"div",children:[ms({tagName:"span",children:[Cc("No newline at end of file")]})],properties:{"data-no-newline":"","data-line-type":e,"data-column-content":""}})}function Np(e){return ms({tagName:"div",children:[PP({name:e==="both"?"diffs-icon-expand-all":"diffs-icon-expand",properties:{"data-icon":""}})],properties:{role:"button","data-expand-button":"","data-expand-both":e==="both"?"":void 0,"data-expand-up":e==="up"?"":void 0,"data-expand-down":e==="down"?"":void 0}})}function Tr({type:e,content:t,expandIndex:n,chunked:s=!1,slotName:o,isFirstHunk:r,isLastHunk:a}){let l=0;const d=[];if(e==="metadata"&&t!=null&&d.push(ms({tagName:"div",children:[Cc(t)],properties:{"data-separator-wrapper":""}})),(e==="line-info"||e==="line-info-basic")&&t!=null){const c=[];n!=null&&(s?(r||(c.push(Np("up")),l++),a||(c.push(Np("down")),l++)):(c.push(Np(!r&&!a?"both":r?"down":"up")),l++)),c.push(ms({tagName:"div",children:[ms({tagName:"span",children:[Cc(t)],properties:{"data-unmodified-lines":""}})],properties:{"data-separator-content":""}})),s&&n!=null&&c.push(ms({tagName:"div",children:[Cc("Expand all")],properties:{role:"button","data-expand-button":"","data-expand-all-button":""}})),d.push(ms({tagName:"div",children:c,properties:{"data-separator-wrapper":"","data-separator-multi-button":l>1?"":void 0}}))}return e==="custom"&&o!=null&&d.push(ms({tagName:"slot",properties:{name:o}})),ms({tagName:"div",children:d,properties:{"data-separator":d.length===0?"simple":e,"data-expand-index":n,"data-separator-first":r?"":void 0,"data-separator-last":a?"":void 0}})}function HU(e,t){return`hunk-separator-${e}-${t}`}function BU(e){const t=e.at(-1);return t==null?0:Math.max(co(t.additionStart,t.additionCount),co(t.deletionStart,t.deletionCount))}function pm(e){return e.startingLine===0&&e.totalLines===1/0&&e.bufferBefore===0&&e.bufferAfter===0}function no(e,t){const n=go({name:e.prevName??e.name,contents:e.deletionLines.join("")},{name:e.name,contents:e.additionLines.join(""),lang:e.lang},t);return{hunks:n.hunks,splitLineCount:n.splitLineCount,unifiedLineCount:n.unifiedLineCount,additionLines:n.additionLines,deletionLines:n.deletionLines,type:n.type}}function VU(e,t){const n=Math.max(e,1);let s=Array.from({length:n},(o,r)=>`${" ".repeat(r+1)}
|
|
48
|
-
`).join("");return s===t&&(s=Array.from({length:n},(o,r)=>`\0${" ".repeat(r)}
|
|
49
|
-
`).join("")),s}function $U(e){for(const t of e)if(t.trim().length>0)return!1;return!0}function fm(e,t){return t.length>0&&t.length<e.deletionLines.length&&$U(t)}function Cu(e,t,n){const s=e.deletionLines.join(""),o=VU(t.length,s),r=go({name:e.prevName??e.name,contents:s},{name:e.name,contents:o,lang:e.lang},n);return{hunks:r.hunks,splitLineCount:r.splitLineCount,unifiedLineCount:r.unifiedLineCount,additionLines:t,deletionLines:r.deletionLines,type:r.type}}function Gc(e,t){return Cu(e,[""],t)}function rT(e,t){if(e.additionLines.length===0)return Gc(e,t);if(fm(e,e.additionLines))return Cu(e,e.additionLines,t);const n=e.additionLines,s=no(e,t);return aT(s,n),s}function WU(e){return e.length>1&&e.at(-1)===""}function aT(e,t){if(!WU(t))return;const n=t.length-e.additionLines.length;if(n<=0)return;const s=e.additionLines.length,o=e.hunks.at(-1);if(o!=null&&co(o.additionStart,o.additionCount)===s){for(const r of o.hunkContent)if(r.type==="change"&&r.additions<r.deletions&&r.additionLineIndex+r.additions===s){e.additionLines=t,r.additions+=n,o.additionCount+=n,o.additionLines+=n,Ox(e);return}}}function UU(e,t,n){if(e.isPartial||e.deletionLines.length!==e.additionLines.length)return qi(e,no(e,n));const s=Array.from(t);if(s.length===0)return qi(e,{hunks:e.hunks,splitLineCount:e.splitLineCount,unifiedLineCount:e.unifiedLineCount,type:e.type});for(const r of s){const a=e.additionLines[r],l=e.deletionLines[r];if(a==null||l==null||Nl(a)===Nl(l))return qi(e,no(e,n))}const o=KU(e,s);if(o.size===0)return qi(e,no(e,n));for(const r of o)if(!YU(e,r,n))return qi(e,no(e,n));return Ox(e),AP(e)?qi(e,no(e,n)):qi(e,{hunks:e.hunks,splitLineCount:e.splitLineCount,unifiedLineCount:e.unifiedLineCount,type:e.type})}function qi(e,t){return Object.assign(e,t),t}function KU(e,t){const n=new Set;for(const s of t){const o=qU(e,s);if(o==null)return new Set;n.add(o)}return n}function qU(e,t){for(const[n,s]of e.hunks.entries()){const o=s.additionLineIndex+s.additionCount;if(t>=s.additionLineIndex&&t<o)return n}}function YU(e,t,n){const s=e.hunks[t];if(s==null)return!1;const o=e.deletionLines.slice(s.deletionLineIndex,s.deletionLineIndex+s.deletionCount),r=e.additionLines.slice(s.additionLineIndex,s.additionLineIndex+s.additionCount),a=go({name:e.prevName??e.name,contents:o.join("")},{name:e.name,contents:r.join(""),lang:e.lang},{...n,context:0}),l=a.hunks[0];return l==null||a.hunks.length!==1?!1:(XU(s,l),lT(e,t),!0)}function lT(e,t){const n=e.hunks[t];if(n==null)return;if(t!==e.hunks.length-1){n.noEOFCRAdditions=!1,n.noEOFCRDeletions=!1;return}const s=e.additionLines.at(-1),o=e.deletionLines.at(-1);n.noEOFCRAdditions=s!=null&&s!==""&&!s.endsWith(`
|
|
50
|
-
`),n.noEOFCRDeletions=o!=null&&o!==""&&!o.endsWith(`
|
|
51
|
-
`)}function XU(e,t){const n=e.additionLineIndex,s=e.deletionLineIndex;e.hunkContent=t.hunkContent.map(o=>dT(o,n,s)),e.additionLineIndex=n+t.additionLineIndex,e.additionStart=e.additionStart+t.additionLineIndex,e.additionCount=t.additionCount,e.additionLines=t.additionLines,t.deletionLineIndex>=0&&(e.deletionLineIndex=s+t.deletionLineIndex,e.deletionStart=e.deletionStart+t.deletionLineIndex),e.deletionCount=t.deletionCount,e.deletionLines=t.deletionLines,e.noEOFCRAdditions=t.noEOFCRAdditions,e.noEOFCRDeletions=t.noEOFCRDeletions,Lx(e)}function dT(e,t,n){return{...e,additionLineIndex:e.additionLineIndex+t,deletionLineIndex:e.deletionLineIndex+n}}function Lx(e){let t=0,n=0;for(const s of e.hunkContent)s.type==="context"?(t+=s.lines,n+=s.lines):(t+=Math.max(s.additions,s.deletions),n+=s.additions+s.deletions);e.splitLineCount=t,e.unifiedLineCount=n}function Ox(e){let t=0,n=0,s=0;for(const o of e.hunks)o.collapsedBefore=Math.max(ga(o.additionStart,o.additionCount)-s,0),o.splitLineStart=t+o.collapsedBefore,o.unifiedLineStart=n+o.collapsedBefore,Lx(o),t+=o.collapsedBefore+o.splitLineCount,n+=o.collapsedBefore+o.unifiedLineCount,s=co(o.additionStart,o.additionCount);if(e.hunks.length>0){const o=e.hunks[e.hunks.length-1],r=Math.max(e.additionLines.length-co(o.additionStart,o.additionCount),0);t+=r,n+=r}e.splitLineCount=t,e.unifiedLineCount=n}const Hw=new WeakMap;function ZU(e){return e.length>1&&e[e.length-1]===""?e.slice(0,-1):e}function JU(e,t){const n=Math.min(e.length,t.length);let s=0;for(;s<n&&e[s]===t[s];)s++;let o=e.length,r=t.length;for(;o>s&&r>s&&e[o-1]===t[r-1];)o--,r--;if(!(s===o&&s===r))return{start:s,deletionEnd:o,additionEnd:r}}function mm(e,t){const n=e.hunks,s=e.additionLines,o=ZU(s),r=o===s?e:{...e,additionLines:o},a=a8(n,r8(r,t),e.deletionLines.length),l=c8(r,a);if(e.additionLines=o,e.hunks=l,e.editSessionDirty=!0,f8(e),aT(e,s),!!h8(n,e.hunks))return{regions:a.map(d=>d.previousSpan)}}function QU(e,t,n,s){const o=Array.from(new Set(t)).filter(d=>d>=0&&d<e.additionLines.length).sort((d,c)=>d-c);if(o.length===0)return;const{hunks:r}=e;let a,l=0;for(const d of o){for(;l<r.length;){const h=r[l];if(d<ku(h)+h.additionCount)break;l++}const c=r[l],u=c==null?void 0:ku(c);if(u==null||d<u||a!=null&&a!==l)return mm(e,n);a=l}if(a!=null){if(e8(e,o,a,s,n)){e.editSessionDirty=!0;return}return mm(e,n)}}function e8(e,t,n,s,o){if(s==null||o?.ignoreWhitespace===!0||o?.stripTrailingCr===!0)return!1;const r=t8(e),a=e.hunks[n];if(a.hunkContent.some(n8))return!1;for(const l of t){const d=s.get(l),c=e.additionLines[l];if(d==null||c==null||r.has(d)||r.has(c))return!1;let u=!1;for(const h of a.hunkContent)if(h.type==="change"&&h.additions===h.deletions&&l>=h.additionLineIndex&&l<h.additionLineIndex+h.additions){u=!0;break}if(!u)return!1}return!0}function t8(e){const t=Hw.get(e);if(t?.lines===e.deletionLines)return t.set;const n=new Set(e.deletionLines);return Hw.set(e,{lines:e.deletionLines,set:n}),n}function n8(e){return e?.type==="change"&&(e.additions===0||e.deletions===0)}function s8(e,t){const n=new Map,{regions:s}=t;for(let o=0;o<=s.length;o++){const r=s[o-1],a=s[o],l=o===0?e.get(0):r==null?void 0:e.get(r.lastIndex+1),d=a==null?void 0:e.get(a.firstIndex),c=l?.fromStart??0,u=d?.fromEnd??0;(c>0||u>0)&&n.set(o,{fromStart:c,fromEnd:u})}return n}function i8(e,t,n){const s=[];if(e.isPartial)return s;for(const[r,a]of e.hunks.entries()){const l=Tl({isPartial:e.isPartial,rangeSize:a.collapsedBefore,expandedHunks:t,hunkIndex:r,collapsedContextThreshold:n});if(l.rangeSize<=n)continue;const d=wr(a),c=d-l.rangeSize;l.fromStart>0&&s.push([c,c+l.fromStart]),l.fromEnd>0&&s.push([d-l.fromEnd,d])}const o=Dl({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:t,collapsedContextThreshold:n,errorPrefix:"captureExpansionAnchors"});if(o!=null&&o.fromStart>0&&o.rangeSize>n){const r=e.hunks[e.hunks.length-1],a=wr(r)+r.deletionCount;s.push([a,a+o.fromStart])}return s}function o8(e,t){const n=new Map;if(t.length===0)return n;const s=(r,a,l)=>{if(l<=a)return;let d=0,c=0;for(const[u,h]of t)h<=a||u>=l||(u<=a&&(d=Math.max(d,Math.min(h,l)-a)),h>=l&&(c=Math.max(c,l-Math.max(u,a))));(d>0||c>0)&&n.set(r,{fromStart:d,fromEnd:c})};for(const[r,a]of e.hunks.entries()){const l=wr(a);s(r,l-Math.max(a.collapsedBefore,0),l)}const o=e.hunks[e.hunks.length-1];return o!=null&&!e.isPartial&&e.deletionLines.length>0&&s(e.hunks.length,wr(o)+o.deletionCount,e.deletionLines.length),n}function gm(e,t){return e.editSessionDirty!==!0?!1:(e.editSessionDirty=void 0,Object.assign(e,e.additionLines.length<=1&&e.additionLines.join("")===""?no(e,t):rT(e,t)),!0)}function r8(e,t){if(JU(e.deletionLines,e.additionLines)==null)return[];const n=go({name:e.prevName??e.name,contents:e.deletionLines.join("")},{name:e.name,contents:e.additionLines.join(""),lang:e.lang},t),s=[];let o=0,r=0;for(const a of n.hunks){const l=a.additionCount>0?a.additionLineIndex-o:a.deletionLineIndex-r;o+=l,r+=l;for(const d of a.hunkContent){if(d.type==="context"){o+=d.lines,r+=d.lines;continue}const c=dT(d,0,0);c.additions===0&&(c.additionLineIndex=o),c.deletions===0&&(c.deletionLineIndex=r),s.push(c),o+=c.additions,r+=c.deletions}}return s}function a8(e,t,n){const s=e.map((a,l)=>{const d=wr(a);return{deletionStart:d,deletionEnd:d+a.deletionCount,blocks:[],previousSpan:{firstIndex:l,lastIndex:l}}}),o=[];let r=0;for(const a of t){const l=a.deletionLineIndex,d=l+a.deletions;for(;r<s.length&&s[r].deletionEnd<l;)o.push(s[r]),r++;let c=o.length>0&&l8(l,d,o[o.length-1])?o.pop():void 0;for(;r<s.length&&s[r].deletionStart<=d;)c=d8(c,s[r]),r++;if(c==null){let u=l,h=d;if((a.deletions===0||a.additions===0)&&n>a.deletions){const p=o[o.length-1]?.deletionEnd??0,f=s[r]?.deletionStart??n;l>p?u--:d<f&&h++}c={deletionStart:u,deletionEnd:h,blocks:[],previousSpan:void 0}}c.deletionStart=Math.min(c.deletionStart,l),c.deletionEnd=Math.max(c.deletionEnd,d),c.blocks.push(a),o.push(c)}for(;r<s.length;)o.push(s[r]),r++;return o}function l8(e,t,n){return e<=n.deletionEnd&&t>=n.deletionStart}function d8(e,t){return e==null?t:(e.deletionStart=Math.min(e.deletionStart,t.deletionStart),e.deletionEnd=Math.max(e.deletionEnd,t.deletionEnd),e.blocks.push(...t.blocks),t.previousSpan!=null&&(e.previousSpan??={...t.previousSpan},e.previousSpan.firstIndex=Math.min(e.previousSpan.firstIndex,t.previousSpan.firstIndex),e.previousSpan.lastIndex=Math.max(e.previousSpan.lastIndex,t.previousSpan.lastIndex)),e)}function c8(e,t){const n=[];let s=0,o=0;for(const r of t){const a=r.deletionStart-s;if(a<0)throw new Error("buildRegionHunks: overlapping old-side regions");s+=a,o+=a;const l=o,d=[];for(const u of r.blocks){const h=u.deletionLineIndex-s,p=u.additionLineIndex-o;if(h<0||h!==p)throw new Error("buildRegionHunks: canonical block context mismatch");Bw(d,h,o,s),s+=h,o+=p,d.push({...u}),s+=u.deletions,o+=u.additions}const c=r.deletionEnd-s;if(c<0)throw new Error("buildRegionHunks: block exceeds its old-side region");Bw(d,c,o,s),s+=c,o+=c,n.push(u8(e,{additionStart:l,additionEnd:o,deletionStart:r.deletionStart,deletionEnd:r.deletionEnd},d))}if(e.deletionLines.length-s!==e.additionLines.length-o)throw new Error("buildRegionHunks: trailing context mismatch");return n}function u8(e,t,n){const s=t.additionEnd-t.additionStart,o=t.deletionEnd-t.deletionStart;let r=0,a=0;for(const d of n)d.type==="change"&&(r+=d.additions,a+=d.deletions);const l={collapsedBefore:0,additionStart:Vd(t.additionStart,s),additionCount:s,additionLines:r,additionLineIndex:$w(t.additionStart,s),deletionStart:Vd(t.deletionStart,o),deletionCount:o,deletionLines:a,deletionLineIndex:$w(t.deletionStart,o),hunkContent:n,hunkSpecs:`@@ -${Vd(t.deletionStart,o)},${o} +${Vd(t.additionStart,s)},${s} @@`,splitLineStart:0,splitLineCount:0,unifiedLineStart:0,unifiedLineCount:0,noEOFCRAdditions:!1,noEOFCRDeletions:!1};return Lx(l),l}function Bw(e,t,n,s){t>0&&e.push({type:"context",lines:t,additionLineIndex:n,deletionLineIndex:s})}function h8(e,t){if(e.length!==t.length)return!0;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];if(wr(s)!==wr(o)||s.deletionCount!==o.deletionCount||ku(s)!==ku(o)||s.additionCount!==o.additionCount||s.splitLineCount!==o.splitLineCount||!p8(s,o))return!0}return!1}function p8(e,t){const n=Vw(e),s=Vw(t);for(;;){const o=n.next(),r=s.next();if(o.done===!0||r.done===!0)return o.done===r.done;if(o.value[0]!==r.value[0]||o.value[1]!==r.value[1])return!1}}function*Vw(e){for(const t of e.hunkContent){if(t.type==="context"){for(let s=0;s<t.lines;s++)yield[t.deletionLineIndex+s,t.additionLineIndex+s];continue}const n=Math.max(t.deletions,t.additions);for(let s=0;s<n;s++)yield[s<t.deletions?t.deletionLineIndex+s:void 0,s<t.additions?t.additionLineIndex+s:void 0]}}function ku(e){return ga(e.additionStart,e.additionCount)}function wr(e){return ga(e.deletionStart,e.deletionCount)}function Vd(e,t){return t===0?e:e+1}function $w(e,t){return t===0?e-1:e}function f8(e){Ox(e);for(let t=0;t<e.hunks.length;t++)lT(e,t)}let m8=-1;var g8=class{options;onRenderUpdate;workerManager;__id=`diff-hunks-renderer:${++m8}`;highlighter;diff;expandedHunks=new Map;deletionAnnotations={};additionAnnotations={};computedLang="text";renderCache;editSessionActive=!1;constructor(e={theme:Ti},t,n){this.options=e,this.onRenderUpdate=t,this.workerManager=n,n?.isWorkingPool()!==!0&&(this.highlighter=Hh(e.theme??Ti)?MP():void 0)}cleanUp(){this.recycle(),this.expandedHunks.clear(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.highlighter=void 0,this.diff=void 0,this.clearRenderCache(),this.additionAnnotations={},this.deletionAnnotations={},this.workerManager?.cleanUpTasks(this),this.endEditSession()}beginEditSession(){this.editSessionActive=!0;const e=this.diffCache;e!=null&&!e.isPartial&&e.additionLines.length===0&&(Object.assign(e,Gc(e,this.options.parseDiffOptions)),this.markEditSessionPass(e),this.clearRenderCache())}endEditSession(){this.editSessionActive=!1}editorRenderReady(){return this.renderCache?.options.useTokenTransformer===!0&&this.renderCache.highlighted&&this.renderCache.result!=null}refreshHighlightedResult(){const{renderCache:e}=this;if(e==null||kc(e.diff)||Ud(e.diff,this.getTokenizeMaxLength()))return Promise.resolve();const{diff:t}=e,{workerManager:n}=this;return!this.editSessionActive&&n?.isWorkingPool()===!0&&t.cacheKey!=null?(n.evictDiffFromCache(t.cacheKey),n.primeDiffHighlightCache(t).then(()=>{this.applyRefreshedResult(t,n.getDiffResultCache(t))}).catch(s=>this.onHighlightError(s))):this.asyncHighlight(t).then(s=>this.applyRefreshedResult(t,s)).catch(s=>this.onHighlightError(s))}applyRefreshedResult(e,t){if(t==null||this.renderCache==null||this.renderCache.diff!==e||this.editSessionActive)return;const{options:n}=this.getRenderOptions(e);_r(n,t.options)&&(this.renderCache={diff:e,options:t.options,highlighted:!0,result:t.result,renderRange:void 0},this.onRenderUpdate?.())}get diffCache(){return this.renderCache?.diff??this.diff}clearRenderCache(){const e=this.renderCache;this.renderCache=void 0,e!=null&&e.isDirty===!0&&e.diff.cacheKey!=null&&this.workerManager?.evictDiffFromCache(e.diff.cacheKey)}setOptions(e){this.options=e}mergeOptions(e){this.options={...this.options,...e}}expandHunk(e,t,n=this.getOptionsWithDefaults().expansionLineCount){const s={...this.expandedHunks.get(e)??{fromStart:0,fromEnd:0}};(t==="up"||t==="both")&&(s.fromStart+=n),(t==="down"||t==="both")&&(s.fromEnd+=n),this.renderCache?.highlighted!==!0&&this.clearRenderCache(),this.expandedHunks.set(e,s)}getExpandedHunk(e){return this.expandedHunks.get(e)??RP}getExpandedHunksMap(){return this.expandedHunks}setExpandedHunksMap(e){this.expandedHunks=e}setLineAnnotations(e){this.additionAnnotations={},this.deletionAnnotations={};for(const t of e){const n=(()=>{switch(t.side){case"deletions":return this.deletionAnnotations;case"additions":return this.additionAnnotations}})(),s=n[t.lineNumber]??[];n[t.lineNumber]=s,s.push(t)}}updateRenderCache(e,t,n=!1){if(this.renderCache==null)return!1;const{result:s,diff:o}=this.renderCache;if(s==null)return!1;if(o.isPartial)throw new Error("Could not update render cache for partial diff");const r=s.code.additionLines,a=[],l=new Map;for(const[c,u]of e){const h=r[c]?.properties??{},p=u.map(v=>v[2]).join(""),f=c<o.additionLines.length,g=f?o.additionLines[c]??"":"",x=Nl(g);f&&(o.additionLines[c]=LP(g,p),x!==p&&(a.push(c),l.set(c,g))),r[c]={type:"element",tagName:"div",properties:{"data-line":h["data-line"]??c+1,"data-line-index":h["data-line-index"]??c,"data-line-type":h["data-line-type"]??"context"},children:u.map(([v,y,w])=>v===0&&y===""?w===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:w}:{type:"element",tagName:"span",properties:{"data-char":v,style:`color:${y};`},children:[{type:"text",value:w}]})}}let d=!1;if(a.length>0)if(this.editSessionActive&&!o.isPartial){if(!n)if(o.additionLines.length<=1&&o.additionLines.join("")==="")Object.assign(o,Gc(o,this.options.parseDiffOptions)),this.markEditSessionPass(o),d=!0;else if(fm(o,o.additionLines))Object.assign(o,Cu(o,o.additionLines,this.options.parseDiffOptions)),this.markEditSessionPass(o),d=!0;else{const c=QU(o,a,this.options.parseDiffOptions,l);this.applyExpansionRemap(c),d=c!=null}}else Object.assign(o,UU(o,a,this.options.parseDiffOptions));return s.baseThemeType=t,this.renderCache.isDirty=!0,d}applyExpansionRemap(e){e!=null&&(this.expandedHunks=s8(this.expandedHunks,e))}applyDocumentChange(e){if(this.renderCache==null)return;const{diff:t,result:n}=this.renderCache;if(n==null)return;if(t.isPartial)throw new Error("Could not apply document change for partial diff");const{additionLines:s}=t;t.additionLines=w8(e,s),n.code.additionLines=b8(s,t.additionLines,n.code.additionLines,e),t.additionLines.length<=1&&t.additionLines.join("")===""?(Object.assign(t,Gc(t,this.options.parseDiffOptions)),n.code.additionLines[0]=xm(0,e.getLineText(0)),this.markEditSessionPass(t)):this.editSessionActive?this.applySessionDocumentChange(t):Object.assign(t,rT(t,this.options.parseDiffOptions)),this.renderCache.isDirty=!0}applySessionDocumentChange(e){const{parseDiffOptions:t}=this.options,n=e.additionLines;if(fm(e,n)){Object.assign(e,Cu(e,n,t)),this.markEditSessionPass(e);return}this.applyExpansionRemap(mm(e,t))}markEditSessionPass(e){this.editSessionActive&&(e.editSessionDirty=!0)}getUnifiedLineDecoration({lineType:e}){return{gutterLineType:e,contentProperties:{"data-line-type":e}}}getSplitLineDecoration({side:e,type:t}){const n=t==="change"?e==="deletions"?"change-deletion":"change-addition":t;return{gutterLineType:n,contentProperties:{"data-line-type":n}}}createAnnotationElement=e=>OP(e);getOptionsWithDefaults(){const{diffIndicators:e="bars",diffStyle:t="split",disableBackground:n=!1,disableFileHeader:s=!1,disableLineNumbers:o=!1,disableVirtualizationBuffers:r=!1,collapsed:a=!1,expandUnchanged:l=!1,collapsedContextThreshold:d=1,expansionLineCount:c=100,hunkSeparators:u="line-info",lineDiffType:h="word-alt",maxLineDiffLength:p=1e3,overflow:f="scroll",stickyHeader:g=!1,theme:x=Ti,headerRenderMode:v="default",tokenizeMaxLineLength:y=1e3,tokenizeMaxLength:w=zP,useTokenTransformer:b=!1,useCSSClasses:_=!1}=this.options;return{diffIndicators:e,diffStyle:t,disableBackground:n,disableFileHeader:s,disableLineNumbers:o,disableVirtualizationBuffers:r,collapsed:a,expandUnchanged:l,collapsedContextThreshold:d,expansionLineCount:c,hunkSeparators:u,lineDiffType:h,maxLineDiffLength:p,overflow:f,stickyHeader:g,theme:this.workerManager?.getDiffRenderOptions().theme??x,headerRenderMode:v,tokenizeMaxLineLength:y,tokenizeMaxLength:w,useTokenTransformer:b,useCSSClasses:_}}async initializeHighlighter(){return this.highlighter=await GP(FP(this.computedLang,{theme:this.getLocalHighlightTheme(),preferredHighlighter:this.workerManager?.getPreferredHighlighter()??this.options.preferredHighlighter})),this.highlighter}hydrate(e){if(e==null)return;this.diff=e;const{options:t}=this.getRenderOptions(e),n=Ud(e,this.getTokenizeMaxLength());let s=this.workerManager?.getDiffResultCache(e);s!=null&&!_r(t,s.options)&&(s=void 0),this.renderCache??={diff:e,highlighted:!n&&!kc(e),options:t,result:n?void 0:s?.result,renderRange:void 0},!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!n&&this.workerManager.highlightDiffAST(this,this.diff):this.highlighter==null&&(this.computedLang=e.lang??Bh(e.name),this.initializeHighlighter())}getLocalHighlightTheme(){return this.workerManager?.getDiffRenderOptions().theme??this.options.theme??Ti}getEffectiveCodeOptions(){const e=this.workerManager?.isWorkingPool()===!0?this.workerManager.getDiffRenderOptions():void 0;return{theme:this.getLocalHighlightTheme(),tokenizeMaxLineLength:e?.tokenizeMaxLineLength??this.options.tokenizeMaxLineLength}}getRenderOptions(e){const t=(()=>{if(this.workerManager?.isWorkingPool()===!0){const l=this.workerManager.getDiffRenderOptions();return this.editSessionActive&&l.useTokenTransformer!==!0?{...l,useTokenTransformer:!0}:l}const{theme:s,tokenizeMaxLineLength:o,lineDiffType:r,maxLineDiffLength:a}=this.getOptionsWithDefaults();return{theme:s,useTokenTransformer:this.editSessionActive||this.options.useTokenTransformer===!0,tokenizeMaxLineLength:o,lineDiffType:r,maxLineDiffLength:a}})();this.getOptionsWithDefaults();const{renderCache:n}=this;return n?.result==null?{options:t,forceHighlight:!0}:!Fr(e,n.diff)||!_r(t,n.options)?{options:t,forceHighlight:!0}:{options:t,forceHighlight:!1}}renderDiff(e=this.renderCache?.diff,t=Rv){if(e==null)return;const{expandUnchanged:n,collapsedContextThreshold:s}=this.getOptionsWithDefaults();let{options:o,forceHighlight:r}=this.getRenderOptions(e);const a=this.getMatchingWorkerResultCache(e,o);a!=null&&!this.hasHighlightedRenderCache(e,o)&&(this.renderCache={diff:e,highlighted:!0,renderRange:void 0,...a},r=!1),this.renderCache??={diff:e,highlighted:!1,options:o,result:void 0,renderRange:void 0};const l=e.additionLines.length>0||e.deletionLines.length>0,d=!l||kc(e)||Ud(e,this.getTokenizeMaxLength()),c=!Fr(e,this.renderCache.diff),u=!uk(this.renderCache.renderRange,t);if(!this.editSessionActive&&this.workerManager?.isWorkingPool()===!0){const h=this.renderCache.result==null&&this.renderCache.highlighted&&!d&&!c&&pm(t);h&&(this.renderCache.highlightPending=!0),!h&&(d||this.renderCache.result==null||!this.renderCache.highlighted&&(c||u))&&(this.renderCache.diff=e,this.renderCache.options=o,this.renderCache.highlighted=!1,(this.renderCache.result==null||c||u||r)&&(this.renderCache.result=this.workerManager.getPlainDiffAST(e,t.startingLine,t.totalLines,pm(t)||n?!0:this.expandedHunks,s)),this.renderCache.renderRange=t),!d&&l&&(!this.renderCache.highlighted||r)&&this.workerManager.highlightDiffAST(this,e)}else{this.computedLang=e.lang??Bh(e.name);const h=this.highlighter!=null&&Hh(o.theme),p=this.highlighter!=null&&Lv(this.computedLang),f=!d&&p;if(this.highlighter!=null&&h&&(r||d||!this.renderCache.highlighted&&f||this.renderCache.result==null)){const{result:g,options:x}=this.renderDiffWithHighlighter(e,this.highlighter,d||!p);this.renderCache={diff:e,options:x,highlighted:f,result:g,renderRange:void 0}}(!h||!d&&!p)&&this.asyncHighlight(e).then(({result:g,options:x})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.applyHighlightResult(e,g,x,!d)})}return this.renderCache.result!=null?this.processDiffResult(this.renderCache.diff,t,this.renderCache.result):void 0}async asyncRender(e,t=Rv){const{result:n}=await this.asyncHighlight(e);return this.processDiffResult(e,t,n)}createPreElement(e,t,n){const{diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a}=this.getOptionsWithDefaults();return HP({type:"diff",diffIndicators:s,disableBackground:o,disableLineNumbers:r,overflow:a,split:e,totalLines:t,customProperties:n})}async asyncHighlight(e){const t=Ud(e,this.getTokenizeMaxLength());this.computedLang=t?"text":e.lang??Bh(e.name);const n=this.highlighter!=null&&Hh(this.getLocalHighlightTheme()),s=t||this.highlighter!=null&&Lv(this.computedLang);return(this.highlighter==null||!n||!s)&&(this.highlighter=await this.initializeHighlighter()),this.renderDiffWithHighlighter(e,this.highlighter,t)}renderDiffWithHighlighter(e,t,n=!1){const{options:s}=this.getRenderOptions(e),{collapsedContextThreshold:o}=this.getOptionsWithDefaults(),r=BP(e,t,s,{forcePlainText:n,expandedHunks:n?!0:void 0,collapsedContextThreshold:o});if(this.editSessionActive&&e.additionLines.length===1&&e.additionLines[0]===""&&r.code.additionLines[0]==null){let a;if(qr({diff:e,diffStyle:"both",expandedHunks:n?!0:void 0,collapsedContextThreshold:o,callback:({additionLine:l})=>{if(l?.lineIndex===0)return a=l,!0}}),a==null)throw new Error("DiffHunksRenderer: missing empty addition line");r.code.additionLines[0]=xm(0,"",a.unifiedLineIndex,a.splitLineIndex)}return{result:r,options:s}}onHighlightSuccess(e,t,n,s=!0){this.editSessionActive||this.applyHighlightResult(e,t,n,s)}applyHighlightResult(e,t,n,s=!0){if(this.renderCache==null)return;const o=this.renderCache.highlightPending===!0||!this.renderCache.highlighted||!_r(this.renderCache.options,n)||!Fr(this.renderCache.diff,e);this.renderCache={diff:e,options:n,highlighted:s,result:t,renderRange:void 0},o&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(e,t){if(this.editSessionActive)return;const n=this.workerManager?.getDiffResultCache(e);if(!(n==null||!_r(t,n.options)))return n}hasHighlightedRenderCache(e,t){const{renderCache:n}=this;return n?.result!=null&&n.highlighted&&Fr(e,n.diff)&&_r(t,n.options)}onHighlightError(e){console.error(e)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}processDiffResult(e,t,{code:n,themeStyles:s,baseThemeType:o}){const{diffStyle:r,disableFileHeader:a,expandUnchanged:l,expansionLineCount:d,collapsedContextThreshold:c,hunkSeparators:u}=this.getOptionsWithDefaults(),h=this.renderCache?.isDirty??!1;this.diff=e;const p=r==="unified",f=C8(e,this.options.loadDiffFiles!=null),g=!e.isPartial||f;let x=[],v=[],y=[];const w=[],{additionLines:b,deletionLines:_}=n,j={rowCount:0,hunkSeparators:u,additionsContentAST:x,deletionsContentAST:v,unifiedContentAST:y,unifiedGutterAST:Dd(),deletionsGutterAST:Dd(),additionsGutterAST:Dd(),expansionLineCount:d,hunkData:w,incrementRowCount(R=1){j.rowCount+=R},pushToGutter(R,B){switch(R){case"unified":j.unifiedGutterAST.children.push(B);break;case"deletions":j.deletionsGutterAST.children.push(B);break;case"additions":j.additionsGutterAST.children.push(B);break}}},N=VP({fileDiff:e,errorPrefix:"DiffHunksRenderer.processDiffResult"}),C={size:0,side:void 0,increment(){this.size+=1},flush(){if(r!=="unified"){if(this.size<=0||this.side==null){this.side=void 0,this.size=0;return}this.side==="additions"?(j.pushToGutter("additions",ri(void 0,"buffer",this.size)),x?.push(Hd(this.size))):(j.pushToGutter("deletions",ri(void 0,"buffer",this.size)),v?.push(Hd(this.size))),this.size=0,this.side=void 0}}},S=(R,B,H,oe,te)=>{j.pushToGutter(R,UP(B,H,oe,te))};function A(R){C.flush(),r==="unified"?Tp("unified",R,j):(Tp("deletions",R,j),Tp("additions",R,j))}this.pushFileLevelAnnotations(e,r,t,j),qr({diff:e,diffStyle:r,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:l?!0:this.expandedHunks,collapsedContextThreshold:c,callback:({hunkIndex:R,hunk:B,collapsedBefore:H,collapsedAfter:oe,additionLine:te,deletionLine:O,type:V})=>{const J=O!=null?O.splitLineIndex:te.splitLineIndex,pe=te!=null?te.unifiedLineIndex:O.unifiedLineIndex;r==="split"&&V!=="change"&&C.flush(),H>0&&A({hunkIndex:R,collapsedLines:H,rangeSize:Math.max(B?.collapsedBefore??0,0),hunkSpecs:B?.hunkSpecs,isFirstHunk:R===0,isLastHunk:!1,isExpandable:g});const fe=r==="unified"?pe:J,_e={type:V,hunkIndex:R,lineIndex:fe,unifiedLineIndex:pe,splitLineIndex:J,deletionLine:O,additionLine:te};if(r==="unified"){const ie=this.getUnifiedInjectedRowsForLine?.(_e);ie?.before!=null&&Uw(ie.before,j);let Z=O!=null?_[O.lineIndex]:void 0,le=te!=null?b[te.lineIndex]:void 0;if(Z==null&&le==null){const Je="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(Je,{file:e.name}),new Error(Je)}const be=V==="change"?te!=null?"change-addition":"change-deletion":V,Fe=this.getUnifiedLineDecoration({type:V,lineType:be,additionLineIndex:te?.lineIndex,deletionLineIndex:O?.lineIndex});S("unified",Fe.gutterLineType,te!=null?te.lineNumber:O.lineNumber,`${pe},${J}`,Fe.gutterProperties),le!=null?le=Wd(le,Fe.contentProperties,h&&te!=null?{"data-line":te.lineNumber,"data-line-index":`${pe},${J}`}:void 0):Z!=null&&(Z=Wd(Z,Fe.contentProperties,h&&O!=null?{"data-line":O.lineNumber,"data-line-index":`${pe},${J}`}:void 0)),$d({diffStyle:"unified",type:V,deletionLine:Z,additionLine:le,unifiedSpan:this.getAnnotations("unified",O?.lineNumber,te?.lineNumber,R,fe),createAnnotationElement:Je=>this.createAnnotationElement(Je),context:j}),ie?.after!=null&&Uw(ie.after,j)}else{const ie=this.getSplitInjectedRowsForLine?.(_e);ie?.before!=null&&Kw(ie.before,j,C);let Z=O!=null?_[O.lineIndex]:void 0,le=te!=null?b[te.lineIndex]:void 0;const be=this.getSplitLineDecoration({side:"deletions",type:V,lineIndex:O?.lineIndex}),Fe=this.getSplitLineDecoration({side:"additions",type:V,lineIndex:te?.lineIndex});if(Z==null&&le==null){const et="DiffHunksRenderer.processDiffResult: deletionLine and additionLine are null, something is wrong";throw console.error(et,{file:e.name}),new Error(et)}const Je=(()=>{if(V==="change"){if(le==null)return"additions";if(Z==null)return"deletions"}})();Je!=null?(C.side!=null&&C.side!==Je&&C.flush(),C.side=Je,C.increment()):V==="change"&&C.flush();const We=this.getAnnotations("split",O?.lineNumber,te?.lineNumber,R,fe);if(We!=null&&C.size>0&&C.flush(),O!=null){const et=Wd(Z,be.contentProperties,h?{"data-line":O.lineNumber,"data-line-index":`${O.unifiedLineIndex},${J}`}:void 0);S("deletions",be.gutterLineType,O.lineNumber,`${O.unifiedLineIndex},${J}`,be.gutterProperties),et!=null&&(Z=et)}if(te!=null){const et=Wd(le,Fe.contentProperties,h?{"data-line":te.lineNumber,"data-line-index":`${te.unifiedLineIndex},${J}`}:void 0);S("additions",Fe.gutterLineType,te.lineNumber,`${te.unifiedLineIndex},${J}`,Fe.gutterProperties),et!=null&&(le=et)}$d({diffStyle:"split",type:V,additionLine:le,deletionLine:Z,...We,createAnnotationElement:et=>this.createAnnotationElement(et),context:j}),ie?.after!=null&&Kw(ie.after,j,C)}const Ee=r==="split"&&B!=null&&J===B.splitLineStart+B.splitLineCount-1,me=R===e.hunks.length-1&&B!=null&&(r==="split"?J===B.splitLineStart+B.splitLineCount-1:pe===B.unifiedLineStart+B.unifiedLineCount-1),W=Ee?B.noEOFCRDeletions:!1,G=Ee?B.noEOFCRAdditions:!1,de=(O?.noEOFCR??!1)||W,X=(te?.noEOFCR??!1)||G;if(X||de){if(r==="split"&&C.flush(),de){const ie=V==="context"||V==="context-expanded"?V:"change-deletion";r==="unified"?(j.unifiedContentAST.push(Bd(ie)),j.pushToGutter("unified",ri(ie,"metadata",1))):(j.deletionsContentAST.push(Bd(ie)),j.pushToGutter("deletions",ri(ie,"metadata",1)),X||(j.pushToGutter("additions",ri(void 0,"buffer",1)),j.additionsContentAST.push(Hd(1))))}if(X){const ie=V==="context"||V==="context-expanded"?V:"change-addition";r==="unified"?(j.unifiedContentAST.push(Bd(ie)),j.pushToGutter("unified",ri(ie,"metadata",1))):(j.additionsContentAST.push(Bd(ie)),j.pushToGutter("additions",ri(ie,"metadata",1)),de||(j.pushToGutter("deletions",ri(void 0,"buffer",1)),j.deletionsContentAST.push(Hd(1))))}j.incrementRowCount(1)}u!=="simple"&&u!=="metadata"&&(oe>0||me&&f)&&A({hunkIndex:V==="context-expanded"?R:R+1,collapsedLines:me&&f?"unknown":oe,rangeSize:N,hunkSpecs:void 0,isFirstHunk:!1,isLastHunk:!0,isExpandable:g}),j.incrementRowCount(1)}}),r==="split"&&C.flush();const E=Math.max(BU(e.hunks),e.additionLines.length??0,e.deletionLines.length??0),I=t.bufferBefore>0||t.bufferAfter>0,D=!p&&e.type!=="deleted",T=!p&&e.type!=="new",z=j.rowCount>0||I;x=D&&z?x:void 0,v=T&&z?v:void 0,y=p&&z?y:void 0;const $=this.createPreElement(v!=null&&x!=null,E);return{unifiedGutterAST:p&&z?j.unifiedGutterAST.children:void 0,unifiedContentAST:y,deletionsGutterAST:T&&z?j.deletionsGutterAST.children:void 0,deletionsContentAST:v,additionsGutterAST:D&&z?j.additionsGutterAST.children:void 0,additionsContentAST:x,hunkData:w,preNode:$,themeStyles:s,baseThemeType:o,headerElement:a?void 0:this.renderHeader(this.diff),totalLines:E,rowCount:j.rowCount,bufferBefore:t.bufferBefore,bufferAfter:t.bufferAfter,css:""}}renderCodeAST(e,t){const n=e==="unified"?t.unifiedGutterAST:e==="deletions"?t.deletionsGutterAST:t.additionsGutterAST,s=e==="unified"?t.unifiedContentAST:e==="deletions"?t.deletionsContentAST:t.additionsContentAST;if(n==null||s==null)return;const o=Dd(n);return o.properties.style=`grid-row: span ${t.rowCount}`,[o,$P(s,t.rowCount)]}renderFullAST(e,t=[]){const n=this.getOptionsWithDefaults().hunkSeparators==="line-info",s=this.renderCodeAST("unified",e);if(s!=null)return t.push(ms({tagName:"code",children:s,properties:{"data-code":"","data-container-size":n?"":void 0,"data-unified":""}})),{...e.preNode,children:t};const o=this.renderCodeAST("deletions",e);o!=null&&t.push(ms({tagName:"code",children:o,properties:{"data-code":"","data-container-size":n?"":void 0,"data-deletions":""}}));const r=this.renderCodeAST("additions",e);return r!=null&&t.push(ms({tagName:"code",children:r,properties:{"data-code":"","data-container-size":n?"":void 0,"data-additions":""}})),{...e.preNode,children:t}}renderFullHTML(e,t=[]){return rr(this.renderFullAST(e,t))}renderPartialHTML(e,t){return t==null?rr(e):rr(ms({tagName:"code",children:e,properties:{"data-code":"","data-container-size":this.getOptionsWithDefaults().hunkSeparators==="line-info"?"":void 0,[`data-${t}`]:""}}))}pushFileLevelAnnotations(e,t,n,s){if(!hk(n))return;const o=e.type!=="new"?Ww(Ov(this.deletionAnnotations)):[],r=e.type!=="deleted"?Ww(Ov(this.additionAnnotations)):[];if(o.length===0&&r.length===0)return;const a=-1,l=-1,{createAnnotationElement:d}=this;if(t==="unified"){$d({diffStyle:t,type:"context",unifiedSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o.concat(r)},createAnnotationElement:d,context:s});return}$d({diffStyle:t,type:"context",deletionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:o},additionSpan:{type:"annotation",hunkIndex:a,lineIndex:l,annotations:r},createAnnotationElement:d,context:s})}getAnnotations(e,t,n,s,o){const r={type:"annotation",hunkIndex:s,lineIndex:o,annotations:[]};if(t!=null)for(const l of this.deletionAnnotations[t]??[])r.annotations.push(sa(l));const a={type:"annotation",hunkIndex:s,lineIndex:o,annotations:[]};if(n!=null)for(const l of this.additionAnnotations[n]??[])(e==="unified"?r:a).annotations.push(sa(l));if(e==="unified")return r.annotations.length>0?r:void 0;if(!(a.annotations.length===0&&r.annotations.length===0))return{deletionSpan:r,additionSpan:a}}renderHeader(e){const{headerRenderMode:t,stickyHeader:n}=this.getOptionsWithDefaults();return WP({fileOrDiff:e,mode:t,stickyHeader:n})}};function Ww(e){return e?.map(t=>sa(t))??[]}const x8=new Intl.PluralRules("en-US");function v8(e){return`${e} unmodified line${x8.select(e)==="one"?"":"s"}`}function Uw(e,t){for(const n of e)t.unifiedContentAST.push(n.content),t.pushToGutter("unified",n.gutter),t.incrementRowCount(1)}function Kw(e,t,n){for(const{deletion:s,addition:o}of e){if(s==null&&o==null)continue;const r=s!=null&&o!=null?void 0:s==null?"deletions":"additions";(r==null||n.side!==r)&&n.flush(),s!=null&&(t.deletionsContentAST.push(s.content),t.pushToGutter("deletions",s.gutter)),o!=null&&(t.additionsContentAST.push(o.content),t.pushToGutter("additions",o.gutter)),r!=null&&(n.side=r,n.increment()),t.incrementRowCount(1)}}function $d({diffStyle:e,type:t,deletionLine:n,additionLine:s,unifiedSpan:o,deletionSpan:r,additionSpan:a,createAnnotationElement:l,context:d}){let c=!1;if(e==="unified"){if(s!=null?d.unifiedContentAST.push(s):n!=null&&d.unifiedContentAST.push(n),o!=null){const u=t==="change"?n!=null?"change-deletion":"change-addition":t;d.unifiedContentAST.push(l(o)),d.pushToGutter("unified",ri(u,"annotation",1)),c=!0}}else if(e==="split"){if(n!=null&&d.deletionsContentAST.push(n),s!=null&&d.additionsContentAST.push(s),r!=null){const u=t==="change"?n!=null?"change-deletion":"context":t;d.deletionsContentAST.push(l(r)),d.pushToGutter("deletions",ri(u,"annotation",1)),c=!0}if(a!=null){const u=t==="change"?s!=null?"change-addition":"context":t;d.additionsContentAST.push(l(a)),d.pushToGutter("additions",ri(u,"annotation",1)),c=!0}}c&&d.incrementRowCount(1)}function Tp(e,{hunkIndex:t,collapsedLines:n,rangeSize:s,hunkSpecs:o,isFirstHunk:r,isLastHunk:a,isExpandable:l},d){if(typeof n=="number"&&n<=0)return;const c=e==="unified"?d.unifiedContentAST:e==="deletions"?d.deletionsContentAST:d.additionsContentAST;if(d.hunkSeparators==="metadata"){o!=null&&(d.pushToGutter(e,Tr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),c.push(Tr({type:"metadata",content:o,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&d.incrementRowCount(1));return}if(d.hunkSeparators==="simple"){t>0&&(d.pushToGutter(e,Tr({type:"simple",isFirstHunk:r,isLastHunk:!1})),c.push(Tr({type:"simple",isFirstHunk:r,isLastHunk:!1})),e!=="additions"&&d.incrementRowCount(1));return}const u=HU(e,t),h=s>d.expansionLineCount,p=l?t:void 0,f=typeof n=="number"?v8(n):"More unchanged context may be available";d.pushToGutter(e,Tr({type:d.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),c.push(Tr({type:d.hunkSeparators,content:f,expandIndex:p,chunked:h,slotName:u,isFirstHunk:r,isLastHunk:a})),e!=="additions"&&d.incrementRowCount(1),d.hunkData.push({slotName:u,hunkIndex:t,lines:typeof n=="number"?n:0,lineCountKnown:typeof n=="number",type:e,expandable:l?{up:!r,down:!a,chunked:h}:void 0})}function Wd(e,t,n){return e==null||e.type!=="element"||t==null&&n==null?e:{...e,properties:{...e.properties,...t,...n}}}function qw(e){return e.length>0&&e[e.length-1]===""?e.length-1:e.length}function b8(e,t,n,s){const o=qw(e),r=qw(t),a=Math.min(o,r);let l=0;for(;l<a&&e[l]===t[l];)l++;let d=0;for(;d<a-l&&e[o-1-d]===t[r-1-d];)d++;const c=new Array(t.length);for(let u=0;u<l;u++)c[u]=n[u];for(let u=0;u<d;u++)c[r-1-u]=n[o-1-u];o<e.length&&r<t.length&&(c[t.length-1]=n[e.length-1]);for(let u=e.length;u<t.length;u++)c[u]??=n[u];for(let u=l;u<t.length;u++)c[u]??=xm(u,s.getLineText(u));return c}function xm(e,t,n=e,s=e){return{type:"element",tagName:"div",properties:{"data-line":e+1,"data-line-index":`${n},${s}`,"data-line-type":"context"},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:t}]}]}}function w8(e,t){const n=[],s=S8(t);for(let o=0;o<e.lineCount;o++){const r=e.getLineText(o,!0);n.push(o<e.lineCount-1&&!y8(r)?r+s:r)}return n}function y8(e){return e.endsWith(`
|
|
52
|
-
`)||e.endsWith("\r")}function S8(e){for(const t of e){if(t.endsWith(`\r
|
|
53
|
-
`))return`\r
|
|
54
|
-
`;if(t.endsWith(`
|
|
55
|
-
`))return`
|
|
56
|
-
`;if(t.endsWith("\r"))return"\r"}return`
|
|
57
|
-
`}function Ud(e,t){return Math.max(e.additionLines.length,e.deletionLines.length)>t}function C8(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function k8(e,t){return e.lineNumber===t.lineNumber&&e.side===t.side&&e.metadata===t.metadata}function j8(e,t){return e.slotName===t.slotName&&e.hunkIndex===t.hunkIndex&&e.lines===t.lines&&e.lineCountKnown===t.lineCountKnown&&e.type===t.type&&e.expandable?.chunked===t.expandable?.chunked&&e.expandable?.up===t.expandable?.up&&e.expandable?.down===t.expandable?.down}async function vm(e,t=300){let n;try{await Promise.race([e(),new Promise(s=>{n=setTimeout(s,t)})])}finally{n!=null&&clearTimeout(n)}}function bm({oldFile:e,newFile:t},n){if(!(e===void 0&&t===void 0)){if(e===void 0||t===void 0)throw new Error(`${n}: Pass null for an intentionally missing oldFile or newFile side`);if(e===null){if(t===null)throw new Error(`${n}: You must pass oldFile, newFile, or both`);return{oldFile:e,newFile:t}}return t===null?{oldFile:e,newFile:t}:{oldFile:e,newFile:t}}}function _8(e){return{theme:e?.theme,disableLineNumbers:e?.disableLineNumbers,overflow:e?.overflow,collapsed:e?.collapsed,disableFileHeader:e?.disableFileHeader,disableVirtualizationBuffers:e?.disableVirtualizationBuffers,stickyHeader:e?.stickyHeader,preferredHighlighter:e?.preferredHighlighter,useCSSClasses:e?.useCSSClasses,useTokenTransformer:KP(e),tokenizeMaxLineLength:e?.tokenizeMaxLineLength,tokenizeMaxLength:e?.tokenizeMaxLength,diffStyle:e?.diffStyle,diffIndicators:e?.diffIndicators,disableBackground:e?.disableBackground,hunkSeparators:typeof e?.hunkSeparators=="function"?"custom":e?.hunkSeparators,expandUnchanged:e?.expandUnchanged,loadDiffFiles:e?.loadDiffFiles,collapsedContextThreshold:e?.collapsedContextThreshold,lineDiffType:e?.lineDiffType,maxLineDiffLength:e?.maxLineDiffLength,expansionLineCount:e?.expansionLineCount,headerRenderMode:e?.renderCustomHeader!=null?"custom":"default"}}function N8(e){return e.isPartial&&(e.type==="change"||e.type==="rename-changed"||e.type==="rename-pure")}let T8=-1;var cT=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file-diff:${++T8}`;type="file-diff";fileContainer;spriteSVG;pre;codeUnified;codeDeletions;codeAdditions;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;headerElement;headerPrefix;headerFilenameSuffix;headerMetadata;headerCustom;separatorCache=new Map;errorWrapper;placeHolder;hunksRenderer;resizeManager;scrollSyncManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;deletionFile;additionFile;fileDiff;renderRange;pendingFiles;appliedPreAttributes;lastRenderedHeaderHTML;cachedHeaderHTML;lastRowCount;mounted=!1;enabled=!0;editor;refreshViewTimeout;lineStateRefreshPending=!1;deferredSelectedLines;deferredEditorActiveLine;constructor(t={theme:Ti},n,s=!1){this.options=t,this.workerManager=n,this.isContainerManaged=s,this.hunksRenderer=this.createHunksRenderer(t),this.resizeManager=new qP,this.scrollSyncManager=new FU,this.interactionManager=new YP("diff",zv(t,typeof t.hunkSeparators=="function"||(t.hunkSeparators??"line-info")==="line-info"||t.hunkSeparators==="line-info-basic"?this.handleExpandHunk:void 0,this.getLineIndex)),this.workerManager?.subscribeToThemeChanges(this),this.enabled=!0}handleHighlightRender=()=>{this.rerender()};getHunksRendererOptions(t){return _8(t)}createHunksRenderer(t){return new g8(this.getHunksRendererOptions(t),this.handleHighlightRender,this.workerManager)}getLineIndex=(t,n="additions")=>{const s=this.fileDiffCache;if(s==null)return;const o=s.hunks.at(-1);let r,a;e:for(const l of s.hunks){const d=n==="deletions"?l.deletionStart:l.additionStart,c=n==="deletions"?l.deletionCount:l.additionCount;let u=ga(d,c)+1,h=l.splitLineStart,p=l.unifiedLineStart;if(t<u){const f=u-t;r=Math.max(p-f,0),a=Math.max(h-f,0);break e}if(t>=u+c){if(l===o){const f=t-(u+c);r=p+l.unifiedLineCount+f,a=h+l.splitLineCount+f;break e}continue}for(const f of l.hunkContent)if(f.type==="context")if(t<u+f.lines){const g=t-u;a=h+g,r=p+g;break e}else u+=f.lines,h+=f.lines,p+=f.lines;else{const g=n==="deletions"?f.deletions:f.additions;if(t<u+g){const x=t-u;r=p+(n==="additions"?f.deletions:0)+x,a=h+x;break e}else u+=g,h+=Math.max(f.deletions,f.additions),p+=f.deletions+f.additions}break e}if(!(r==null||a==null))return[r,a]};setOptions(t){t!=null&&(this.options=t,this.cachedHeaderHTML=void 0,this.hunksRenderer.setOptions(this.getHunksRendererOptions(t)),this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(zv(this.options,typeof this.options.hunkSeparators=="function"||(this.options.hunkSeparators??"line-info")==="line-info"||this.options.hunkSeparators==="line-info-basic"?this.handleExpandHunk:void 0,this.getLineIndex))}mergeOptions(t){this.options={...this.options,...t}}setThemeType(t){(this.options.themeType??"system")!==t&&(this.mergeOptions({themeType:t}),this.applyCachedThemeState(t))}applyCachedThemeState(t){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const n=this.appliedThemeCSS.baseThemeType??t;return this.appliedThemeCSS.themeType===n?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,t,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!pk(this.appliedThemeCSS.theme,this.options.theme??Ti)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(t){this.lineAnnotations=t}canPartiallyRender(t,n,s){return!(t||n||s||typeof this.options.hunkSeparators=="function")}setSelectedLines(t,n){this.lineStateRefreshPending?this.deferredSelectedLines=[t,n]:this.interactionManager.setSelection(t,n)}setEditorActiveLine(t,n){this.lineStateRefreshPending?this.deferredEditorActiveLine=[t,n]:this.interactionManager.setEditorActiveLine(t,{lineNumberOnly:n?.lineNumberOnly,side:n?.side??"additions"})}flushDeferredLineState(){const{deferredEditorActiveLine:t,deferredSelectedLines:n}=this;this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,t!=null&&this.setEditorActiveLine(...t),n!=null&&this.interactionManager.setSelection(...n)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{diffStyle:t="split",overflow:n="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,{disableAnnotations:n==="wrap",columnVariables:this.shouldApplyColumnVariables(n)?"apply":"measure"}),n==="scroll"&&t==="split"?this.scrollSyncManager.setup(this.pre,this.codeDeletions,this.codeAdditions):this.scrollSyncManager.cleanUp(),this.managersDirty=!1}shouldApplyColumnVariables(t){return typeof this.options.hunkSeparators=="function"?!0:t==="scroll"&&(this.lineAnnotations.length>0||this.pre?.hasAttribute("data-has-merge-conflict")===!0)}getCodeScrollLeft(){return Math.max(this.codeUnified?.scrollLeft??0,this.codeDeletions?.scrollLeft??0,this.codeAdditions?.scrollLeft??0)}setCodeScrollLeft(t){this.codeUnified!=null&&(this.codeUnified.scrollLeft=t),this.codeAdditions!=null&&(this.codeAdditions.scrollLeft=t),this.codeDeletions!=null&&(this.codeDeletions.scrollLeft=t)}__getEffectiveCodeOptions(){return{...this.options,...this.hunksRenderer.getEffectiveCodeOptions()}}cleanUp(t=!1){hf(this.handleEditSessionRender),this.emitPostRender(!0),this.editor?.cleanUp(t),this.editor=void 0,this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.pendingFiles=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,t||(this.lineAnnotations=[]),this.clearAuxiliaryNodes(),this.annotationCache.clear(),this.pre=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.placeHolder?.remove(),this.placeHolder=void 0,this.lastRenderedHeaderHTML=void 0,t||(this.cachedHeaderHTML=void 0),this.errorWrapper?.remove(),this.errorWrapper=void 0,this.spriteSVG=void 0,this.lastRowCount=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,t?this.hunksRenderer.recycle():(this.hunksRenderer.cleanUp(),this.workerManager=void 0,this.fileDiff=void 0,this.deletionFile=void 0,this.additionFile=void 0),this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!1,this.deferredEditorActiveLine=void 0,this.deferredSelectedLines=void 0,this.enabled=!1}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate({fileContainer:t,prerenderedHTML:n,preventEmit:s=!1,lineAnnotations:o,fileDiff:r,...a}){if(!this.enabled)throw new Error("FileDiff.hydrate: attempting to call hydrate after cleaned up");if(this.fileContainer!=null)throw new Error("FileDiff.hydrate: hydrate can only be called before the instance has rendered or hydrated");const l=bm(a,"FileDiff.hydrate"),d=l?.oldFile,c=l?.newFile;this.hydrateElements(t,n),E8(this.pre,D8({fileDiff:r,oldFile:d,newFile:c}),this.options.collapsed)||P8(this.headerElement,I8({fileDiff:r,oldFile:d,newFile:c}),this.options.disableFileHeader)?this.render({...a,fileContainer:t,lineAnnotations:o,fileDiff:r,preventEmit:!0}):this.hydrationSetup({fileDiff:r,lineAnnotations:o,...l}),s||this.emitPostRender()}hydrateElements(t,n){this.fileContainer!==t&&this.emitPostRender(!0),XP(t,n);for(const s of t.shadowRoot?.children??[]){if(s instanceof SVGElement){this.spriteSVG=s;continue}if(s instanceof HTMLElement){if(s instanceof HTMLPreElement){this.pre=s;for(const o of s.children)!(o instanceof HTMLElement)||o.tagName.toLowerCase()!=="code"||("deletions"in o.dataset&&(this.codeDeletions=o),"additions"in o.dataset&&(this.codeAdditions=o),"unified"in o.dataset&&(this.codeUnified=o));continue}if("diffsHeader"in s.dataset){this.headerElement=s;continue}if(s instanceof HTMLStyleElement&&s.hasAttribute("data-theme-css")){this.themeCSSStyle=s;continue}if(s instanceof HTMLStyleElement&&s.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=s,this.appliedUnsafeCSS=s.textContent;continue}}}this.pre!=null&&(this.syncCodeNodesFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=t,this.hydrateMeasuredScrollbar()}hydrationSetup({fileDiff:t,oldFile:n,newFile:s,lineAnnotations:o}){this.lineAnnotations=o??this.lineAnnotations,this.additionFile=s,this.deletionFile=n,this.fileDiff=t??(n!==void 0&&s!==void 0?go(n,s,this.options.parseDiffOptions):void 0),this.pre!=null&&(this.syncInteractionOptions(),this.hunksRenderer.hydrate(this.fileDiff),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}rerender(){!this.enabled||this.fileDiff==null&&this.additionFile==null&&this.deletionFile==null||this.render({forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.hunksRenderer.clearRenderCache(),this.rerender()}handleExpandHunk=(t,n,s)=>{this.expandHunk(t,n,s)};expandHunk=(t,n,s)=>{this.hunksRenderer.expandHunk(t,n,s),this.loadFilesIfNecessary(),this.rerender()};loadFilesIfNecessary(){const{fileDiff:t,options:{loadDiffFiles:n}}=this;t==null||n==null||!N8(t)||this.pendingFiles?.fileDiff===t||(this.pendingFiles={fileDiff:t,promise:this.loadFilesForDiff(t,n)})}async loadFilesForDiff(t,n){try{const s=await n(t);if(!this.enabled||this.fileDiff!==t)return;await this.handleFilesLoaded(t,s)}catch(s){if(this.options.disableErrorHandling===!0)throw s;console.error(s)}finally{this.pendingFiles?.fileDiff===t&&(this.pendingFiles=void 0)}}async handleFilesLoaded(t,n){this.fileDiff!==t||!t.isPartial||(hm("merge",t,n),this.setHydratedState(n),await vm(()=>this.primeHighlightCache(t)),!(!this.enabled||this.fileDiff!==t)&&this.rerender())}setHydratedState(t){this.deletionFile=t.oldFile,this.additionFile=t.newFile,this.workerManager?.cleanUpTasks(this.hunksRenderer),this.hunksRenderer.clearRenderCache()}render({fileDiff:t,deferManagers:n=!1,forceRender:s=!1,preventEmit:o=!1,lineAnnotations:r,fileContainer:a,containerWrapper:l,renderRange:d,...c}){const u=bm(c,"FileDiff.render"),h=u?.oldFile,p=u?.newFile;if(!this.enabled)throw new Error("FileDiff.render: attempting to call render after cleaned up");t!=null&&t.cacheKey===void 0&&(t.cacheKey=t.prevName!=null?t.prevName+":"+t.name:t.name),this.editor?.__postponeBgTokenizeToNextFrame();const{collapsed:f=!1,themeType:g="system",expandUnchanged:x=!1}=this.options,v=f?void 0:d,y=this.hasThemeChanged(),w=u!=null,b=w&&(!Yw(h,this.deletionFile)||!Yw(p,this.additionFile));let _=t!=null&&t!==this.fileDiff;const j=r!=null&&(r.length>0||this.lineAnnotations.length>0)?r!==this.lineAnnotations:!1;if(!f&&uk(v,this.renderRange)&&!s&&!j&&!y&&(t!=null&&t===this.fileDiff||t==null&&!b))return this.applyCachedThemeState(g);let N;t==null&&w&&(b||this.fileDiff==null)&&(N=go(u.oldFile,u.newFile,this.options.parseDiffOptions));const{renderRange:C}=this;if(this.renderRange=v,w?(this.deletionFile=h,this.additionFile=p):t!=null&&(this.deletionFile=void 0,this.additionFile=void 0),t!=null?this.fileDiff=t:N!=null&&(_=!0,this.fileDiff=N),_&&(this.cachedHeaderHTML=void 0),r!=null&&this.setLineAnnotations(r),this.fileDiff==null)return!1;this.fileDiff.editSessionDirty===!0&&this.shouldSelfHealEditSession()&&(gm(this.fileDiff,this.options.parseDiffOptions),this.hunksRenderer.refreshHighlightedResult()),x&&this.loadFilesIfNecessary(),this.hunksRenderer.setOptions(this.getHunksRendererOptions(this.options)),this.syncInteractionOptions(),this.hunksRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:S=!1,disableFileHeader:A=!1}=this.options;if(A&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),a=this.getOrCreateFileContainer(a,l),this.applyCachedThemeState(g),f){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const E=this.hunksRenderer.renderDiff(this.fileDiff,ZP);E!=null&&this.applyThemeState(a,E.themeStyles,g,E.baseThemeType),E?.headerElement!=null&&this.applyHeaderToDOM(E.headerElement,a),this.renderSeparators([]),this.injectUnsafeCSS()}catch(E){if(S)throw E;console.error(E),E instanceof Error&&this.applyErrorToDOM(E,a)}return o||this.emitPostRender(),!0}try{const E=this.getOrCreatePreNode(a);if(!(this.canPartiallyRender(s,j,b||_||y)&&this.applyPartialRender({previousRenderRange:C,renderRange:v}))){const I=this.hunksRenderer.renderDiff(this.fileDiff,v);if(I==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(a,I.themeStyles,g,I.baseThemeType),I.headerElement!=null&&this.applyHeaderToDOM(I.headerElement,a),I.additionsContentAST!=null||I.deletionsContentAST!=null||I.unifiedContentAST!=null?this.applyHunksToDOM(E,I):this.pre!=null&&(this.pre.remove(),this.pre=void 0),this.renderSeparators(I.hunkData)}this.applyBuffers(E,v),this.injectUnsafeCSS(),this.renderAnnotations(),this.renderGutterUtility(),this.managersDirty=!0,n||this.flushManagers(),this.editor!=null&&this.syncRenderViewToEditor()}catch(E){if(S)throw E;console.error(E),E instanceof Error&&this.applyErrorToDOM(E,a)}return o||this.emitPostRender(),!0}emitPostRender(t=!1){const{fileContainer:n,options:{onPostRender:s}}=this;if(t){if(!this.mounted||(this.mounted=!1,n==null))return;this.options.onPostRender?.(n,this,"unmount");return}if(n==null)return;const o=this.mounted?"update":"mount";this.mounted=!0,s?.(n,this,o)}get fileDiffCache(){return this.hunksRenderer.diffCache??this.fileDiff}syncRenderViewToEditor(){const t=this.editor,n=this.fileContainer,s=this.fileDiffCache,o=this.lineAnnotations,r=this.computeEditorRenderRange(this.renderRange);t!=null&&n!=null&&s!=null&&!s.isPartial&&this.hunksRenderer.initializeHighlighter().then(a=>{!this.enabled||this.editor!==t||this.fileContainer!==n||this.fileDiffCache!==s||t.__syncRenderView(a,n,s,o,r)})}computeEditorRenderRange(t){const n=this.fileDiffCache;if(t==null||n==null||pm(t))return t;const{diffStyle:s="split",expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;let a,l;return qr({diff:n,diffStyle:s,startingLine:t.startingLine,totalLines:t.totalLines,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r,callback:({additionLine:d})=>{d!=null&&(a??=d.lineNumber,l=d.lineNumber)}}),a==null||l==null?{...t,startingLine:0,totalLines:0}:{...t,startingLine:a-1,totalLines:l-a+1}}attachEditor(t){if(this.type!=="file-diff")throw new Error(`FileDiff.attachEditor: cannot attach an editor to a "${this.type}" diff`);return this.editor?.cleanUp(),this.editor=t,this.hunksRenderer.beginEditSession(),this.fileDiff?.isPartial===!0&&this.loadFilesIfNecessary(),this.hunksRenderer.editorRenderReady()?this.syncRenderViewToEditor():this.rerender(),n=>{this.editor=void 0,n!==!0&&this.finishEditSession()}}finishEditSession(){this.hunksRenderer.endEditSession(),this.completeEditSession()}completeEditSession(){const t=this.fileDiffCache;if(t==null||t.editSessionDirty!==!0)return!1;const{collapsedContextThreshold:n=1}=this.options,s=i8(t,this.hunksRenderer.getExpandedHunksMap(),n);return gm(t,this.options.parseDiffOptions),this.hunksRenderer.setExpandedHunksMap(o8(t,s)),this.hunksRenderer.refreshHighlightedResult(),this.escalateEditSessionRender(),!0}applyDocumentChange(t,n){this.hunksRenderer.applyDocumentChange(t);const s=this.hunksRenderer.diffCache;if(s!=null){const o=this.fileDiff?.cacheKey;o!=null&&s.cacheKey==null&&(s.cacheKey=o),this.fileDiff=s}n!==void 0&&n!==this.lineAnnotations&&(this.setLineAnnotations(n),this.hunksRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations()),this.rerender(),this.interactionManager.setSelectionDirty()}updateRenderCache(t,n,s={}){const{shouldRefreshDiffsView:o,lineCountChangeInFlight:r}=s;if(this.hunksRenderer.updateRenderCache(t,n,r)){this.refreshViewTimeout!=null&&(clearTimeout(this.refreshViewTimeout),this.refreshViewTimeout=void 0),this.lineStateRefreshPending=!0,this.escalateEditSessionRender();return}o===!0&&(this.refreshViewTimeout!=null&&clearTimeout(this.refreshViewTimeout),this.lineStateRefreshPending=!0,this.refreshViewTimeout=setTimeout(()=>{this.refreshViewTimeout=void 0,this.options.diffStyle==="split"?this.refreshSplitDiffView():this.refreshUnifiedDiffView(),this.flushDeferredLineState()},150))}isLineRenderable(t){const n=this.fileDiffCache;if(n==null)return!0;const{expandUnchanged:s=!1,collapsedContextThreshold:o=1}=this.options;return fk({fileDiff:n,lineNumber:t,expandedHunks:s?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:o})}getNearestRenderableLine(t,n){const s=this.fileDiffCache;if(s==null)return t;const{expandUnchanged:o=!1,collapsedContextThreshold:r=1}=this.options;return JP({fileDiff:s,lineNumber:t,direction:n,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:r})}revealLine(t){const n=this.fileDiffCache,{expandUnchanged:s=!1,collapsedContextThreshold:o=1,expansionLineCount:r=100}=this.options;if(n==null||n.isPartial||s)return!1;const a=this.hunksRenderer.getExpandedHunksMap();for(const[u,h]of n.hunks.entries()){const[p,f]=Gv(h);if(t<p){const g=Tl({isPartial:n.isPartial,rangeSize:h.collapsedBefore,expandedHunks:a,hunkIndex:u,collapsedContextThreshold:o}),x=p-g.rangeSize;if(g.renderAll||t<x+g.fromStart||t>=p-g.fromEnd)return!1;const v=t-(x+g.fromStart)+1,y=p-g.fromEnd-t;return v<=y?this.expandHunk(u,"up",v+r):this.expandHunk(u,"down",y+r),!0}if(t<f)return!1}const l=Dl({fileDiff:n,hunkIndex:n.hunks.length-1,expandedHunks:a,collapsedContextThreshold:o,errorPrefix:"FileDiff.revealLine"});if(l==null||l.renderAll)return!1;const d=n.hunks[n.hunks.length-1],[,c]=Gv(d);return t<c+l.fromStart||t>=c+l.rangeSize?!1:(this.expandHunk(n.hunks.length,"up",t-(c+l.fromStart)+1+r),!0)}shouldSelfHealEditSession(){return this.editor==null}escalateEditSessionRender(){mk(this.handleEditSessionRender)}handleEditSessionRender=()=>{this.rerender(),this.flushDeferredLineState()};removeRenderedCode(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:t}of this.separatorCache.values())t.remove();this.separatorCache.clear();for(const{element:t}of this.annotationCache.values())t.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}renderPlaceholder(t){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const n=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",n.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${t}px`),!0}async primeHighlightCache(t=this.fileDiff){const{workerManager:n}=this;if(t==null||n==null||!n.isWorkingPool()||t.cacheKey==null||kc(t))return;const s=this.options.tokenizeMaxLength??1e5;Math.max(t.additionLines.length,t.deletionLines.length)>s||await n.primeDiffHighlightCache(t).catch(o=>{console.error(o)})}cleanChildNodes(){this.resizeManager.cleanUp(),this.scrollSyncManager.cleanUp(),this.interactionManager.cleanUp(),this.clearAuxiliaryNodes(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.codeAdditions?.remove(),this.codeDeletions?.remove(),this.codeUnified?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.codeAdditions=void 0,this.codeDeletions=void 0,this.codeUnified=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderSeparators(t){const{hunkSeparators:n}=this.options;if(this.isContainerManaged||this.fileContainer==null||typeof n!="function"){for(const{element:o}of this.separatorCache.values())o.remove();this.separatorCache.clear();return}const s=new Map(this.separatorCache);for(const o of t){const r=o.slotName;let a=this.separatorCache.get(r);if(a==null||!j8(o,a.hunkData)){a?.element.remove();const l=document.createElement("div");l.style.display="contents",l.slot=o.slotName;const d=n(o,this);d!=null&&l.appendChild(d),this.fileContainer.appendChild(l),a={element:l,hunkData:o},this.separatorCache.set(r,a)}s.delete(r)}for(const[o,{element:r}]of s.entries())this.separatorCache.delete(o),r.remove()}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:s}of this.annotationCache.values())s.remove();this.annotationCache.clear();return}const t=new Map(this.annotationCache),{renderAnnotation:n}=this.options;if(n!=null&&this.lineAnnotations.length>0)for(const[s,o]of this.lineAnnotations.entries()){const r=`${s}-${sa(o)}`;let a=this.annotationCache.get(r);if(a==null||!k8(o,a.annotation)){a?.element.remove();const l=n(o);if(l==null)continue;a={element:QP(sa(o)),annotation:o},a.element.appendChild(l),this.fileContainer.appendChild(a.element),this.annotationCache.set(r,a)}t.delete(r)}for(const[s,{element:o}]of t.entries())this.annotationCache.delete(s),o.remove()}renderGutterUtility(){const{renderGutterUtility:t}=this.options;if(this.fileContainer==null||t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=t(this.interactionManager.getHoveredLine);if(n!=null&&this.gutterUtilityContent!=null)return;if(n==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const s=eA();s.appendChild(n),this.fileContainer.appendChild(s),this.gutterUtilityContent=s}getOrCreateFileContainer(t,n){const{fileContainer:s}=this,o=t??s??document.createElement("diffs-container"),r=s!==o;return s!=null&&r&&this.editor?.__captureFocusForDOMReplacement(),r&&this.emitPostRender(!0),this.fileContainer=o,s!=null&&r&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),n!=null&&this.fileContainer.parentNode!==n&&n.appendChild(this.fileContainer),r&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(t){const{shadowRoot:n}=t;if(n!=null)for(const s of n.children)s instanceof SVGElement?this.spriteSVG??=s:pf(s)&&s.hasAttribute("data-theme-css")?(this.themeCSSStyle??=s,this.hasAdoptedThemeCSS=!0):pf(s)&&s.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=s,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(t){const n=t.shadowRoot??t.attachShadow({mode:"open"});if(this.spriteSVG==null){const s=document.createElement("div");s.innerHTML=tA;const o=s.firstChild;o instanceof SVGElement&&(this.spriteSVG=o)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==n&&n.appendChild(this.spriteSVG)}getOrCreatePreNode(t){const n=t.shadowRoot??t.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0,n.appendChild(this.pre)):this.pre.parentNode!==n&&(this.editor?.__captureFocusForDOMReplacement(),n.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodesFromPre(t){this.codeUnified=void 0,this.codeDeletions=void 0,this.codeAdditions=void 0;for(const n of Array.from(t.children))n instanceof HTMLElement&&(n.hasAttribute("data-unified")?this.codeUnified=n:n.hasAttribute("data-deletions")?this.codeDeletions=n:n.hasAttribute("data-additions")&&(this.codeAdditions=n))}applyHeaderToDOM(t,n){this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const{fileDiff:s}=this,o=this.cachedHeaderHTML??rr(t);if(this.cachedHeaderHTML=o,o!==this.lastRenderedHeaderHTML){const p=document.createElement("div");p.innerHTML=o;const f=p.firstElementChild;if(!(f instanceof HTMLElement))return;this.headerElement!=null?n.shadowRoot?.replaceChild(f,this.headerElement):n.shadowRoot?.prepend(f),this.headerElement=f,this.lastRenderedHeaderHTML=o}if(this.isContainerManaged||s==null)return;const{renderCustomHeader:r,renderHeaderPrefix:a,renderHeaderFilenameSuffix:l,renderHeaderMetadata:d}=this.options;if(r!=null){const p=r(s)??void 0;this.headerCustom=this.upsertHeaderSlotElement(n,this.headerCustom,gk,p),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0;return}const c=a?.(s)??void 0,u=l?.(s)??void 0,h=d?.(s)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(n,this.headerPrefix,nA,c),this.headerFilenameSuffix=this.upsertHeaderSlotElement(n,this.headerFilenameSuffix,sA,u),this.headerMetadata=this.upsertHeaderSlotElement(n,this.headerMetadata,iA,h),this.headerCustom?.remove(),this.headerCustom=void 0}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(t,n,s,o){if(o==null){n?.remove();return}const r=n??this.createHeaderSlotElement(s);return n==null&&t.appendChild(r),this.replaceHeaderSlotContent(r,o),r}replaceHeaderSlotContent(t,n){t.replaceChildren(),n instanceof Element?t.appendChild(n):t.innerText=`${n}`}createHeaderSlotElement(t){const n=document.createElement("div");return n.slot=t,n}injectUnsafeCSS(){const{unsafeCSS:t}=this.options,n=this.fileContainer?.shadowRoot;if(n!=null){if(t==null||t===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===n&&this.appliedUnsafeCSS===t||(this.unsafeCSSStyle??=oA(),this.unsafeCSSStyle.parentNode!==n&&n.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=rA(t),this.appliedUnsafeCSS=t)}}applyThemeState(t,n,s,o){const r=t.shadowRoot??t.attachShadow({mode:"open"}),a=o??s,l=this.options.theme??Ti,d=typeof l=="string"?l:{...l},c=Fv(r);if(this.themeCSSStyle?.parentNode===r&&this.appliedThemeCSS?.themeStyles===n&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===c){this.appliedThemeCSS.theme=d;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===r){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:d,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:c};return}this.themeCSSStyle=aA({shadowRoot:r,currentNode:this.themeCSSStyle,themeCSS:hA(n,a,c)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:d,themeStyles:n,themeType:a,baseThemeType:o,scrollbarGutter:c}:void 0}hydrateMeasuredScrollbar(){const t=this.fileContainer?.shadowRoot;t==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=lA(this.themeCSSStyle.textContent??"",Fv(t)))}shouldGuardRebuildScroll(){return this.editor!=null&&dA()}applyHunksToDOM(t,n){this.shouldGuardRebuildScroll()?Hv(t,()=>this.replaceCodeColumns(t,n)):this.replaceCodeColumns(t,n)}applyCodeColumnsInPlace(t,n,s){const o=this.getColumnPair(t);if(o==null)return!1;const r=ko(n[0]),a=ko(n[1]);return r==null||a==null?!1:(o.gutter.innerHTML=rr(r),o.content.innerHTML=rr(a),s!==this.lastRowCount&&(o.gutter.style.setProperty("grid-row",`span ${s}`),o.content.style.setProperty("grid-row",`span ${s}`)),!0)}replaceCodeColumns(t,n){const{overflow:s="scroll"}=this.options,o=(this.options.hunkSeparators??"line-info")==="line-info",r=s==="wrap"?n.rowCount:void 0;this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,n);let a=!1;const l=[],d=this.hunksRenderer.renderCodeAST("unified",n),c=this.hunksRenderer.renderCodeAST("deletions",n),u=this.hunksRenderer.renderCodeAST("additions",n);this.editor?.__captureFocusForDOMReplacement(),d!=null?(a=this.codeUnified==null||this.codeAdditions!=null||this.codeDeletions!=null,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0,this.codeUnified=Vh({code:this.codeUnified,columnType:"unified",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeUnified,d,n.rowCount)||(this.codeUnified.innerHTML=this.hunksRenderer.renderPartialHTML(d)),l.push(this.codeUnified)):c!=null||u!=null?(c!=null?(a=this.codeDeletions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions=Vh({code:this.codeDeletions,columnType:"deletions",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeDeletions,c,n.rowCount)||(this.codeDeletions.innerHTML=this.hunksRenderer.renderPartialHTML(c)),l.push(this.codeDeletions)):(this.codeDeletions?.remove(),this.codeDeletions=void 0),u!=null?(a=a||this.codeAdditions==null||this.codeUnified!=null,this.codeUnified?.remove(),this.codeUnified=void 0,this.codeAdditions=Vh({code:this.codeAdditions,columnType:"additions",rowSpan:r,containerSize:o}),this.applyCodeColumnsInPlace(this.codeAdditions,u,n.rowCount)||(this.codeAdditions.innerHTML=this.hunksRenderer.renderPartialHTML(u)),l.push(this.codeAdditions)):(this.codeAdditions?.remove(),this.codeAdditions=void 0)):(this.codeUnified?.remove(),this.codeUnified=void 0,this.codeDeletions?.remove(),this.codeDeletions=void 0,this.codeAdditions?.remove(),this.codeAdditions=void 0),l.length===0?t.textContent="":a&&t.replaceChildren(...l),this.lastRowCount=n.rowCount}applyPartialRender({previousRenderRange:t,renderRange:n}){const{pre:s,codeUnified:o,codeAdditions:r,codeDeletions:a,options:{diffStyle:l="split"}}=this;if(s==null||t==null||n==null||!Number.isFinite(t.totalLines)||!Number.isFinite(n.totalLines)||this.lastRowCount==null)return!1;const d=this.getCodeColumns(l,o,a,r);if(d==null)return!1;const c=t.startingLine,u=n.startingLine,h=c+t.totalLines,p=u+n.totalLines,f=Math.max(c,u),g=Math.min(h,p);if(g<=f)return!1;const x=Math.max(0,f-c),v=Math.max(0,h-g),y=this.trimColumns({columns:d,trimStart:x,trimEnd:v,previousStart:c,overlapStart:f,overlapEnd:g,diffStyle:l});if(y<0)throw new Error("FileDiff.applyPartialRender: failed to trim to overlap");if(this.lastRowCount<y)throw new Error("FileDiff.applyPartialRender: trimmed beyond DOM row count");let w=this.lastRowCount-y;const b=(C,S)=>{if(!(S<=0||this.fileDiff==null))return this.hunksRenderer.renderDiff(this.fileDiff,{startingLine:C,totalLines:S,bufferBefore:0,bufferAfter:0})},_=b(u,Math.max(f-u,0));if(_==null&&u<f)return!1;const j=b(g,Math.max(p-g,0));if(j==null&&p>g)return!1;const N=(C,S)=>{if(C!=null){if(l==="unified"&&!Array.isArray(d))this.insertPartialHTML(l,d,C,S);else if(l==="split"&&Array.isArray(d))this.insertPartialHTML(l,d,C,S);else throw new Error("FileDiff.applyPartialRender.applyChunk: invalid chunk application");w+=C.rowCount}};return this.cleanupErrorWrapper(),N(_,"afterbegin"),N(j,"beforeend"),this.lastRowCount!==w&&(this.applyRowSpan(l,d,w),this.lastRowCount=w),!0}insertPartialHTML(t,n,s,o){if(t==="unified"&&!Array.isArray(n)){const r=this.hunksRenderer.renderCodeAST("unified",s);this.renderPartialColumn(n,r,o)}else if(t==="split"&&Array.isArray(n)){const r=this.hunksRenderer.renderCodeAST("deletions",s),a=this.hunksRenderer.renderCodeAST("additions",s);this.renderPartialColumn(n[0],r,o),this.renderPartialColumn(n[1],a,o)}else throw new Error("FileDiff.insertPartialHTML: Invalid argument composition")}refreshSplitDiffView(){if(this.options.diffStyle!=="split")return;const t=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(t==null)return;const n=this.getCodeColumns("split",this.codeUnified,this.codeDeletions,this.codeAdditions);if(!Array.isArray(n))return;const s=(o,r)=>{if(r==null)return;const a=this.hunksRenderer.renderCodeAST(o,t),l=ko(a?.[0]),d=ko(a?.[1]);for(const[c,u]of[[r.gutter,l],[r.content,d]])if(u!=null&&c.childElementCount===u.length)for(let h=0;h<u.length;h++){const p=c.children[h],f=u[h].properties["data-line-type"];f!=null&&p.dataset.lineType!==f&&(p.dataset.lineType=f)}};s("deletions",n[0]),s("additions",n[1])}refreshUnifiedDiffView(){if(this.options.diffStyle!=="unified")return;const t=this.hunksRenderer.renderDiff(this.fileDiff,this.renderRange);if(t==null)return;const n=this.getCodeColumns("unified",this.codeUnified,this.codeDeletions,this.codeAdditions);if(n==null||Array.isArray(n))return;const s=this.hunksRenderer.renderCodeAST("unified",t),o=ko(s?.[0]),r=ko(s?.[1]),a=()=>{for(const[l,d]of[[n.gutter,o],[n.content,r]])d!=null&&(l.innerHTML=rr(d));t.rowCount!==this.lastRowCount&&(this.applyRowSpan("unified",n,t.rowCount),this.lastRowCount=t.rowCount)};this.shouldGuardRebuildScroll()?Hv(this.pre,a):a(),this.renderSeparators(t.hunkData),this.managersDirty=!0,this.flushManagers(),this.syncRenderViewToEditor()}renderPartialColumn(t,n,s){if(t==null||n==null)return;const o=ko(n[0]),r=ko(n[1]);if(o==null||r==null)throw new Error("FileDiff.insertPartialHTML: Unexpected AST structure");const a=r.at(0);s==="beforeend"&&a?.type==="element"&&typeof a.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(a.properties["data-buffer-size"],t.content.children[t.content.children.length-1],t.gutter.children[t.gutter.children.length-1],o,r,!0);const l=r.at(-1);s==="afterbegin"&&l?.type==="element"&&typeof l.properties["data-buffer-size"]=="number"&&this.mergeBuffersIfNecessary(l.properties["data-buffer-size"],t.content.children[0],t.gutter.children[0],o,r,!1),t.gutter.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(o)),t.content.insertAdjacentHTML(s,this.hunksRenderer.renderPartialHTML(r))}mergeBuffersIfNecessary(t,n,s,o,r,a){if(!(n instanceof HTMLElement)||!(s instanceof HTMLElement))return;const l=this.getBufferSize(n.dataset);l!=null&&(a?(o.shift(),r.shift()):(o.pop(),r.pop()),this.updateBufferSize(n,l+t),this.updateBufferSize(s,l+t))}applyRowSpan(t,n,s){const o=r=>{r!=null&&(r.gutter.style.setProperty("grid-row",`span ${s}`),r.content.style.setProperty("grid-row",`span ${s}`))};if(t==="unified"&&!Array.isArray(n))o(n);else if(t==="split"&&Array.isArray(n))o(n[0]),o(n[1]);else throw new Error("dun fuuuuked up")}trimColumnRows(t,n,s){let o=0,r=0,a=0,l=!1;const d=s>=0;if(t==null)return 0;const c=Array.from(t.content.children),u=Array.from(t.gutter.children);if(c.length!==u.length)throw new Error("FileDiff.trimColumnRows: columns do not match");for(;a<c.length&&!(n<=0&&!d&&!l);){const h=u[a],p=c[a];if(a++,!(h instanceof HTMLElement)||!(p instanceof HTMLElement))throw console.error({gutterElement:h,contentElement:p}),new Error("FileDiff.trimColumnRows: invalid row elements");if(l&&(l=!1,h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset||h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset)){h.remove(),p.remove(),r++;continue}if("lineIndex"in h.dataset&&"lineIndex"in p.dataset){(n>0||d&&o>=s)&&(h.remove(),p.remove(),n>0&&(n--,n===0&&(l=!0)),r++),o++;continue}if("separator"in h.dataset&&"separator"in p.dataset){(n>0||d&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="annotation"&&"lineAnnotation"in p.dataset){(n>0||d&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="metadata"&&"noNewline"in p.dataset){(n>0||d&&o>=s)&&(h.remove(),p.remove(),r++);continue}if(h.dataset.gutterBuffer==="buffer"&&"contentBuffer"in p.dataset){const f=this.getBufferSize(p.dataset);if(f==null)throw new Error("FileDiff.trimColumnRows: invalid element");if(n>0){const g=Math.min(n,f),x=f-g;x>0?(this.updateBufferSize(h,x),this.updateBufferSize(p,x),r+=g):(h.remove(),p.remove(),r+=f),n-=g,n===0&&x===0&&(l=!0)}else if(d){const g=o,x=o+f-1;if(s<=g)h.remove(),p.remove(),r+=f;else if(s<=x){const v=x-s+1,y=f-v;this.updateBufferSize(h,y),this.updateBufferSize(p,y),r+=v}}o+=f;continue}throw console.error({gutterElement:h,contentElement:p}),new Error("FileDiff.trimColumnRows: unknown row elements")}return r}trimColumns({columns:t,diffStyle:n,overlapEnd:s,overlapStart:o,previousStart:r,trimEnd:a,trimStart:l}){const d=Math.max(0,o-r),c=s-r;if(c<0)throw new Error("FileDiff.trimColumns: overlap ends before previous");const u=l>0,h=a>0;if(!u&&!h)return 0;const p=u?d:0,f=h?c:-1;if(n==="unified"&&!Array.isArray(t))return this.trimColumnRows(t,p,f);if(n==="split"&&Array.isArray(t)){const g=this.trimColumnRows(t[0],p,f),x=this.trimColumnRows(t[1],p,f);if(t[0]!=null&&t[1]!=null&&g!==x)throw new Error("FileDiff.trimColumns: split columns out of sync");return t[0]!=null?g:x}else throw console.error({diffStyle:n,columns:t}),new Error("FileDiff.trimColumns: Invalid columns for diffType")}getBufferSize(t){const n=Number.parseInt(t?.bufferSize??"",10);return Number.isNaN(n)?void 0:n}updateBufferSize(t,n){t.dataset.bufferSize=`${n}`,t.style.setProperty("grid-row",`span ${n}`),t.style.setProperty("min-height",`calc(${n} * 1lh)`)}getColumnPair(t){if(t==null)return;const n=t.children[0],s=t.children[1];if(!(!(n instanceof HTMLElement)||!(s instanceof HTMLElement)||n.dataset.gutter==null||s.dataset.content==null))return{gutter:n,content:s}}getCodeColumns(t,n,s,o){if(t==="unified")return this.getColumnPair(n);{const r=this.getColumnPair(s),a=this.getColumnPair(o);return r!=null||a!=null?[r,a]:void 0}}updateBuffers(t){this.pre!=null&&this.applyBuffers(this.pre,t)}applyBuffers(t,n){if(n==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}n.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",t.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${n.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),n.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",t.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${n.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyPreNodeAttributes(t,{additionsContentAST:n,deletionsContentAST:s,totalLines:o},r){const{diffIndicators:a="bars",disableBackground:l=!1,disableLineNumbers:d=!1,overflow:c="scroll",diffStyle:u="split"}=this.options,h={type:"diff",diffIndicators:a,disableBackground:l,disableLineNumbers:d,overflow:c,split:u==="unified"?!1:n!=null&&s!=null,totalLines:o,customProperties:r};cA(h,this.appliedPreAttributes)||(uA(t,h),this.appliedPreAttributes=h)}applyErrorToDOM(t,n){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const s=n.shadowRoot??n.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",s.appendChild(this.errorWrapper);const o=document.createElement("div");o.dataset.errorMessage="",o.innerText=t.message,this.errorWrapper.appendChild(o);const r=document.createElement("pre");r.dataset.errorStack="",r.innerText=t.stack??"No Error Stack",this.errorWrapper.appendChild(r)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function Yw(e,t){return e==null||t==null?e==null&&t==null:xk(e,t)}function D8({fileDiff:e,oldFile:t,newFile:n}){return e!=null&&e.hunks.length>0||t!=null||n!=null}function I8({fileDiff:e,oldFile:t,newFile:n}){return e!=null||t!=null||n!=null}function E8(e,t,n=!1){return!n&&e==null&&t}function P8(e,t,n=!1){return e==null&&t&&!n}function ko(e){if(!(e==null||e.type!=="element"))return e.children??[]}function A8({fileDiff:e,metrics:t,disableFileHeader:n,hunkSeparators:s,expandUnchanged:o,expandedHunks:r,collapsedContextThreshold:a,canHydratePartialDiff:l}){let d=Lr(t,n),c=d;const u=o?!0:r,h=e.hunks.length-1;for(let p=0;p<e.hunks.length;p++){const f=e.hunks[p];if(f==null)throw new Error("computeEstimatedDiffHeights: invalid hunk index");const g=Tl({isPartial:e.isPartial,rangeSize:f.collapsedBefore,expandedHunks:u,hunkIndex:p,collapsedContextThreshold:a}),x=(g.fromStart+g.fromEnd)*t.lineHeight;if(d+=x,c+=x,g.collapsedLines>0){const w=qa({type:s,metrics:t,hunkIndex:p,hunkSpecs:f.hunkSpecs})?.totalHeight??0;d+=w,c+=w}d+=f.splitLineCount*t.lineHeight,c+=f.unifiedLineCount*t.lineHeight;const v=M8(f);d+=v.split*t.lineHeight,c+=v.unified*t.lineHeight;const y=p===h?Dl({fileDiff:e,hunkIndex:p,expandedHunks:u,collapsedContextThreshold:a,errorPrefix:"computeEstimatedDiffHeights"}):void 0;if(y!=null){const w=(y.fromStart+y.fromEnd)*t.lineHeight;if(d+=w,c+=w,y.collapsedLines>0){const b=or({type:s,metrics:t})?.totalHeight??0;d+=b,c+=b}}else if(p===h&&e.isPartial&&l){const w=or({type:s,metrics:t})?.totalHeight??0;d+=w,c+=w}}if(e.hunks.length>0){const p=vk(t);d+=p,c+=p}return{splitHeight:d,unifiedHeight:c}}function M8(e){if(!e.noEOFCRAdditions&&!e.noEOFCRDeletions)return{split:0,unified:0};const t=e.hunkContent.at(-1);if(t==null)return{split:0,unified:0};if(t.type==="context"){const n=t.lines>0?1:0;return{split:n,unified:n}}return R8(e,t)}function R8(e,t){const n=(t.deletions>0&&e.noEOFCRDeletions?1:0)+(t.additions>0&&e.noEOFCRAdditions?1:0),s=t.deletions>0&&e.noEOFCRDeletions,o=t.additions>0&&e.noEOFCRAdditions;return{split:s||o?1:0,unified:n}}const wm=3e3;let L8=-1;var uT=class extends cT{__id=`little-virtualized-file-diff:${++L8}`;top;height=0;metrics;cache={heightDeltas:new Map,measuredHeightDeltaTotal:0,estimatedSplitHeight:void 0,estimatedUnifiedHeight:void 0,checkpoints:[],totalLines:0,fileAnnotationHeight:0};isVisible=!1;isSetup=!1;virtualizer;layoutDirty=!0;forceRenderOverride;currentCollapsed;currentExpandUnchanged;pendingHydratedDiff;pendingExpansions;constructor(e,t,n,s,o=!1){super(e,s,o),this.virtualizer=t,this.metrics=$h(n)}setMetrics(e,t=!1){const n=$h(e);!t&&ff(this.metrics,n)||(this.metrics=n,this.resetLayoutCache({includeEstimatedHeights:!0}))}setLineAnnotations(e){this.syncLineAnnotations(e)&&this.resetLayoutCache({includeEstimatedHeights:!1})}syncLineAnnotations(e){return e==null||e===this.lineAnnotations||e.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(e),!0)}setFileAnnotationHeight(e){const t=this.cache.fileAnnotationHeight;return e===t?!1:(this.cache.fileAnnotationHeight=e,this.cache.measuredHeightDeltaTotal+=e-t,!0)}hasFileAnnotations(e=this.fileDiff){return e==null||!pA(this.lineAnnotations)?!1:this.lineAnnotations.some(t=>t.lineNumber!==0?!1:e.type==="new"?t.side==="additions":e.type==="deleted"?t.side==="deletions":!0)}getLineHeight(e,t=!1){return this.getEstimatedLineHeight(t)+(this.cache.heightDeltas.get(e)??0)}getEstimatedLineHeight(e=!1){const t=e?2:1;return this.metrics.lineHeight*t}setOptions(e){if(this.isAdvancedMode())throw new Error("VirtualizedFileDiff.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(e==null)return;const{options:t}=this,n=!Hu(t,e),s=n&&B8(t,e);super.setOptions(e),s&&this.resetLayoutCache({forceSimpleRecompute:!0,includeEstimatedHeights:V8(t,e)}),n&&(this.forceRenderOverride=!0),n&&this.isSimpleMode()&&this.virtualizer.instanceChanged(this,s)}setThemeType(e){if(this.isAdvancedMode())throw new Error("VirtualizedFileDiff.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(e)}resetLayoutCache({forceSimpleRecompute:e=!1,includeEstimatedHeights:t=!1,resetRenderRange:n=!0}={}){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heightDeltas.size>0&&this.cache.heightDeltas.clear(),this.cache.measuredHeightDeltaTotal!==0&&(this.cache.measuredHeightDeltaTotal=0),this.invalidateDerivedLayoutCache(t,n),e&&this.isSimpleMode()&&this.computeApproximateSize()}invalidateDerivedLayoutCache(e,t=!0){this.layoutDirty=!0,this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.cache.totalLines!==0&&(this.cache.totalLines=0),e&&(this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0),this.renderRange!=null&&t&&(this.renderRange=void 0)}reconcileHeights(){let e=!1;const{overflow:t="scroll"}=this.options;if(this.fileContainer==null||this.fileDiff==null)return this.height!==0&&(e=!0),this.height=0,e;if(this.top=this.getVirtualizedTop(),t==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled())return e;const n=this.getDiffStyle(),s=n==="split"?[this.codeDeletions,this.codeAdditions]:[this.codeUnified],o=this.hasFileAnnotations(this.fileDiff);if(this.renderRange!=null&&o&&hk(this.renderRange)){const r=O8(s)??0;this.setFileAnnotationHeight(r)&&(e=!0)}else!o&&this.setFileAnnotationHeight(0)&&(e=!0);for(const r of s){if(r==null)continue;const a=r.children[1];if(a instanceof HTMLElement)for(const l of a.children){if(!(l instanceof HTMLElement))continue;const d=l.dataset.lineIndex;if(d==null)continue;const c=W8(d,n);let u=l.getBoundingClientRect().height,h=!1;l.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in l.nextElementSibling.dataset||"noNewline"in l.nextElementSibling.dataset)&&("noNewline"in l.nextElementSibling.dataset&&(h=!0),u+=l.nextElementSibling.getBoundingClientRect().height);const p=this.getEstimatedLineHeight(h),f=this.cache.heightDeltas.get(c)??0,g=u-p;g!==f&&(e=!0,this.cache.measuredHeightDeltaTotal+=g-f,g===0?this.cache.heightDeltas.delete(c):this.cache.heightDeltas.set(c,g))}}return(e||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),e}onRender=e=>this.fileContainer==null?!1:(e&&(this.top=this.getVirtualizedTop()),this.render());flushManagers(){super.flushManagers(),this.lineStateRefreshPending&&this.flushDeferredLineState()}prepareCodeViewItem(e,t,n,s){const o=!Fr(this.fileDiff,e),r=this.syncLineAnnotations(s);let a=n?.resetDiffLayoutCache===!0||o||r,l=o||n?.resetDiffLayoutCache===!0&&n.includeEstimatedDiffHeights;n?.metrics!=null&&(this.metrics=$h(n.metrics),a=!0,l=!0);const{collapsed:d=!1,expandUnchanged:c=!1}=this.options;return this.currentCollapsed!==d&&(this.currentCollapsed=d,a=!0),this.currentExpandUnchanged!==c&&(this.currentExpandUnchanged=c,a=!0,l=!0),a&&this.resetLayoutCache({includeEstimatedHeights:l}),this.fileDiff=e,this.top=t,this.computeApproximateSize(),this.height}getLinePosition(e,t="additions"){if(this.fileDiff==null||e<1)return;const n=this.getLineIndex(e,t);if(n==null)return;const{disableFileHeader:s=!1,expandUnchanged:o=!1,collapsed:r=!1,collapsedContextThreshold:a=1}=this.options,l=this.getDiffStyle(),d=this.getHunkSeparatorType(),c=l==="split"?n[1]:n[0];this.approximateLayoutCheckpoints();const u=Lr(this.metrics,s),h=this.getLayoutCheckpointBeforeLineIndex(c);let p=h?.top??u+this.cache.fileAnnotationHeight;if(r)return{top:u,height:0};let f;return qr({diff:this.fileDiff,diffStyle:l,startingLine:h?.renderedLineIndex??0,expandedHunks:o?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:g,hunk:x,collapsedBefore:v,collapsedAfter:y,deletionLine:w,additionLine:b})=>{const _=l==="split"?b?.splitLineIndex??w?.splitLineIndex:b?.unifiedLineIndex??w?.unifiedLineIndex;if(_==null)throw new Error("VirtualizedFileDiff.getLinePosition: missing line index data");if(v>0){const N=qa({type:d,metrics:this.metrics,hunkIndex:g,hunkSpecs:x?.hunkSpecs});if(N!=null){if(p+=N.gapBefore,c>=_-v&&c<_)return f={top:p,height:N.height},!0;p+=N.height+N.gapAfter}}const j=this.getLineHeight(_,(b?.noEOFCR??!1)||(w?.noEOFCR??!1));if(_===c)return f={top:p,height:j},!0;if(p+=j,y>0){const N=or({type:d,metrics:this.metrics});if(N!=null){if(c>_&&c<=_+y)return f={top:p+N.gapBefore,height:N.height},!0;p+=N.totalHeight}}return!1}}),f}getEditorViewport(){return this.virtualizer.type==="simple"?this.virtualizer.getRoot():this.virtualizer.getContainerElement()}getNumericScrollAnchor(e){if(this.fileDiff==null)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsed:s=!1,collapsedContextThreshold:o=1}=this.options;if(s)return;const r=this.getDiffStyle(),a=this.getHunkSeparatorType();this.approximateLayoutCheckpoints();const l=this.getLayoutCheckpointBeforeTop(e);let d=l?.top??Lr(this.metrics,t)+this.cache.fileAnnotationHeight,c;return qr({diff:this.fileDiff,diffStyle:r,startingLine:l?.renderedLineIndex??0,expandedHunks:n?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:o,callback:({hunkIndex:u,hunk:h,collapsedBefore:p,collapsedAfter:f,deletionLine:g,additionLine:x})=>{const v=r==="split"?x?.splitLineIndex??g?.splitLineIndex:x?.unifiedLineIndex??g?.unifiedLineIndex;if(v==null)throw new Error("VirtualizedFileDiff.getNumericScrollAnchor: missing line index data");if(p>0){const w=qa({type:a,metrics:this.metrics,hunkIndex:u,hunkSpecs:h?.hunkSpecs});w!=null&&(d+=w.totalHeight)}if(d>=e&&(g!=null?c={lineNumber:g.lineNumber,side:"deletions",top:d}:x!=null&&(c={lineNumber:x.lineNumber,side:"additions",top:d}),c!=null))return!0;const y=this.getLineHeight(v,(x?.noEOFCR??!1)||(g?.noEOFCR??!1));if(d+=y,f>0){const w=or({type:a,metrics:this.metrics});w!=null&&(d+=w.totalHeight)}return!1}}),c}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(e){if(this.top==null||this.fileDiff==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const t=e!=null?this.computeRenderRangeFromWindow(this.fileDiff,this.top,e):this.renderRange;if(t==null)return;const{bufferBefore:n,bufferAfter:s,totalLines:o}=t;let r=0;if(o===0){const a=e??this.virtualizer.getWindowSpecs();this.top<a.top&&(r=s)}return{topOffset:this.top+n+r,height:this.height-(n+s)}}cleanUp(e=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),e||(this.resetLayoutCache({includeEstimatedHeights:!0}),this.pendingExpansions=void 0,this.pendingHydratedDiff=void 0),this.isSetup=!1,super.cleanUp(e)}expandHunk=(e,t,n)=>{this.fileDiff!=null&&(this.isAdvancedMode()?(this.pendingExpansions??=[],this.pendingExpansions.push({hunkIndex:e,direction:t,expansionLineCountOverride:n})):(this.hunksRenderer.expandHunk(e,t,n),this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()),this.loadFilesIfNecessary(),this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))};async handleFilesLoaded(e,t){if(!(this.fileDiff!==e||!e.isPartial)){if(this.isAdvancedMode()){const n=hm("clone",e,t);if(await vm(()=>this.primeHighlightCache(n)),!this.enabled||this.fileDiff!==e)return;this.pendingHydratedDiff={expectedDiff:e,nextDiff:n,files:t}}else{if(hm("merge",e,t),this.setHydratedState(t),await vm(()=>this.primeHighlightCache(e)),!this.enabled||this.fileDiff!==e)return;this.resetLayoutCache({includeEstimatedHeights:!0}),this.computeApproximateSize()}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}}consumeCodeViewLayoutChanges(e){let t=!1,n;const{pendingExpansions:s,pendingHydratedDiff:o}=this;if(s!=null){this.pendingExpansions=void 0;for(const r of s)this.hunksRenderer.expandHunk(r.hunkIndex,r.direction,r.expansionLineCountOverride),t=!0}return o!=null&&(this.pendingHydratedDiff=void 0,o.expectedDiff===e&&(this.setHydratedState(o.files),n=o.nextDiff)),n!=null?(this.forceRenderOverride=!0,this.resetLayoutCache({includeEstimatedHeights:!0})):t&&(this.forceRenderOverride=!0,this.invalidateDerivedLayoutCache(!0)),n}loadFilesIfNecessary(){if(this.pendingHydratedDiff!=null){if(this.pendingHydratedDiff.expectedDiff===this.fileDiff)return;this.pendingHydratedDiff=void 0}super.loadFilesIfNecessary()}isLineRenderable(e){if(super.isLineRenderable(e))return!0;const{pendingExpansions:t}=this,n=this.fileDiffCache;if(t==null||t.length===0||n==null)return!1;const{expansionLineCount:s=100,collapsedContextThreshold:o=1}=this.options,r=new Map(this.hunksRenderer.getExpandedHunksMap());for(const a of t){const l={...r.get(a.hunkIndex)??{fromStart:0,fromEnd:0}},d=a.expansionLineCountOverride??s;(a.direction==="up"||a.direction==="both")&&(l.fromStart+=d),(a.direction==="down"||a.direction==="both")&&(l.fromEnd+=d),r.set(a.hunkIndex,l)}return fk({fileDiff:n,lineNumber:e,expandedHunks:r,collapsedContextThreshold:o})}invalidateEditSessionLayout(){this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),this.isSimpleMode()||this.computeApproximateSize(!0),this.getSimpleVirtualizer()?.requestHeightReconcile(this)}escalateEditSessionRender(){this.invalidateEditSessionLayout(),!(!this.enabled||this.fileDiff==null)&&(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0))}shouldSelfHealEditSession(){return!this.isAdvancedMode()&&super.shouldSelfHealEditSession()}setVisibility(e){this.isAdvancedMode()||this.fileContainer==null||(this.renderRange=void 0,e&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!e&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.fileDiff==null&&this.additionFile==null&&this.deletionFile==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(e,t,n=!1){const{renderRange:s}=this;if(this.getAdvancedVirtualizer()?.capturePendingLayoutAnchor(),super.applyDocumentChange(e,t),this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache({forceSimpleRecompute:this.isSimpleMode(),includeEstimatedHeights:!0,resetRenderRange:!1}),!this.isSimpleMode())this.computeApproximateSize(!0);else if(n&&s!==void 0&&this.fileDiff!==void 0){const o=this.virtualizer.getWindowSpecs(),r=this.computeRenderRangeFromWindow(this.fileDiff,this.top??0,o);r.bufferAfter!==s.bufferAfter&&this.updateBuffers(r)}this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!0)}computeApproximateSize(e=!1,t=this.fileDiff){const n=this.isResizeDebuggingEnabled();if(!e&&!this.layoutDirty&&!n)return;const s=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.cache.totalLines=0,t==null){this.layoutDirty=!1;return}const{disableFileHeader:o=!1,collapsed:r=!1}=this.options,a=Lr(this.metrics,o);if(this.height+=a,r){this.layoutDirty=!1;return}this.height=this.getActiveEstimatedHeight(t)+this.cache.measuredHeightDeltaTotal,n&&!s&&this.validateComputedHeight(t),this.layoutDirty=!1}getActiveEstimatedHeight(e=this.fileDiff){this.ensureEstimatedDiffHeights(e);const t=this.getDiffStyle()==="split"?this.cache.estimatedSplitHeight:this.cache.estimatedUnifiedHeight;if(t==null)throw new Error("VirtualizedFileDiff.getActiveEstimatedHeight: missing estimated height");return t}ensureEstimatedDiffHeights(e=this.fileDiff){if(e==null){this.cache.estimatedSplitHeight=void 0,this.cache.estimatedUnifiedHeight=void 0;return}if(this.cache.estimatedSplitHeight!=null&&this.cache.estimatedUnifiedHeight!=null)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsedContextThreshold:s=1}=this.options,{splitHeight:o,unifiedHeight:r}=A8({fileDiff:e,metrics:this.metrics,disableFileHeader:t,hunkSeparators:this.getHunkSeparatorType(),expandUnchanged:n,expandedHunks:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:s,canHydratePartialDiff:Dp(e,this.options.loadDiffFiles!=null)});this.cache.estimatedSplitHeight=o,this.cache.estimatedUnifiedHeight=r}validateComputedHeight(e=this.fileDiff){if(this.fileContainer==null||e==null)return;const t=this.fileContainer.getBoundingClientRect();t.height!==this.height?console.log("VirtualizedFileDiff.computeApproximateSize: computed height doesnt match",{name:e.name,elementHeight:t.height,computedHeight:this.height}):console.log("VirtualizedFileDiff.computeApproximateSize: computed height IS CORRECT")}render({fileContainer:e,fileDiff:t,forceRender:n=!1,lineAnnotations:s,...o}={}){const r=bm(o,"VirtualizedFileDiff.render"),a=r!=null,l=r?.oldFile,d=r?.newFile,c=a&&(!Jw(l,this.deletionFile)||!Jw(d,this.additionFile));let u=t??this.fileDiff;t==null&&a&&(c||this.fileDiff==null)&&(u=go(r.oldFile,r.newFile,this.options.parseDiffOptions));const{forceRenderOverride:h,isSetup:p}=this;this.forceRenderOverride=void 0;const f=this.syncLineAnnotations(s);f&&this.resetLayoutCache({includeEstimatedHeights:!1});const g=t!=null&&t!==this.fileDiff,x=u!=null&&!Fr(this.fileDiff,u),v=g||c;if(x&&this.resetLayoutCache({includeEstimatedHeights:!0}),e=this.getOrCreateFileContainer(e),u==null)return console.error("VirtualizedFileDiff.render: attempting to virtually render when we dont have the correct data"),!1;if(p)this.top??=this.getVirtualizedTop(),x&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.computeApproximateSize(!1,u));else{this.computeApproximateSize(!1,u);const j=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(j==null)throw new Error("VirtualizedFileDiff.render: simple virtualizer is not available");j.connect(e,this),this.isVisible=j.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode()&&(!v||!p))return this.fileDiff=u,r!=null&&(this.deletionFile=l,this.additionFile=d),x&&(this.cachedHeaderHTML=void 0),this.renderPlaceholder(this.height);const y=this.virtualizer.getWindowSpecs(),w=this.top??0,b=this.computeRenderRangeFromWindow(u,w,y),_=super.render({fileDiff:u,fileContainer:e,renderRange:b,lineAnnotations:s,forceRender:(h??n)||f||x,...r,...o});return this.isSimpleMode()&&_&&this.getSimpleVirtualizer()?.requestHeightReconcile(this),_}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}shouldGuardRebuildScroll(){return!1}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}getAdvancedVirtualizer(){return this.virtualizer.type==="advanced"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}getDiffStyle(){return this.options.diffStyle??"split"}getHunkSeparatorType(){return $8(this.options.hunkSeparators)}approximateLayoutCheckpoints(e=this.fileDiff){if(!this.layoutDirty&&this.cache.checkpoints.length>0||e==null||e.hunks.length===0||this.options.collapsed===!0)return;const{disableFileHeader:t=!1,expandUnchanged:n=!1,collapsedContextThreshold:s=1}=this.options,o=e.hunks.length-1,r=Dp(e,this.options.loadDiffFiles!=null),a=this.getDiffStyle(),l=this.getHunkSeparatorType(),d=n?!0:this.hunksRenderer.getExpandedHunksMap(),c=z8(this.cache.heightDeltas);let u=Lr(this.metrics,t)+this.cache.fileAnnotationHeight,h=0;const p=({rowCount:f,startLineIndex:g,preSeparatorHeight:x=0,postSeparatorHeight:v=0,metadataOffsets:y=[]})=>{if(f<=0)return;const w=h,b=h+f;let _=G8(w);for(;_<b;){const j=_-w,N=u+(j>0?x:0)+j*this.metrics.lineHeight+F8(y,j)*this.metrics.lineHeight+Xw(c,g,g+j);this.cache.checkpoints.push({renderedLineIndex:_,lineIndex:g+j,top:N}),_+=wm}u+=x+f*this.metrics.lineHeight+y.length*this.metrics.lineHeight+Xw(c,g,g+f)+v,h=b};for(let f=0;f<e.hunks.length;f++){const g=e.hunks[f];if(g==null)throw new Error("VirtualizedFileDiff.approximateLayoutCheckpoints: invalid hunk index");const x=Tl({isPartial:e.isPartial,rangeSize:g.collapsedBefore,expandedHunks:d,hunkIndex:f,collapsedContextThreshold:s}),v=x.collapsedLines>0?qa({type:l,metrics:this.metrics,hunkIndex:f,hunkSpecs:g.hunkSpecs})?.totalHeight??0:0;p({rowCount:x.fromStart,startLineIndex:(a==="split"?g.splitLineStart:g.unifiedLineStart)-x.rangeSize});let y=v;p({rowCount:x.fromEnd,startLineIndex:(a==="split"?g.splitLineStart:g.unifiedLineStart)-x.fromEnd,preSeparatorHeight:y}),x.fromEnd>0&&(y=0);const w=f===o?Dl({fileDiff:e,hunkIndex:f,expandedHunks:d,collapsedContextThreshold:s,errorPrefix:"VirtualizedFileDiff"}):void 0,b=w!=null&&w.collapsedLines>0?or({type:l,metrics:this.metrics})?.totalHeight??0:f===o&&r?or({type:l,metrics:this.metrics})?.totalHeight??0:0,_=w!=null?w.fromStart+w.fromEnd:0,j=a==="split"?g.splitLineCount:g.unifiedLineCount,N=a==="split"?g.splitLineStart:g.unifiedLineStart;p({rowCount:j,startLineIndex:N,preSeparatorHeight:y,postSeparatorHeight:_===0?b:0,metadataOffsets:H8({diffStyle:a,hunk:g,rowCount:j})}),w!=null&&_>0&&p({rowCount:_,startLineIndex:N+j,postSeparatorHeight:b})}this.cache.totalLines=h}getLayoutCheckpointBeforeLineIndex(e){if(e<=0||this.cache.checkpoints.length===0)return;let t=0,n=this.cache.checkpoints.length-1,s;for(;t<=n;){const o=t+n>>1,r=this.cache.checkpoints[o];if(r==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");r.lineIndex<=e?(s=r,t=o+1):n=o-1}return s}getLayoutCheckpointBeforeTop(e,t){let n=0,s=this.cache.checkpoints.length-1,o=-1;for(;n<=s;){const r=n+s>>1,a=this.cache.checkpoints[r];if(a==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");a.top<=e?(o=r,n=r+1):s=r-1}if(t==null)return o>=0?this.cache.checkpoints[o]:void 0;for(let r=o;r>=0;r--){const a=this.cache.checkpoints[r];if(a==null)throw new Error("VirtualizedFileDiff: invalid checkpoint index");if(a.renderedLineIndex%t===0)return a}}getExpandedLineCount(e,t){let n=0;if(e.isPartial){for(const l of e.hunks)n+=t==="split"?l.splitLineCount:l.unifiedLineCount;return n}const{expandUnchanged:s=!1,collapsedContextThreshold:o=1}=this.options,r=s?!0:this.hunksRenderer.getExpandedHunksMap();for(const[l,d]of e.hunks.entries()){const c=t==="split"?d.splitLineCount:d.unifiedLineCount;n+=c;const u=Math.max(d.collapsedBefore,0),{fromStart:h,fromEnd:p,renderAll:f}=Tl({isPartial:e.isPartial,rangeSize:u,expandedHunks:r,hunkIndex:l,collapsedContextThreshold:o});u>0&&(n+=f?u:h+p)}const a=Dl({fileDiff:e,hunkIndex:e.hunks.length-1,expandedHunks:r,collapsedContextThreshold:o,errorPrefix:"VirtualizedFileDiff"});return a!=null&&(n+=a.fromStart+a.fromEnd),n}getLayoutLineCount(e,t){const n=this.getExpandedLineCount(e,t),s=t==="split"?e.splitLineCount:e.unifiedLineCount;return Math.max(n,s,e.additionLines.length,e.deletionLines.length,this.cache.totalLines)}computeRenderRangeFromWindow(e,t,{top:n,bottom:s}){const{disableFileHeader:o=!1,expandUnchanged:r=!1,collapsedContextThreshold:a=1}=this.options,{hunkLineCount:l,lineHeight:d}=this.metrics,c=this.getDiffStyle(),u=this.getHunkSeparatorType(),h=Dp(e,this.options.loadDiffFiles!=null),p=this.height;let f=this.getLayoutLineCount(e,c);const g=Lr(this.metrics,o),x=e.hunks.length>0?vk(this.metrics):0,{fileAnnotationHeight:v}=this.cache,y=g+v,w=Math.max(0,p-g-v-x),b=this.hasFileAnnotations(e),_=t+g,j=v>0&&b&&_<s&&_+v>n;if(t<n-p||t>s)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};if(f<=l||e.hunks.length===0)return{startingLine:0,totalLines:l,bufferBefore:0,bufferAfter:0};this.approximateLayoutCheckpoints(e),f=this.getLayoutLineCount(e,c);const N=Math.ceil(Math.max(s-n,0)/d),C=Math.ceil(N/l)*l+l,S=C/l,A=S,E=[],I=(n+s)/2,D=this.getLayoutCheckpointBeforeTop(Math.max(0,n-t-C*d*2),l);let T=t+(D?.top??y),z=D?.renderedLineIndex??0,$,R,B;if(qr({diff:e,diffStyle:c,startingLine:D?.renderedLineIndex??0,expandedHunks:r?!0:this.hunksRenderer.getExpandedHunksMap(),collapsedContextThreshold:a,callback:({hunkIndex:Ee,hunk:me,collapsedBefore:W,collapsedAfter:G,deletionLine:de,additionLine:X})=>{const ie=X!=null?X.splitLineIndex:de.splitLineIndex,Z=X!=null?X.unifiedLineIndex:de.unifiedLineIndex,le=(X?.noEOFCR??!1)||(de?.noEOFCR??!1),be=Ee===e.hunks.length-1&&me!=null&&(c==="split"?ie===me.splitLineStart+me.splitLineCount-1:Z===me.unifiedLineStart+me.unifiedLineCount-1),Fe=(W>0?qa({type:u,metrics:this.metrics,hunkIndex:Ee,hunkSpecs:me?.hunkSpecs}):void 0)?.totalHeight??0;T+=Fe;const Je=z%l===0,We=Math.floor(z/l);if(Je&&(E[We]=T-(t+y+Fe),B!=null)){if(B<=0)return!0;B--}const et=this.getLineHeight(c==="split"?ie:Z,le);if(T>n-et&&T<s&&($??=We),R==null&&T+et>I&&(R=We),B==null&&T>=s&&Je&&(B=A),z++,T+=et,G>0||be&&h){const qe=or({type:u,metrics:this.metrics});qe!=null&&(T<s&&T+qe.totalHeight>n&&($??=We),R==null&&T+qe.totalHeight>I&&(R=We),T+=qe.totalHeight)}return!1}}),$==null)if(j)$=0,R=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:p-g-x};R??=$;const H=Math.round(R-S/2),oe=Math.max(0,Math.ceil(f/l)-S),te=Math.max(0,Math.min(H,oe)),O=te*l,V=H<0?C+H*l:C,J=E[te]??0,pe=O===0?0:v+J,fe=te+V/l,_e=fe<E.length?w-E[fe]:w-(T-t-y);return{startingLine:O,totalLines:V,bufferBefore:pe,bufferAfter:Math.max(0,_e)}}};function O8(e){let t;for(const n of e){if(n==null)continue;const s=n.children[1];if(s instanceof HTMLElement)for(const o of s.children)o instanceof HTMLElement&&o.dataset.lineAnnotation===fA&&(t=Math.max(t??0,o.getBoundingClientRect().height))}return t}function z8(e){const t=Array.from(e).sort((r,a)=>r[0]-a[0]),n=[],s=[0];let o=0;for(const[r,a]of t)n.push(r),o+=a,s.push(o);return{lineIndexes:n,prefixTotals:s}}function Xw({lineIndexes:e,prefixTotals:t},n,s){if(n>=s||e.length===0)return 0;const o=Zw(e,n);return(t[Zw(e,s)]??0)-(t[o]??0)}function Zw(e,t){let n=0,s=e.length;for(;n<s;){const o=n+s>>1,r=e[o];if(r==null)throw new Error("VirtualizedFileDiff: invalid prefix index");r<t?n=o+1:s=o}return n}function G8(e){return Math.ceil(e/wm)*wm}function F8(e,t){let n=0;for(const s of e)s<t&&n++;return n}function H8({diffStyle:e,hunk:t,rowCount:n}){if(n<=0||!t.noEOFCRAdditions&&!t.noEOFCRDeletions)return[];const s=t.hunkContent.at(-1);if(s==null)return[];if(s.type==="context")return[n-1];const o=Math.max(s.deletions,s.additions),r=s.deletions+s.additions;if(e==="split")return o>0&&(t.noEOFCRAdditions||t.noEOFCRDeletions)?[n-1]:[];const a=[],l=n-r;return s.deletions>0&&t.noEOFCRDeletions&&a.push(l+s.deletions-1),s.additions>0&&t.noEOFCRAdditions&&a.push(n-1),a}function B8(e,t){return(e.diffStyle??"split")!==(t.diffStyle??"split")||(e.overflow??"scroll")!==(t.overflow??"scroll")||(e.collapsed??!1)!==(t.collapsed??!1)||(e.disableLineNumbers??!1)!==(t.disableLineNumbers??!1)||(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.diffIndicators??"bars")!==(t.diffIndicators??"bars")||(e.hunkSeparators??"line-info")!==(t.hunkSeparators??"line-info")||!!e.loadDiffFiles!=!!t.loadDiffFiles||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)||e.unsafeCSS!==t.unsafeCSS}function V8(e,t){return(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.hunkSeparators??"line-info")!==(t.hunkSeparators??"line-info")||!!e.loadDiffFiles!=!!t.loadDiffFiles||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function Dp(e,t){return e.isPartial&&t&&(e.type==="change"||e.type==="rename-changed")}function $8(e){return typeof e=="function"?"custom":e??"line-info"}function Jw(e,t){return e==null||t==null?e==null&&t==null:xk(e,t)}function W8(e,t){const[n,s]=e.split(",").map(Number);return t==="split"?s:n}function hT(e,t){return e==null||t==null?e===t:e.header!==t.header||e.footer!==t.footer?!1:U8(e.items,t.items)}function U8(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const s=e[n],o=t[n];if(s==null||o==null||s.id!==o.id||s.type!==o.type||s.element!==o.element||s.instance!==o.instance||s.version!==o.version)return!1}return!0}function K8(e,t,n){const s=document.createElement("div");return s.style.display="flow-root",e==="header"?(s.setAttribute(mA,""),t.before(s)):(s.setAttribute(gA,""),t.after(s)),n?.observe(s),s}function Si(e){const t=window.devicePixelRatio??1;return Math.round(e*t)/t}const q8=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","diffStyle","diffIndicators","disableBackground","expandUnchanged","loadDiffFiles","collapsedContextThreshold","lineDiffType","maxLineDiffLength","expansionLineCount","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],Y8=["theme","disableLineNumbers","overflow","themeType","disableFileHeader","disableVirtualizationBuffers","preferredHighlighter","useCSSClasses","useTokenTransformer","tokenizeMaxLineLength","tokenizeMaxLength","unsafeCSS","lineHoverHighlight","enableTokenInteractionsOnWhitespace","enableGutterUtility","__debugPointerEvents","enableLineSelection","controlledSelection","disableErrorHandling"],Qw=["renderCustomHeader","renderHeaderPrefix","renderHeaderFilenameSuffix","renderHeaderMetadata","renderAnnotation","renderGutterUtility","onPostRender","onGutterUtilityClick","onLineClick","onLineNumberClick","onLineEnter","onLineLeave","onTokenClick","onTokenEnter","onTokenLeave"],ey=["onLineSelected","onLineSelectionStart","onLineSelectionChange","onLineSelectionEnd"],pT=Symbol("CodeView.itemOptionsState");function ty(e,t){Object.defineProperty(e,pT,{configurable:!1,enumerable:!1,value:t})}function Aa(e){return e[pT]}function Yi(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}const X8=120,ny=1,sy="--diffs-overflow-override",zx=12e6,fT=1e6,mT=2e6,Z8=zx-mT,iy=zx-fT;function J8(e){if(e==null)throw new Error("CodeView: createEditor is required for items with edit: true")}const Q8=(()=>{const{navigator:e}=globalThis,t=e.userAgent,n=/iP(?:hone|ad|od)/.test(t),s=e.platform==="MacIntel"&&e.maxTouchPoints>1;return(n||s)&&/AppleWebKit/.test(t)&&/Safari/.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS)/.test(t)})();var e9=class to{static __STOP=!1;static __lastScrollPosition=0;type="advanced";config={overscrollSize:200,intersectionObserverMargin:0,resizeDebugging:!1};items=[];idToItem=new Map;selectedLines=null;itemEditors=new Map;attachedEditors=new Set;instanceToItem=new Map;layoutDirtyIndex;pendingLayoutReset;renderOptionsRevision=0;slotCoordinator;slotSnapshot;scrollListeners=new Set;scrollHeight=0;containerHeight=-1;scrollTop=0;scrollPageOffset=0;scrollDirty=!0;scrollInteractionFixTimer;pointerEventsDisabled=!1;codeOverflowFix=!1;height=0;heightDirty=!0;windowSpecs={top:0,bottom:0};renderState={scrollTop:-1,firstIndex:-1,lastIndex:-1,stickyHeight:0,stickyTop:-1,stickyBottom:-1};itemMetricsCache=Ia;fileOptionsPrototype;diffOptionsPrototype;pendingScrollTarget;pendingLayoutAnchor;shouldFixContainerFocus=!1;scrollAnimation;root;resizeObserver;container=document.createElement("div");stickyContainer=document.createElement("div");stickyOffset=document.createElement("div");header={element:void 0,render:void 0,height:0};footer={element:void 0,render:void 0,height:0};elementPool=[];elementPoolVersion=0;elementPoolTracker=new WeakMap;pendingElementPool=[];options;workerManager;isReadySubscription;isContainerManaged;constructor(t={theme:Ti},n,s=!1){this.options=t,this.computeMetricsCache(t.itemMetrics),this.fileOptionsPrototype=this.createFileOptionsPrototype(),this.diffOptionsPrototype=this.createDiffOptionsPrototype(),this.workerManager=n,this.isContainerManaged=s,this.stickyOffset.style.contain="layout size",this.stickyContainer.style.position="sticky",this.stickyContainer.style.width="100%",this.stickyContainer.style.contain="layout style inline-size",this.stickyContainer.style.isolation="isolate",this.stickyContainer.style.display="flex",this.stickyContainer.style.flexDirection="column"}getLayout(){return this.options.layout??xA}getItemTopOffset(){return this.getLayout().paddingTop+this.header.height}computeMetricsCache(t){return this.itemMetricsCache={hunkLineCount:t?.hunkLineCount??Ia.hunkLineCount,lineHeight:t?.lineHeight??Ia.lineHeight,diffHeaderHeight:t?.diffHeaderHeight??Ia.diffHeaderHeight,hunkSeparatorHeight:t?.hunkSeparatorHeight,spacing:t?.spacing??Ia.spacing,paddingTop:t?.paddingTop,paddingBottom:t?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??vA}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return bA&&this.options.__devOnlyValidateItemHeights===!0}validateRenderedItemHeight(t){if(!this.shouldValidateItemHeights()||t.element==null)return;const n=t.instance.getAdvancedStickySpecs();if(n==null)return;const s=n.height,o=t.element.getBoundingClientRect().height;s!==o&&console.error("CodeView: reconciled item height does not match DOM height",{id:t.item.id,type:t.type,index:t.index,version:t.version,expectedHeight:s,actualHeight:o,delta:o-s,stickyTopOffset:n.topOffset,virtualizedHeight:t.instance.getVirtualizedHeight(),top:t.top,scrollTop:this.getScrollTop(),windowSpecs:{...this.windowSpecs},element:t.element,instance:t.instance})}validateStickyContainerHeight(){if(!this.shouldValidateItemHeights())return;const{firstIndex:t,lastIndex:n,stickyHeight:s,stickyTop:o,stickyBottom:r}=this.renderState;if(t===-1||n===-1)return;const a=this.stickyContainer.getBoundingClientRect().height;Math.abs(a-s)<ny||console.error("CodeView: sticky container height does not match computed layout",{computedStickyHeight:s,actualStickyHeight:a,delta:a-s,stickyTop:o,stickyBottom:r,firstIndex:t,lastIndex:n,firstStickySpecs:this.items[t]?.instance.getAdvancedStickySpecs(),lastStickySpecs:this.items[n]?.instance.getAdvancedStickySpecs(),scrollTop:this.getScrollTop(),scrollPageOffset:this.scrollPageOffset,windowSpecs:{...this.windowSpecs},stickyContainer:this.stickyContainer})}clearScrollInteractionTimer(){this.scrollInteractionFixTimer!=null&&(clearTimeout(this.scrollInteractionFixTimer),this.scrollInteractionFixTimer=void 0)}suspendScrollInteractions(){this.clearScrollInteractionTimer(),this.shouldDisablePointerEvents()&&!this.pointerEventsDisabled&&(this.stickyContainer.style.pointerEvents="none",this.pointerEventsDisabled=!0),Q8&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(sy,"hidden"),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,X8)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&(this.stickyContainer.style.removeProperty("pointer-events"),this.pointerEventsDisabled=!1),this.codeOverflowFix&&(this.stickyContainer.style.setProperty(sy,"auto"),this.codeOverflowFix=!1)};syncLayout(){const{gap:t,paddingBottom:n,paddingTop:s}=this.getLayout();this.stickyContainer.style.gap=`${t}px`,this.container?.style.setProperty("margin-top",`${s}px`),this.container?.style.setProperty("margin-bottom",`${n}px`)}reconcileHeaderFooterHosts(){const t=this.reconcileHost("header"),n=this.reconcileHost("footer");return t||n}reconcileHost(t){const{root:n,container:s}=this;if(n==null||s==null)return!1;const o=t==="header"?this.header:this.footer,r=t==="header"?this.options.renderCodeViewHeader:this.options.renderCodeViewFooter;if(r==null)return o.element==null||(this.resizeObserver?.unobserve(o.element),o.element.remove(),o.element=void 0,o.render=void 0,this.setHostHeight(o,0)),!1;if(o.element!=null&&r===o.render)return!1;const a=o.element??K8(t,s,this.resizeObserver);o.element=a;const l=r();return l!=null?a.replaceChildren(l):!this.isContainerManaged&&a.children.length>0&&(a.textContent=""),o.render=r,!0}setHostHeight(t,n){t.height!==n&&(t.height=n,this.scrollDirty=!0)}measureMountedHosts(){this.header.element!=null&&this.setHostHeight(this.header,this.header.element.getBoundingClientRect().height),this.footer.element!=null&&this.setHostHeight(this.footer,this.footer.element.getBoundingClientRect().height)}setup(t){if(this.root!=null)throw new Error("CodeView.setup: already setup");this.workerManager?.subscribeToThemeChanges(this),this.root=t,this.root.style.overflowAnchor="none",this.root.hasAttribute("tabindex")||(this.root.tabIndex=-1),this.container??=document.createElement("div"),this.container.style.contain="layout style",this.syncLayout(),this.container.appendChild(this.stickyOffset),this.container.appendChild(this.stickyContainer),this.root.appendChild(this.container),this.scrollDirty=!0,this.heightDirty=!0,this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.stickyContainer),this.root.addEventListener("scroll",this.handleScroll,{passive:!0}),this.root.addEventListener("wheel",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("touchstart",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("pointerdown",this.clearPendingScroll,{passive:!0}),this.root.addEventListener("keydown",this.clearPendingScroll,{passive:!0}),this.resizeObserver.observe(this.root),this.render(!0),window.__INSTANCE=this,window.__TOGGLE=()=>{to.__STOP?(to.__STOP=!1,this.scrollTo({type:"position",position:to.__lastScrollPosition,behavior:"instant"})):(to.__lastScrollPosition=this.getScrollTop(),to.__STOP=!0)}}reset(){hf(this.computeRenderRangeAndEmit),this.clearReadySubscription(),this.restoreScrollInteractions(),this.cleanAllRenderedItems();for(const t of this.itemEditors.values())t.editor.cleanUp();this.itemEditors.clear(),this.attachedEditors.clear(),this.selectedLines=null,this.items.length=0,this.idToItem.clear(),this.instanceToItem.clear(),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,this.stickyContainer.textContent="",this.stickyOffset.style.height="",this.container?.style.removeProperty("height"),this.containerHeight=-1,this.windowSpecs={top:0,bottom:0},this.pendingLayoutAnchor=void 0,this.shouldFixContainerFocus=!1,this.height=0,this.scrollTop=0,this.scrollPageOffset=0,this.scrollHeight=0,this.scrollDirty=!0,this.heightDirty=!0,this.resetRenderState(),this.isContainerManaged||this.flushSlotCoordinator()}cleanUp(){this.reset(),this.clearElementPool(),this.restoreScrollInteractions(),this.workerManager?.unsubscribeToThemeChanges(this),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.root?.removeEventListener("scroll",this.handleScroll),this.root?.removeEventListener("wheel",this.clearPendingScroll),this.root?.removeEventListener("touchstart",this.clearPendingScroll),this.root?.removeEventListener("pointerdown",this.clearPendingScroll),this.root?.removeEventListener("keydown",this.clearPendingScroll),this.root?.style.removeProperty("overflow-anchor"),this.container?.remove(),this.stickyOffset.remove(),this.stickyContainer.remove(),this.stickyContainer.textContent="",this.header.element?.remove(),this.header.element=void 0,this.header.render=void 0,this.header.height=0,this.footer.element?.remove(),this.footer.element=void 0,this.footer.render=void 0,this.footer.height=0,this.root=void 0,this.container=void 0}cleanAllRenderedItems(){if(this.renderState.firstIndex!==-1)for(let t=this.renderState.firstIndex;t<=this.renderState.lastIndex;t++){const n=this.items[t];if(n==null)throw new Error(`CodeView.cleanAllRenderedItems: Item does not exist at index: ${t}`);this.releaseRenderedItem(n)}}primeScrollTarget(t){if(t.type==="position")return;const n=this.idToItem.get(t.id);n?.instance.primeHighlightCache()}getElementPoolLimit(){const t=this.getHeight()+this.config.overscrollSize*2,{diffHeaderHeight:n}=this.itemMetricsCache;return Math.max(8,Math.ceil(t/Math.max(n,10))+1)*(this.isContainerManaged?2:1)}acquireElement(){this.promotePendingPooledElements();let t=this.elementPool.pop();for(;t!=null&&!this.isElementPoolGenerationCurrent(t);)t=this.elementPool.pop();return t??=document.createElement(bk),this.markElementPoolGenerationCurrent(t),t}releaseRenderedItem(t){const{element:n}=t;n!=null&&this.renderedItemOwnsFocus(n)&&(this.shouldFixContainerFocus=!0),t.instance.cleanUp(!0),this.attachedEditors.delete(t.item.id),t.element=void 0,n!=null&&(n.remove(),this.cleanElement(n),this.queueElementForPool(n))}renderedItemOwnsFocus(t){const{activeElement:n}=document;return n===t||t.contains(n)||t.shadowRoot?.activeElement!=null}fixContainerFocus(){this.shouldFixContainerFocus&&(this.shouldFixContainerFocus=!1,this.root?.focus({preventScroll:!0}))}cleanElement(t){const{shadowRoot:n}=t;if(n!=null)for(const s of Array.from(n.children))o9(s)||s.remove();this.isContainerManaged||t.replaceChildren()}queueElementForPool(t){const n=this.getElementPoolLimit();!this.isElementPoolGenerationCurrent(t)||this.getElementPoolSize()>=n||(this.isElementClean(t)?this.elementPool.push(t):this.pendingElementPool.push(t))}promotePendingPooledElements(){if(this.pendingElementPool.length===0)return;const{pendingElementPool:t}=this;this.pendingElementPool=[];const n=this.getElementPoolLimit();for(const s of t)this.isElementPoolGenerationCurrent(s)&&this.isElementClean(s)&&this.elementPool.length<n?this.elementPool.push(s):this.isElementPoolGenerationCurrent(s)&&this.getElementPoolSize()<n&&this.pendingElementPool.push(s)}isElementClean(t){return t.childNodes.length===0}getElementPoolSize(){return this.elementPool.length+this.pendingElementPool.length}clearElementPool(){this.elementPool.length=0,this.pendingElementPool.length=0}invalidateElementPool(){this.elementPoolVersion++,this.clearElementPool()}markElementPoolGenerationCurrent(t){this.elementPoolTracker.set(t,this.elementPoolVersion)}isElementPoolGenerationCurrent(t){return this.elementPoolTracker.get(t)===this.elementPoolVersion}resolveEffectiveScrollBehavior(t,n){return PU()?"instant":t.behavior!=="smooth-auto"?t.behavior??"instant":Math.abs(n-this.getScrollTop())<=this.getHeight()*10?"smooth":"instant"}scrollTo(t){if(this.root==null)return;const n=this.normalizeScrollTarget(t);if(n==null)return;const s=this.resolveScrollTargetTop(n);s!=null&&(this.primeScrollTarget(n),this.resolveEffectiveScrollBehavior(n,s)==="smooth"?this.scrollAnimation??={position:this.getScrollTop(),velocity:0,lastTimestamp:performance.now()}:this.scrollAnimation=void 0,this.suspendScrollInteractions(),this.pendingLayoutAnchor=void 0,this.pendingScrollTarget=n,this.render())}setSelectedLines(t,n){this.applySelectedLines(t,n)}getSelectedLines(){return this.selectedLines}clearSelectedLines(t){this.applySelectedLines(null,t)}getItem(t){return this.idToItem.get(t)?.item}getEditor(t){return this.itemEditors.get(t)?.editor}updateItem(t){const n=this.idToItem.get(t.id);return n==null?(console.error(`CodeView.updateItem: unknown item id "${t.id}"`),!1):this.syncItemRecord(n,t)?(this.markItemLayoutDirty(n),this.scrollDirty=!0,this.render(),this.syncItemEditors(),this.syncSelection(),!0):!1}updateItemId(t,n){if(t===n)return!0;const s=this.idToItem.get(t);if(s==null)return console.error(`CodeView.updateItemId: unknown item id "${t}"`),!1;if(this.idToItem.has(n))return console.error(`CodeView.updateItemId: duplicate item id "${n}"`),!1;this.idToItem.delete(t),s.item.id=n,this.idToItem.set(n,s),this.updateItemOptionsId(s.instance.options,n),this.selectedLines?.id===t&&(this.selectedLines={...this.selectedLines,id:n},this.options.onSelectedLinesChange?.(this.selectedLines));const o=this.itemEditors.get(t);return o!=null&&(o.state.id=n,this.itemEditors.delete(t),this.itemEditors.set(n,o),this.attachedEditors.delete(t)&&this.attachedEditors.add(n)),this.renamePendingScrollTarget(t,n),this.renamePendingLayoutAnchor(t,n),this.render(),!0}addItem(t){this.addItems([t])}addItems(t){this.appendItemsInternal(t),this.syncItemEditors(),this.syncSelection()}removeItem(t){const n=this.idToItem.get(t);if(n==null)return console.error(`CodeView.removeItem: unknown item id "${t}"`),!1;const s=[];for(const o of this.items)o!==n&&s.push(o.item);return this.setItems(s),!0}setItems(t){let n;this.items.length===0?this.appendItemsInternal(t):this.tryAppendItems(t)||(n=this.reconcileItems(t)),this.syncItemEditors(n),this.syncSelection()}appendItemsInternal(t,n=!0){if(t.length===0)return;const s=this.getLayout();let o=this.items.length===0?0:this.scrollHeight+s.gap;const r=o;for(let a=0;a<t.length;a++){const l=t[a];if(l==null)throw new Error("CodeView.appendItemsInternal: missing input item");if(this.idToItem.has(l.id))throw new Error(`CodeView.addItem: duplicate id "${l.id}"`);const d=this.createItem(l,this.items.length,o);this.items.push(d),this.idToItem.set(d.item.id,d),this.instanceToItem.set(d.instance,d),d.height=t9(d),o+=d.height+s.gap}this.scrollHeight=o-s.gap,this.scrollDirty=!0,n&&(this.canSkipRenderForAppend(r)?this.syncContainerHeight():this.render())}canSkipRenderForAppend(t){return this.container!=null&&this.renderState.firstIndex!==-1&&this.pendingScrollTarget==null&&this.scrollAnimation==null&&this.layoutDirtyIndex==null&&t>this.windowSpecs.bottom}onThemeChange(){this.invalidateElementPool()}setOptions(t){if(t==null)return;this.capturePendingLayoutAnchor();const{options:n}=this,s=this.getLayout(),{itemMetricsCache:o}=this;n9(n,t)&&this.invalidateElementPool(),this.options=t;const r=this.computeMetricsCache(t.itemMetrics),a=!ff(o,r),l=!ff(s,this.getLayout());l&&this.syncLayout();const d=a||s9(n,t);if(d){const u=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?r:u?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:u?.includeEstimatedDiffHeights===!0||a||i9(n,t)}}(l||d)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),Hu(n,t)||this.renderOptionsRevision++,this.syncItemEditors();const c=n.renderCodeViewHeader!==t.renderCodeViewHeader||n.renderCodeViewFooter!==t.renderCodeViewFooter;!this.isContainerManaged&&(this.items.length>0||c)&&this.render()}capturePendingLayoutAnchor(t=this.idToItem){this.root==null||this.items.length===0||this.pendingScrollTarget!=null||(this.pendingLayoutAnchor=this.getScrollAnchor(this.getScrollTop(),t))}render(t=!1){to.__STOP||(t?(hf(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):mk(this.computeRenderRangeAndEmit))}isReady(){const{workerManager:t}=this;return t==null||t.isInitialized()||t.getStats().workersFailed?(this.clearReadySubscription(),!0):(this.isReadySubscription??=t.subscribeToStatChanges(n=>{n.managerState!=="initialized"&&!n.workersFailed||(this.clearReadySubscription(),this.render(!0))}),t.getStats().managerState==="waiting"&&t.initialize().catch(()=>{}),!1)}clearReadySubscription(){this.isReadySubscription!=null&&(this.isReadySubscription(),this.isReadySubscription=void 0)}instanceChanged(t,n){const s=this.instanceToItem.get(t);if(s==null)throw new Error("CodeView.instanceChanged: An instance has changed that is not registered");n&&this.markItemLayoutDirty(s),this.render()}getWindowSpecs(){return this.windowSpecs}getContainerElement(){return this.root}getHeaderElement(){return this.header.element}getFooterElement(){return this.footer.element}getRenderedItems(){const{firstIndex:t,lastIndex:n}=this.renderState;if(t===-1||n===-1||n<t)return[];const s=[];for(let o=t;o<=n;o++){const r=this.items[o];r?.element!=null&&(r.type==="diff"?s.push({id:r.item.id,type:"diff",item:r.item,version:r.version,element:r.element,instance:r.instance}):s.push({id:r.item.id,type:"file",item:r.item,version:r.version,element:r.element,instance:r.instance}))}return s}setSlotCoordinator(t){return t===this.slotCoordinator?!1:(this.slotCoordinator=t,this.slotSnapshot=void 0,!0)}getSlotSnapshot(t){return this.buildSlotSnapshot(t)}buildSlotSnapshot(t){const n=a9(this.getRenderedItems(),t),{element:s}=this.header,{element:o}=this.footer;if(!(n==null&&s==null&&o==null))return{items:n,header:s,footer:o}}subscribeToScroll(t){return this.scrollListeners.add(t),()=>{this.scrollListeners.delete(t)}}getLocalTopForInstance(t){const n=this.instanceToItem.get(t);if(n==null)throw new Error("CodeView.getLocalTopForInstance: unknown virtualized instance");return n.top}getTopForItem(t){const n=this.idToItem.get(t);if(n!=null)return n.top+this.getItemTopOffset()}createItem(t,n,s){const{itemMetricsCache:o}=this;if(t.type==="diff"){const a=new uT(this.createDiffOptions(t.id),this,o,this.workerManager,this.isContainerManaged);return{type:"diff",item:t,version:t.version,index:n,top:s,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:a}}const r=new wA(this.createFileOptions(t.id),this,o,this.workerManager,this.isContainerManaged);return{type:"file",item:t,version:t.version,index:n,top:s,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:r}}applySelectedLines(t,n){const{selectedLines:s}=this;t==null&&s==null||t!=null&&s?.id===t.id&&yA(s.range,t.range)||(s!=null&&s.id!==t?.id&&this.idToItem.get(s.id)?.instance.setSelectedLines(null,{notify:!1}),this.selectedLines=t,this.idToItem.get(t?.id??"")?.instance.setSelectedLines(t?.range??null,n))}syncSelection(){if(this.selectedLines==null)return;const t=this.idToItem.get(this.selectedLines.id);if(t==null){this.selectedLines=null,this.options.onSelectedLinesChange?.(null);return}t.instance.setSelectedLines(this.selectedLines.range,{notify:!1})}isItemInEditMode(t){return t.item.edit===!0&&t.item.collapsed!==!0}attachItemEditor(t){const{id:n}=t.item,{createEditor:s}=this.options;if(t.element==null||this.attachedEditors.has(n)||!this.isItemInEditMode(t))return;let o=this.itemEditors.get(n),r=!1;try{if(o==null){J8(s);const a={id:n},l=s({onChange:(d,c)=>{const u=this.idToItem.get(a.id);u!=null&&(a.lastChange={item:u.item,file:d,lineAnnotations:c},this.options.onItemEditChange?.(u.item,d,c))}});if(l==null)return;o={editor:l,state:a},this.itemEditors.set(n,o),r=!0}o.editor.edit(t.instance),this.attachedEditors.add(n)}catch(a){throw r&&o!=null&&(this.itemEditors.delete(n),o.editor.cleanUp()),this.releaseRenderedItem(t),a}}syncItemEditors(t){if(this.itemEditors.size===0)return;const n=[];for(const[s,o]of this.itemEditors){const r=this.idToItem.get(s),a=t?.get(s);if(a==null&&r!=null&&this.isItemInEditMode(r))continue;o.editor.cleanUp(),this.itemEditors.delete(s),this.attachedEditors.delete(s);const{lastChange:l}=o.state,d=a==null?r?.item??l?.item:l?.item??a.item;d?.type==="diff"&&(a==null&&r!=null&&r.type==="diff"&&r.instance.completeEditSession()&&(this.markItemLayoutDirty(r),this.render()),gm(d.fileDiff)),l!=null&&n.push(a!=null||r==null?l:{...l,item:r.item})}for(const{item:s,file:o,lineAnnotations:r}of n)this.options.onItemEditComplete?.(s,o,r)}renamePendingScrollTarget(t,n){const{pendingScrollTarget:s}=this;s==null||s.type==="position"||s.id!==t||(this.pendingScrollTarget={...s,id:n})}renamePendingLayoutAnchor(t,n){this.pendingLayoutAnchor?.id===t&&(this.pendingLayoutAnchor.id=n)}createFileOptionsPrototype(){const t={};for(const n of Y8)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"collapsed",n=>{const s=Aa(n);if(s!=null)return this.getItemOptions(s,"file")?.item.collapsed});for(const n of Qw)this.defineItemSharedCallback(t,"file",n);for(const n of ey)this.defineItemSelectionCallback(t,"file",n);return t}createDiffOptionsPrototype(){const t={};for(const n of q8)Yi(t,n,()=>this.options[n]);Yi(t,"stickyHeader",()=>this.options.stickyHeaders),Yi(t,"hunkSeparators",()=>this.options.hunkSeparators),Yi(t,"collapsed",n=>{const s=Aa(n);if(s!=null)return this.getItemOptions(s,"diff")?.item.collapsed});for(const n of Qw)this.defineItemSharedCallback(t,"diff",n);for(const n of ey)this.defineItemSelectionCallback(t,"diff",n);return t}createFileOptions(t){const n=Object.create(this.fileOptionsPrototype);return ty(n,{id:t}),n}createDiffOptions(t){const n=Object.create(this.diffOptionsPrototype);return ty(n,{id:t}),n}updateItemOptionsId(t,n){const s=Aa(t);if(s==null)throw new Error("CodeView.updateItemOptionsId: No valid state");s.id=n}getItemOptions(t,n){const s=this.idToItem.get(t.id);if(!(s==null||s.type!==n))return s}defineItemSharedCallback(t,n,s){Yi(t,s,o=>{if(this.options[s]==null)return;const r=Aa(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=((...d)=>{const c=this.getItemOptions(r,n);if(c==null)return;const u=this.options[s];return u?.(...d,c)}),a[s]=l),l})}defineItemSelectionCallback(t,n,s){Yi(t,s,o=>{const r=Aa(o);if(r==null)return;const a=r.callbackCache??={};let l=a[s];return l==null&&(l=(d=>{const c=this.getItemOptions(r,n);if(c==null)return;const u=d==null?null:{id:c.item.id,range:d};this.options.controlledSelection!==!0&&(d!=null||this.selectedLines?.id===c.item.id)&&this.applySelectedLines(u,{notify:!1}),this.options.onSelectedLinesChange?.(u);const h=this.options[s];return h?.(d,c)}),a[s]=l),l})}markLayoutDirtyFromIndex(t){this.layoutDirtyIndex=Math.min(this.layoutDirtyIndex??t,t)}markItemLayoutDirty(t){if(this.items[t.index]!==t)throw new Error(`CodeView.markItemLayoutDirty: unknown item id "${t.item.id}"`);this.markLayoutDirtyFromIndex(t.index)}tryAppendItems(t){if(t.length<=this.items.length)return!1;for(let n=0;n<this.items.length;n++){const s=this.items[n];if(s==null)throw new Error("CodeView.tryAppendItems: missing existing item");const o=t[n];if(o==null||s.item.id!==o.id||s.type!==o.type)return!1}for(let n=0;n<this.items.length;n++){const s=this.items[n];if(s==null)throw new Error("CodeView.tryAppendItems: missing existing item");const o=t[n];if(o==null)throw new Error("CodeView.tryAppendItems: append candidate missing prefix item");this.syncItemRecord(s,o)&&this.markLayoutDirtyFromIndex(n)}return this.appendItemsInternal(t.slice(this.items.length),!1),this.scrollDirty=!0,this.render(),!0}reconcileItems(t){const{items:n,idToItem:s}=this,o=new Set(n),r=[],a=new Map,l=new Map,d=new Map;let c;for(let u=0;u<t.length;u++){const h=t[u];if(h==null)throw new Error("CodeView.reconcileItems: missing input item");if(a.has(h.id))throw new Error(`CodeView.setItems: duplicate id "${h.id}"`);const p=s.get(h.id),f=p!=null&&p.type===h.type?p:this.createItem(h,u,0);f.index=u,p!=null&&p.type===h.type?(o.delete(p),this.syncItemRecord(f,h)&&(c=Math.min(c??u,u))):c=Math.min(c??u,u),n[u]!==f&&(c=Math.min(c??u,u)),r.push(f),a.set(h.id,f),l.set(f.instance,f)}if(c==null){if(o.size===0)return;c=Math.max(r.length-1,0)}this.capturePendingLayoutAnchor(a);for(let u=0;u<n.length;u++){const h=n[u];if(h==null||!o.has(h))continue;d.set(h.item.id,h),this.releaseRenderedItem(h);const p=Math.max(r.length-1,0);c=Math.min(c??p,p)}return this.items=r,this.idToItem=a,this.instanceToItem=l,this.renderState.firstIndex>=r.length?this.resetRenderState():this.renderState.lastIndex>=r.length&&(this.renderState.lastIndex=r.length-1),this.markLayoutDirtyFromIndex(c),this.scrollDirty=!0,this.render(),d.size>0?d:void 0}syncItemRecord(t,n){if(t.type!==n.type)throw new Error(`CodeView.syncItemRecord: type mismatch for id "${n.id}"`);return t.version===n.version?!1:(t.item=n,t.version=n.version,t.renderedOptionsRevision=-1,!0)}getMaxScrollTopForHeight(t){const{paddingBottom:n,paddingTop:s}=this.getLayout();return Math.max(s+this.header.height+t+this.footer.height+n-this.getHeight(),0)}getMaxScrollTop(){return this.getMaxScrollTopForHeight(this.getScrollHeight())}shouldRebaseScroll(){return this.getMaxScrollTop()>iy}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),zx):this.getScrollHeight()}getMaxPagedScrollTop(){return this.getMaxScrollTopForHeight(this.getPagedScrollHeight())}clampPagedScrollTop(t){const n=this.getMaxPagedScrollTop();return Math.max(0,Math.min(t,n))}clampScrollTop(t){const n=this.getMaxScrollTop();return Math.max(0,Math.min(t,n))}getMaxScrollPageOffset(){return Math.max(this.getMaxScrollTop()-this.getMaxPagedScrollTop(),0)}clampScrollPageOffset(t){const n=this.getMaxScrollPageOffset();return Math.max(0,Math.min(t,n))}resolveScrollPageWindow(t,n){let s=Si(this.clampPagedScrollTop(n)),o=this.clampScrollPageOffset(t-s);return s=Si(this.clampPagedScrollTop(t-o)),o=this.clampScrollPageOffset(t-s),{pagedScrollTop:s,scrollPageOffset:o}}resolvePagedScrollPosition(t){if(!this.shouldRebaseScroll())return{pagedScrollTop:this.clampPagedScrollTop(t),scrollPageOffset:0};const n=this.clampScrollPageOffset(this.scrollPageOffset),s=t-n,o=this.getMaxPagedScrollTop(),r=this.getMaxScrollPageOffset(),a=s>iy&&n<r,l=s<fT&&n>0;return s<0||s>o||a||l?this.resolveScrollPageWindow(t,l?Math.min(Z8,o):mT):{pagedScrollTop:Si(this.clampPagedScrollTop(s)),scrollPageOffset:n}}needsScrollPageUpdate(t){const n=Si(this.clampScrollTop(t)),{scrollPageOffset:s}=this.resolvePagedScrollPosition(n);return s!==this.scrollPageOffset}getPagedLayoutTop(t){return this.shouldRebaseScroll()?Math.max(t-this.scrollPageOffset,0):t}getStickyHeaderOffset(){return this.options.stickyHeaders===!0&&this.options.disableFileHeader!==!0?this.itemMetricsCache.diffHeaderHeight:0}getScrollTargetRect(t){const n=this.idToItem.get(t.id);if(n==null){console.warn(`CodeView.scrollTo: unknown item id "${t.id}"`);return}if(t.type==="item")return{top:n.top,height:n.height};if(t.type==="range"){const o=this.getRangeScrollPosition(n,t);if(o==null){console.warn(`CodeView.scrollTo: unable to resolve range ${oy(t.range)} for item "${t.id}"`);return}return{top:n.top+o.top,height:o.height}}const s=this.getLineScrollPosition(n,t);if(s==null){console.warn(`CodeView.scrollTo: unable to resolve line ${t.lineNumber} for item "${t.id}"`);return}return{top:n.top+s.top,height:s.height}}normalizeScrollTarget(t){if(t.type==="position"||t.align!=="nearest")return t;const n=this.getScrollTargetRect(t);if(n==null)return;const s=t.offset??0,o=this.getItemTopOffset()+n.top,r=o+n.height,a=this.getScrollTop(),l=a+(t.type==="line"||t.type==="range"?this.getStickyHeaderOffset():0),d=a+this.getHeight();if(!(o-s<=l&&r+s>=d)){if(o-s<l)return{...t,align:"start"};if(r+s>d)return{...t,align:"end"}}}resolveScrollTargetTop(t){if(t.type==="position"){const o=this.clampScrollTop(t.position);return o!==t.position?o:this.clampScrollTop(t.position-this.getStickyHeaderOffset())}const n=this.idToItem.get(t.id);if(n==null){console.warn(`CodeView.scrollTo: unknown item id "${t.id}"`);return}if(t.type==="item")return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top,n.height,t.align,t.offset));if(t.type==="range"){const o=this.getRangeScrollPosition(n,t);if(o==null){console.warn(`CodeView.scrollTo: unable to resolve range ${oy(t.range)} for item "${t.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top+o.top,o.height,t.align,t.offset,this.getStickyHeaderOffset()))}const s=this.getLineScrollPosition(n,t);if(s==null){console.warn(`CodeView.scrollTo: unable to resolve line ${t.lineNumber} for item "${t.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(n.top+s.top,s.height,t.align,t.offset,this.getStickyHeaderOffset()))}resolveAlignedScrollPosition(t,n,s,o=0,r=0){t+=this.getItemTopOffset();const a=this.getHeight();return s==="center"&&n+o<a?t-(a-n)/2+o:s==="end"?t-(a-n)+o:t-r-o}getLineScrollPosition(t,n){return t.type==="diff"?t.instance.getLinePosition(n.lineNumber,n.side):t.instance.getLinePosition(n.lineNumber)}getRangeScrollPosition(t,n){const{range:s}=n,o=this.getLineScrollPosition(t,{type:"line",id:n.id,lineNumber:s.start,side:s.side}),r=this.getLineScrollPosition(t,{type:"line",id:n.id,lineNumber:s.end,side:s.endSide??s.side});if(o==null||r==null)return;const a=o.top,l=a+o.height,d=r.top,c=d+r.height,u=Math.min(a,d);return{top:u,height:Math.max(l,c)-u}}computeTargetScrollTopForFrame(t,n){if(this.pendingScrollTarget==null)return t;const s=this.resolveScrollTargetTop(this.pendingScrollTarget);if(s==null)return t;const{scrollAnimation:o}=this;return o==null?s:this.computeSpringStep(o,s,n).position}computeSpringStep(t,n,s){const o=Math.max(0,s-t.lastTimestamp),{omega:r}=this.getSmoothScrollSettings(),a=Math.exp(-r*o),l=t.position-n,d=t.velocity+r*l;return{position:n+(l+d*o)*a,velocity:(d*(1-r*o)-r*l)*a}}advanceScrollAnimation(t,n){if(this.pendingScrollTarget==null)return;const s=this.resolveScrollTargetTop(this.pendingScrollTarget);if(s==null){this.pendingScrollTarget=void 0,this.scrollAnimation=void 0;return}const o=this.scrollAnimation;if(o==null)return s;o.position+=n;const{position:r,velocity:a}=this.computeSpringStep(o,s,t);o.lastTimestamp=t,o.position=r,o.velocity=a;const{positionEpsilon:l,velocityEpsilon:d}=this.getSmoothScrollSettings();return Math.abs(s-r)<=l&&Math.abs(a)<=d?(o.position=s,o.velocity=0,this.scrollAnimation=void 0,s):o.position}computeRenderRangeAndEmit=(t=performance.now())=>{if(to.__STOP||this.container==null||!this.isReady())return;const n=this.getHeight(),s=this.getScrollTop();let o=s,r=this.pendingLayoutAnchor!=null,a=this.getScrollAnchor(o);if(this.layoutDirtyIndex!=null&&(this.recomputeLayout(this.layoutDirtyIndex,this.pendingLayoutReset),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,r=!0),r&&a!=null){const C=this.resolveAnchoredScrollTop(a);if(C!=null){const S=C-o;o=C,this.scrollAnimation!=null&&(this.scrollAnimation.position+=S)}}r&&(o=this.clampScrollTop(o),this.syncContainerHeight());const l=this.computeTargetScrollTopForFrame(o,t),d=!r&&(this.renderState.scrollTop===-1||Math.abs(l-this.renderState.scrollTop)>n+this.config.overscrollSize*2);d&&(a=void 0),this.windowSpecs=SA({scrollTop:l-this.header.height,height:n,scrollHeight:this.getScrollHeight(),fitPerfectly:d,fitPerfectlyOverscroll:this.getFitPerfectlyOverscroll(),overscrollSize:this.config.overscrollSize});let c=s;(this.pendingScrollTarget!=null&&l!==c||this.needsScrollPageUpdate(l))&&(this.applyScrollFix(l,c,this.windowSpecs),c=l);const{top:u,bottom:h}=this.windowSpecs,{firstIndex:p,lastIndex:f}=this.renderState;if(p>=0)for(let C=p;C<=f;C++){const S=this.items[C];if(S==null)throw new Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${C}`);S.top>u-S.height&&S.top<=h||this.releaseRenderedItem(S)}const g=this.reconcileHeaderFooterHosts();let x;const v=new Set,y=this.findFirstVisibleIndex(u),w=this.findLastVisibleIndex(h);for(let C=y;C<=w;C++){const S=this.items[C];if(S==null)throw new Error("CodeView.computeRenderRangeAndEmit: missing item");const{instance:A}=S;S.element==null?(S.element=this.acquireElement(),ly(this.stickyContainer,S.element,x),A.virtualizedSetup(),ay(S,S.element)&&(S.renderedOptionsRevision=this.renderOptionsRevision,v.add(S)),x=S.element):(ly(this.stickyContainer,S.element,x),ay(S,void 0,S.renderedOptionsRevision!==this.renderOptionsRevision)&&(S.renderedOptionsRevision=this.renderOptionsRevision,v.add(S)),x=S.element),S.item.edit===!0&&this.attachItemEditor(S)}this.renderState.firstIndex=y<=w?y:-1,this.renderState.lastIndex=w,this.flushSlotCoordinator(),this.flushManagers(v),g&&this.measureMountedHosts(),this.reconcileRenderedItems(v),this.syncContainerHeight(),this.updateStickyPositioning();const b=a!=null?this.resolveAnchoredScrollTop(a):void 0;a===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);const _=b!=null?b-o:0;let j=l,N=!1;if(this.pendingScrollTarget!=null){const C=this.advanceScrollAnimation(t,_);C!=null?(j=C,N=!0):j=o}else j=b??l;j!==c&&(this.applyScrollFix(j,c,this.windowSpecs),c=j),N&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=Si(c),this.updateStickyPositioning(),this.validateStickyContainerHeight(),this.fixContainerFocus(),(d||this.scrollAnimation!=null)&&this.render()};flushManagers(t){for(const n of t)n.instance.flushManagers()}syncContainerHeight(){const t=this.getPagedScrollHeight();this.container==null||this.containerHeight===t||(this.container.style.height=`${t}px`,this.containerHeight=t)}getStickyBounds(t){const{firstIndex:n,lastIndex:s}=t!=null?{firstIndex:this.findFirstVisibleIndex(t.top),lastIndex:this.findLastVisibleIndex(t.bottom)}:this.renderState;if(n===-1||s===-1||n>s)return;const o=this.items[n]?.instance.getAdvancedStickySpecs(t),r=this.items[s]?.instance.getAdvancedStickySpecs(t);if(!(o==null||r==null))return{stickyTop:this.getPagedLayoutTop(Math.max(o.topOffset,0)),stickyBottom:this.getPagedLayoutTop(r.topOffset+r.height)}}applyStickyPositioning({stickyTop:t,stickyBottom:n}){const s=this.getHeight(),{itemMetricsCache:o}=this,r=n-t;this.renderState.stickyHeight=r,this.renderState.stickyTop=t,this.renderState.stickyBottom=n,this.stickyOffset.style.height=`${t}px`;const a=(Math.random()*o.lineHeight>>0)*-1,l=-Math.max(r+a,0)+s;this.stickyContainer.style.top=`${l}px`,this.stickyContainer.style.bottom=`${l+o.diffHeaderHeight}px`}syncPagedScrollScaffolding(t){this.syncContainerHeight();const n=this.getStickyBounds(t);n!=null&&this.applyStickyPositioning(n)}reconcileRenderedItems(t){const{firstIndex:n,lastIndex:s}=this.renderState;if(n===-1)return;let o=-1,r=!1;for(let a=n;a<this.items.length&&!(!r&&a>s);a++){const l=this.items[a];if(l==null)throw new Error("CodeView.reconcileRenderedItems: Invalid item");o===-1?o=l.top:l.top!==o&&(l.top=o,l.instance.syncVirtualizedTop(),r=!0),(t==null?a<=s:t.has(l))&&(l.instance.reconcileHeights()&&(r=!0,l.height=l.instance.getVirtualizedHeight()),this.validateRenderedItemHeight(l)),o+=l.instance.getVirtualizedHeight(),a<this.items.length-1&&(o+=this.getLayout().gap)}r&&o!=null&&(this.scrollDirty=!0,this.scrollHeight=o)}updateStickyPositioning(){const t=this.getStickyBounds();if(t==null){this.renderState.firstIndex===-1&&(this.stickyOffset.style.height="");return}const{stickyTop:n,stickyBottom:s}=t;s-n===this.renderState.stickyHeight&&n===this.renderState.stickyTop&&s===this.renderState.stickyBottom||this.applyStickyPositioning(t)}handleScroll=()=>{to.__STOP||(this.suspendScrollInteractions(),this.scrollDirty=!0,this.notifyScroll(),this.render())};clearPendingScroll=()=>{this.pendingScrollTarget=void 0,this.pendingLayoutAnchor=void 0,this.scrollAnimation=void 0};handleResize=t=>{let n=!1;for(const s of t)if(s.target===this.stickyContainer){const o=s.borderBoxSize[0].blockSize;if(Math.abs(o-this.renderState.stickyHeight)>=ny){const r=this.getScrollTop(),a=this.getScrollAnchor(r);this.reconcileRenderedItems(),this.updateStickyPositioning();const l=a!=null?this.resolveAnchoredScrollTop(a):void 0;if(l!=null){const d=l-r;this.applyScrollFix(l,r,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=d)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),n=!0}}else if(s.target===this.header.element||s.target===this.footer.element){const o=s.target===this.header.element?this.header:this.footer,r=s.borderBoxSize[0].blockSize;if(r!==o.height){const a=this.getScrollTop(),l=this.getScrollAnchor(a);this.setHostHeight(o,r);const d=l!=null?this.resolveAnchoredScrollTop(l):void 0;if(d!=null){const c=d-a;this.applyScrollFix(d,a,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=c)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),n=!0}}else this.scrollDirty=!0,this.heightDirty=!0,n=!0;n&&this.render(!0)};getScrollAnchorViewportTop(t,n){return t<n?n+this.getStickyHeaderOffset():n}getScrollAnchor(t,n=this.idToItem){let s;const{pendingLayoutAnchor:o}=this;if(o!=null){const u=this.idToItem.get(o.id);if(u!=null&&n.get(o.id)===u)return o;u!=null&&(s=u)}if(t<=0)return;const{firstIndex:r,lastIndex:a,stickyTop:l,stickyBottom:d}=this.renderState;if(r===-1||a===-1)return;const c=this.getHeight();if(!(l===-1||d===-1)){for(let u=r;u<=a;u++){const h=this.items[u];if(h==null)continue;const p=this.getItemTopOffset()+h.top;if(p+h.height<=t)continue;if(p>=t+c)break;if(n.get(h.item.id)!==h){s??=h;continue}if(p>=t)return{type:"item",id:h.item.id,viewportOffset:p-t};const f=this.getScrollAnchorViewportTop(p,t)-p,g=h.instance.getNumericScrollAnchor(f);if(g!=null){const x=p+g.top;return{type:"line",id:h.item.id,lineNumber:g.lineNumber,side:g.side,viewportOffset:x-t}}}if(s!=null)for(let u=s.index+1;u<this.items.length;u++){const h=this.items[u];if(h!=null&&n.get(h.item.id)===h)return{type:"item",id:h.item.id,viewportOffset:0}}}}resolveAnchoredScrollTop(t){const n=this.idToItem.get(t.id);if(n==null)return;const s=this.getItemTopOffset();if(t.type==="item"){const a=s+n.top;return this.clampScrollTop(a-t.viewportOffset)}const o=n.type==="diff"?n.instance.getLinePosition(t.lineNumber,t.side):n.instance.getLinePosition(t.lineNumber);if(o==null)return;const r=s+n.top+o.top;return this.clampScrollTop(r-t.viewportOffset)}applyScrollFix(t,n,s){if(this.root==null)return;const o=Si(this.clampScrollTop(t)),r=Si(n),{scrollPageOffset:a}=this,l=Si(this.clampPagedScrollTop(r-a)),{pagedScrollTop:d,scrollPageOffset:c}=this.resolvePagedScrollPosition(o),u=d,h=a!==c;o===this.renderState.scrollTop&&o===r&&u===l&&!h||(this.suspendScrollInteractions(),(u!==l||h)&&(this.scrollPageOffset=c,this.syncPagedScrollScaffolding(s)),u!==l&&this.root.scrollTo({top:u,behavior:"instant"}),this.renderState.scrollTop=o,this.scrollTop=o,this.scrollDirty=!1)}isPendingTargetSettled(t){const n=this.resolveScrollTargetTop(t);return n==null?!0:Si(this.getScrollTop())===Si(n)}getScrollTop(){if(!this.scrollDirty)return this.scrollTop;this.scrollDirty=!1;const t=this.root?.scrollTop??0;return this.scrollTop=this.clampScrollTop(t+this.scrollPageOffset),this.scrollTop}getHeight(){return this.heightDirty?(this.heightDirty=!1,this.height=this.root?.getBoundingClientRect().height??0,this.height):this.height}getScrollHeight(){return this.scrollHeight}flushSlotCoordinator(){if(this.slotCoordinator==null)return;const t=this.buildSlotSnapshot(this.slotCoordinator);hT(this.slotSnapshot,t)||(this.slotSnapshot=t,this.slotCoordinator.onSnapshotChange(t))}notifyScroll(){if(this.scrollListeners.size===0)return;const t=this.getScrollTop();for(const n of this.scrollListeners)n(t,this)}findFirstVisibleIndex(t){let n=0,s=this.items.length-1,o=this.items.length;for(;n<=s;){const r=n+s>>1,a=this.items[r];if(a==null)throw new Error("CodeView.findFirstVisibleIndex: invalid item index");a.top+a.height>t?(o=r,s=r-1):n=r+1}return o}findLastVisibleIndex(t){let n=0,s=this.items.length-1,o=-1;for(;n<=s;){const r=n+s>>1,a=this.items[r];if(a==null)throw new Error("CodeView.findLastVisibleIndex: invalid item index");a.top<=t?(o=r,n=r+1):s=r-1}return o}recomputeLayout(t=0,n){if(this.items.length===0){this.scrollHeight=0;return}const s=this.getLayout();let o=0;if(t>0){const r=this.items[t-1];if(r==null)throw new Error("CodeView.recomputeLayout: invalid dirty index");o=r.top+r.height+s.gap}for(let r=t;r<this.items.length;r++){const a=this.items[r];if(a==null)throw new Error("CodeView.recomputeLayout: invalid item index");if(a.top=o,a.type==="diff"){const l=a.instance.consumeCodeViewLayoutChanges(a.item.fileDiff);l!=null&&Object.assign(a.item.fileDiff,l),a.height=a.instance.prepareCodeViewItem(a.item.fileDiff,o,n,a.item.annotations??[])}else a.height=a.instance.prepareCodeViewItem(a.item.file,o,n,a.item.annotations??[]);o+=a.height,r<this.items.length-1&&(o+=s.gap)}o!==this.scrollHeight&&(this.scrollDirty=!0),this.scrollHeight=o}resetRenderState(){this.renderState.scrollTop=-1,this.renderState.firstIndex=-1,this.renderState.lastIndex=-1,this.renderState.stickyHeight=0,this.renderState.stickyTop=-1,this.renderState.stickyBottom=-1}getFitPerfectlyOverscroll(){return this.getLayout().gap+this.itemMetricsCache.diffHeaderHeight}};function t9(e){return e.instance.cleanUp(!0),e.type==="diff"?e.instance.prepareCodeViewItem(e.item.fileDiff,e.top,void 0,e.item.annotations??[]):e.instance.prepareCodeViewItem(e.item.file,e.top,void 0,e.item.annotations??[])}function n9(e,t){return!pk(e.theme??Ti,t.theme??Ti)||(e.themeType??"system")!==(t.themeType??"system")||e.unsafeCSS!==t.unsafeCSS}function s9(e,t){return(e.overflow??"scroll")!==(t.overflow??"scroll")||(e.disableLineNumbers??!1)!==(t.disableLineNumbers??!1)||(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||e.unsafeCSS!==t.unsafeCSS||(e.diffStyle??"split")!==(t.diffStyle??"split")||(e.diffIndicators??"bars")!==(t.diffIndicators??"bars")||(e.hunkSeparators??"line-info")!==(t.hunkSeparators??"line-info")||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function i9(e,t){return(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.hunkSeparators??"line-info")!==(t.hunkSeparators??"line-info")||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function o9(e){return e instanceof SVGElement?!0:pf(e)&&(e.hasAttribute("data-core-css")||e.hasAttribute("data-theme-css")||e.hasAttribute("data-unsafe-css"))}function oy(e){const t=ry(e.start,e.side),n=ry(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function ry(e,t){return t==null?`${e}`:`${t==="deletions"?"D":"A"}${e}`}function ay(e,t,n=!1){return e.type==="diff"?e.instance.render({deferManagers:!0,fileContainer:t,fileDiff:e.item.fileDiff,forceRender:n,lineAnnotations:e.item.annotations??[]}):e.instance.render({deferManagers:!0,fileContainer:t,file:e.item.file,forceRender:n,lineAnnotations:e.item.annotations??[]})}function ly(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function r9(e){return(e.annotations?.length??0)>0}function a9(e,{hasHeaderRenderers:t,hasAnnotationRenderer:n,hasGutterRenderer:s}){if(e.length===0)return;if(t||s)return e;if(!n)return;const o=[];for(const r of e)r9(r.item)&&o.push(r);return o.length>0?o:void 0}function l9({hunkIndex:e,lineIndex:t,conflictIndex:n}){return`merge-conflict-action-${e}-${t}-${n}`}function d9(e,t){const n=t.hunks[e.hunkIndex];if(n!=null)return{hunkIndex:e.hunkIndex,lineIndex:c9(n,e.startContentIndex)}}function c9(e,t){let n=e.unifiedLineStart;for(let s=0;s<t;s++){const o=e.hunkContent[s];n+=o.type==="context"?o.lines:o.deletions+o.additions}return n}function gT({fileDiff:e,actions:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderMergeConflictUtility:d,lineAnnotations:c,getHoveredLine:u,getInstance:h}){const p=n?.(e),f=s?.(e),g=o?.(e),x=r?.(e);return i.jsxs(i.Fragment,{children:[p!=null?i.jsx("div",{slot:gk,children:p}):i.jsxs(i.Fragment,{children:[f!=null&&i.jsx("div",{slot:"header-prefix",children:f}),g!=null&&i.jsx("div",{slot:"header-filename-suffix",children:g}),x!=null&&i.jsx("div",{slot:"header-metadata",children:x})]}),a!=null&&c?.map((v,y)=>i.jsx("div",{slot:sa(v),children:a(v)},y)),t!=null&&d!=null&&h!=null&&t.map(v=>{if(v==null)return;const y=u9(v,e);return i.jsx("div",{slot:y,style:CA,children:d(v,h)},y)}),l!=null&&i.jsx("div",{slot:"gutter-utility-slot",style:kA,children:l(u)})]})}function u9(e,t){const n=d9(e,t);return n!=null?l9({hunkIndex:n.hunkIndex,lineIndex:n.lineIndex,conflictIndex:e.conflictIndex}):void 0}const dy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function cy(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function h9(e,t){const{className:n,containerRef:s,disableWorkerPool:o=!1,editorOptions:r,initialItems:a,items:l,onItemEditChange:d,onItemEditComplete:c,onScroll:u,onSelectedLinesChange:h,options:p,renderAnnotation:f,renderCodeViewFooter:g,renderCodeViewHeader:x,renderCustomHeader:v,renderGutterUtility:y,renderHeaderFilenameSuffix:w,renderHeaderMetadata:b,renderHeaderPrefix:_,selectedLines:j,style:N}=e,C=l!==void 0,S=wk(),A=m.useContext(yk),E=m.useRef(cy(C)),I=v!=null,D=f!=null,T=y!=null,z=I||_!=null||w!=null||b!=null,$=z||D||T,R=x!=null,B=g!=null,H=so(W=>{h?.(W)}),oe=j!==void 0,te=so(W=>{if(S==null)throw new Error("CodeView: EditContext is not attached");const G=S({...r,...W});if(G==null)throw new Error("CodeView: EditProvider.createEditor must return an editor instance");return G}),O=so((W,G,de)=>{d?.(W,G,de)}),V=so((W,G,de)=>{c?.(W,G,de)}),J=m.useMemo(()=>g9({options:p,hasCustomHeader:I,hasGutterRenderer:T,hasCodeViewHeader:R,hasCodeViewFooter:B,onSelectedLinesChange:h!=null?H:void 0,controlledSelection:oe,createEditor:S!=null?te:void 0,onItemEditChange:d!=null?O:void 0,onItemEditComplete:c!=null?V:void 0}),[S,oe,te,O,V,H,B,R,I,T,d,c,h,p]),[pe]=m.useState(()=>m9()),[,fe]=m.useState({}),_e=so(W=>{E.current.instance!=null&&(W==null||W!==E.current.instance.getContainerElement())&&(E.current.instance.cleanUp(),pe.publish(void 0),E.current=cy(C)),W!=null&&W!==E.current.instance?.getContainerElement()&&(E.current.instance=new e9(J,o?void 0:A,!0),E.current.instance.setup(W)),typeof s=="function"?s(W):s!=null&&(s.current=W)}),Ee=so(W=>{E.current.disableFlushSync?pe.publish(W):Ws.flushSync(()=>{pe.publish(W)})}),me=m.useMemo(()=>{if(!(!z&&!D&&!T&&!R&&!B))return{hasHeaderRenderers:z,hasAnnotationRenderer:D,hasGutterRenderer:T,onSnapshotChange:Ee}},[Ee,D,T,z,R,B]);return dy(()=>u!=null?E.current.instance?.subscribeToScroll(u):void 0),dy(()=>{const{instance:W,controlled:G,items:de,managedOptions:X,slotCoordinator:ie}=E.current;if(W!=null)try{E.current.disableFlushSync=!0;let Z=!1;if(Hu(J,X)||(E.current.managedOptions=J,W.setOptions(J),Z=!0),G!==C){console.error("CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.");return}if(C)l!==de&&(f9(de,l)?E.current.items=l:p9(de,l)?(E.current.items=l,W.addItems(l.slice(de.length))):(E.current.items=l,W.setItems(l),Z=!0));else if(de==null){const Fe=a??[];E.current.items=Fe,Fe.length>0&&(W.setItems(Fe),Z=!0)}j!==void 0&&W.setSelectedLines(j,{notify:!1});const le=W.setSlotCoordinator(me);let be=!1;me!==ie&&((me==null||ie==null)&&(be=!0),E.current.slotCoordinator=me),(Z||le)&&W.render(!0),le&&me==null&&pe.publish(void 0),be&&fe({})}finally{E.current.disableFlushSync=!1}}),m.useImperativeHandle(t,()=>({addItems(W){const{controlled:G,instance:de}=E.current;Kd(G,"addItems"),de==null?console.error("CodeView.addItems: no valid instance to append items with",W):de.addItems(W)},getItem(W){const{instance:G}=E.current;if(G==null){console.error("CodeView.getItem: no valid instance exists",W);return}else return G.getItem(W)},removeItem(W){const{controlled:G,instance:de}=E.current;return Kd(G,"removeItem"),de==null?(console.error("CodeView.removeItem: no valid instance to remove item from",W),!1):de.removeItem(W)},updateItem(W){const{controlled:G,instance:de}=E.current;return Kd(G,"updateItem"),de==null?(console.error("CodeView.updateItem: no valid instance to update item with",W),!1):de.updateItem(W)},updateItemId(W,G){const{controlled:de,instance:X}=E.current;return Kd(de,"updateItemId"),X==null?(console.error("CodeView.updateItemId: no valid instance to update item id with",W,G),!1):X.updateItemId(W,G)},scrollTo(W){const{instance:G}=E.current;G==null?console.error("CodeView.scrollTo: no valid instance to scroll with",W):G.scrollTo(W)},setSelectedLines(W){const{instance:G}=E.current;G==null?console.error("CodeView.setSelectedLines: no valid instance to update selection with",W):(G.setSelectedLines(W,{notify:!1}),H(W))},getSelectedLines(){const{instance:W}=E.current;return W==null?(console.error("CodeView.getSelectedLines: no valid instance exists"),null):W.getSelectedLines()},clearSelectedLines(){const{instance:W}=E.current;W==null?console.error("CodeView.clearSelectedLines: no valid instance to update selection with"):(W.clearSelectedLines({notify:!1}),H(null))},getEditor(W){const{instance:G}=E.current;if(G==null){console.error("CodeView.getEditor: no valid instance exists",W);return}return G.getEditor(W)},getInstance(){return E.current.instance}}),[H]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:_e,className:n,style:N}),($||R||B)&&i.jsx(x9,{managedContentStore:pe,renderCustomHeader:v,renderHeaderPrefix:_,renderHeaderFilenameSuffix:w,renderHeaderMetadata:b,renderAnnotation:f,renderGutterUtility:y,renderCodeViewHeader:x,renderCodeViewFooter:g})]})}const xT=m.forwardRef(h9);function p9(e,t){if(e==null||t.length<=e.length)return!1;if(e.length===0)return!0;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function f9(e,t){if(e==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Kd(e,t){if(e)throw new Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function m9(){let e;const t=new Set;return{getSnapshot(){return e},publish(n){if(!hT(e,n)){e=n;for(const s of t)s()}},subscribe(n){return t.add(n),()=>{t.delete(n)}}}}function g9({options:e,hasCustomHeader:t,hasGutterRenderer:n,hasCodeViewHeader:s,hasCodeViewFooter:o,onSelectedLinesChange:r,controlledSelection:a,createEditor:l,onItemEditChange:d,onItemEditComplete:c}){const u={...e,controlledSelection:a,onSelectedLinesChange:r,createEditor:l};return d!=null&&(u.onItemEditChange=d),c!=null&&(u.onItemEditComplete=c),t&&(u.renderCustomHeader=qd),n&&(u.renderGutterUtility=qd),s&&(u.renderCodeViewHeader=qd),o&&(u.renderCodeViewFooter=qd),u}const x9=m.memo(function({managedContentStore:t,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l,renderCodeViewHeader:d,renderCodeViewFooter:c}){"use no memo";const u=so(g=>t.subscribe(g)),h=so(()=>t.getSnapshot()),p=m.useSyncExternalStore(u,h,h);let f="";for(const g of p?.items??[])f+=`${g.id}:${g.version}:${g.type}`;return i.jsxs(i.Fragment,{children:[m.useMemo(()=>p?.items?.map(g=>Ws.createPortal(v9({renderedItem:g,renderCustomHeader:n,renderHeaderPrefix:s,renderHeaderFilenameSuffix:o,renderHeaderMetadata:r,renderAnnotation:a,renderGutterUtility:l}),g.element,g.id)),[n,s,o,r,a,l,f]),m.useMemo(()=>d!=null&&p?.header!=null?Ws.createPortal(d(),p.header):null,[d,p?.header]),m.useMemo(()=>c!=null&&p?.footer!=null?Ws.createPortal(c(),p.footer):null,[c,p?.footer])]})});function v9({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderFilenameSuffix:s,renderHeaderMetadata:o,renderAnnotation:r,renderGutterUtility:a}){if(e.type==="diff"){const{item:l,instance:d}=e;return gT({fileDiff:l.fileDiff,renderCustomHeader:t!=null?()=>t(l):void 0,renderHeaderPrefix:n!=null?()=>n(l):void 0,renderHeaderFilenameSuffix:s!=null?()=>s(l):void 0,renderHeaderMetadata:o!=null?()=>o(l):void 0,renderAnnotation:r!=null?c=>r(c,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?c=>a(c,l):void 0,getHoveredLine:d.getHoveredLine})}else{const{item:l,instance:d}=e;return jA({file:l.file,renderCustomHeader:t!=null?()=>t(l):void 0,renderHeaderPrefix:n!=null?()=>n(l):void 0,renderHeaderFilenameSuffix:s!=null?()=>s(l):void 0,renderHeaderMetadata:o!=null?()=>o(l):void 0,renderAnnotation:r!=null?c=>r(c,l):void 0,lineAnnotations:l.annotations,renderGutterUtility:a!=null?c=>a(c,l):void 0,getHoveredLine:d.getHoveredLine})}}function qd(){}const uy=typeof window>"u"?m.useEffect:m.useLayoutEffect;function b9({fileDiff:e,options:t,editorOptions:n,lineAnnotations:s,selectedLines:o,prerenderedHTML:r,metrics:a,hasGutterRenderUtility:l,hasCustomHeader:d,disableWorkerPool:c,edit:u}){const h=_A(),p=o!==void 0,f=m.useContext(yk),g=wk(),x=m.useRef(null),v=so(y=>{if(y!=null){if(x.current!=null)throw new Error("useFileDiffInstance: An instance should not already exist when a node is created");h!=null?x.current=new uT(Ip({controlledSelection:p,hasCustomHeader:d,hasGutterRenderUtility:l,options:t}),h,a,c?void 0:f,!0):x.current=new cT(Ip({controlledSelection:p,hasCustomHeader:d,hasGutterRenderUtility:l,options:t}),c?void 0:f,!0),x.current.hydrate({fileDiff:e,fileContainer:y,lineAnnotations:s,prerenderedHTML:r})}else{if(x.current==null)throw new Error("useFileDiffInstance: A FileDiff instance should exist when unmounting");x.current.cleanUp(),x.current=null}});return uy(()=>{const{current:y}=x;if(y==null)return;const w=Ip({controlledSelection:p,hasCustomHeader:d,hasGutterRenderUtility:l,options:t}),b=w!==void 0&&!Hu(y.options,w);y.setOptions(w),y.render({forceRender:b,fileDiff:e,lineAnnotations:s}),o!==void 0&&y.setSelectedLines(o)}),uy(()=>{if(u&&x.current!=null){if(g===void 0)throw new Error("FileDiff: EditContext is not attached");const y=g(n??{});if(y==null)throw new Error("FileDiff: EditProvider.createEditor must return an editor instance");try{return y.edit(x.current)}catch(w){throw y.cleanUp(),w}}},[u]),{ref:v,getHoveredLine:m.useCallback(()=>x.current?.getHoveredLine(),[])}}function Ip({options:e,controlledSelection:t,hasCustomHeader:n,hasGutterRenderUtility:s}){return t||s||n?{...e,controlledSelection:t,renderCustomHeader:n?Bv:e?.renderCustomHeader,renderGutterUtility:s?Bv:e?.renderGutterUtility}:e}function w9({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,className:a,style:l,prerenderedHTML:d,renderAnnotation:c,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderGutterUtility:g,disableWorkerPool:x=!1,edit:v=!1}){const{ref:y,getHoveredLine:w}=b9({fileDiff:e,options:t,editorOptions:n,metrics:s,lineAnnotations:o,selectedLines:r,prerenderedHTML:d,hasGutterRenderUtility:g!=null,hasCustomHeader:u!=null,disableWorkerPool:x,edit:v});return i.jsx(bk,{ref:y,className:a,style:l,children:NA(gT({fileDiff:e,renderCustomHeader:u,renderHeaderPrefix:h,renderHeaderFilenameSuffix:p,renderHeaderMetadata:f,renderAnnotation:c,renderGutterUtility:g,lineAnnotations:o,getHoveredLine:w}),d)})}function y9(e,t){return e.length===t.length&&e.every((n,s)=>n.path===t[s].path&&n.edits===t[s].edits&&n.writeContent===t[s].writeContent&&n.fileChange===t[s].fileChange)}function S9(e,t){const n=Object.keys(t);return n.length===Object.keys(e).length&&n.every(s=>e[s]===t[s])}function vT(e,t){let n=e;for(let s=t.length-1;s>=0;s--){const{oldText:o,newText:r}=t[s],a=n.indexOf(r);if(a===-1)return null;n=n.slice(0,a)+o+n.slice(a+r.length)}return n}function C9(e){const t=new Map;for(const r of e.tools){if(!r.path)continue;const a=t.get(r.path)??[];a.push(r),t.set(r.path,a)}const n=[],s=new Set(Object.entries(e.snapshots).flatMap(([r,a])=>a===null?[r]:[])),o={...e.snapshots};for(const[r,a]of t){const l=e.currentByPath[r],d=a.flatMap(w=>w.edits??[]),c=a.flatMap(w=>w.fileChange&&w.fileChange.truncated!==!0?[w.fileChange]:[]),u=[...a].reverse().find(w=>w.writeContent!=null)?.writeContent,h=a.find(w=>w.fileChange)?.fileChange,p=[...a].reverse().find(w=>w.fileChange||w.writeContent!=null||w.edits?.length),f=p?.fileChange?p.fileChange.truncated===!0?null:p.fileChange.newText:p?.writeContent??null,g=Object.hasOwn(o,r),x=o[r];if(!g&&h?.truncated===!0){o[r]=null,s.add(r);continue}if(g&&x===null){s.add(r);continue}let v=typeof x=="string"?x:c[0]?.oldText??null;const y=typeof l=="string"?l:f;v==null&&(d.length>0&&typeof l=="string"?v=vT(l,d):u!=null&&d.length===0&&(v="")),y==null&&p?.fileChange?.truncated===!0&&s.add(r),!(v==null||y==null)&&(v===y&&c.length===0||(o[r]=v,n.push({path:r,oldText:v,newText:y})))}return{files:n,snapshots:o,...s.size>0?{incompletePaths:[...s]}:{}}}const k9={theme:xa,diffStyle:"split",lineDiffType:"word",disableFileHeader:!0,preferredHighlighter:"shiki-js",overflow:"wrap"};function hy({path:e,blocks:t,snapshot:n}){const{t:s}=Q(),o=e.split("/").pop()||"file",[r,a]=m.useState({kind:"loading"});return m.useEffect(()=>{let l=!0;return n?(a({kind:"loading"}),ia().then(()=>{l&&a({kind:"full",oldText:n.oldText,newText:n.newText})}).catch(()=>{l&&a({kind:"blocks"})}),()=>{l=!1}):(Promise.all([ia(),window.electronAPI.files.read(e)]).then(([,d])=>{if(!l)return;const c=typeof d=="string"?vT(d,t):null;a(c!=null&&typeof d=="string"?{kind:"full",oldText:c,newText:d}:{kind:"blocks"})}).catch(()=>{l&&a({kind:"blocks"})}),()=>{l=!1})},[e,t,n]),r.kind==="loading"?i.jsx("div",{className:"border-t border-border/60 px-3 py-2 text-xs text-muted-foreground",children:s("Loading diff…")}):i.jsx("div",{className:"border-t border-border/60 text-xs",children:r.kind==="full"?i.jsx(py,{name:o,oldText:r.oldText,newText:r.newText}):t.map((l,d)=>i.jsx(py,{name:o,oldText:l.oldText,newText:l.newText},d))})}function py({name:e,oldText:t,newText:n}){const s=id(k9),o=m.useMemo(()=>{const r=go({name:e,contents:t},{name:e,contents:n});return r.cacheKey=Rx(e,t,n),r},[e,t,n]);return i.jsx(w9,{fileDiff:o,options:s})}function ym({hits:e,defaultOpen:t=!1}){const{t:n}=Q();return e.length===0?i.jsx("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("No results")}):i.jsx("ul",{className:"divide-y divide-border/60",children:e.map(s=>i.jsx(_9,{hit:s,defaultOpen:t},s.id))})}function j9({view:e}){const{t}=Q(),n=e.written?e.deduplicated&&t("Identical memory already exists, nothing new was written"):t("Similar memories already exist, nothing was written");return i.jsxs(i.Fragment,{children:[n&&i.jsx("p",{className:"px-3 pt-2 text-xs text-muted-foreground",children:n}),e.written?i.jsx(ym,{hits:[e.memory],defaultOpen:!0}):i.jsx(ym,{hits:e.candidates})]})}function _9({hit:e,defaultOpen:t}){const{t:n}=Q(),[s,o]=m.useState(t);return i.jsx("li",{children:i.jsxs("button",{type:"button","aria-expanded":s,onClick:r=>{const a=window.getSelection();a?.toString()&&r.currentTarget.contains(a.anchorNode)||o(l=>!l)},className:"block w-full cursor-pointer px-3 py-2 text-left transition-colors hover:bg-muted/40",children:[i.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:q("min-w-0 flex-1 font-medium text-foreground text-xs",s?"break-words":"truncate"),children:e.title}),e.unitType&&i.jsx(oa,{variant:"secondary",size:"sm",children:e.unitType}),e.space&&i.jsx(oa,{variant:"outline",size:"sm",children:n(e.space==="global"?"Global":"Project")}),e.relevance!==null&&i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",title:n("Semantic similarity"),children:e.relevance.toFixed(2)})]}),i.jsx("span",{className:q("mt-0.5 whitespace-pre-wrap break-words text-muted-foreground text-xs leading-relaxed",s?"block":"line-clamp-2"),children:e.content})]})})}const N9={"agent-type":"bg-purple-500/15 text-purple-600 dark:text-purple-400",file:"bg-success/15 text-success",chat:"bg-warning/25 text-warning-foreground dark:bg-warning/15 dark:text-warning","ui-element":"bg-purple-500/15 text-purple-600 dark:text-purple-400"};function Gx(e){return q("inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",N9[e])}function T9({label:e,onRemove:t}){return i.jsx("button",{type:"button",onClick:t,className:"rounded-sm opacity-70 transition-opacity hover:opacity-100","aria-label":e,children:i.jsx(an,{className:"h-3 w-3"})})}function D9({recipient:e,onRemove:t}){const{t:n}=Q();return i.jsxs("span",{className:q(Gx("agent-type"),"mt-0.5 shrink-0"),children:[i.jsx(Hs,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:e.label}),i.jsx(T9,{label:n("Remove Agent recipient"),onRemove:t}),i.jsx("span",{className:"sr-only",children:e.typeKey})]})}const Fx=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bT(e){if(!e)return null;try{const t=JSON.parse(e);return Fx(t)?t:null}catch{return null}}function Sm(e,t){if(!Array.isArray(e))return null;const n=[];for(const s of e){if(!Fx(s)||typeof s.id!="string"||!s.id||typeof s.title!="string"||typeof s.content!="string")return null;const{spaceId:o,[t]:r}=s;n.push({id:s.id,title:s.title,content:s.content,unitType:typeof s.unitType=="string"&&s.unitType?s.unitType:null,space:o==="global"?"global":typeof o=="string"&&o.startsWith("proj:")?"project":null,relevance:typeof r=="number"&&Number.isFinite(r)?r:null})}return n}function I9(e){const t=bT(e);return t?Sm(t.results,"relevance"):null}function E9(e,t){const n=bT(e);if(n?.status==="candidates_found"){const o=Sm(n.candidates,"similarity");return o?{written:!1,candidates:o}:null}if(n?.status!=="inserted"||!Fx(n.memory)||!t)return null;const s=Sm([{...n.memory,content:t}],"relevance")?.[0];return s?{written:!0,deduplicated:n.deduplicated===!0,memory:s}:null}const wT=m.createContext(void 0);function jd(e){const t=m.useContext(wT);if(t===void 0&&!e)throw new Error(od(50));return t}const P9=600,yT=300,A9={...DA,instantType:e=>e.instantType,adaptiveOrigin:e=>e.adaptiveOrigin,closeDelay:e=>e.closeDelay};class M9 extends TA{constructor(t,n,s){const o=new AA;super(R9(t,o,n,s),L9(o),A9)}setOpen=(t,n)=>{const{inlineRectCoordsRef:s}=this.context;IA(this,t,n,{onBeforeDispatch(){const o=n.event;t&&n.reason===MA&&n.trigger&&"clientX"in o&&"clientY"in o&&s.current?.element!==n.trigger&&fN(s,n.trigger,o.clientX,o.clientY)}})}}function R9(e,t,n,s=!1){const o={...EA(),instantType:void 0,adaptiveOrigin:void 0,closeDelay:yT,...e};return o.floatingRootContext=PA(t,n,s),o}function L9(e){return{popupRef:m.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e,inlineRectCoordsRef:{current:void 0}}}function fy(e){const{open:t,defaultOpen:n=!1,onOpenChange:s,onOpenChangeComplete:o,actionsRef:r,handle:a,triggerId:l,defaultTriggerId:d=null,children:c}=e,u=OA((y,w)=>new M9({open:n,openProp:t,activeTriggerId:d,triggerIdProp:l},y,w));u.useControlledProp("openProp",t),u.useControlledProp("triggerIdProp",l),u.useContextCallback("onOpenChange",s),u.useContextCallback("onOpenChangeComplete",o);const h=u.useState("open"),p=u.useState("activeTriggerId"),f=u.useState("mounted"),g=u.useState("payload");zA(u,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:x}=GA(h,u,()=>{u.context.inlineRectCoordsRef.current=void 0});lg(()=>{h&&p==null&&u.set("payload",void 0)},[u,p,h]),m.useImperativeHandle(r,()=>({unmount:x,close:()=>u.setOpen(!1,FA(HA))}),[x,u]);const v=h||f;return i.jsxs(wT.Provider,{value:u,children:[a&&i.jsx(BA,{handle:a,store:u}),v&&i.jsx(O9,{store:u}),typeof c=="function"?c({payload:g}):c]})}function O9({store:e}){const t=e.useState("floatingRootContext"),n=VA(t);return $A(e,{activeTriggerProps:n.reference,inactiveTriggerProps:n.trigger,popupProps:n.floating}),null}const z9=RA(function(t){return jd(!0)?i.jsx(fy,{...t}):i.jsx(LA,{children:i.jsx(fy,{...t})})}),ST=m.createContext(void 0);function G9(){const e=m.useContext(ST);if(e===void 0)throw new Error(od(48));return e}const F9=m.forwardRef(function(t,n){const{keepMounted:s=!1,...o}=t;return jd().useState("mounted")||s?i.jsx(ST.Provider,{value:s,children:i.jsx(WA,{ref:n,...o})}):null}),H9=UA(function(t,n){const{render:s,className:o,delay:r,closeDelay:a,id:l,payload:d,handle:c,style:u,...h}=t,p=jd(!0),g=KA(c)??p;if(!g)throw new Error(od(89));const x=Sk(l),v=g.useState("isTriggerActive",x),y=g.useState("isOpenedByTrigger",x),w=g.useState("floatingRootContext"),b=g.context.inlineRectCoordsRef,_=m.useRef(null),j=r??P9,N=a??yT,{registerTrigger:C,isMountedByThisTrigger:S}=qA(x,_,g,{payload:d,closeDelay:N}),A=YA(w,{mouseOnly:!0,move:!1,handleClose:XA(),delay:()=>({open:j,close:N}),triggerElementRef:_,isActiveTrigger:v,isClosing:()=>g.select("transitionStatus")==="ending"}),E=ZA(w,{delay:j}),I={open:y},D=g.useState("triggerProps",S),T=q6(b,y);return rd("a",t,{state:I,ref:[n,C,_],props:[A,E.reference,D,T,{id:x},h],stateAttributesMapping:JA})}),CT=m.createContext(void 0);function B9(){const e=m.useContext(CT);if(e===void 0)throw new Error(od(49));return e}const V9=m.forwardRef(function(t,n){const{render:s,className:o,anchor:r,positionMethod:a="absolute",side:l="bottom",align:d="center",sideOffset:c=0,alignOffset:u=0,collisionBoundary:h="clipping-ancestors",collisionPadding:p=5,arrowPadding:f=5,sticky:g=!1,disableAnchorTracking:x=!1,collisionAvoidance:v=QA,style:y,...w}=t,b=jd(),_=G9(),j=eM(),N=b.useState("open"),C=b.useState("mounted"),S=b.useState("floatingRootContext"),A=b.useState("instantType"),E=b.useState("transitionStatus"),I=b.useState("adaptiveOrigin"),D=b.context.inlineRectCoordsRef,T=tM({anchor:r,floatingRootContext:S,positionMethod:a,mounted:C,side:l,sideOffset:c,align:d,alignOffset:u,arrowPadding:f,collisionBoundary:h,collisionPadding:p,sticky:g,disableAnchorTracking:x,keepMounted:_,nodeId:j,collisionAvoidance:v,adaptiveOrigin:I,inline:Y6(D)}),z=T.update;lg(()=>{N&&C&&z()},[N,C,z]);const $={open:N,side:T.side,align:T.align,anchorHidden:T.anchorHidden,instant:A},R=nM(t,$,{styles:T.positionerStyles,transitionStatus:E,props:w,refs:[n,b.useStateSetter("positionerElement")],hidden:!C,inert:!N});return i.jsx(CT.Provider,{value:T,children:i.jsx(sM,{id:j,children:R})})}),$9=m.forwardRef(function(t,n){const{className:s,render:o,style:r,...a}=t,l=jd(),{side:d,align:c}=B9(),u=l.useState("open"),h=l.useState("instantType"),p=l.useState("transitionStatus"),f=l.useState("popupProps"),g=l.useState("floatingRootContext"),x=l.useState("closeDelay");return iM({open:u,ref:l.context.popupRef,onComplete(){u&&l.context.onOpenChangeComplete?.(!0)}}),oM(g,{closeDelay:x}),rd("div",t,{state:{open:u,side:d,align:c,instant:h,transitionStatus:p},ref:[n,l.context.popupRef,l.useStateSetter("popupElement")],props:[rM,f,lM(p),a],stateAttributesMapping:aM})}),Hx=z9;function Bx({...e}){return i.jsx(H9,{"data-slot":"preview-card-trigger",...e})}function kT({className:e,children:t,align:n="center",sideOffset:s=4,...o}){return i.jsx(F9,{children:i.jsx(V9,{align:n,className:"z-50","data-slot":"preview-card-positioner",sideOffset:s,children:i.jsx($9,{className:q("relative flex w-64 origin-(--transform-origin) text-balance rounded-lg border bg-popover bg-clip-padding p-4 text-popover-foreground text-sm shadow-lg transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"preview-card-content",...o,children:t})})})}const my={mask:"text-sky-600 dark:text-sky-400",warn:"text-amber-600 dark:text-amber-400",block:"text-red-600 dark:text-red-400"},W9={mask:Bu,warn:ta,block:Ck},U9={mask:"Mask",warn:"Warn only",block:"Block"},K9={system:"System prompt",user:"Your message",tool_result:"Tool output",tool_args:"Tool arguments",assistant:"Earlier replies",tools:"Tool descriptions"};function q9({report:e}){const{t}=Q(),n=dM(e);if(!n)return null;const s=W9[n],o=new Set(e.hits.map(r=>r.token)).size;return i.jsxs(Hx,{children:[i.jsxs(Bx,{render:i.jsx("span",{className:q("inline-flex shrink-0 items-center gap-0.5 text-[11px]",my[n]),"data-privacy-mask":n}),children:[i.jsx(s,{className:"size-3.5"}),i.jsx("span",{className:"tabular-nums",children:o})]}),i.jsxs(kT,{className:"max-h-(--available-height) w-72 flex-col overflow-y-auto overscroll-contain text-xs",children:[i.jsx("p",{className:"mb-1.5 font-medium",children:t("Privacy masking")}),i.jsx("ul",{className:"space-y-1",children:cM(e.hits).map(r=>i.jsxs("li",{className:"flex flex-wrap gap-x-2",children:[i.jsx("span",{className:my[r.action],children:t(U9[r.action])}),i.jsx("span",{children:r.kind}),i.jsx("span",{className:"text-muted-foreground",children:t(K9[r.where]??r.where)}),i.jsx("span",{className:"text-muted-foreground",children:r.values>1?t("{{count}} values",{count:r.values}):r.preview}),r.count>1&&i.jsxs("span",{className:"text-muted-foreground",children:["×",r.count]})]},`${r.action}-${r.kind}-${r.where}`))}),e.restored>0&&i.jsx("p",{className:"mt-1.5 text-muted-foreground",children:t("Restored {{count}} in the reply",{count:e.restored})})]})]})}const Y9=/^\[.+#[0-9A-Fa-f]{4}\]$/;function X9(e){const t=e.indexOf(`
|
|
58
|
-
`),n=t===-1?e:e.slice(0,t);return Y9.test(n)?t===-1?"":e.slice(t+1).split(`
|
|
59
|
-
`).map(s=>s.replace(/^\d+:/,"")).join(`
|
|
60
|
-
`):e}const Z9={theme:xa,disableFileHeader:!0,overflow:"wrap",preferredHighlighter:"shiki-js"};function Fc({path:e,contents:t}){const{t:n}=Q(),[s,o]=m.useState(!1),r=id(Z9);m.useEffect(()=>{let l=!0;return ia().then(()=>{l&&o(!0)}),()=>{l=!1}},[]);const a=m.useMemo(()=>({name:e.split("/").pop()||"file",contents:X9(t)}),[e,t]);return s?i.jsx(kk,{file:a,disableWorkerPool:!0,options:r}):i.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:n("Loading...")})}function J9(e){const{inputTokens:t,outputTokens:n}=e;if(typeof t!="number"||!Number.isFinite(t)||t<0||typeof n!="number"||!Number.isFinite(n)||n<0)return null;const s=Math.max(0,t-n);return{tokens:s,percent:t>0?Math.round(s/t*100):null}}const Q9={compressed:"Compressed",unchanged:"Unchanged",pending:"Background task started",bypassed:"Bypassed",unavailable:"Unavailable"};function e7({value:e}){const t=C6(e),{t:n}=Q();if(!t)return null;const s=J9(t);return i.jsxs("div",{className:"border-border/60 border-t text-[10px] text-muted-foreground","data-rtk-status":t.status,children:[i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 px-3 py-1",children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:"RTK"}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n(Q9[t.status])}),s&&i.jsxs(i.Fragment,{children:[i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:n("~{{count}} tokens saved",{count:gs(s.tokens)})}),s.percent!==null&&i.jsxs("span",{children:["(",s.percent,"%)"]})]})]}),i.jsxs("div",{className:"space-y-2 px-3 pb-2",children:[t.status==="pending"&&i.jsx("p",{className:"rounded bg-muted/40 px-2 py-1 text-foreground/80",children:n("This is the startup receipt; see the task_output result for final statistics.")}),(t.inputTokens!==void 0||t.reason)&&i.jsxs("dl",{className:"grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1",children:[t.inputTokens!==void 0&&t.outputTokens!==void 0&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{children:n("Input estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:gs(t.inputTokens)})}),i.jsx("dt",{children:n("Output estimate")}),i.jsx("dd",{className:"font-mono text-foreground/80",children:n("{{count}} tokens",{count:gs(t.outputTokens)})})]}),t.reason&&i.jsxs(i.Fragment,{children:[i.jsx("dt",{children:n("Reason")}),i.jsx("dd",{className:"min-w-0 whitespace-pre-wrap text-foreground/80",children:t.reason})]})]})]})]})}function t7(e,t,n){if(e==null||t===void 0||t<=e)return null;const s=Math.max(0,t-n);return{remainingMs:s,fraction:Math.min(1,s/(t-e))}}function n7(e,t,n=k6){const s=t-e;return s>=n?s:null}const s7={exit_nonzero:"Exit {{code}}",deadline:"Killed at timeout",stopped_by_user:"Stopped by you",tty_required:"Needs terminal",auth_required:"Needs login",not_found:"Command not found",not_executable:"Not executable",binary_output:"Binary output",output_truncated:"Log truncated"},i7={deadline:"Killed when its timeout was reached. Raise the timeout or run it in the background.",tty_required:"Needs an interactive terminal. Use a non-interactive flag (such as --yes) or run it in your own terminal.",auth_required:"Needs credentials. Sign in from your own terminal, then retry.",not_found:"The program is not installed or not on PATH."},jT=600;function o7(e){return e?.kind==="deadline"?["background","timeout"]:[]}function r7(e,t,n){const s=`\`\`\`
|
|
61
|
-
${t}
|
|
62
|
-
\`\`\``;return e==="background"?n(`Rerun this command with background: true:
|
|
63
|
-
|
|
64
|
-
{{command}}`,{command:s}):n(`Rerun this command with timeout: {{seconds}}:
|
|
65
|
-
|
|
66
|
-
{{command}}`,{seconds:jT,command:s})}function a7(e,t,n){return t(e)?(n(),!0):!1}let gl=null,xl=null,vl=null,bl=null,wl=null,yl=null;function l7(e){return gl=e,()=>{gl===e&&(gl=null)}}function d7(e){return vl=e,()=>{vl===e&&(vl=null)}}function c7(e){return xl=e,()=>{xl===e&&(xl=null)}}function wo(){return vl?(vl(),!0):!1}function u7(e){return yl=e,()=>{yl===e&&(yl=null)}}function h7(e){return yl?yl(e):!1}function Xl(e){return gl?(gl(e),!0):!1}function wh(e){return xl?(xl(e),!0):!1}function p7(e){return bl=e,()=>{bl===e&&(bl=null)}}function Vx(e,t){return bl?(bl(e,t),!0):!1}function f7(e){return wl=e,()=>{wl===e&&(wl=null)}}function m7(e){return wl?(wl(e),!0):!1}function g7(){const[e,t]=m.useState(()=>Date.now());return m.useEffect(()=>{const n=setInterval(()=>t(Date.now()),1e3);return()=>clearInterval(n)},[]),e}const Cm=5,gy=2*Math.PI*Cm;function x7({startedAt:e,deadlineAt:t,output:n}){const{t:s}=Q(),o=g7(),r=m.useRef({output:n,at:e??Date.now()});r.current.output!==n&&(r.current={output:n,at:Date.now()});const a=t7(e,t,o),l=n7(r.current.at,o);return!a&&l===null?null:i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[10px] text-muted-foreground/70 tabular-nums",children:[l!==null&&i.jsx("span",{"data-shell-quiet":!0,className:"rounded bg-muted px-1",children:s("No output for {{seconds}}s",{seconds:Math.floor(l/1e3)})}),a&&a.remainingMs>0&&i.jsxs("span",{className:"flex items-center gap-0.5",title:s("Moves to background in {{seconds}}s",{seconds:Math.ceil(a.remainingMs/1e3)}),children:[i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12","aria-hidden":"true",children:[i.jsx("circle",{cx:"6",cy:"6",r:Cm,fill:"none",stroke:"currentColor",opacity:"0.25"}),i.jsx("circle",{cx:"6",cy:"6",r:Cm,fill:"none",stroke:"currentColor",strokeDasharray:gy,strokeDashoffset:gy*(1-a.fraction),transform:"rotate(-90 6 6)"})]}),Math.ceil(a.remainingMs/1e3),"s"]})]})}function _T(e,t){return e.kind==="exit_nonzero"&&e.exitCode===void 0?t("Failed"):t(s7[e.kind],{code:e.exitCode??""})}function v7({failure:e}){const{t}=Q();return i.jsx("span",{"data-shell-failure":e.kind,className:q("shrink-0 rounded px-1 text-[10px]",e.retryable?"bg-muted text-muted-foreground":"bg-destructive/10 text-destructive"),children:_T(e,t)})}function b7({failure:e,command:t}){const{t:n}=Q(),[s,o]=m.useState(!1);if(!e)return null;const r=i7[e.kind],a=o7(e);return i.jsxs("div",{"data-shell-status":e.kind,className:"mt-2 flex items-center gap-2 border-t border-current/10 pt-1.5 text-[11px] opacity-80",children:[i.jsx("span",{className:"shrink-0 font-medium",children:_T(e,n)}),r&&i.jsx("span",{className:"min-w-0 flex-1",children:n(r)}),a.map(l=>i.jsx("button",{type:"button","data-shell-rerun":l,onClick:()=>{a7(r7(l,t,n),wh,wo)},className:"flex shrink-0 items-center gap-1 underline-offset-2 hover:underline hover:opacity-100",children:l==="background"?n("Rerun in background"):n("Rerun with {{seconds}}s timeout",{seconds:jT})},l)),i.jsxs("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(t).then(()=>{o(!0),setTimeout(()=>o(!1),1e3)})},className:"ml-auto flex shrink-0 items-center gap-1 hover:opacity-100",title:n("Copy command"),children:[s?i.jsx(Un,{className:"h-3 w-3"}):i.jsx(Vu,{className:"h-3 w-3"}),n("Copy command")]})]})}function w7(e){return e.startsWith("/skill:")?"skill":e==="/goal"?"goal":"command"}function y7(e){return e.startsWith("/skill:")?e.slice(7):e.replace(/^\//,"")}function ju(e){const t=/^\/skill:(\S+)(?:\s+([\s\S]*))?$/.exec(e);if(t)return{slash:`/skill:${t[1]}`,rest:t[2]??""};const n=/^\/([A-Za-z][\w:-]*)(?:\s+([\s\S]*))?$/.exec(e);return n?{slash:`/${n[1]}`,rest:n[2]??""}:{slash:null,rest:e}}const S7={skill:zs,goal:Na,command:iN},C7={skill:"bg-info/15 text-info",goal:"bg-warning/25 text-warning-foreground dark:bg-warning/15 dark:text-warning",command:"bg-foreground/10 text-foreground"};function NT(e,t=!1){return q("inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium",C7[e],t&&e==="skill"&&"hover:bg-info/25",t&&e==="goal"&&"hover:bg-warning/35 dark:hover:bg-warning/25",t&&e==="command"&&"hover:bg-foreground/15")}function _u({name:e,className:t,interactive:n=!1,trailing:s}){const o=w7(e),r=S7[o];return i.jsxs("span",{className:q(NT(o,n),t),children:[i.jsx(r,{className:"h-3 w-3"}),y7(e),s]})}function k7({icon:e,state:t}){const n=t==="running"||t==="reviewing";return i.jsxs("span",{className:q("relative flex size-[22px] shrink-0 items-center justify-center rounded-full border text-muted-foreground",n&&"border-transparent text-brand",t==="error"&&"border-destructive/40 text-destructive"),children:[i.jsx(e,{className:"size-3"}),n&&i.jsx("span",{className:"absolute -inset-px animate-spin rounded-full border-[1.5px] border-brand/20 border-t-brand"})]})}function TT({state:e}){const t=e==="running"||e==="reviewing";return i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:t?i.jsx("span",{className:"size-2.5 animate-spin rounded-full border-[1.5px] border-border border-t-brand"}):e==="error"?i.jsx("span",{className:"size-1.5 rounded-full bg-destructive"}):i.jsx("span",{className:"size-1 rounded-full bg-current opacity-60"})})}const j7={queued:["Queued","bg-muted-foreground"],running:["running","bg-amber-500"],awaiting_input:["awaiting input","bg-amber-500"],validating:["validating","bg-amber-500"],succeeded:["succeeded","bg-emerald-500"],failed:["failed","bg-destructive"],cancelled:["cancelled","bg-muted-foreground"],interrupted:["interrupted","bg-muted-foreground"],creating:["creating","bg-amber-500"],ready:["idle","bg-muted-foreground"],active:["running","bg-amber-500"],parked:["parked","bg-muted-foreground"],closed:["closed","bg-muted-foreground"]};function _7({view:e,titles:t}){const{t:n}=Q();return i.jsxs("div",{className:"space-y-2 px-3 py-2 text-sm",children:[e.kind==="report"&&e.text&&i.jsx(js,{text:e.text}),e.kind==="report"&&e.value&&i.jsx(js,{text:`\`\`\`json
|
|
67
|
-
${e.value}
|
|
68
|
-
\`\`\``}),e.kind==="report"&&e.error&&i.jsx("p",{className:"whitespace-pre-wrap text-destructive",children:e.error}),e.runs.length>0&&i.jsx("ul",{className:"space-y-0.5 text-xs text-muted-foreground",children:e.runs.map(s=>i.jsx(N7,{run:s,title:t?.[s.agentId]},s.runId||s.agentId))}),e.kind==="list"&&e.runs.length===0&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("No agents")}),e.kind==="wait"&&e.timedOut&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Timed out; unfinished agents keep running")}),e.kind==="wait"&&e.interrupted&&i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Wait was interrupted")}),i.jsxs("details",{className:"text-xs text-muted-foreground",children:[i.jsx("summary",{className:"cursor-pointer hover:text-foreground",children:n("Run info")}),i.jsx("pre",{className:"mt-1 whitespace-pre-wrap font-mono",children:e.info})]}),e.head&&i.jsx("pre",{className:"whitespace-pre-wrap font-mono text-xs text-muted-foreground",children:e.head})]})}function N7({run:e,title:t}){const{t:n}=Q(),[s,o]=j7[e.status]??[null,"bg-muted-foreground"],r=e.durationMs===null?"":n("took {{duration}}",{duration:ss(e.durationMs)});return i.jsxs("li",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",o)}),t&&i.jsx("span",{className:"truncate text-foreground",children:t}),i.jsx("span",{className:"shrink-0",children:[s?n(s):e.status,r].filter(Boolean).join(" · ")})]})}const $x=e=>!!e&&typeof e=="object"&&!Array.isArray(e),xy=e=>typeof e=="string"&&e.trim()?e:null;function km(e){if(!$x(e))return null;const{agentId:t,runId:n,status:s,createdAt:o,startedAt:r,finishedAt:a}=e;if(typeof t!="string"||typeof n!="string"||typeof s!="string")return null;const l=typeof r=="number"?r:o;return{agentId:t,runId:n,status:s,durationMs:typeof a=="number"&&typeof l=="number"?Math.max(0,a-l):null}}const T7=new Set(["closed","parked","creating"]);function D7(e){if(!$x(e))return null;const{agentId:t,status:n,latestRun:s}=e;return typeof t!="string"||typeof n!="string"?null:(T7.has(n)?null:km(s))??{agentId:t,runId:"",status:n,durationMs:null}}function I7(e,t){const n=uM(t);if(!n)return null;const{head:s,value:o}=n;if(e==="report"){const l=km(o.run);if(!l)return null;const{text:d,value:c,error:u,...h}=o;return{kind:"report",head:s,runs:[l],text:xy(d),value:c==null?null:JSON.stringify(c,null,2),error:xy(u),info:JSON.stringify(h,null,2)}}if(e==="list"){if(!Array.isArray(o.agents))return null;const l=o.agents.flatMap(d=>D7(d)??[]);return l.length===o.agents.length?{kind:"list",head:s,runs:l,info:JSON.stringify(o,null,2)}:null}const r=e==="wait"?o:e===void 0?o.report:null;if(!$x(r)||!Array.isArray(r.runs))return e===void 0&&o.report===void 0&&typeof o.agentId=="string"&&typeof o.runId=="string"?{kind:"receipt",head:s,runs:[],info:JSON.stringify(o,null,2)}:null;const a=r.runs.flatMap(l=>km(l)??[]);return a.length!==r.runs.length?null:{kind:"wait",head:s,runs:a,timedOut:r.timedOut===!0,interrupted:r.interrupted===!0,info:JSON.stringify(o,null,2)}}function E7({command:e,output:t,failure:n}){const s=Ce(a=>a.terminalTheme),o=Ce(a=>a.terminalFontFamily),r=$u(s)??hM;return i.jsxs("div",{"data-slot":"terminal-output",className:"px-3 py-2 text-xs leading-relaxed",style:{backgroundColor:r.background,"--terminal-bg":r.background,color:r.foreground,fontFamily:o},children:[i.jsxs("div",{className:"whitespace-pre-wrap [overflow-wrap:anywhere]",children:[i.jsx("span",{style:{color:r.green},children:"$ "}),e]}),t&&i.jsx("pre",{className:"mt-1 whitespace-pre-wrap [overflow-wrap:anywhere]",style:{fontFamily:"inherit"},children:vi(t)}),i.jsx(b7,{failure:n,command:e})]})}function P7(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(!(n.role!=="toolResult"||n.toolName!=="todo"||!n.todos))return n.todos.some(s=>s.status!=="completed")?{id:n.toolCallId??String(t),todos:n.todos}:null}return null}function DT({todos:e}){return i.jsx("ul",{className:"space-y-0.5 text-xs",children:e.map(t=>i.jsxs("li",{className:"flex items-start gap-1.5",children:[t.status==="completed"?i.jsx(Un,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):t.status==="in_progress"?i.jsx(NV,{className:"mt-0.5 h-3 w-3 shrink-0 text-brand"}):i.jsx(gx,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground/50"}),i.jsx("span",{className:q(t.status==="completed"?"text-muted-foreground line-through":t.status==="in_progress"?"font-medium":"text-muted-foreground"),children:t.content})]},t.content))})}function IT({done:e,total:t,className:n}){return i.jsx("div",{className:q("h-0.5 overflow-hidden rounded-full bg-border",n),children:i.jsx("div",{className:"h-full rounded-full bg-brand transition-[width]",style:{width:`${t?e/t*100:0}%`}})})}const vy=new Set;function A7({conversationId:e}){const{t}=Q(),n=Ce(u=>u.pinUnfinishedTodos),s=re(u=>u.conversations[e]?.messages),o=m.useMemo(()=>n&&s?P7(s):null,[n,s]),[r,a]=m.useState(!1),[,l]=m.useState(0);if(!o||vy.has(o.id))return null;const d=o.todos.filter(u=>u.status==="completed").length,c=o.todos.find(u=>u.status==="in_progress")??o.todos.find(u=>u.status==="pending");return i.jsxs("div",{"data-enso":"todo",className:"mb-1.5 rounded-xl border bg-card px-3 py-1.5 text-xs shadow-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>a(u=>!u),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(jk,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-medium",children:t("Todos")}),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums",children:[d,"/",o.todos.length]}),!r&&c&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",title:c.content,children:c.content}),r?i.jsx(Vn,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(bn,{className:"ml-auto h-3.5 w-3.5 shrink-0 text-muted-foreground"})]}),i.jsx("button",{type:"button",title:t("Hide until the todo list updates"),onClick:()=>{vy.add(o.id),l(u=>u+1)},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}),r&&i.jsxs("div",{className:"mt-1.5 max-h-48 overflow-y-auto pb-0.5",children:[i.jsx(IT,{done:d,total:o.todos.length,className:"mb-2"}),i.jsx(DT,{todos:o.todos})]})]})}const M7={report:()=>{},scroller:{current:null}},ET=m.createContext(M7),R7=ET.Provider;function L7(){return m.useContext(ET)}async function O7(e){const t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(!t)return(await fetch(e)).blob();const n=atob(t[2]),s=new Uint8Array(n.length);for(let o=0;o<n.length;o++)s[o]=n.charCodeAt(o);return new Blob([s],{type:t[1]})}async function z7(e){const t=await O7(e);let n=t;if(t.type!=="image/png"){const s=await createImageBitmap(t),o=new OffscreenCanvas(s.width,s.height);o.getContext("2d")?.drawImage(s,0,0),s.close(),n=await o.convertToBlob({type:"image/png"})}await navigator.clipboard.write([new ClipboardItem({"image/png":n})])}function PT({src:e,className:t,frameClassName:n,onError:s}){const{t:o}=Q(),[r,a]=m.useState(!1);_k(r),m.useEffect(()=>{if(!r)return;const d=c=>{c.key==="Escape"&&a(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]);const l=()=>{z7(e).then(()=>Be({type:"success",title:o("Image copied")}),d=>Be({type:"error",title:o("Could not copy image"),description:d instanceof Error?d.message:String(d)}))};return i.jsxs(i.Fragment,{children:[i.jsxs(uo,{children:[i.jsx(ho,{render:i.jsx("button",{type:"button",onClick:()=>a(!0),className:q("cursor-zoom-in",n),children:i.jsx("img",{src:e,alt:"",className:t,onError:s})}),onContextMenu:d=>d.stopPropagation()}),i.jsx(po,{className:"min-w-36",children:i.jsx(Ut,{closeOnClick:!0,onClick:l,children:o("Copy image")})})]}),r&&i.jsx("button",{type:"button",onClick:()=>a(!1),className:q("fixed inset-0 flex cursor-zoom-out items-center justify-center bg-black/75"),style:{zIndex:kn.NESTED_MODAL_BACKDROP},"data-enso-float":"",children:i.jsx("img",{src:e,alt:"",className:"max-h-[92vh] max-w-[92vw] rounded-lg object-contain"})})]})}const G7=(e,t)=>e===t||!!e&&!!t&&e.runMs===t.runMs&&e.turnMs===t.turnMs&&e.ttftMs===t.ttftMs&&e.tps===t.tps;function F7(e,t){const n=e.item,s=t.item;if(n===s)return!0;if(n.kind!==s.kind||n.key!==s.key)return!1;switch(n.kind){case"user":return s.kind!=="user"||n.text!==s.text||n.images.length!==s.images.length||n.timestamp!==s.timestamp||n.deliveryState!==s.deliveryState||n.turnDurationMs!==s.turnDurationMs||n.collapsed!==s.collapsed||n.canCollapse!==s.canCollapse?!1:n.images.every((o,r)=>o===s.images[r]);case"text":case"thinking":return s.kind===n.kind&&n.text===s.text&&n.streaming===s.streaming&&(n.kind!=="text"||s.kind==="text"&&G7(n.perf,s.perf)&&n.timestamp===s.timestamp&&n.turnDurationMs===s.turnDurationMs)&&(n.kind!=="thinking"||s.kind==="thinking"&&n.durationMs===s.durationMs);case"tool":return s.kind==="tool"&&n.state===s.state&&n.name===s.name&&n.summary===s.summary&&n.output===s.output&&n.edits===s.edits&&n.writeContent===s.writeContent&&n.fileChanges===s.fileChanges&&n.imagePath===s.imagePath&&n.generatedImages===s.generatedImages&&n.todos===s.todos&&n.durationMs===s.durationMs&&n.startedAt===s.startedAt&&n.agentMeta===s.agentMeta&&n.source===s.source&&n.nestedPending===s.nestedPending&&JSON.stringify(n.sandbox)===JSON.stringify(s.sandbox)&&n.rtk===s.rtk&&n.approvalReview===s.approvalReview&&n.plan?.title===s.plan?.title&&n.plan?.text===s.plan?.text&&n.sentMessage===s.sentMessage&&n.memoryContent===s.memoryContent&&n.ask?.question===s.ask?.question&&n.ask?.options.join(`
|
|
69
|
-
`)===s.ask?.options.join(`
|
|
70
|
-
`)&&n.ask?.answer===s.ask?.answer&&n.ask?.autoSelected===s.ask?.autoSelected&&n.subagentOp===s.subagentOp&&JSON.stringify(n.subagentTitles)===JSON.stringify(s.subagentTitles)&&n.waiting===s.waiting&&n.pluginArtifacts===s.pluginArtifacts&&n.shellFailure===s.shellFailure;case"tool-group":return s.kind==="tool-group"&&n.expanded===s.expanded&&n.count===s.count&&n.stats.commands===s.stats.commands&&n.stats.reads===s.stats.reads&&n.stats.searches===s.stats.searches&&n.stats.others===s.stats.others&&n.exploring===s.exploring&&n.activity?.thinking===s.activity?.thinking&&n.activity?.workedMs===s.activity?.workedMs&&n.explore?.goal===s.explore?.goal&&n.explore?.report===s.explore?.report&&n.explore?.steps===s.explore?.steps;case"error":return s.kind==="error"&&n.text===s.text;case"task-note":return s.kind==="task-note"&&n.detail===s.detail;case"compaction":case"compaction-notice":return(s.kind==="compaction"||s.kind==="compaction-notice")&&n.kind===s.kind&&n.summary===s.summary&&n.tokensBefore===s.tokensBefore&&n.verified===s.verified;case"compaction-progress":return s.kind==="compaction-progress"&&n.state===s.state;case"session-custom":return s.kind==="session-custom"&&n.entry===s.entry;case"divider":return s.kind==="divider"&&n.text===s.text;case"plugin-message":return s.kind==="plugin-message"&&n.text===s.text&&n.pluginId===s.pluginId}}const H7=/^<(agent-notification|goal-continuation|coworker-hired|coworker-dismissed|background-task-update)>\n?([\s\S]*?)\n?<\/\1>\s*$/,AT=/^<role>\n?([\s\S]*?)\n?<\/role>\s*/,B7=/^<workspace-migrated>\n?([\s\S]*?)\n?<\/workspace-migrated>\s*/;function V7({note:e}){const{t}=Q(),n=/(?:moved to|main working tree): (.+)$/m.exec(e)?.[1]?.trim(),s=e.includes("main working tree");return i.jsxs("aside",{title:e,className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(Ei,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0",children:[t(s?"Workspace fell back to the main working tree":"Workspace moved to an isolated worktree"),n&&i.jsx("span",{className:"ml-1.5 break-all font-mono text-[11px] opacity-80",children:n})]})]})}function MT({note:e}){const{t}=Q();return i.jsxs("aside",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(ma,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0",children:t(e==="on"?"Plan mode on: read-only research, then a plan for your approval":e==="off"?"Plan mode off":"Context compacted: the approved plan was attached again")})]})}function RT({note:e}){const{t}=Q(),n=e==="on";return i.jsxs("aside",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[n?i.jsx(MM,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}):i.jsx(w6,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0",children:t(n?"Unattended mode on: no one is watching, so it decides and keeps going":"Unattended mode off: a person is available again")})]})}function $7({tag:e,body:t}){const n=e==="agent-notification"?oU(t):null;return n?i.jsx(W7,{notices:n}):i.jsx(U7,{tag:e,body:t})}function W7({notices:e}){const{t}=Q(),[n,s]=m.useState(!1);return i.jsxs("div",{className:"w-full overflow-hidden rounded-lg border border-dashed border-border/60 text-xs text-muted-foreground",children:[i.jsxs("button",{type:"button",onClick:()=>s(o=>!o),className:"flex w-full items-start gap-2 px-3 py-2 text-left hover:text-foreground",children:[i.jsx(Hs,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.map(o=>o.header).join(" · ")}),i.jsx(bn,{className:q("mt-0.5 h-3 w-3 shrink-0 transition-transform",n&&"rotate-90")})]}),n&&e.map((o,r)=>i.jsxs("div",{className:"border-border/60 border-t",children:[e.length>1&&i.jsx("p",{className:"truncate px-3 pt-2",children:o.header}),o.report&&i.jsx("div",{className:"max-h-80 overflow-auto px-3 py-2 text-sm text-foreground",children:i.jsx(js,{text:o.report})}),o.usage&&i.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-1.5 border-border/60 border-t px-3 py-1 text-[10px]",children:[i.jsx("span",{className:"font-semibold tracking-wide text-foreground/75",children:"Subagent"}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:t("{{count}} tokens",{count:gs(o.usage.tokens)})}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:t("{{count}} tool calls",{count:o.usage.toolUses})}),i.jsx("span",{"aria-hidden":"true",children:"·"}),i.jsx("span",{children:ss(o.usage.durationMs)})]})]},r))]})}function U7({tag:e,body:t}){const[n,s]=m.useState(!1),o=t.trim(),r=o.indexOf(`
|
|
71
|
-
`),a=r>0,l=e.startsWith("coworker-")||e==="agent-notification"?Hs:Go;return i.jsxs("div",{className:"w-full rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsxs("button",{type:"button",disabled:!a,onClick:()=>s(d=>!d),className:"flex w-full items-start gap-2 text-left enabled:hover:text-foreground",children:[i.jsx(l,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:q("min-w-0 flex-1",a?"truncate":"whitespace-pre-wrap"),children:a?o.slice(0,r):o}),a&&i.jsx(bn,{className:q("mt-0.5 h-3 w-3 shrink-0 transition-transform",n&&"rotate-90")})]}),a&&n&&i.jsx("pre",{className:"mt-1.5 max-h-80 overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-words",children:o.slice(r+1)})]})}const LT=/^<message-from-main-agent>\n?([\s\S]*?)\n?<\/message-from-main-agent>\s*$/;function K7(e){const t=AT.exec(e);return LT.test(t?e.slice(t[0].length):e)}function q7({name:e,content:t}){const{t:n}=Q();return i.jsxs(wn,{children:[i.jsxs(GM,{className:NT("skill",!0),children:[i.jsx(zs,{className:"h-3 w-3"}),e]}),i.jsxs(yn,{className:"max-w-lg",children:[i.jsx(Sn,{children:i.jsxs(Cn,{className:"text-base",children:[n("Skill")," · ",e]})}),i.jsx(On,{className:"max-h-[50vh] text-sm",children:i.jsx(js,{text:t})})]})]})}function jm({chip:e,extra:t}){return i.jsxs("div",{className:"max-w-[80%] rounded-2xl rounded-br-md bg-muted px-4 py-2.5 text-sm",children:[e,t?i.jsx("span",{className:"ml-1.5 align-middle whitespace-pre-wrap",children:t}):null]})}function Y7({blocks:e}){const t=OM(e.rest),n=i.jsx(jm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:e.skills.map(s=>i.jsx(q7,{name:s.name,content:s.body},s.location))}),extra:t.rest.trim()});return!t.plan&&!t.unattended?n:i.jsxs(i.Fragment,{children:[t.plan&&i.jsx(MT,{note:t.plan}),t.unattended&&i.jsx(RT,{note:t.unattended}),n]})}function X7({text:e}){const t=Ek(e);if(t.names.length>1)return i.jsx(jm,{chip:i.jsx("span",{className:"inline-flex flex-wrap gap-1 align-middle",children:t.names.map(s=>i.jsx(_u,{name:`/skill:${s}`},s))}),extra:t.rest});const n=ju(e);return n.slash?i.jsx(jm,{chip:i.jsx(_u,{name:n.slash}),extra:n.rest.trim()}):null}function Z7({preset:e}){const{t}=Q();return i.jsxs("div",{className:"min-w-64 max-w-[80%] overflow-hidden rounded-2xl rounded-br-md bg-muted text-sm",children:[i.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2.5",children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-info/15 text-info",children:i.jsx(cg,{className:"h-4 w-4"})}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"text-[11px] text-muted-foreground",children:t("Workflow preset")}),i.jsx("p",{className:"truncate font-medium",title:e.id,children:e.name||e.id})]})]}),e.args.length>0&&i.jsx("dl",{className:"space-y-1 border-t border-border/60 px-3.5 py-2 text-xs",children:e.args.map(([n,s])=>i.jsxs("div",{className:"flex gap-2",children:[i.jsx("dt",{className:"shrink-0 font-mono text-muted-foreground",children:n}),i.jsx("dd",{className:"min-w-0 whitespace-pre-wrap break-words",children:s})]},n))})]})}function Sl({kind:e,label:t,title:n}){const s=e==="file"?bo:e==="chat"?Bo:i6;return i.jsxs("span",{className:q(Gx(e),"mx-0.5 max-w-52 rounded-md px-1.5 align-middle leading-4"),title:n,children:[i.jsx(s,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:t})]})}function Ma({text:e,searchQuery:t="",activeNth:n=-1}){const s=A6(RM(e)),o={n:0};return i.jsx("span",{className:"whitespace-pre-wrap",children:s.map((r,a)=>r.type==="file"?i.jsx(Ik,{path:r.path,children:i.jsx(Sl,{kind:"file",label:fh(r.path),title:r.path})},a):r.type==="chat"?i.jsx(Sl,{kind:"chat",label:r.label,title:r.sessionFile},a):r.type==="ui-element"?i.jsx(Sl,{kind:"ui-element",label:r.label,title:`${r.path}${r.text?` · ${r.text}`:""}`},a):i.jsx("span",{children:t.trim()?LM(r.text,t,n,o):r.text},a))})}function J7({files:e,chats:t}){return i.jsxs("span",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[e.map(n=>i.jsx(Ik,{path:n,children:i.jsx(Sl,{kind:"file",label:fh(n),title:n})},`f:${n}`)),t.map(n=>i.jsx(Sl,{kind:"chat",label:n.label,title:n.sessionFile},`c:${n.sessionFile}`))]})}const Za="max-w-[82%] rounded-[10px] bg-muted px-3.5 py-[9px] text-(length:--chat-body-size) leading-[1.6]";function Ja({text:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=Q(),o=Wi(),r=!!(o?.speaker||o?.botSession),a=r?CM(e):null;if(a)return i.jsx(VW,{message:a});const l=r?kM(e):e;if(l!==e)return i.jsx(Ja,{text:l,searchQuery:t,activeNth:n});const d=r?jM(e):null;if(d?.refs.length)return i.jsxs("div",{className:"flex w-full flex-col items-end gap-1.5",children:[d.body&&i.jsx(Ja,{text:d.body,searchQuery:t,activeNth:n}),i.jsx("div",{className:"flex flex-wrap justify-end gap-1.5",children:d.refs.map(N=>i.jsxs("span",{title:s("Referenced chat"),className:"inline-flex h-6 max-w-56 items-center gap-1 rounded-md bg-muted px-1.5 text-xs",children:[i.jsx(ca,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:N.title})]},N.id))})]});const c=_M(e);if(c.note){const N=c.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(MT,{note:c.note}),N&&i.jsx(Ja,{text:N,searchQuery:t,activeNth:n})]})}const u=NM(e);if(u.note){const N=u.rest.trim();return i.jsxs(i.Fragment,{children:[i.jsx(RT,{note:u.note}),N&&i.jsx(Ja,{text:N,searchQuery:t,activeNth:n})]})}const h=TM(e);if(h?.kind==="approved")return i.jsxs("div",{className:"flex w-full items-start gap-2 rounded-lg border border-dashed border-border/60 px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(Z1,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0",children:[s("Plan approved, executing"),i.jsx("span",{className:"ml-1.5 text-foreground",children:h.title})]})]});if(h?.kind==="feedback")return i.jsxs("div",{className:q(Za,"whitespace-pre-wrap"),children:[i.jsxs("p",{className:"mb-1 flex items-center gap-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:[i.jsx(ma,{className:"h-3 w-3"}),s("Plan feedback")]}),i.jsx(Ma,{text:h.feedback,searchQuery:t,activeNth:n})]});const p=DM(e);if(p)return i.jsx(Z7,{preset:p});const f=G6(e);if(f.files.length>0||f.chats.length>0){const N=ju(f.body);return i.jsxs("div",{className:Za,children:[N.slash?i.jsxs(i.Fragment,{children:[i.jsx(_u,{name:N.slash}),N.rest.trim()?i.jsx("span",{className:"ml-1.5 align-middle",children:i.jsx(Ma,{text:N.rest.trim(),searchQuery:t,activeNth:n})}):null]}):i.jsx(Ma,{text:f.body,searchQuery:t,activeNth:n}),i.jsx(J7,{files:f.files,chats:f.chats})]})}const x=IM(e);if(x)return i.jsx(Y7,{blocks:x});if(ju(e).slash)return i.jsx(X7,{text:e});const v=B7.exec(e);if(v){const N=e.slice(v[0].length).trim();return i.jsxs(i.Fragment,{children:[i.jsx(V7,{note:v[1]}),N&&i.jsx("div",{className:q(Za,"whitespace-pre-wrap"),children:i.jsx(Ma,{text:N,searchQuery:t,activeNth:n})})]})}const y=H7.exec(e);if(y)return i.jsx($7,{tag:y[1],body:y[2]});const w=AT.exec(e),b=w?e.slice(w[0].length):e,_=LT.exec(b),j=_?_[1]:b;return i.jsxs("div",{className:q(_?"max-w-[80%] rounded-2xl rounded-bl-md border border-blue-500/20 bg-blue-500/8 px-4 py-2.5 text-sm":q(Za,"whitespace-pre-wrap")),children:[_&&i.jsxs("p",{className:"mb-1 flex items-center gap-1 text-[10px] font-medium tracking-wide text-blue-600 uppercase dark:text-blue-400",children:[i.jsx(Hs,{className:"h-3 w-3"}),s("From main agent")]}),w?.[1]&&!HW(w[1])&&i.jsxs("div",{className:"mb-2 rounded-md bg-background/60 px-2.5 py-1.5 text-xs text-muted-foreground",children:[i.jsx("span",{className:"font-semibold",children:s("Role")})," · ",w[1]]}),_?i.jsx(js,{text:j,searchQuery:t,activeNth:n}):i.jsx(Ma,{text:j,searchQuery:t,activeNth:n})]})}function by(e){return e.kind==="tool-group"||e.kind==="thinking"||e.kind==="tool"&&Nk(e)}const yh="text-[color:var(--subtle-foreground,var(--muted-foreground))]";function Q7({model:e,at:t,privacyMask:n}){const s=Wi()?.speaker,o=[e,typeof t=="number"?Sh(t):null].filter(Boolean).join(" · ");return!s&&!o&&!n?null:i.jsxs("div",{className:"mb-2 flex h-6 min-w-0 items-center gap-2 text-xs select-none",children:[s&&(s.image?i.jsx("img",{src:s.image,alt:"",draggable:!1,className:"size-[22px] shrink-0 rounded-full object-cover",style:{backgroundColor:s.color}}):i.jsx("span",{className:"flex size-[22px] shrink-0 items-center justify-center rounded-full font-semibold text-[11px] text-white",style:{backgroundColor:s.color},children:[...s.name.trim()][0]?.toUpperCase()??"?"})),s&&i.jsx("span",{className:"shrink-0 truncate text-[13px] font-semibold text-foreground",children:s.name}),o&&i.jsx("span",{className:q("min-w-0 truncate text-[11.5px]",yh),children:o}),n&&i.jsx(q9,{report:n})]})}const eK=m.memo(function({item:t,onToggleGroup:n,onToggleTurn:s}){const o=pM(),r=o.query,a=o.activeKey===t.key?o.activeNth:-1;switch(t.kind){case"user":{const l=t.text?K7(t.text):!1,d=t.collapsed===!0;return i.jsxs("div",{"data-enso":"message-user",className:q("group/user flex flex-col gap-1.5",l?"items-start":"items-end"),children:[t.images.map((c,u)=>i.jsx(PT,{src:`data:${c.mimeType};base64,${c.data}`,className:"max-h-48 max-w-full rounded-lg border object-contain"},u)),t.text&&i.jsx(Ja,{text:t.text,searchQuery:r,activeNth:a}),d?i.jsx(lK,{turnKey:t.key,timestamp:t.timestamp,turnDurationMs:t.turnDurationMs,onToggle:s}):i.jsx(dK,{turnKey:t.key,messageIndex:Number(t.key),timestamp:t.timestamp,deliveryState:t.deliveryState,canCollapse:t.canCollapse,onToggleTurn:s})]})}case"text":return i.jsx(cK,{item:t,searchQuery:r,activeNth:a});case"thinking":return i.jsx(pK,{itemKey:t.key,text:t.text,streaming:t.streaming,durationMs:t.durationMs,startedAt:t.startedAt});case"tool":return i.jsxs(i.Fragment,{children:[i.jsx(fM,{name:t.name,output:t.output,state:t.state}),i.jsx(wK,{item:t}),t.pluginArtifacts?i.jsx(mM,{artifacts:t.pluginArtifacts}):null]});case"tool-group":return i.jsx(xK,{item:t,onToggle:n});case"error":return i.jsxs("div",{className:"flex items-start gap-2 text-sm text-destructive",children:[i.jsx(gr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsx("p",{className:"min-w-0 flex-1 whitespace-pre-wrap",children:t.text}),i.jsx(zT,{})]});case"task-note":return i.jsx(fK,{item:t});case"compaction":case"compaction-notice":return i.jsx(gK,{item:t});case"compaction-progress":return i.jsx(mK,{state:t.state});case"session-custom":return i.jsx(sK,{entry:t.entry});case"plugin-message":return i.jsx(nK,{item:t});case"divider":return i.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"h-px flex-1 bg-border"}),t.text,i.jsx("span",{className:"h-px flex-1 bg-border"})]})}},F7),wy=e=>{if(typeof e=="string")return e;if(e===void 0)return"—";try{return JSON.stringify(e)}catch{return String(e)}};function tK({entry:e}){const{t}=Q(),n=WW(),s=n.get(e.accountKey),o=e.previousAccountKey?n.get(e.previousAccountKey):void 0,r=e.previousAccountKey?o&&s?t("ChatGPT account switched: {{previous}} → {{current}}",{previous:o,current:s}):t("ChatGPT account switched"):s?t("ChatGPT account selected: {{account}}",{account:s}):t("ChatGPT account selected");return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-xs",children:[i.jsx(Fo,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("p",{className:"min-w-0 break-words text-muted-foreground",children:r})]})}function nK({item:e}){const{t}=Q();return i.jsxs("div",{"data-plugin-message":e.pluginId,className:"rounded-md border border-dashed border-border bg-muted/20 px-3 py-2 text-xs",children:[i.jsxs("p",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground",children:[i.jsx(dg,{pluginId:e.pluginId,className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{children:t("From plugin {{name}}",{name:e.pluginName})}),i.jsx("span",{className:"font-mono opacity-70",children:e.pluginId})]}),i.jsx("p",{className:"whitespace-pre-wrap break-words text-foreground",children:e.text})]})}function sK({entry:e}){const{t}=Q();if(e.kind==="oauth-account-selected")return i.jsx(tK,{entry:e});if(e.kind==="agent-dispatch")return i.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-muted/20 px-2.5 py-2 text-xs",children:[i.jsx(Hs,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("span",{className:"text-muted-foreground",children:t("Dispatched to")}),i.jsx("span",{className:"font-medium",children:e.child.instanceName})]});if(e.kind==="agent-completed")return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-emerald-500/20 bg-emerald-500/5 px-2.5 py-2 text-xs",children:[i.jsx(Un,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Completed")]}),e.receiptSummary&&i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.receiptSummary})]})]});if(e.kind==="agent-failed")return i.jsxs("div",{className:"flex items-start gap-2 rounded-md border border-destructive/20 bg-destructive/5 px-2.5 py-2 text-xs",children:[i.jsx(gr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-destructive"}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium",children:[e.child.instanceName," · ",t("Failed")]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:e.message})]})]});const n=e.receipt,s=n.outcome==="succeeded";return i.jsx("div",{className:q("rounded-md border px-2.5 py-2 text-xs",s?"border-emerald-500/20 bg-emerald-500/5":n.outcome==="failed"?"border-destructive/20 bg-destructive/5":"border-amber-500/20 bg-amber-500/5"),children:i.jsxs("div",{className:"flex items-start gap-2",children:[s?i.jsx(Un,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-emerald-500"}):i.jsx(gr,{className:q("mt-0.5 h-3.5 w-3.5 shrink-0",n.outcome==="failed"?"text-destructive":"text-amber-500")}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("p",{className:"font-medium",children:[n.subject.label," · ",t(n.outcome)]}),i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground",children:n.summary}),n.changes&&n.changes.length>0&&i.jsx("dl",{className:"mt-2 space-y-1 border-t border-border/50 pt-2",children:n.changes.map(o=>i.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] gap-2",children:[i.jsx("dt",{className:"truncate text-muted-foreground",children:o.field}),i.jsxs("dd",{className:"text-right font-mono",children:[wy(o.previous)," → ",wy(o.value)]})]},o.field))})]})]})})}function Es(e){const t=e.activeId?e.conversations[e.activeId]:null;return t?t.activeTabId?e.conversations[t.activeTabId]??t:t:null}const OT=()=>()=>{};function zT(){const{t:e}=Q(),t=Wi(),n=t?.botControls,s=re(l=>{if(t&&(!t.canRetry||t.botControls))return!1;const d=Es(l);return!!(d?.started&&!d.spawning&&d.status!=="running")}),o=()=>{if(!n||!t?.canRetry)return!1;const l=n.projection();return!!(l&&l.status!=="running")},r=m.useSyncExternalStore(n?.subscribe??OT,o,o);return(n?r:s)?i.jsxs("button",{type:"button",title:e("Retry"),onClick:()=>{if(n)return n.retry();const l=Es(re.getState());l&&re.getState().retry(l.id)},className:"mt-0.5 inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground",children:[i.jsx(Fo,{className:"h-3 w-3"}),e("Retry")]}):null}function iK(e,t){return zM(Es(e),t)}const Wx="flex items-center gap-1 text-[11px] text-muted-foreground transition-opacity hover:text-foreground";function oK({messageIndex:e}){const{t}=Q(),n=Wi();return re(o=>PM(Es(o),n))?i.jsxs("button",{type:"button",className:Wx,title:t("Keep this session and start a parallel one from here"),onClick:()=>{const o=re.getState(),r=Es(o);if(!r)return;const a=AM(r,e);a!==null&&o.forkFromMessage(r.id,a)},children:[i.jsx(Ei,{className:"h-3 w-3"}),t("Conversation branch")]}):null}function rK({messageIndex:e}){const{t}=Q(),n=Wi(),s=re(r=>Es(r)?.id),o=re(r=>{const a=s?r.conversations[s]:void 0;if(n||!a||a.historyOnly||a.rewinding||a.restoringFiles||a.workspaceMigrating)return;const l=a.messages[e-(a.historyBaseIndex??0)];return EM(l)?l.deliveryId:void 0});return!s||!o?null:i.jsxs("button",{type:"button",title:t("Withdraw message"),onClick:()=>re.getState().withdrawMessage(s,{kind:"delivery",id:o}),className:"inline-flex items-center gap-1 hover:text-foreground",children:[i.jsx(ua,{className:"h-3 w-3"}),t("Withdraw message")]})}function aK({messageIndex:e}){const{t}=Q(),[n,s]=m.useState(!1),[o,r]=m.useState(null),a=Wi(),l=a?.botControls,d=re(x=>{if(a?.botControls)return!1;const v=Es(x);return iK(x,a)&&!!(v&&Id(v.id,v.id,v,e))}),c=()=>{if(!l||!a?.canRewind||!a.sessionId)return null;const x=l.projection();return!x||x.status==="running"?null:Id(a.sessionId,a.sessionId,x,e)?.entryId??null},u=m.useSyncExternalStore(l?.subscribe??OT,c,c);if(!(l?u!==null:d))return null;const p=x=>{if(l&&a?.sessionId&&u){r({restoreFiles:x,conversationId:a.sessionId,entryId:u});return}const v=Es(re.getState());if(!v)return;const y=Id(v.id,v.id,v,e);y&&r({restoreFiles:x,conversationId:v.id,entryId:y.entryId})},f=(x,v,y)=>{if(l)return l.rewind(y,x);const w=re.getState(),b=Es(w),_=Id(v,b?.id,w.conversations[v],e,y);_&&w.rewind(_.conversationId,_.entryId,x)},g=[{icon:ua,label:t("Conversation only"),desc:t("Rewind to this message"),restoreFiles:!1,action:()=>p(!1)},{icon:Bo,label:t("Conversation + files"),desc:t("Rewind and restore files to before this turn"),restoreFiles:!0,action:()=>p(!0)}];return i.jsxs(Ri,{open:n,onOpenChange:s,children:[i.jsxs(Li,{className:Wx,title:t("Rewind to this message"),children:[i.jsx(ua,{className:"h-3 w-3"}),t("Rewind")]}),i.jsx(Oi,{side:"bottom",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",children:g.map(x=>i.jsxs("button",{type:"button",onClick:()=>{s(!1),x.action()},className:"flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors hover:bg-muted/60",children:[i.jsx(x.icon,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block",children:x.label}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:x.desc})]})]},x.label))}),i.jsx(fs,{open:o!==null,onOpenChange:x=>{x||r(null)},title:t("Rewind to this message?"),description:o?.restoreFiles?t("Later messages leave the current branch and working-tree files are restored to before this turn."):t("Later messages leave the current branch; the text returns to the input box."),confirmLabel:t("Rewind"),onConfirm:()=>{o&&f(o.restoreFiles,o.conversationId,o.entryId)}})]})}function lK({turnKey:e,timestamp:t,turnDurationMs:n,onToggle:s}){const{t:o}=Q();return i.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground/80 select-none",children:[i.jsxs("button",{type:"button",onClick:()=>s?.(e,!1),className:"inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-muted-foreground transition-colors hover:bg-muted/70 hover:text-foreground cursor-pointer border border-border/40",title:o("Expand"),children:[i.jsx(bn,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:o("Expand")})]}),typeof t=="number"&&i.jsx("span",{children:Sh(t)}),n!==void 0&&i.jsxs("span",{children:["· ",o("took {{duration}}",{duration:ss(n)})]})]})}function dK({turnKey:e,messageIndex:t,timestamp:n,canCollapse:s,deliveryState:o,onToggleTurn:r}){const{t:a}=Q(),l=Ce(d=>d.autoCollapseTurns);return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground/75 select-none",children:[i.jsx(aK,{messageIndex:t}),i.jsx(rK,{messageIndex:t}),o&&i.jsx("span",{children:a(o==="rejected"?"Not sent":"Delivery unconfirmed")}),l&&s&&r&&i.jsxs("button",{type:"button",onClick:()=>r(e,!0),className:q(Wx,"cursor-pointer opacity-0 group-hover/user:opacity-100"),title:a("Collapse"),children:[i.jsx(Vn,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{children:a("Collapse")})]}),typeof n=="number"&&i.jsx("span",{children:Sh(n)})]})}function cK({item:e,searchQuery:t="",activeNth:n=-1}){const{t:s}=Q(),o=Wi(),r=e.perf?hK(e.perf,s,e.turnDurationMs!==void 0):"",a=re(d=>Es(d)?.id??null),l={text:e.text,messageIndex:Number(e.key.split("-")[0]),sessionId:o?o.sessionId:a};return i.jsxs("div",{"data-enso":"message-assistant",className:"group text-(length:--chat-body-size)",children:[i.jsx(js,{text:e.text,streaming:e.streaming,searchQuery:t,activeNth:n,leaf:{messageIndex:l.messageIndex,sessionId:l.sessionId}}),e.turnEnd&&!e.streaming&&o?.turnFooter?.(Number(e.key.split("-")[0])),!e.streaming&&i.jsxs("div",{className:"mt-1 flex items-center gap-2 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:[i.jsx(Vv,{position:"left",...l}),i.jsx(uK,{text:e.text}),i.jsx(Vv,{position:"right",...l}),e.turnEnd&&i.jsx(oK,{messageIndex:Number(e.key.split("-")[0])}),e.timestamp&&!e.turnEnd&&i.jsx("span",{children:Sh(e.timestamp)}),e.turnDurationMs!==void 0&&i.jsxs("span",{children:[e.timestamp&&!e.turnEnd&&"· ",s("took {{duration}}",{duration:ss(e.turnDurationMs)})]}),r&&i.jsxs("span",{children:["· ",r]})]})]})}function uK({text:e}){const{t}=Q(),[n,s]=m.useState(!1);return i.jsx("button",{type:"button",onClick:()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),1e3)})},className:"flex items-center gap-1 transition-colors hover:text-foreground",title:t("Copy"),children:n?i.jsx(Un,{className:"h-3 w-3"}):i.jsx(Vu,{className:"h-3 w-3"})})}const yy=e=>String(e).padStart(2,"0"),Sh=e=>{const t=new Date(e);return`${yy(t.getHours())}:${yy(t.getMinutes())}`},Sy=e=>{const t=e/1e3;return t<10?String(Math.round(t*10)/10):String(Math.round(t))};function hK(e,t,n=!1){const s=[];return(!n||e.turnMs!==void 0)&&s.push(`${Sy(e.runMs)}s`),e.ttftMs!==void 0&&s.push(`TTFT ${Sy(e.ttftMs)}s`),e.tps!==void 0&&s.push(`${Math.round(e.tps)} tok/s`),!n&&e.turnMs!==void 0&&s.push(t("total {{duration}}",{duration:ss(e.turnMs)})),s.join(" · ")}function pK({itemKey:e,text:t,streaming:n,durationMs:s,startedAt:o}){const{t:r}=Q(),a=Ce(u=>u.expandLiveReasoning),[l,d]=m.useState(null),c=SM(l,n,a);return i.jsxs("div",{"data-enso":"thinking","data-live":n||void 0,children:[i.jsxs("button",{type:"button",onClick:()=>d(!c),className:q("flex min-h-6 items-center gap-2 text-[13px] transition-colors hover:text-foreground",yh),children:[i.jsx("span",{className:"flex size-3 shrink-0 items-center justify-center",children:i.jsx(gM,{className:q("size-3",n&&"animate-pulse text-brand")})}),n?i.jsx("span",{className:"t-shimmer","data-text":r("Thinking…"),children:r("Thinking…")}):s!==null?i.jsx("span",{children:r("Thought for {{duration}}",{duration:ss(s)})}):i.jsx("span",{children:r("Thought process")}),n&&i.jsx(GT,{itemKey:e,since:o}),i.jsx(bn,{className:q("h-3 w-3 transition-transform",c&&"rotate-90")})]}),c&&i.jsx(xM,{text:t,streaming:n,itemKey:e})]})}function fK({item:e}){const{t}=Q(),[n,s]=m.useState(!1),[o,r]=m.useState(void 0),a=/^Background task (\S+) finished \((.+?), ran (.+?)\)/.exec(e.summary),l=a?`${a[1]} · ${a[2]} · ${a[3]}`:e.summary,d=/(?:read (\/.+?\.log) for the complete log|Full log: (\/\S+?\.log))/.exec(e.detail)?.slice(1).find(Boolean)??null;return m.useEffect(()=>{!n||!d||o!==void 0||window.electronAPI.files.read(d).then(c=>{r(typeof c=="string"?c:null)}).catch(()=>r(null))},[n,d,o]),i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>s(c=>!c),className:"flex w-full items-center gap-3",title:e.detail,children:[i.jsx("span",{className:"h-px flex-1 bg-border"}),i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx(Un,{className:"h-3 w-3 text-green-600 dark:text-green-500"}),l,i.jsx(bn,{className:q("h-3 w-3 transition-transform",n&&"rotate-90")})]}),i.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&i.jsxs("div",{className:"mt-1.5 rounded-lg border border-border/60 bg-muted/20",children:[i.jsx("pre",{className:"border-b border-border/60 px-3 py-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:e.detail}),i.jsx("pre",{className:"max-h-64 overflow-auto px-3 py-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:d?o===void 0?t("Loading…"):vi(o??t("(log unavailable)")):t("(no log available)")})]})]})}function mK({state:e}){const{t}=Q();return i.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[i.jsx(qt,{className:"h-3 w-3 animate-spin"}),i.jsx("span",{children:t(e==="queued"?"Compacts after this turn":"Compacting…")})]})}function gK({item:e}){const{t}=Q(),[n,s]=m.useState(!1),o=e.kind==="compaction",r=e.tokensBefore===null?null:gs(e.tokensBefore),a=e.memory?r===null?t("Memory context compacted"):t("Memory context compacted ({{tokens}} tokens before)",{tokens:r}):e.verified?r===null?t("Verified context compacted"):t("Verified context compacted ({{tokens}} tokens before)",{tokens:r}):r===null?t("Context compacted"):t("Context compacted ({{tokens}} tokens before)",{tokens:r});return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>s(l=>!l),className:q("flex items-center gap-3",o&&"w-full"),title:e.memory?t("Summary rendered from continuous memory. Messages above are no longer in the model context; use recall for sources."):e.verified?t("Verified summary from smart compaction. Messages above are no longer in the model context."):t(o?"Messages above are no longer in the model context; only this summary is.":"Latest compaction summary — expand to read what the model kept."),children:[o&&i.jsx("span",{className:"h-px flex-1 bg-border"}),i.jsxs("span",{className:"flex shrink-0 items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx(H$,{className:"h-3 w-3"}),a,i.jsx(bn,{className:q("h-3 w-3 transition-transform",n&&"rotate-90")})]}),o&&i.jsx("span",{className:"h-px flex-1 bg-border"})]}),n&&i.jsx("pre",{className:"mt-1.5 max-h-80 overflow-auto rounded-lg border border-border/60 bg-muted/20 px-3 py-2 font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:e.summary||t("(summary unavailable)")})]})}function xK({item:e,onToggle:t}){const{t:n}=Q(),s=Ce(p=>p.compactReadOnlyTools),o=[];e.stats.commands>0&&o.push(n("ran {{count}} commands",{count:e.stats.commands})),e.stats.reads>0&&o.push(n("read {{count}} files",{count:e.stats.reads})),e.stats.searches>0&&o.push(n("searched {{count}} times",{count:e.stats.searches})),e.stats.others>0&&o.push(n("{{count}} other calls",{count:e.stats.others}));const r=[];s&&(e.stats.reads>0&&r.push(n("{{count}} files",{count:e.stats.reads})),e.stats.searches>0&&r.push(n("{{count}} searches",{count:e.stats.searches})));const a=e.activity,l=[];a&&(a.thinking>0&&l.push(n("{{count}} thinking steps",{count:a.thinking})),e.count>0&&l.push(n("{{count}} tool calls",{count:e.count})));const d=e.explore,c=d?ha("explore_fold",n):a?a.workedMs>0?n("Worked for {{duration}}",{duration:ss(a.workedMs)}):n("Activity"):s?e.exploring?n("Exploring"):n("Explored"):n("{{count}} tool calls",{count:e.count}),u=d?[d.goal,n("{{count}} tool calls",{count:e.count})].filter(Boolean):a?l:s?r:o,h=i.jsxs("button",{type:"button",onClick:()=>{d?.steps&&t?.($v(e.key)),t?.(e.key)},title:d?.goal,"data-explore-head":d?"":void 0,"data-enso":"tool-row",className:q("group/step flex min-h-6 w-full items-center gap-2 text-left text-[13px] transition-colors hover:text-foreground",yh),children:[i.jsx(TT,{state:e.exploring?"running":"ok"}),e.exploring?i.jsx("span",{className:"t-shimmer shrink-0 font-medium","data-text":c,children:c}):i.jsx("span",{className:"shrink-0 text-muted-foreground group-hover/step:text-foreground",children:c}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:u.join(" · ")}),i.jsx(bn,{className:q("h-3 w-3 shrink-0 transition-transform",e.expanded&&"rotate-90")})]});return!d||!e.expanded?h:i.jsxs(i.Fragment,{children:[h,i.jsxs("div",{"data-slot":"tool-details",className:"t-acc-reveal mt-1 mb-1.5 ml-5 overflow-hidden rounded-lg border border-border/70 bg-card text-sm shadow-xs",children:[d.goal&&i.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[i.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Goal")}),i.jsx("p",{className:"whitespace-pre-wrap",children:d.goal})]}),d.report&&i.jsxs("div",{className:"border-b border-border/60 px-3 py-2",children:[i.jsx("div",{className:"mb-0.5 text-[11px] text-muted-foreground",children:n("Result")}),i.jsx(js,{text:d.report})]}),i.jsxs("button",{type:"button",onClick:()=>t?.($v(e.key)),className:"flex w-full items-center gap-1.5 px-3 py-1.5 text-left text-xs text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground",children:[i.jsx(bn,{className:q("h-3 w-3 shrink-0 transition-transform",d.steps&&"rotate-90")}),i.jsx("span",{children:d.steps?n("Hide process"):n("Show process")}),i.jsxs("span",{children:["· ",n("{{count}} tool calls",{count:e.count})]})]})]})]})}function Ra({children:e,className:t,follow:n}){const s=m.useRef(null),o=m.useRef(null),r=m.useRef(n),a=m.useRef(n),l=m.useRef(null),d=m.useRef(null),c=m.useRef(0);a.current=n;const u=m.useCallback(()=>{r.current=!1,l.current=null,cancelAnimationFrame(c.current)},[]),h=m.useCallback(()=>{!a.current||!r.current||(cancelAnimationFrame(c.current),c.current=requestAnimationFrame(()=>{const p=s.current;if(!p||!a.current||!r.current)return;const f=Math.max(0,p.scrollHeight-p.clientHeight);l.current=f,p.scrollTop=f}))},[]);return m.useEffect(()=>{n?(r.current=!0,h()):(l.current=null,cancelAnimationFrame(c.current))},[n,h]),m.useEffect(h),m.useEffect(()=>{const p=o.current;if(!p)return;const f=new ResizeObserver(h);return f.observe(p),()=>f.disconnect()},[h]),m.useEffect(()=>()=>cancelAnimationFrame(c.current),[]),i.jsx("div",{ref:s,onWheel:p=>{p.deltaY<0&&u()},onPointerDown:p=>{p.target===p.currentTarget&&u()},onTouchStart:p=>{d.current=p.touches[0]?.clientY??null},onTouchMove:p=>{const f=p.touches[0]?.clientY;f!==void 0&&d.current!==null&&f>d.current&&u(),d.current=f??null},onTouchEnd:()=>{d.current=null},onScroll:p=>{if(!a.current)return;const f=p.currentTarget;if(f.scrollHeight-f.scrollTop-f.clientHeight<=2){r.current=!0,l.current=null;return}const x=l.current;if(x!==null&&f.scrollTop>=x-2){l.current=null,h();return}u()},className:q("max-h-96 overflow-auto [overflow-anchor:none]",t),children:i.jsx("div",{ref:o,children:e})})}function vK(e){if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)??""}catch{return String(e)}}function bK({source:e,output:t,view:n}){const s=n?.status==="completed"?vK(n.value):n?.error??t;return i.jsxs("div",{className:"space-y-1 px-3 py-1",children:[e?i.jsx(Wv,{code:e,language:"javascript"}):null,n&&n.calls.length>0?i.jsx("div",{className:"flex flex-wrap gap-1",children:[...new Map(n.calls.map(o=>[o.name,o])).keys()].map(o=>{const r=n.calls.filter(d=>d.name===o),a=r.find(d=>!d.ok),l=`${o} ×${r.length}`;return i.jsx("span",{className:q("rounded-md border px-1.5 py-0.5 font-mono text-[10px]",a?"border-destructive/40 text-destructive":"text-muted-foreground"),title:r.map(d=>d.summary).filter(Boolean).join(`
|
|
72
|
-
`),children:a?`${l} · ${a.error??"error"}`:l},o)})}):null,s?n?.status==="completed"&&typeof n.value!="string"?i.jsx(Wv,{code:s,language:"json"}):i.jsx("pre",{className:"font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:vi(s)}):null,n?.console?i.jsx("pre",{className:"border-l-2 pl-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:vi(n.console)}):null]})}function Cy({path:e,fallback:t}){const[n,s]=m.useState(!1);return n?t:i.jsx("div",{"data-slot":"read-image",className:"w-full min-w-0 px-3 py-3",children:i.jsx(PT,{src:uf(e),onError:()=>s(!0),frameClassName:"block w-full",className:"mx-auto block max-h-80 max-w-full rounded-md bg-muted/40 object-contain"})})}function wK({item:e}){const{t}=Q(),n=Wi(),s=Ce(z=>z.compactReadOnlyTools),o=Ce(z=>z.expandLiveEdits),r=s&&e.name!=="bash"&&Nk(e),a=!!(e.edits&&e.edits.length>0),l=!!e.writeContent,d=!!(e.fileChanges&&e.fileChanges.length>0),c=e.sandbox??null,u=e.state==="error"?null:e.sentMessage,h=!!e.imagePath&&e.state!=="error",p=vN[e.name],f=Tk(e.name),g=e.subagentOp?[t(n4[e.subagentOp]),e.summary].filter(Boolean).join(" · "):e.summary,x=e.nestedPending&&e.state==="running"?`${g} · ${e.nestedPending} pending`:c?.calls.length&&e.state!=="error"?vM(c.calls):g,v=!!(e.output||e.source||u||e.ask),y=e.state==="running"&&e.waiting==="subagent"&&!n,w=a||l||d||v||y||h,b=o&&(a||l||h)&&e.state==="running",[_,j]=m.useState(b),[N,C]=m.useState(!1),S=m.useRef(null),A=L7();m.useEffect(()=>{if(!N)return;const z=S.current;if(!z)return;const $=e.key,R=A.report,B=new IntersectionObserver(([H])=>R($,H?.isIntersecting===!0),{root:A.scroller.current});return B.observe(z),()=>{B.disconnect(),R($,!1)}},[N,e.key,A]);const E=_&&e.name==="memory_search"?I9(e.output):null,I=_&&e.name==="memory_capture"?E9(e.output,e.memoryContent):null,D=_&&e.name==="subagent"&&e.state!=="error"?I7(e.subagentOp,e.output):null,T=m.useRef(d);return m.useEffect(()=>{const z=bM(e,T.current);T.current=d,(b||o&&z)&&j(!0)},[b,o,d,e]),e.todos?i.jsx(CK,{todos:e.todos}):e.name.startsWith("goal_")?i.jsx(yK,{item:e}):e.plan&&e.state!=="error"?i.jsx(SK,{plan:e.plan}):i.jsxs("div",{ref:S,"data-enso":"tool-row","data-tool-style":r?"compact":"full","data-user-open":N?"true":void 0,children:[i.jsxs("div",{className:"flex items-center gap-1",children:[i.jsxs("button",{type:"button",disabled:!w,onClick:()=>{const z=!_;j(z),C(z),A.report(e.key,z)},className:q("group/step flex min-h-6 min-w-0 flex-1 items-center gap-2 text-left text-[13px]",yh,w&&"cursor-pointer"),children:[i.jsx(TT,{state:e.state}),i.jsx("span",{className:"shrink-0 text-muted-foreground transition-colors group-hover/step:text-foreground",children:p?t(p):f?.tool??e.name}),i.jsx("span",{className:q("min-w-0 flex-1 truncate font-mono text-[12px]",e.state==="error"?"text-destructive":"text-muted-foreground"),children:e.state==="error"&&e.output?g&&e.name==="apply_patch"&&d?`${x} · ${_y(e.output)}`:_y(e.output):g?x:null}),e.backgroundTaskId&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:e.backgroundTaskId,children:t("Moved to background")}),e.shellFailure&&e.state!=="running"&&i.jsx(v7,{failure:e.shellFailure}),e.state==="reviewing"?i.jsx("span",{className:"t-shimmer shrink-0 text-[11px]","data-text":t("Assistant reviewing…"),children:t("Assistant reviewing…")}):e.state==="running"&&e.startedAt!==null?i.jsxs(i.Fragment,{children:[e.callId&&(e.name==="bash"||e.name==="powershell")&&i.jsx(DK,{callId:e.callId,startedAt:e.startedAt,output:e.output??""}),i.jsx(GT,{itemKey:e.key,since:e.startedAt??void 0})]}):(e.agentMeta||e.durationMs!==null)&&i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:[e.agentMeta?.modelId,e.agentMeta?.outputTokens?`${e.agentMeta.outputTokens} tok`:null,e.durationMs!==null?ss(e.durationMs):null].filter(Boolean).join(" · ")}),w&&i.jsx(bn,{className:q("h-3 w-3 shrink-0 text-muted-foreground opacity-0 transition-[opacity,transform] group-hover/step:opacity-100",_&&"rotate-90 opacity-100")})]}),e.state==="running"&&e.callId&&!n&&i.jsx(kK,{callId:e.callId,waiting:!!e.waiting}),(a||l||d)&&(e.state==="ok"||d)&&i.jsx("button",{type:"button",title:t("Open in side panel"),className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:()=>Dk(),children:i.jsx(xx,{className:"h-3 w-3"})})]}),e.generatedImages?.length?i.jsx("div",{"data-slot":"generated-images",className:"mt-2 mb-3 ml-5 grid gap-3",children:e.generatedImages.map(z=>i.jsx(Cy,{path:z,fallback:i.jsx("p",{className:"break-all px-3 py-2 text-xs text-muted-foreground",children:z})},z))}):null,_&&w&&i.jsxs("div",{"data-slot":"tool-details",className:"t-acc-reveal mt-1 mb-1.5 ml-5 overflow-hidden rounded-lg border border-border/70 bg-card shadow-xs",children:[f&&i.jsxs("div",{className:"truncate border-b border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",children:[f.server,".",f.tool]}),y&&i.jsx(TK,{agentIds:e.subagentTitles?Object.keys(e.subagentTitles):void 0}),a&&e.edits&&i.jsx(Ra,{follow:e.state==="running",children:i.jsx(hy,{path:e.summary,blocks:e.edits})}),d&&e.fileChanges&&i.jsx(Ra,{follow:e.state==="running",children:e.fileChanges.map((z,$)=>i.jsxs("div",{children:[i.jsxs("div",{className:q("flex items-center gap-2 border-border/60 px-3 py-1 font-mono text-[10px] text-muted-foreground",($>0||a)&&"border-t"),children:[i.jsx("span",{className:"uppercase",children:z.type}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:z.path,children:z.path}),z.truncated&&i.jsx("span",{children:t("Truncated preview")})]}),i.jsx(hy,{path:z.path,blocks:[z],snapshot:z})]},`${z.type}:${Rx(z.path,z.oldText,z.newText)}`))}),wM(e)&&i.jsx(Ra,{follow:!1,className:"border-t border-border/60",children:i.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:vi(e.output??"")})}),l&&e.writeContent&&i.jsx(Ra,{follow:e.state==="running",className:q((a||d)&&"border-t border-border/60"),children:i.jsx(Fc,{path:e.summary,contents:e.writeContent})}),!a&&!l&&!d&&(v||h)&&i.jsxs(Ra,{follow:e.state==="running",children:[yM(e.name)?i.jsx(bK,{source:e.source,output:e.output,view:c}):e.name==="bash"||e.name==="powershell"?i.jsx(E7,{command:e.summary,output:e.output??"",failure:e.shellFailure}):e.name==="read"&&h&&e.imagePath?i.jsx(Cy,{path:e.imagePath,fallback:i.jsx(Fc,{path:e.summary,contents:e.output??""})},e.imagePath):e.name==="read"?i.jsx(Fc,{path:e.summary,contents:e.output??""}):e.name==="subagent"&&e.state!=="error"&&!u&&!D?i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(js,{text:e.output??""})}):E?i.jsx(ym,{hits:E}):I?i.jsx(j9,{view:I}):i.jsxs(i.Fragment,{children:[e.ask&&i.jsx(eU,{ask:e.ask,waiting:e.state==="running"}),u&&i.jsx("div",{className:"px-3 py-2 text-sm",children:i.jsx(js,{text:u})}),D?i.jsx(_7,{view:D,titles:e.subagentTitles}):e.output&&i.jsx("pre",{className:"px-3 py-2 font-mono text-xs leading-relaxed text-muted-foreground whitespace-pre-wrap",children:vi(e.output)})]}),i.jsx(e7,{value:e.rtk}),i.jsx(QW,{value:e.approvalReview})]})]})]})}function yK({item:e}){const{t}=Q(),n=e.name.replace("goal_",""),s=t(n==="complete"?"Goal completed":n==="blocked"?"Goal blocked":"Goal waiting");return i.jsxs("div",{className:q("flex items-start gap-2 rounded-lg border px-3 py-2 text-sm",n==="complete"&&"border-green-500/50 bg-green-500/5",n==="blocked"&&"border-destructive/50 bg-destructive/5",n==="wait"&&"border-amber-500/50 bg-amber-500/5"),children:[i.jsx(Na,{className:q("mt-0.5 h-4 w-4 shrink-0",n==="complete"&&"text-green-600 dark:text-green-500",n==="blocked"&&"text-destructive",n==="wait"&&"text-amber-500")}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium",children:s}),e.summary&&i.jsx("p",{className:"mt-0.5 whitespace-pre-wrap text-muted-foreground text-xs",children:e.summary})]})]})}function SK({plan:e}){const{t}=Q(),[n,s]=m.useState(!1);return i.jsxs("div",{className:"rounded-lg border border-border/60 bg-muted/30 px-3 py-2",children:[i.jsxs("button",{type:"button",onClick:()=>s(o=>!o),className:"flex w-full min-w-0 items-center gap-2 text-left text-xs",children:[i.jsx(ma,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-medium text-muted-foreground",children:t("Plan")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e.title}),i.jsx(bn,{className:q("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&i.jsx("div",{className:"mt-2 border-border/60 border-t pt-2 text-sm",children:i.jsx(js,{text:e.text})})]})}function CK({todos:e}){const{t}=Q(),n=e.filter(s=>s.status==="completed").length;return i.jsxs("div",{"data-enso":"todo",className:"rounded-lg border bg-card px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[i.jsx(jk,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"font-medium text-foreground",children:t("Todos")}),i.jsxs("span",{className:"ml-auto tabular-nums",children:[n,"/",e.length]})]}),i.jsx(IT,{done:n,total:e.length,className:"mt-1.5 mb-2"}),i.jsx(DT,{todos:e})]})}const ky=new Map;function kK({callId:e,waiting:t}){const{t:n}=Q(),s=re(d=>Es(d)?.id??""),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!o)return;const d=setTimeout(()=>r(!1),5e3);return()=>clearTimeout(d)},[o]),!s)return null;const a=n(t?o?"Stopping wait…":"Stop waiting":o?"Moving to background…":"Move to background"),l=t?e6:pV;return i.jsxs("button",{type:"button",disabled:o,title:a,className:"flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-60",onClick:()=>{r(!0),window.electronAPI.agent.backgroundTool(s,e).then(d=>{d.ok||r(!1)},()=>r(!1))},children:[i.jsx(l,{className:"h-3 w-3"}),a]})}const jK=5e3,_K=[];function NK(e,t){if(e.status==="queued")return t("Queued");const n=e.activity;return n?.phase==="tool"?[n.tool,n.detail].filter(Boolean).join(" "):n?.phase==="writing"?t("Writing reply…"):t("Thinking…")}function TK({agentIds:e}){const{t}=Q(),n=re(l=>Es(l)?.id??""),s=Iw(l=>l.byConversation[n]??_K),[o,r]=m.useState(!1);if(m.useEffect(()=>{if(!n)return;let l=!0;const d=p=>{l&&(Iw.getState().replace(n,p),r(!0))},c=()=>window.electronAPI.agent.subagentProgress(n).then(d,()=>{}),u=window.electronAPI.agent.onSubagentProgress(p=>{p.sessionId===n&&d(p.runs)});c();const h=setInterval(c,jK);return()=>{l=!1,clearInterval(h),u()}},[n]),!o)return null;const a=e?.length?s.filter(l=>e.includes(l.agentId)):s;return i.jsxs("div",{className:"border-b border-border/60 px-3 py-2 text-xs",children:[a.length===0?i.jsx("div",{className:"text-muted-foreground",children:t("No running subagents")}):a.map(l=>i.jsxs("div",{className:"py-0.5",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"max-w-[40%] shrink-0 truncate font-medium",children:l.title??l.agentId.slice(0,8)}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:NK(l,t)}),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:ss(l.elapsedMs)})]}),l.text&&i.jsx("div",{className:"line-clamp-2 break-words pl-2 text-[11px] text-muted-foreground/80",children:l.text.replace(/\s+/g," ")})]},l.runId)),i.jsx("div",{className:"mt-1 text-[11px] text-muted-foreground/80",children:t("Stopping the wait does not stop subagents; the assistant is notified when they finish.")})]})}function GT({itemKey:e,since:t}){const n=Wi(),s=re(d=>Es(d)?.id??""),o=n?n.sessionId??"":s,r=m.useRef(null);if(r.current===null){const d=`${o}:${e}`;r.current=t??ky.get(d)??Date.now(),t===void 0&&ky.set(d,r.current)}const a=t??r.current,[,l]=m.useState(0);return m.useEffect(()=>{const d=setInterval(()=>l(c=>c+1),1e3);return()=>clearInterval(d)},[]),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:ss(Date.now()-a)})}function DK({callId:e,startedAt:t,output:n}){const s=Wi(),o=re(r=>s?void 0:Es(r)?.toolDeadlineAt?.[e]);return i.jsx(x7,{startedAt:t,deadlineAt:o,output:n})}function jy(e){return e.kind==="tool-group"?!0:e.kind==="tool"&&!e.todos&&!e.name.startsWith("goal_")}const _y=e=>vi(e.split(`
|
|
73
|
-
`,1)[0]??""),IK=100;function EK(e,t,n,s,o=IK){if(s||!n)return{hiddenSince:t,delayMs:null};const r=t??e;return{hiddenSince:r,delayMs:Math.max(0,o-(e-r))}}const PK=1e6;function AK(e,t,n=PK){if(t.length===0)return{anchor:null,firstItemIndex:n,remount:!1};if(!e)return{anchor:{keys:t,index:n},firstItemIndex:n,remount:!1};const s=new Map(t.map((o,r)=>[o,r]));for(let o=0;o<e.keys.length;o++){const r=s.get(e.keys[o]);if(r===void 0)continue;const a=e.index+o-r;return{anchor:{keys:t,index:a},firstItemIndex:a,remount:!1}}return{anchor:{keys:t,index:n},firstItemIndex:n,remount:!0}}function MK(e,t){return t}const RK=new Set(["text","thinking","tool","tool-group"]);function LK(e,t,n,s){const o=m.useRef(Uv),[r,a]=m.useState(()=>Date.now()),l=s.compact,d=s.autoCollapseCompletedTurns,c=s.collapseCompletedActivity===!0,u=s.collapseLiveActivity===!0,h=s.turnOverrides,p={compact:l,autoCollapseCompletedTurns:d,turnOverrides:h},f=u?FM(e,t,s,o.current,r):null;o.current=f?.witness??Uv;const g=f?.wakeAt??null,x=HM(e,t,n,{...p,collapseCompletedActivity:c,collapseLiveActivity:u,releasedLiveActivity:f?.released,heldOpenTools:s.heldOpenTools});return m.useEffect(()=>{if(g===null||g<=r)return;const v=window.setTimeout(()=>a(g),g-r);return()=>window.clearTimeout(v)},[g,r]),x}const OK=[{icon:VV,title:"Map the project",hint:"Entry points, modules and key dependencies",prompt:"Walk me through this project's structure: entry points, module layout and key dependencies."},{icon:X1,title:"Find potential issues",hint:"Suspicious logic and unhandled edge cases",prompt:"Review this project for potential bugs, suspicious logic and unhandled edge cases, and list them by severity."},{icon:Pk,title:"Add unit tests",hint:"Cover the core modules with tests",prompt:"Find the core modules that lack tests and add unit tests for them."},{icon:Bo,title:"Summarize recent changes",hint:"A digest based on git log",prompt:"Summarize the recent changes in this repository based on git log."}];function zK({onPick:e}){const{t}=Q();return i.jsx("div",{className:"mx-auto grid w-full max-w-[560px] grid-cols-1 gap-2.5 text-left @min-[36rem]:grid-cols-2",children:OK.map(({icon:n,title:s,hint:o,prompt:r})=>i.jsxs("button",{type:"button",onClick:()=>e(t(r)),"data-slot":"welcome-suggestion",className:"group flex items-start gap-3 rounded-xl border bg-card px-3.5 py-3 text-left shadow-xs transition-[border-color,box-shadow,transform] duration-200 hover:-translate-y-px hover:border-brand/25 hover:shadow-float",children:[i.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center rounded-lg bg-brand/8 text-brand dark:bg-brand/14",children:i.jsx(n,{className:"size-3.5"})}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block text-[13px] font-medium",children:t(s)}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:t(o)})]})]},s))})}const yi="enso-chat-col mx-auto w-full max-w-2xl px-4 @min-[56rem]:max-w-3xl @min-[72rem]:max-w-4xl @min-[84rem]:max-w-5xl @min-[96rem]:max-w-6xl @min-[112rem]:max-w-7xl",Ny=1e3;function Ty({className:e,children:t}){const[n,s]=m.useState(!1);return m.useEffect(()=>{const o=requestAnimationFrame(()=>s(!0));return()=>cancelAnimationFrame(o)},[]),i.jsx("div",{className:q("t-stagger",n&&"is-shown",e),children:t})}const Dy=40,GK={index:"LAST",align:"end"},FK={top:600,bottom:600},HK=e=>e?"auto":!1;function BK({style:e,...t}){const n=e?.visibility==="hidden",[s,o]=m.useState(!1),r=m.useRef(null);return m.useEffect(()=>{const a=EK(Date.now(),r.current,n,s);if(r.current=a.hiddenSince,a.delayMs===null)return;const l=window.setTimeout(()=>o(!0),a.delayMs);return()=>window.clearTimeout(l)},[n,s]),i.jsx("div",{...t,style:n&&s?{...e,visibility:"visible"}:e})}function Ch({ref:e,items:t,busy:n,loading:s=!1,running:o,runStartedAt:r,lastOutputAt:a,error:l,emptyTitle:d,emptyDescription:c,onSuggestion:u,onRetryResume:h,virtualize:p=!0,onStartReached:f,historyLoading:g=!1,hasOlder:x,olderCursor:v,searchQuery:y="",activeHit:w=null}){const{t:b}=Q(),_=m.useRef(null),[j,N]=m.useState(!0),[C,S]=m.useState(!1),A=m.useRef(!0),E=m.useRef(null),I=m.useRef(0),D=m.useRef(0),T=m.useRef(null),z=m.useRef(!1),$=m.useRef(!1),R=m.useRef(0),[B,H]=m.useState(null),oe=m.useRef(0),te=m.useCallback(Ie=>{cancelAnimationFrame(oe.current),oe.current=requestAnimationFrame(()=>H(Ie()))},[]);m.useEffect(()=>()=>cancelAnimationFrame(oe.current),[]);const[O,V]=m.useState(new Set),J=m.useRef(new Set),[pe,fe]=m.useState(()=>new Set),_e=m.useCallback((Ie,it)=>{const dt=J.current;it!==dt.has(Ie)&&(it?dt.add(Ie):dt.delete(Ie),fe(new Set(dt)))},[]),Ee=m.useRef({report:_e,scroller:E});Ee.current.report=_e;const me=m.useCallback(Ie=>{V(it=>{const dt=new Set(it);return dt.has(Ie)?dt.delete(Ie):dt.add(Ie),dt})},[]),[W,G]=m.useState(new Map),de=Ce(Ie=>Ie.autoCollapseTurns),X=Ce(Ie=>Ie.collapseCompletedActivity),ie=Ce(Ie=>Ie.collapseLiveActivity),Z=Ce(Ie=>Ie.liveActivityFoldDelaySec),le=Ce(Ie=>Ie.compactReadOnlyTools),be=LK(t,o,O,{compact:le,autoCollapseCompletedTurns:de,collapseCompletedActivity:X,collapseLiveActivity:ie,liveActivityFoldDelaySec:Z,heldOpenTools:pe,turnOverrides:W}),Fe=m.useRef({state:MW,collapse:new Map,reveal:new Map}),Je=m.useMemo(()=>{const Ie=Fe.current,it=Rt=>E.current?.querySelector(`[data-nav-key="${CSS.escape(Rt)}"]`),dt=RW(Ie.state,be,(Rt,dn)=>{const P=it(Rt)?.getBoundingClientRect().top,M=it(dn)?.getBoundingClientRect().bottom;return P===void 0||M===void 0?0:M-P}),jt=Date.now();Ie.state=dt.next;for(const{key:Rt,...dn}of dt.collapses)Ie.collapse.set(Rt,{at:jt,...dn});for(const Rt of dt.expands)Ie.reveal.set(Rt,jt);return dt.children},[be]),We=m.useRef(null),et=m.useRef(0),qe=m.useRef(null),Lt=AK(We.current,be.map(Ie=>Ie.key));We.current=Lt.anchor,Lt.remount&&(et.current+=1,qe.current=null);const Bt=Lt.firstItemIndex,Mt=m.useCallback((Ie,it)=>{G(dt=>dt.get(Ie)===it?dt:new Map(dt).set(Ie,it))},[]),ne=m.useMemo(()=>{const Ie=[];for(let it=0;it<t.length;it++){const dt=t[it];if(dt.kind!=="user")continue;let jt="";for(let Rt=it+1;Rt<t.length;Rt++){const dn=t[Rt];if(dn.kind==="user")break;if(dn.kind==="text"){jt=dn.text;break}}Ie.push({key:dt.key,question:dt.text||"[image]",answer:jt})}return Ie},[t]),se=m.useCallback(()=>{const Ie=E.current;Ie&&Ie.scrollHeight-Ie.scrollTop-Ie.clientHeight>2&&(z.current=!0,Ie.scrollTop=Ie.scrollHeight)},[]),He=m.useCallback(()=>{cancelAnimationFrame(I.current);const Ie=Date.now()+1200;let it=null;const dt=()=>{cancelAnimationFrame(I.current),z.current=!1,it?.removeEventListener("touchstart",dt),it?.removeEventListener("wheel",dt)},jt=()=>{if($.current){dt();return}!it&&E.current&&(it=E.current,it.addEventListener("touchstart",dt,{passive:!0,once:!0}),it.addEventListener("wheel",dt,{passive:!0,once:!0})),se(),A.current=!0,N(!0),Date.now()<Ie?I.current=requestAnimationFrame(jt):dt()};jt(),N(!0),A.current=!0},[se]);m.useEffect(()=>()=>{cancelAnimationFrame(I.current),cancelAnimationFrame(D.current),window.clearTimeout(R.current)},[]);const kt=()=>{$.current=!0,window.clearTimeout(R.current)},st=()=>{window.clearTimeout(R.current),R.current=window.setTimeout(()=>{$.current=!1},400)},ke=()=>{kt(),st()},ut=()=>{cancelAnimationFrame(I.current),cancelAnimationFrame(D.current),z.current=!1,A.current=!1,N(!1)},ft=m.useCallback(Ie=>{if(T.current?.disconnect(),T.current=null,!Ie)return;const it=new ResizeObserver(()=>{if(!A.current&&!z.current)return;cancelAnimationFrame(D.current);let dt=8;const jt=()=>{se();const Rt=E.current;(Rt?Rt.scrollHeight-Rt.scrollTop-Rt.clientHeight:0)<=2||(--dt>0?D.current=requestAnimationFrame(jt):He())};jt()});it.observe(Ie),T.current=it,He()},[se,He]);m.useEffect(()=>()=>T.current?.disconnect(),[]);const ze=Ie=>be.findIndex(it=>it.key===Ie||it.kind==="tool-group"&&FT(it,Ie)),wt=Ie=>{if(!p){E.current?.querySelector(`[data-nav-key="${CSS.escape(Ie)}"]`)?.scrollIntoView({block:"center"});return}const it=ze(Ie);it>=0&&_.current?.scrollToIndex({index:MK(Bt,it),align:"center"})},Y=m.useRef(null),U=Ie=>{if(ut(),ze(Ie)>=0){Y.current=null,wt(Ie);return}let it=null,dt=!1;for(const jt of t)if(jt.kind==="user"&&(it=jt.key),jt.key===Ie){dt=!0;break}!dt||!it||(Y.current=Ie,Mt(it,!1))};m.useLayoutEffect(()=>{const Ie=Y.current;!Ie||ze(Ie)<0||(Y.current=null,wt(Ie))},[be]),m.useImperativeHandle(e,()=>({scrollToBottom:He,pinToBottom:se,isAtBottom:()=>A.current,getScroller:()=>p?null:E.current,scrollToKey:U}));const ue=m.useRef(!1),je=`${v}:${Bt}`,De=m.useRef(je);De.current!==je&&(De.current=je,ue.current=!1);const Le=()=>{!f||ue.current||(ue.current=!0,f())};m.useEffect(()=>{p&&!g&&qe.current===Bt&&Le()},[v,g]);const tt=m.useMemo(()=>({query:y,activeKey:w?.key??"",activeNth:w?.nth??-1}),[y,w?.key,w?.nth]),bt=(Ie,it)=>{const dt=be[it+1];if(dt!==void 0&&jy(Ie)&&jy(dt))return"pb-0";if(!le)return"pb-4";const jt=dt!==void 0&&by(dt);return by(Ie)?jt?"pb-1":"pb-2":Ie.kind==="text"&&jt?"pb-1":"pb-4"},Vt=(Ie,it)=>{const dt=be[it-1],jt=dt?.kind==="user"&&!dt.collapsed&&RK.has(Ie.kind)?dt:void 0,Rt=Date.now(),dn=Fe.current.collapse.get(Ie.key),P=dn&&Rt-dn.at<Ny?dn:void 0,M=Je.get(Ie.key),L=M&&Fe.current.reveal.get(M.group),k=M&&L!==void 0&&Rt-L<Ny;return i.jsxs("div",{"data-nav-key":Ie.key,"data-fold-collapse":P?P.pair?"pair":"toggle":void 0,style:P?{"--fold-from":`${P.height}px`}:k?{"--fold-i":M.index}:void 0,className:q(yi,bt(Ie,it),k&&"t-fold-reveal","[overflow-wrap:anywhere]"),children:[jt&&i.jsx(Q7,{model:jt.replyModel,at:jt.replyAt,privacyMask:jt.replyPrivacyMask}),i.jsx(qK,{itemKey:Ie.key,children:i.jsx(eK,{item:Ie,onToggleGroup:me,onToggleTurn:Mt})})]},Ie.key)},Jt=m.useRef(!1);x===!0&&(Jt.current=!0);const un=BM(t.length>0,g,x,Jt.current,!p&&C);m.useLayoutEffect(()=>{if(p){S(!1);return}const Ie=E.current;S(!!Ie&&VM(x===!0,g,Ie.scrollHeight,Ie.clientHeight))},[p,x,g,Bt,be.length,t.length]);const nn={pageChrome:un,onLoadMore:un==="more"?Le:void 0,busy:n,loading:!!s,since:s?void 0:a??r,error:l,onRetryResume:h};return i.jsx($M.Provider,{value:tt,children:i.jsx(R7,{value:Ee.current,children:i.jsxs("div",{"data-enso":"timeline",className:"@container relative min-h-0 flex-1",onWheel:ke,onKeyDown:ke,onTouchStart:kt,onTouchEnd:st,onPointerDown:Ie=>{Ie.target===E.current&&(kt(),window.addEventListener("pointerup",st,{once:!0}))},children:[i.jsx(zW,{items:ne,activeKey:B,onJump:U}),t.length===0&&!n?i.jsxs(Ty,{className:"flex h-full flex-col items-center justify-center gap-2 overflow-y-auto px-4 text-center",children:[i.jsx("span",{className:"t-stagger-line t-stagger-line--1 mb-3",children:i.jsx("span",{className:"flex size-11 items-center justify-center rounded-[13px] border border-brand/20 bg-brand/8 text-brand dark:bg-brand/14",children:i.jsx(AW,{className:"size-6"})})}),i.jsx("p",{className:"t-stagger-line t-stagger-line--1 text-[22px] font-semibold tracking-tight",children:d}),l?i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--2 max-w-md text-sm text-destructive whitespace-pre-wrap",children:b(l)}),h&&i.jsx(ge,{size:"sm",variant:"outline",onClick:h,children:b("Retry resume")})]}):i.jsxs(i.Fragment,{children:[c!==""&&i.jsx("p",{className:"t-stagger-line t-stagger-line--2 text-sm text-muted-foreground",children:c??b("Ask the agent…")}),u&&i.jsx("div",{className:"t-stagger-line t-stagger-line--3 mt-5 w-full",children:i.jsx(zK,{onPick:u})})]})]}):t.length===0&&l?i.jsxs(Ty,{className:"flex h-full flex-col items-center justify-center gap-2 text-center",children:[i.jsx("p",{className:"t-stagger-line t-stagger-line--1 max-w-md text-sm text-destructive whitespace-pre-wrap",children:b(l)}),h&&i.jsx(ge,{size:"sm",variant:"outline",onClick:h,children:b("Retry resume")})]}):t.length===0?i.jsxs("div",{"data-timeline-loading":"",className:"flex h-full flex-col items-center justify-center gap-2.5 text-center",children:[i.jsx(qt,{className:"h-5 w-5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:b("Preparing session…")})]}):p?i.jsx(xW,{ref:_,data:be,defaultItemHeight:80,computeItemKey:(Ie,it)=>it.key,firstItemIndex:Bt,startReached:Le,followOutput:HK,atBottomThreshold:Dy,atBottomStateChange:Ie=>{if(!Ie&&A.current&&!$.current){He();return}N(Ie),A.current=Ie},increaseViewportBy:FK,initialTopMostItemIndex:GK,rangeChanged:({startIndex:Ie})=>{qe.current=Ie,Ie>Bt+4&&(ue.current=!1),te(()=>{const it=Math.max(0,Ie-Bt);let dt=null;for(let jt=0;jt<=Math.min(it+1,be.length-1);jt++)be[jt]?.kind==="user"&&(dt=be[jt].key);return dt})},scrollerRef:Ie=>{E.current=Ie instanceof HTMLElement?Ie:null},className:"h-full select-text",context:nn,components:$K,itemContent:(Ie,it)=>Vt(it,Ie-Bt)},et.current):i.jsx("div",{ref:Ie=>{E.current=Ie},onScroll:Ie=>{const it=Ie.currentTarget;if(z.current){z.current=!1,A.current=!0,N(!0);return}if(!$.current){A.current&&se();return}const dt=it.scrollHeight-it.scrollTop-it.clientHeight<=Dy;dt!==A.current&&(A.current=dt,N(dt)),f&&(it.scrollTop<80&&!ue.current?(ue.current=!0,f()):it.scrollTop>240&&(ue.current=!1))},className:"h-full select-text overflow-y-auto [overflow-anchor:none]",children:i.jsxs("div",{ref:ft,children:[i.jsx(HT,{context:nn}),be.map((Ie,it)=>Vt(Ie,it)),i.jsx(BT,{context:nn})]})}),!j&&t.length>0&&i.jsxs("button",{type:"button",onClick:He,className:"absolute bottom-4 left-1/2 z-10 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full border bg-card px-3 text-xs text-muted-foreground shadow-float transition-colors hover:text-foreground",children:[i.jsx(uh,{className:"h-3 w-3"}),b("Scroll to bottom")]})]})})})}function FT(e,t){return e.children.some(n=>n.key===t||n.kind==="tool-group"&&FT(n,t))}function VK({chrome:e,onLoadMore:t}){const{t:n}=Q();return e==="none"?i.jsx("div",{className:"h-6"}):i.jsx("div",{className:q(yi,"flex items-center justify-center gap-2 py-3"),children:e==="loading"?i.jsxs(i.Fragment,{children:[i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}),i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Loading earlier messages…")})]}):e==="more"?i.jsx("button",{type:"button",className:"text-xs text-muted-foreground underline-offset-2 hover:underline",onClick:t,children:n("Load earlier messages")}):i.jsx("p",{className:"text-xs text-muted-foreground",children:n("Beginning of conversation")})})}function HT({context:e}){return i.jsx(VK,{chrome:e.pageChrome,onLoadMore:e.onLoadMore})}function BT({context:e}){const{t}=Q(),{busy:n,loading:s,since:o,error:r,onRetryResume:a}=e;return i.jsxs("div",{className:q(yi,"pb-6 [overflow-wrap:anywhere]"),children:[n&&i.jsxs("div",{className:"flex min-h-[26px] items-center gap-2 text-[13px]",children:[i.jsx(WK,{}),i.jsx("span",{className:"t-shimmer","data-text":t(s?"Loading…":"Working…"),children:t(s?"Loading…":"Working…")}),o!==void 0&&i.jsx(KK,{since:o})]}),r&&i.jsxs("div",{className:"flex items-start gap-2",children:[i.jsx("p",{className:"min-w-0 flex-1 text-sm text-destructive whitespace-pre-wrap",children:t(r)}),i.jsx(zT,{}),a&&i.jsx(ge,{size:"sm",variant:"outline",onClick:a,children:t("Retry resume")})]})]})}const $K={List:BK,Header:HT,Footer:BT};function WK(){return i.jsxs("span",{className:"relative flex size-[22px] shrink-0 items-center justify-center",children:[i.jsx("span",{className:"absolute size-2 animate-ping rounded-full bg-brand/50"}),i.jsx("span",{className:"relative size-2 rounded-full bg-brand"})]})}const UK=e=>{const t=Math.max(0,Math.round(e/1e3));return t<60?`${t}s`:`${Math.floor(t/60)}m${t%60}s`},KK=m.memo(function({since:t}){const[,n]=m.useState(0);return m.useEffect(()=>{const s=setInterval(()=>n(o=>o+1),1e3);return()=>clearInterval(s)},[]),i.jsx("span",{className:"font-mono text-[11px] text-muted-foreground tabular-nums",children:UK(Date.now()-t)})});class qK extends m.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidUpdate(t){t.itemKey!==this.props.itemKey&&this.state.failed&&this.setState({failed:!1})}render(){return this.state.failed?i.jsxs("p",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-3 py-1.5 text-xs text-destructive",children:["message render failed · ",this.props.itemKey]}):this.props.children}}const Jr={type:"spring",stiffness:400,damping:30},Nu={type:"tween",duration:.22,ease:[.2,0,0,1]},Ep={initial:{height:0,opacity:0},animate:{height:"auto",opacity:1,transition:Nu},exit:{height:0,opacity:0,transition:Nu}};function YK(e){return e.resizing?!0:e.previousConversationId!==void 0&&e.conversationId!==void 0&&e.previousConversationId!==e.conversationId}function VT(e){return e.skip?{duration:0}:e.cover||e.targetW===0?Nu:Jr}const $T=e=>{const t=window.electronAPI.speech,n=crypto.randomUUID(),s=t.onPartial(r=>{r.sessionId===n&&e(r.text,r.correcting===!0)});let o=!1;return{push:r=>{o||t.pushAudio(n,r)},finish:()=>(o=!0,t.finishSession(n).finally(s)),cancel:()=>{o||(o=!0,s(),t.cancelSession(n))}}},XK={ts:Ea,tsx:Ea,js:Ea,jsx:Ea,mjs:Ea,json:ug,html:GV,css:Kv,scss:Kv,md:bo,sh:mf,bash:mf,yml:ui,yaml:ui,toml:ui},ZK={ts:"text-blue-500",tsx:"text-blue-500",js:"text-yellow-500",jsx:"text-yellow-500",mjs:"text-yellow-500",json:"text-yellow-600",html:"text-orange-500",css:"text-pink-500",scss:"text-pink-500",md:"text-sky-500",sh:"text-muted-foreground"};function _d(e,t,n=!1){if(t)return n?ni:yd;const s=e.split(".").pop()?.toLowerCase()??"";return XK[s]??r$}function Nd(e,t){if(t)return"text-amber-500";const n=e.split(".").pop()?.toLowerCase()??"";return ZK[n]??"text-muted-foreground"}const JK={artifacts:[],media:[]},Pp=new Map,Ap=new Map,QK=new Set(["image","markdown","html","text"]),eq=e=>e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(1)} MB`;function tq(e){const t=JSON.stringify(e),[n,s]=m.useState(()=>Pp.get(t)??JK);return m.useEffect(()=>{if(Pp.has(t))return;let o=!0;return window.electronAPI.bots.artifacts.list(JSON.parse(t)).then(r=>{if(!o||!r.ok)return;const a={artifacts:r.artifacts,media:r.media??[]};(a.artifacts.length>0||a.media.length>0)&&Pp.set(t,a),s(a)}).catch(()=>{}),()=>{o=!1}},[t]),n}function nq(e){const{t}=Q();return(n,s)=>{window.electronAPI.bots.artifacts.open({...e,rel:n.rel,action:s}).then(o=>{o.ok||Be({type:"error",title:o.error==="not-openable"?t("This file type is only shown in Finder"):t("Could not open the file")})})}}function Tu({target:e}){const{artifacts:t,media:n}=tq(e);return i.jsxs(i.Fragment,{children:[n.length>0&&i.jsx(iq,{target:e,media:n}),t.length>0&&i.jsx(aq,{target:e,artifacts:t})]})}function sq(){const{t:e}=Q();return({source:t,name:n})=>t==="upload"?"":t==="web"?e("Web screenshot"):t==="desktop"?e("Desktop screenshot"):n&&/^(?:\/|[A-Za-z]:[\\/])/.test(n)?e("This computer"):e("Workspace image")}function WT(e,t,n){const s=JSON.stringify(e),o=t&&n==="thumb"?Ap.get(t):void 0,[r,a]=m.useState(o?{ok:!0,kind:"image",dataUrl:o}:null);return m.useEffect(()=>{const l=t&&n==="thumb"?Ap.get(t):void 0;if(a(l?{ok:!0,kind:"image",dataUrl:l}:null),!t||l)return;let d=!0;return window.electronAPI.bots.artifacts.read({...JSON.parse(s),mediaId:t,variant:n}).then(c=>{n==="thumb"&&c.ok&&c.kind==="image"&&Ap.set(t,c.dataUrl),d&&a(c)}).catch(()=>d&&a({ok:!1,error:"unavailable"})),()=>{d=!1}},[s,t,n]),r}function iq({target:e,media:t}){const{t:n}=Q(),s=sq(),[o,r]=m.useState(null),a=t.some(l=>l.ok&&l.source==="desktop");return i.jsxs("div",{className:"mt-2","data-bot-media":"",children:[i.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.map((l,d)=>l.ok?i.jsx(oq,{target:e,item:l,label:s(l),onOpen:()=>r(l)},l.mediaId):i.jsxs("div",{className:"flex w-40 flex-col gap-1 rounded-lg border border-destructive/60 border-dashed p-2 text-destructive text-xs",children:[i.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[i.jsx(eN,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:l.name??s(l)})]}),i.jsx("span",{children:l.error==="quota"?n("Chat image storage is full (200 MiB); not saved"):n("Not sent: still over 10 MiB after compression")})]},`failed-${d}`))}),a&&i.jsx("p",{className:"mt-1 text-warning text-xs",children:n("Desktop screenshots may capture sensitive content from other windows.")}),i.jsx(rq,{target:e,item:o,label:o?s(o):"",onClose:()=>r(null)})]})}function oq({target:e,item:t,label:n,onOpen:s}){const o=WT(e,t.mediaId,"thumb"),r=t.caption??t.name??n;return i.jsxs("button",{type:"button",title:r,onClick:s,className:"relative h-24 w-36 overflow-hidden rounded-lg border bg-muted",children:[o?.ok&&o.kind==="image"?i.jsx("img",{src:o.dataUrl,alt:r,className:"h-full w-full object-cover"}):o?i.jsx(eN,{className:"m-auto h-4 w-4 text-muted-foreground"}):i.jsx(qt,{className:"m-auto h-4 w-4 animate-spin text-muted-foreground"}),n&&i.jsx("span",{className:q("absolute top-1 left-1 rounded px-1 text-[10px] leading-4",t.source==="desktop"?"bg-warning text-warning-foreground":"bg-black/60 text-white"),children:n}),(t.caption||t.name)&&i.jsx("span",{className:"absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/70 to-transparent px-1.5 pt-3 pb-0.5 text-left text-[10px] text-white",children:t.caption??t.name})]})}function rq({target:e,item:t,label:n,onClose:s}){const{t:o}=Q(),r=WT(e,t?.mediaId??null,"full"),a=t?.caption??t?.name??n;return i.jsx(wn,{open:t!==null,onOpenChange:l=>!l&&s(),children:i.jsxs(yn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(Sn,{children:i.jsxs(Cn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[i.jsx("span",{className:"truncate",children:a}),i.jsx("span",{className:"shrink-0 font-normal text-muted-foreground text-xs",children:n})]})}),t?.source==="desktop"&&i.jsx("p",{className:"text-warning text-xs",children:o("Desktop screenshots may capture sensitive content from other windows.")}),t?.source==="file"&&i.jsx("p",{className:"text-muted-foreground text-xs",children:o("Copied into this chat: later edits or deletion of the original do not change it. Deleted together with the chat.")}),i.jsx(UT,{name:a,content:r})]})})}function aq({target:e,artifacts:t}){const{t:n}=Q(),s=nq(e),[o,r]=m.useState(null);return i.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5","data-bot-artifacts":"",children:[t.map(a=>{const l=_d(a.name,!1),d=QK.has(a.kind)||a.kind==="pdf";return i.jsxs("div",{"data-slot":"bot-card",className:"group/artifact flex max-w-64 items-center gap-1 rounded-lg border bg-card py-1 pr-1 pl-2 text-xs",children:[i.jsxs("button",{type:"button",title:a.rel,disabled:!d,onClick:()=>a.kind==="pdf"?s(a,"preview"):r(a),className:"flex min-w-0 items-center gap-1.5 text-left enabled:hover:underline disabled:cursor-default",children:[i.jsx(l,{className:q("h-3.5 w-3.5 shrink-0",Nd(a.name,!1))}),i.jsx("span",{className:"truncate",children:a.name}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:eq(a.size)})]}),i.jsx("button",{type:"button",title:n("Show in Finder"),onClick:()=>s(a,"reveal"),className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(ni,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",title:n("Open with default app"),onClick:()=>s(a,"open"),className:"rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Ak,{className:"h-3.5 w-3.5"})})]},a.rel)}),i.jsx(lq,{target:e,artifact:o,onOpen:s,onClose:()=>r(null)})]})}function lq({target:e,artifact:t,onOpen:n,onClose:s}){const{t:o}=Q(),[r,a]=m.useState(null),l=t?.rel,d=JSON.stringify(e);return m.useEffect(()=>{if(a(null),!l)return;let c=!0;return window.electronAPI.bots.artifacts.read({...JSON.parse(d),rel:l}).then(u=>c&&a(u)).catch(()=>c&&a({ok:!1,error:"unavailable"})),()=>{c=!1}},[d,l]),i.jsx(wn,{open:t!==null,onOpenChange:c=>!c&&s(),children:i.jsxs(yn,{className:"flex h-[80vh] max-w-4xl flex-col",children:[i.jsx(Sn,{children:i.jsxs(Cn,{className:"flex min-w-0 items-center gap-2 pr-8",children:[i.jsx("span",{className:"truncate",children:t?.name}),i.jsx("span",{className:"truncate font-normal text-muted-foreground text-xs",children:t?.rel}),i.jsx("span",{className:"flex-1"}),t&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",title:o("Show in Finder"),onClick:()=>n(t,"reveal"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(ni,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",title:o("Open with default app"),onClick:()=>n(t,"open"),className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(Ak,{className:"h-4 w-4"})})]})]})}),i.jsx(UT,{name:t?.name??"",content:r})]})})}function UT({name:e,content:t}){const{t:n}=Q();return i.jsxs("div",{className:"min-h-0 flex-1 select-text overflow-auto border-t","data-bot-artifact-preview":"",children:[!t&&i.jsx("div",{className:"flex justify-center p-6 text-muted-foreground",children:i.jsx(qt,{className:"h-4 w-4 animate-spin"})}),t&&!t.ok&&i.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:t.error==="too-large"?n("The file is too large to preview"):n("Could not open the file")}),t?.ok&&t.kind==="image"&&i.jsx("img",{src:t.dataUrl,alt:e,className:"mx-auto max-h-full max-w-full object-contain p-4"}),t?.ok&&t.kind==="markdown"&&i.jsx("div",{className:"px-6 py-4 text-sm",children:i.jsx(js,{text:t.text})}),t?.ok&&t.kind==="html"&&i.jsx("iframe",{title:e,sandbox:"",srcDoc:t.text,className:"h-full w-full bg-white"}),t?.ok&&t.kind==="text"&&i.jsx("div",{className:"p-2 text-xs",children:i.jsx(Fc,{path:e,contents:t.text})})]})}const KT="enso:design-annotations:v1",qT="enso:annotate-prefs:v1",Iy=qM(e=>e.pageKey),Ey=[],Py=new WeakMap,To={annotateHovered:!1,annotateEntered:!1,annotateUseCount:0,annotateSendImmediately:!0};function YT(e){try{return typeof localStorage>"u"?null:localStorage.getItem(e)}catch{return null}}function XT(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(e,t)}catch{}}function dq(){const e=YT(qT);if(!e)return To;try{const t=JSON.parse(e);return{annotateHovered:typeof t.annotateHovered=="boolean"?t.annotateHovered:To.annotateHovered,annotateEntered:typeof t.annotateEntered=="boolean"?t.annotateEntered:To.annotateEntered,annotateUseCount:typeof t.annotateUseCount=="number"&&Number.isFinite(t.annotateUseCount)?t.annotateUseCount:To.annotateUseCount,annotateSendImmediately:typeof t.annotateSendImmediately=="boolean"?t.annotateSendImmediately:To.annotateSendImmediately}}catch{return To}}function La(e){XT(qT,JSON.stringify(e))}const Ay=WM(YT(KT)),cq=dq();function Yd(e,t){XT(KT,KM({queues:e,pages:t}))}const Wn=rg((e,t)=>({...cq,queues:Ay.queues,pages:Ay.pages,sessions:new Map,familiarity:()=>{const n=t();return UM(n.annotateEntered,n.annotateUseCount)},markHovered:()=>{const n=t();if(n.annotateHovered)return;const s={annotateHovered:!0,annotateEntered:n.annotateEntered,annotateUseCount:n.annotateUseCount,annotateSendImmediately:n.annotateSendImmediately};La(s),e({annotateHovered:!0})},markEntered:()=>{const n=t();if(n.annotateEntered)return;const s={annotateHovered:n.annotateHovered,annotateEntered:!0,annotateUseCount:n.annotateUseCount,annotateSendImmediately:n.annotateSendImmediately};La(s),e({annotateEntered:!0})},setSendImmediately:n=>{const s=t();if(s.annotateSendImmediately===n)return;const o={annotateHovered:s.annotateHovered,annotateEntered:s.annotateEntered,annotateUseCount:s.annotateUseCount,annotateSendImmediately:n};La(o),e({annotateSendImmediately:n})},annotationsFor:(n,s)=>{const o=t().queues.get(n);if(!o||o.items.length===0)return Ey;if(!s)return o.items;let r=Py.get(o.items);r||(r=new Map,Py.set(o.items,r));const a=r.get(s);if(a)return a;const l=o.items.filter(c=>c.browserId===s),d=l.length===0?Ey:l;return r.set(s,d),d},pageKeyOf:n=>t().pages.get(n),setBrowserUrl:(n,s)=>{if(!s)return;const o=Mk(s),r=t().pages;if(r.get(n)===o)return;const a=new Map(r);a.delete(n),a.set(n,o),Yd(t().queues,a),e({pages:a})},dispatchQueue:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=Iy(r,s);if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),Yd(l,o.pages),e({queues:l})},addAnnotation:(n,s)=>{const o=t(),r=o.queues.get(n)??{items:[]},a=Iy(r,{type:"add",draft:s});if(a===r)return;const l=new Map(o.queues);l.delete(n),a.items.length>0&&l.set(n,a),Yd(l,o.pages);const d=o.annotateUseCount+1;return La({annotateHovered:o.annotateHovered,annotateEntered:o.annotateEntered,annotateUseCount:d,annotateSendImmediately:o.annotateSendImmediately}),e({queues:l,annotateUseCount:d}),a.items.find(c=>c.id===s.id)},updateAnnotation:(n,s,o,r)=>{t().dispatchQueue(n,{type:"update",id:s,comment:o,images:r})},removeAnnotations:(n,s)=>{t().dispatchQueue(n,{type:"remove",ids:s})},clearAnnotations:(n,s)=>{if(!s){t().dispatchQueue(n,{type:"clear"});return}const o=t().annotationsFor(n,s).map(r=>r.id);o.length>0&&t().dispatchQueue(n,{type:"remove",ids:o})},restoreAnnotations:(n,s)=>{t().dispatchQueue(n,{type:"restore",items:s})},registerSession:(n,{url:s,...o})=>{t().setBrowserUrl(n,s);const r=new Map(t().sessions);return r.set(n,{...o,pinned:new Set}),e({sessions:r}),()=>{const a=t().sessions;if(a.get(n)?.exit!==o.exit)return;const l=new Map(a);l.delete(n),e({sessions:l})}},setPinnedIds:(n,s)=>{const o=t().sessions,r=o.get(n);if(!r)return;const a=new Set(s);if(r.pinned.size===a.size&&[...r.pinned].every(d=>a.has(d)))return;const l=new Map(o);l.set(n,{...r,pinned:a}),e({sessions:l})},exitAgentSessions:n=>{for(const s of t().sessions.values())s.agent===n&&s.exit()},resetForTests:()=>{La(To),Yd(new Map,new Map),e({...To,queues:new Map,pages:new Map,sessions:new Map})}})),Qr=typeof navigator<"u"&&navigator.platform?navigator.platform.startsWith("Mac"):!0,_m=Qr?"⌘⇧D":"Ctrl+Shift+D";function Mp({className:e}){return i.jsx("svg",{viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":"true",className:q("h-3.5 w-3.5 shrink-0",e),children:i.jsx("path",{d:"M3 1.5v11.2l3-2.9 2 4.7 1.9-.8-2-4.6h4.3z"})})}async function uq(e){return e.markup.length===0||!e.base64?e.base64:new Promise(t=>{const n=new Image;n.onload=()=>{try{const s=document.createElement("canvas");s.width=Math.max(1,n.naturalWidth||n.width),s.height=Math.max(1,n.naturalHeight||n.height);const o=s.getContext("2d");if(!o){t(e.base64);return}o.drawImage(n,0,0);const r=s.width/Math.max(1,e.cropWidth);o.scale(r,r),o.fillStyle=Hr,o.strokeStyle=Hr,o.lineWidth=vf,o.lineCap="round",o.lineJoin="round";for(const l of e.markup)for(const d of xf(l,"complete")){const c=new Path2D(d.d);d.paint==="fill"?o.fill(c):o.stroke(c)}const a=s.toDataURL("image/png");t(a.slice(a.indexOf(",")+1))}catch{t(e.base64)}},n.onerror=()=>t(e.base64),n.src=e.base64.startsWith("data:")?e.base64:`data:image/png;base64,${e.base64}`})}function hq({active:e}){const t=m.useRef(null),[n,s]=m.useState(null),o=m.useRef(e),[r,a]=m.useState({width:0,height:0});m.useEffect(()=>{o.current!==e&&(o.current=e,s(e?"in":"out"))},[e]),m.useEffect(()=>{const d=t.current;if(!d)return;const c=()=>{const h=d.getBoundingClientRect();a({width:Math.round(h.width),height:Math.round(h.height)})};c();const u=new ResizeObserver(c);return u.observe(d),()=>u.disconnect()},[]);const l=m.useMemo(()=>r.width>4&&r.height>4?tR(r.width,r.height,{topLeft:6,topRight:6,bottomRight:6,bottomLeft:6}):null,[r.width,r.height]);return!n&&!e?i.jsx("div",{ref:t,className:"pointer-events-none absolute inset-0"}):i.jsx("div",{ref:t,"aria-hidden":"true","data-component":"design-frame-ring","data-trace":n??(e?"in":"out"),className:"pointer-events-none absolute inset-0 z-20 overflow-hidden",children:l&&i.jsxs("svg",{width:r.width,height:r.height,"aria-hidden":"true",className:"block h-full w-full overflow-visible",onAnimationEnd:()=>{e||s(null)},children:[i.jsx("path",{d:l.right,pathLength:1,fill:"none",stroke:"rgb(58, 150, 221)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:1,strokeDashoffset:n==="out"?1:0,transition:n==="out"?"stroke-dashoffset 350ms cubic-bezier(0.65, 0, 0.35, 1)":"stroke-dashoffset 550ms cubic-bezier(0.65, 0, 0.35, 1)"}}),i.jsx("path",{d:l.left,pathLength:1,fill:"none",stroke:"rgb(58, 150, 221)",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",style:{strokeDasharray:1,strokeDashoffset:n==="out"?1:0,transition:n==="out"?"stroke-dashoffset 350ms cubic-bezier(0.65, 0, 0.35, 1)":"stroke-dashoffset 550ms cubic-bezier(0.65, 0, 0.35, 1)"}})]})})}function pq({drawing:e,pick:t,markupTool:n,editorOpen:s,onMarkupToolChange:o,onExit:r}){const a=JM({drawing:e,pick:t?{region:t.region}:null,markupToolHeld:n!==null,editorOpen:s}),d=m.useMemo(()=>QM(Qr),[])[a],c=h=>h.map((p,f)=>typeof p=="string"?i.jsx("span",{children:p},f):i.jsx("strong",{className:"font-semibold text-foreground",children:p.key},f)),u=h=>{switch(h){case"pencil":return i.jsx(Fs,{className:"h-3.5 w-3.5"});case"circle":return i.jsx(gx,{className:"h-3.5 w-3.5"});case"square":return i.jsx(ld,{className:"h-3.5 w-3.5"});case"arrow-right-up":return i.jsx(gV,{className:"h-3.5 w-3.5"})}};return i.jsxs("div",{"data-component":"design-hint-row",style:{backgroundColor:"var(--background)"},className:"flex h-8 shrink-0 items-center justify-between gap-2 border-b px-2.5 text-xs",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("button",{type:"button",onClick:r,"aria-label":"Exit design mode",title:`Exit Design Mode (${_m})`,className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-black/5 hover:text-foreground dark:hover:bg-white/10",children:i.jsx(an,{className:"h-3.5 w-3.5"})}),i.jsx("span",{"data-hint":"",className:"truncate text-[12px] text-muted-foreground transition-all duration-150",children:c(d)})]}),i.jsx("div",{role:"toolbar","aria-label":"Screenshot markup tools",className:"flex shrink-0 items-center gap-0.5 rounded-md border bg-background/90 p-0.5 shadow-2xs",children:eR.map(h=>{const p=n===h.tool;return i.jsx("button",{type:"button","aria-label":h.label,"aria-pressed":p,title:h.label,onClick:()=>o(p?null:h.tool),className:q("flex h-5 w-5 items-center justify-center rounded-sm transition-colors",p?"bg-[#3a96dd] text-white":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:u(h.icon)},h.tool)})})]})}function fq({tabId:e,conversationId:t,active:n,disabled:s,queueOpen:o,onQueueOpenChange:r,onToggleDesignMode:a,onOpenPinFromQueue:l,onSendQueue:d}){const{t:c}=Q(),u=Wn(j=>j.familiarity()),h=Wn(j=>j.annotateHovered),p=Wn(j=>j.markHovered),f=Wn(j=>j.annotationsFor(t)),g=Wn(j=>j.annotationsFor(t,e)),x=Wn(j=>j.removeAnnotations),v=Wn(j=>j.clearAnnotations),[y,w]=m.useState(!1),b=n?f:g,_=b.length;return _===0&&!n?i.jsxs("div",{className:"relative flex shrink-0 items-center",children:[i.jsxs("button",{type:"button",disabled:s,"aria-label":"Annotate","aria-pressed":n,title:`Annotate (${_m}) — Point at anything and tell the agent what to fix`,onPointerEnter:()=>{p(),u==="never"&&w(!0)},onPointerLeave:()=>w(!1),onClick:()=>{w(!1),a(!0)},className:q("relative flex h-6 items-center justify-center gap-1 overflow-hidden rounded text-xs font-medium transition-colors disabled:opacity-40",u==="many"?"w-6 text-muted-foreground hover:bg-muted hover:text-foreground":"px-2 text-foreground hover:bg-muted",u==="never"&&!h&&"border border-sky-500/40 bg-sky-500/10"),children:[i.jsx(Mp,{}),u!=="many"&&i.jsx("span",{children:"Annotate"}),u==="never"&&!h&&!s&&i.jsx("span",{"aria-hidden":"true","data-gradient-sweep":"",className:"pointer-events-none absolute inset-0 bg-linear-to-r from-transparent via-sky-400/20 to-transparent animate-pulse"})]}),y&&!s&&i.jsxs("div",{"data-enso-float":"",role:"tooltip","aria-label":"Try Annotate",className:"absolute top-full right-0 z-50 mt-1.5 w-64 rounded-lg border bg-popover p-3 text-popover-foreground shadow-xl",children:[i.jsx("div",{className:"mb-2 flex h-24 items-center justify-center rounded-md border border-sky-500/20 bg-sky-500/5",children:i.jsxs("div",{className:"flex flex-col items-center gap-1 text-sky-500",children:[i.jsx(Mp,{className:"h-6 w-6"}),i.jsx("span",{className:"rounded bg-sky-500 px-1.5 py-0.5 text-[10px] font-semibold text-white",children:"Click · Drag · Draw · Edit CSS"})]})}),i.jsx("h2",{className:"text-xs font-semibold",children:"Try Annotate"}),i.jsx("p",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"Point at anything on the page and tell the agent what to fix."})]})]}):i.jsxs("div",{className:"relative flex shrink-0 items-center","data-design-annotation-queue":"",children:[_>0?i.jsxs("div",{className:"flex h-6 items-center overflow-hidden rounded-md border border-[#3a96dd]/40 bg-[#3a96dd] text-white shadow-2xs",children:[i.jsxs("button",{type:"button",onClick:()=>d(n?void 0:new Set(g.map(j=>j.id))),title:c("Send annotations to chat"),className:"flex h-full items-center gap-1 px-2 text-xs font-medium transition-opacity hover:opacity-90",children:[i.jsx("span",{children:"Send"}),i.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-white/20 px-1 text-[10px] font-semibold tabular-nums",children:_})]}),i.jsx("button",{type:"button","aria-label":`Open annotation queue (${_})`,"aria-expanded":o,onClick:()=>r(!o),className:"flex h-full items-center border-l border-white/20 px-1 transition-colors hover:bg-black/10",children:i.jsx(Vn,{className:"h-3 w-3"})})]}):i.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-label":"Annotate","aria-pressed":n,title:`Exit Design Mode (${_m})`,className:"flex h-6 items-center gap-1 rounded bg-[#3a96dd]/15 px-2 text-xs font-medium text-[#3a96dd]",children:[i.jsx(Mp,{}),u!=="many"&&i.jsx("span",{children:"Annotate"})]}),o&&_>0&&i.jsxs("div",{"data-enso-float":"","data-design-owns-escape":"",className:"absolute top-full right-0 z-50 mt-1.5 w-72 overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-xl",children:[i.jsxs("div",{className:"flex items-center justify-between border-b px-3 py-2 text-xs",children:[i.jsx("span",{className:"font-medium text-muted-foreground",children:_===1?"1 edit":`${_} edits`}),i.jsx("button",{type:"button",onClick:()=>{v(t,n?void 0:e),r(!1)},className:"text-[11px] text-muted-foreground transition-colors hover:text-destructive",children:"Clear All"})]}),i.jsx("div",{className:"max-h-64 divide-y overflow-y-auto",children:b.map(j=>{const N=j.kind==="region"&&j.images[0]?`data:${j.images[0].mimeType};base64,${j.images[0].data}`:null,C=j.kind==="element"&&j.elements.length>1?j.elements.length-1:0,S=j.comment.trim()||(j.kind==="element"&&j.elements[0]?ZM(j.elements[0]):j.kind==="region"?`Screenshot region ${Math.round(j.region.rect.width)} × ${Math.round(j.region.rect.height)}`:"Annotation");return i.jsxs("div",{className:"group flex items-center gap-2 px-2.5 py-2 text-xs hover:bg-muted/60",children:[i.jsxs("button",{type:"button",onClick:()=>{r(!1),l(j)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx("span",{className:"flex h-5 w-5 shrink-0 items-center justify-center rounded-t-full rounded-br-full rounded-bl-xs bg-[#3a96dd] text-[11px] font-semibold text-white tabular-nums",children:j.number}),N&&i.jsx("img",{src:N,alt:"",className:"h-5 w-7 shrink-0 rounded border object-cover"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:S}),C>0&&i.jsxs("span",{className:"shrink-0 rounded bg-muted px-1 py-0.5 text-[10px] text-muted-foreground",children:["+",C]})]}),i.jsx("button",{type:"button","aria-label":"Delete annotation",onClick:()=>x(t,[j.id]),className:"flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-destructive/10 hover:text-destructive",children:i.jsx(Gs,{className:"h-3 w-3"})})]},j.id)})})]})]})}function mq({stage:e,pinned:t,onTogglePinned:n,onClose:s,onStageChange:o}){const[r,a]=m.useState(""),l=m.useMemo(()=>Lk(e),[e]),d=m.useMemo(()=>{const h={...e.baseline.values};for(const[p,f]of e.edits)f&&(h[p]=f);return h},[e.baseline.values,e.edits]),c=m.useMemo(()=>{const h=r.trim().toLowerCase();return gR.filter(p=>xR(p,{rendersText:e.baseline.rendersText,values:d})&&p.name.includes(h))},[r,e.baseline.rendersText,d]),u=h=>{const p=wR(e,h);o(p.staging,p.filed)};return i.jsxs("div",{className:"flex flex-col border-t bg-background/95",children:[i.jsxs("div",{className:"flex items-center gap-1.5 border-b px-2.5 py-1.5",children:[i.jsx("input",{type:"text",value:r,onChange:h=>a(h.target.value),placeholder:"Filter CSS properties...",className:"min-w-0 flex-1 rounded border bg-muted/40 px-2 py-0.5 text-[11px] outline-none focus:border-ring"}),l.canReset&&i.jsx("button",{type:"button","aria-label":"Reset all CSS edits",title:"Reset all CSS edits",onClick:()=>u({kind:"resetAll"}),className:"flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(na,{className:"h-3 w-3"})}),i.jsx("button",{type:"button","aria-label":"Pin CSS inspector","aria-pressed":t,title:t?"Unpin inspector":"Pin inspector to top right",onClick:n,className:q("flex h-5 w-5 items-center justify-center rounded transition-colors",t?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:i.jsx(di,{className:"h-3 w-3"})}),i.jsx("button",{type:"button","aria-label":"Close CSS inspector",onClick:s,className:"flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(an,{className:"h-3 w-3"})})]}),i.jsx("div",{className:"max-h-52 divide-y overflow-y-auto px-2 py-1 text-[11px]",children:c.map(h=>{const p=e.edits.get(h.name),f=p===null,g=l.isEdited(h.name),x=l.isAuthored(h.name),v=f?e.baseline.values[h.name]??"":p??e.baseline.values[h.name]??"",y=h.name.endsWith("color"),w=`css-presets-${h.name}`;return i.jsxs("div",{className:"flex items-center gap-1.5 py-1",children:[i.jsx("input",{type:"checkbox",checked:!f&&(g||x),"aria-label":`Toggle ${h.name}`,onChange:b=>{b.target.checked?u({kind:"enable",property:h.name}):u({kind:"disable",property:h.name})},className:"h-3 w-3 shrink-0 accent-[#3a96dd]"}),i.jsx("span",{className:q("w-28 shrink-0 truncate font-mono text-[10px]",f&&"line-through opacity-50",g?"font-semibold text-[#3a96dd]":x?"text-foreground":"text-muted-foreground"),title:h.name,children:h.name}),y&&i.jsx("input",{type:"color","aria-label":`${h.name} color picker`,value:/^#[0-9a-fA-F]{6}$/.test(v)?v:"#3a96dd",onChange:b=>u({kind:"edit",property:h.name,value:b.target.value}),className:"h-4 w-4 shrink-0 cursor-pointer rounded border bg-transparent p-0"}),i.jsx("input",{type:"text",list:h.presets?.length?w:void 0,value:v,disabled:f,onChange:b=>u({kind:"edit",property:h.name,value:b.target.value}),onKeyDown:b=>{if(b.key!=="ArrowUp"&&b.key!=="ArrowDown")return;const _=vR(v,b.key==="ArrowUp"?1:-1,b.shiftKey,h);_!==null&&(b.preventDefault(),b.stopPropagation(),u({kind:"edit",property:h.name,value:_}))},className:q("min-w-0 flex-1 rounded border bg-transparent px-1.5 py-0.5 font-mono text-[10px] outline-none focus:border-ring",f&&"opacity-40")}),h.presets&&h.presets.length>0&&i.jsxs("datalist",{id:w,children:[h.presets.map(b=>i.jsx("option",{value:b},b)),e.baseline.variables.lengths.map(b=>i.jsx("option",{value:`var(${b.name})`},b.name)),y&&e.baseline.variables.colors.map(b=>i.jsx("option",{value:`var(${b.name})`},b.name))]}),(g||f)&&i.jsx("button",{type:"button","aria-label":`Reset ${h.name}`,title:"Reset property",onClick:()=>u({kind:"reset",property:h.name}),className:"flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(na,{className:"h-2.5 w-2.5"})})]},h.name)})})]})}function gq({tabId:e,conversationId:t,stageSize:n,draftPick:s,openPin:o,markupTool:r,warningShown:a,onWarningShownChange:l,onDraftPickChange:d,onMoveSelection:c,onCancelDraft:u,onCloseOpenPin:h,onSendQueue:p,onStrokeStateChange:f}){const{t:g}=Q(),x=Wn(U=>U.annotateSendImmediately),v=Wn(U=>U.setSendImmediately),y=Wn(U=>U.addAnnotation),w=Wn(U=>U.updateAnnotation),b=Wn(U=>U.removeAnnotations),_=Wn(U=>U.annotationsFor(t)),j=m.useMemo(()=>o?_.find(U=>U.id===o.id)??null:null,[_,o]),N=m.useMemo(()=>nR(j?.comment??""),[j?.comment]),[C,S]=m.useState(""),[A,E]=m.useState([]),[I,D]=m.useState(!1),[T,z]=m.useState(!1),[$,R]=m.useState(null),[B,H]=m.useState({x:0,y:0}),[oe,te]=m.useState(!1),[O,V]=m.useState(null),[J,pe]=m.useState("move"),[fe,_e]=m.useState(null),Ee=m.useRef(null),me=m.useRef(null),W=m.useRef(null),G=m.useRef(null),de=m.useId(),X=o?`pin:${o.id}`:s?"draft":"none";m.useEffect(()=>{S(N.prose),E(j?j.images.slice(1):[]),D(!1),R(null),H({x:0,y:0}),l(!1),window.setTimeout(()=>W.current?.focus(),10)},[X]),m.useEffect(()=>{const U=sR(_.filter(ue=>ue.browserId===e));window.electronAPI.browser.previewDesignCss(e,"queue",U)},[_,e]);const ie=m.useMemo(()=>j?j.kind==="element"?j.elements:[]:s?.description.elements??[],[j,s]),Z=ie.length===1?ie[0]:null,le=m.useCallback(async()=>{if(!Z)return;if(I){D(!1);return}const U=await window.electronAPI.browser.readDesignCss(e,Z.uniqueId);if(!U){Be({type:"warning",title:g("Could not read CSS for this element")});return}R(iR(U,N.css)),D(!0)},[Z,I,e,N.css,g]);m.useEffect(()=>{if(!s?.region)return;const U=ue=>{if(!(Qr?ue.metaKey:ue.ctrlKey)||ue.altKey||ue.key.toLowerCase()!=="z")return;const De=document.activeElement===W.current&&C.length>0;if(fR({markCount:s.markup.length+s.redoMarkup.length,toolHeld:r!==null,noteOwnsUndo:De}))if(ue.preventDefault(),ue.stopPropagation(),ue.shiftKey){const Le=s.redoMarkup.at(-1);if(!Le)return;d({...s,markup:[...s.markup,Le],redoMarkup:s.redoMarkup.slice(0,-1)})}else{const Le=s.markup.at(-1);if(!Le)return;d({...s,markup:s.markup.slice(0,-1),redoMarkup:[...s.redoMarkup,Le]})}};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[s,r,C.length,d]),m.useEffect(()=>{if(!O||!s)return;const U={left:0,top:0,width:n.width,height:n.height},ue=(Le,tt)=>{const bt=Le.key===" "?"Space":Le.key==="Shift"||Le.key==="Alt"||Le.key==="Escape"?Le.key:null;bt&&(bt==="Space"&&Le.preventDefault(),V(Vt=>Vt?Jv(Vt,{type:"key",key:bt,down:tt},U):null))},je=Le=>ue(Le,!0),De=Le=>ue(Le,!1);return window.addEventListener("keydown",je,!0),window.addEventListener("keyup",De,!0),()=>{window.removeEventListener("keydown",je,!0),window.removeEventListener("keyup",De,!0)}},[O,s,n.width,n.height]);const be=m.useMemo(()=>$?Lk($):null,[$]),Fe=!!(be&&be.changes.size>0),Je=C.trim().length>0,We=j!==null,et=We?C.trim()!==N.prose.trim()||!!be?.isDirty:Je||Fe||(s?.markup.length??0)>0,qe=m.useMemo(()=>be?qv(C,be.changes):N.css.size>0?qv(C,N.css):C.trim(),[C,be,N.css]),Lt=We?!0:qe.length>0||s?.region!==null&&(s?.markup.length??0)>0,Bt=mR({sendImmediately:x,isOnStack:We}),Mt=Fe&&!Je?Yv[Bt].css:Yv[Bt].note,ne=m.useCallback(()=>{const U=ie;if(U.length===0)return;let ue=!1;U.forEach((je,De)=>{const Le=`ui-${Date.now()}-${De}`,tt=gf(je),bt=De===0&&s?.description.image?{data:s.description.image.data,mimeType:s.description.image.mimeType}:void 0;Vx({kind:"ui-element",id:Le,label:tt,path:je.path||je.tagName.toLowerCase(),text:(je.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Rk(je),imageId:`img-${Le}`},bt)&&(ue=!0)}),ue?(wo(),u()):Be({type:"warning",title:g("No Composer for this selection")})},[ie,s?.description.image,u,g]),se=m.useCallback(async()=>{if(!(oe||!Lt)){te(!0);try{if(We&&j){const tt=j.images.length>0?[j.images[0],...A]:[...A];w(t,j.id,qe,tt),window.electronAPI.browser.previewDesignCss(e,"draft",{}),h(),x&&p(new Set([j.id]));return}if(!s)return;const U=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ann-${Date.now()}`,ue=Wn.getState().pageKeyOf(e)??"http://localhost/",je=s.description.image,De=[];if(je){const tt=s.region&&s.markup.length>0?await uq({base64:je.data,markup:s.markup,cropWidth:s.region.width}):je.data;De.push({id:`img-${U}`,data:tt,mimeType:je.mimeType,name:je.name,width:je.width,height:je.height})}De.push(...A);let Le;if(s.region){const tt=s.description.regionAnchor??{tagName:"BODY",id:"",uniqueId:"region-root",className:"",innerText:"",path:"body",attributes:[],rect:{top:s.region.top,left:s.region.left,width:s.region.width,height:s.region.height},styles:{color:"",backgroundColor:"",fontSize:"",fontFamily:"",display:"block",position:"static"}};Le=y(t,{id:U,kind:"region",comment:qe,browserId:e,pageKey:ue,images:De,region:{rect:s.region,anchor:tt,markup:s.markup}})}else Le=y(t,{id:U,kind:"element",comment:qe,browserId:e,pageKey:ue,images:De,elements:s.description.elements});window.electronAPI.browser.previewDesignCss(e,"draft",{}),u(),x&&Le&&p(new Set([Le.id]))}finally{te(!1)}}},[oe,Lt,We,j,A,w,t,qe,e,h,x,p,s,y,u]),He=m.useCallback(()=>{if(et&&!a){l(!0);return}l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),We?h():u()},[et,a,l,e,We,h,u]),kt=U=>{for(const ue of U){if(!ue.type.startsWith("image/"))continue;const je=new FileReader;je.onload=()=>{const De=je.result,Le=De.slice(De.indexOf(",")+1);E(tt=>[...tt,{id:`att-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,data:Le,mimeType:ue.type,name:ue.name}])},je.readAsDataURL(ue)}},st=O?O.rect:s?.region??null,ke=Math.min(320,Math.max(240,n.width-16)),ut=I?360:148,ft=m.useMemo(()=>{if(o)return oR(o.badge,n,{width:ke,height:ut});if(st)return Xv({x:st.left,y:st.top,width:st.width,height:st.height},n,ke,ut);if(s&&s.elements.length>0){const U=s.elements.map(bt=>bt.rect.x),ue=s.elements.map(bt=>bt.rect.y),je=s.elements.map(bt=>bt.rect.x+bt.rect.width),De=s.elements.map(bt=>bt.rect.y+bt.rect.height),Le=Math.min(...U),tt=Math.min(...ue);return Xv({x:Le,y:tt,width:Math.max(...je)-Le,height:Math.max(...De)-tt},n,ke,ut)}return{x:16,y:16}},[o,st,s,n,ke,ut]),ze=T?Math.max(8,n.width-ke-8):Math.max(8,Math.min(ft.x+B.x,n.width-ke-8)),wt=T?8:Math.max(8,Math.min(ft.y+B.y,n.height-120));if(!s&&!o)return null;const Y=s?.description.frame?`data:${s.description.frame.mimeType};base64,${s.description.frame.data}`:null;return i.jsxs("div",{"data-enso-float":"",className:"absolute inset-0 z-30 select-none overflow-hidden",onMouseDown:U=>{U.target===U.currentTarget&&He()},children:[s&&st&&i.jsxs(i.Fragment,{children:[Y&&i.jsx("img",{src:Y,alt:"",draggable:!1,className:"pointer-events-none absolute inset-0 h-full w-full object-fill"}),i.jsx("div",{"aria-hidden":"true",className:"pointer-events-none absolute inset-0 bg-slate-950/35",style:{clipPath:`polygon(0% 0%, 0% 100%, ${st.left}px 100%, ${st.left}px ${st.top}px, ${st.left+st.width}px ${st.top}px, ${st.left+st.width}px ${st.top+st.height}px, ${st.left}px ${st.top+st.height}px, ${st.left}px 100%, 100% 100%, 100% 0%)`}}),i.jsxs("div",{role:"application","aria-label":"Selected screenshot region",style:{left:st.left,top:st.top,width:st.width,height:st.height,cursor:r!==null?"crosshair":hR(O?O.handle:J,O!==null)},onPointerMove:U=>{const ue=U.currentTarget.getBoundingClientRect(),je={x:U.clientX-ue.left,y:U.clientY-ue.top};if(r!==null){if(!fe||!Ee.current)return;const De={x:Math.max(0,Math.min(st.width,je.x)),y:Math.max(0,Math.min(st.height,je.y))};if(fe.kind==="pen")_e({kind:"pen",points:cR(fe.points,De)});else{const Le=U.shiftKey?uR({kind:fe.kind,from:Ee.current,to:De}):De;_e({kind:fe.kind,from:Ee.current,to:Le})}return}if(O){const De=U.currentTarget.parentElement?.getBoundingClientRect(),Le={x:U.clientX-(De?.left??0),y:U.clientY-(De?.top??0)};V(tt=>tt?Jv(tt,{type:"move",point:Le,altKey:U.altKey,shiftKey:U.shiftKey},{left:0,top:0,width:n.width,height:n.height}):null);return}pe(Zv(je,st))},onPointerDown:U=>{if(U.button!==0)return;U.preventDefault(),U.stopPropagation(),U.currentTarget.setPointerCapture(U.pointerId);const ue=U.currentTarget.getBoundingClientRect(),je={x:Math.max(0,Math.min(st.width,U.clientX-ue.left)),y:Math.max(0,Math.min(st.height,U.clientY-ue.top))};if(r!==null){Ee.current=je,f(!0),_e(r==="pen"?{kind:"pen",points:[je]}:{kind:r,from:je,to:je});return}const De=U.currentTarget.parentElement?.getBoundingClientRect(),Le={x:U.clientX-(De?.left??0),y:U.clientY-(De?.top??0)},tt=Zv(je,st);V(dR({handle:tt,point:Le,rect:st,modifiers:{altKey:U.altKey,shiftKey:U.shiftKey}}))},onPointerUp:async()=>{if(fe){const U=rR(s.markup,fe);_e(null),Ee.current=null,f(!1),U.length!==s.markup.length&&d({...s,markup:U,redoMarkup:[]});return}if(O){const U=aR({rect:O.rect,viewport:n}),ue=lR({markup:s.markup,from:s.region??U,to:U,markupScale:1});V(null);const je=await window.electronAPI.browser.describeSelection(e,{x:U.left,y:U.top,width:U.width,height:U.height});d({...s,region:U,markup:ue,description:je.image?je:s.description})}},className:"absolute box-border border-2 border-[#3a96dd] border-dashed shadow-lg",children:[i.jsxs("svg",{role:"img","aria-label":"Draw on screenshot region",width:st.width,height:st.height,className:"pointer-events-none block h-full w-full overflow-visible",children:[s.markup.map((U,ue)=>xf(U,"complete").map((je,De)=>i.jsx("path",{d:je.d,"data-design-markup-stroke":"",fill:je.paint==="fill"?Hr:"none",stroke:je.paint==="stroke"?Hr:"none",strokeWidth:je.paint==="stroke"?vf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`${ue}-${De}`))),fe&&xf(fe,"active").map((U,ue)=>i.jsx("path",{d:U.d,"data-design-markup-stroke":"active",fill:U.paint==="fill"?Hr:"none",stroke:U.paint==="stroke"?Hr:"none",strokeWidth:U.paint==="stroke"?vf:void 0,strokeLinecap:"round",strokeLinejoin:"round"},`active-${ue}`))]}),r===null&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -top-1.5 -right-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -bottom-1.5 -left-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"}),i.jsx("span",{className:"pointer-events-none absolute -right-1.5 -bottom-1.5 h-2.5 w-2.5 rounded-xs border border-[#3a96dd] bg-white shadow-2xs"})]})]})]}),i.jsxs("div",{style:{left:ze,top:wt,width:ke},onMouseDown:U=>U.stopPropagation(),className:"glass-browser-design-input absolute z-40 flex flex-col overflow-hidden rounded-2xl border border-border/80 bg-popover/95 text-popover-foreground shadow-[0_14px_38px_-8px_rgba(0,0,0,0.32),0_4px_14px_-2px_rgba(0,0,0,0.16)] backdrop-blur-xl transition-shadow duration-150 focus-within:border-[#3a96dd]/55 focus-within:ring-2 focus-within:ring-[#3a96dd]/15 dark:border-white/12",children:[i.jsxs("div",{onPointerDown:U=>{U.button!==0||T||U.target instanceof Element&&U.target.closest("button, input")||(U.preventDefault(),U.currentTarget.setPointerCapture(U.pointerId),me.current={pointerId:U.pointerId,startX:U.clientX,startY:U.clientY,nudgeX:B.x,nudgeY:B.y})},onPointerMove:U=>{const ue=me.current;!ue||ue.pointerId!==U.pointerId||H({x:ue.nudgeX+(U.clientX-ue.startX),y:ue.nudgeY+(U.clientY-ue.startY)})},onPointerUp:()=>{me.current=null},className:q("flex items-center justify-between gap-2 px-3 pt-2.5 pb-1",!T&&"cursor-grab active:cursor-grabbing"),children:[i.jsx("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-1.5",children:st||j?.kind==="region"?i.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-md border border-[#3a96dd]/25 bg-[#3a96dd]/12 px-2 py-0.5 text-[11px] font-medium text-[#3a96dd]",children:[s?.description.image&&i.jsx("img",{src:`data:${s.description.image.mimeType};base64,${s.description.image.data}`,alt:"",className:"h-4 w-5 rounded-[3px] object-cover ring-1 ring-black/10 dark:ring-white/15"}),i.jsxs("span",{children:["Region"," ",Math.round(st?.width??(j?.kind==="region"?j.region.rect.width:0))," ","×"," ",Math.round(st?.height??(j?.kind==="region"?j.region.rect.height:0))]})]}):ie.map((U,ue)=>{const je=Wh[(U.hueIndex??ue)%Wh.length]??Wh[0],De=Uh[(U.hueIndex??ue)%Uh.length]??Uh[0];return i.jsxs("span",{style:{backgroundColor:je.bg,borderColor:De.stroke,color:je.border},title:`${pR(U)} — ${U.path}`,className:"inline-flex max-w-48 items-center gap-1.5 truncate rounded-md border px-2 py-0.5 font-mono text-[11px] font-medium shadow-2xs",children:[i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full",style:{backgroundColor:je.border}}),i.jsx("span",{className:"truncate",children:gf(U)})]},U.uniqueId||`${U.tagName}-${ue}`)})}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 rounded-lg bg-muted/50 p-0.5",children:[!We&&!st&&ie.length===1&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>c("parent"),title:"Select parent element (Shift+Enter or \\)","aria-label":"Select parent element",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(KV,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>c("previous"),title:"Select previous sibling (Shift+Tab)","aria-label":"Select previous sibling",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(ad,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",onClick:()=>c("next"),title:"Select next sibling (Tab)","aria-label":"Select next sibling",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(Ok,{className:"h-3 w-3"})})]}),ie.length>0&&i.jsx("button",{type:"button",onClick:ne,title:`Add element to chat (${Qr?"⌘L":"Ctrl+L"})`,"aria-label":"Add element to chat",className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-background/80 hover:text-foreground",children:i.jsx(Ro,{className:"h-3 w-3"})}),Z&&i.jsx("button",{type:"button",onClick:()=>{le()},"aria-label":"Edit CSS properties","aria-pressed":I,title:"Edit CSS properties",className:q("flex h-5 w-5 items-center justify-center rounded-md transition-colors",I||Fe?"bg-[#3a96dd]/15 text-[#3a96dd]":"text-muted-foreground hover:bg-background/80 hover:text-foreground"),children:i.jsx(n6,{className:"h-3 w-3"})}),We&&j&&i.jsx("button",{type:"button","aria-label":"Delete annotation",title:"Delete annotation",onClick:()=>{b(t,[j.id]),h()},className:"flex h-5 w-5 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/15 hover:text-destructive",children:i.jsx(Gs,{className:"h-3 w-3"})})]})]}),A.length>0&&i.jsx("div",{className:"flex flex-wrap gap-1.5 px-3 pt-1.5",children:A.map(U=>i.jsxs("div",{className:"group relative h-11 w-15 overflow-hidden rounded-lg border border-border/70 shadow-2xs",children:[i.jsx("img",{src:`data:${U.mimeType};base64,${U.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":"Remove attached image",onClick:()=>E(ue=>ue.filter(je=>je.id!==U.id)),className:"absolute top-0.5 right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-black/70 text-white opacity-0 transition-opacity group-hover:opacity-100",children:i.jsx(an,{className:"h-2.5 w-2.5"})})]},U.id))}),i.jsxs("div",{className:"px-3 py-1.5",children:[i.jsx("textarea",{ref:W,rows:2,value:C,onChange:U=>{S(U.target.value),a&&l(!1);const ue=U.currentTarget;ue.style.height="auto",ue.style.height=`${Math.min(144,Math.max(44,ue.scrollHeight))}px`},onPaste:U=>{const ue=Array.from(U.clipboardData.files);ue.length>0&&(U.preventDefault(),kt(ue))},onKeyDown:U=>{if(U.nativeEvent.isComposing)return;const ue=Qr?U.metaKey:U.ctrlKey;if(ue&&U.key.toLowerCase()==="l"){U.preventDefault(),U.stopPropagation(),ne();return}if(U.key==="Enter"&&!U.shiftKey){if(Lt||ue){U.preventDefault(),U.stopPropagation(),se();return}if(!We&&!st&&ie.length>0){U.preventDefault(),U.stopPropagation(),c("child");return}}if(!Lt&&!We&&!st&&ie.length>0){if(U.key==="Enter"&&U.shiftKey||U.key==="\\"){U.preventDefault(),U.stopPropagation(),c("parent");return}if(U.key==="Tab"){U.preventDefault(),U.stopPropagation(),c(U.shiftKey?"previous":"next");return}}We&&j&&!Je&&!Fe&&(U.key==="Backspace"||U.key==="Delete")&&!U.altKey&&!U.ctrlKey&&!U.metaKey&&!U.repeat&&(U.preventDefault(),U.stopPropagation(),b(t,[j.id]),h())},placeholder:Fe?"Add a note (optional)…":"Describe the change…",className:"min-h-[44px] w-full resize-none bg-transparent text-[13px] leading-5 outline-none placeholder:text-muted-foreground/60"}),Fe&&!I&&be&&i.jsx("section",{"aria-label":"CSS edits",className:"mt-1.5 flex flex-wrap gap-1 text-[10px] text-[#3a96dd]",children:[...be.changes].map(([U,ue])=>i.jsxs("span",{className:"inline-flex items-center gap-1 rounded-md border border-[#3a96dd]/20 bg-[#3a96dd]/10 px-1.5 py-0.5 font-mono",children:[i.jsxs("span",{className:"font-medium",children:[U,":"]}),ue.to===null?i.jsx("span",{children:"removed"}):i.jsxs(i.Fragment,{children:[i.jsx("del",{className:"opacity-65",children:ue.from}),i.jsx("span",{className:"opacity-60",children:"→"}),i.jsx("ins",{className:"font-semibold no-underline",children:ue.to})]})]},U))})]}),I&&$&&Z&&i.jsx(mq,{stage:$,pinned:T,onTogglePinned:()=>z(U=>!U),onClose:()=>D(!1),onStageChange:(U,ue)=>{R(U),window.electronAPI.browser.previewDesignCss(e,"draft",{[Z.uniqueId]:ue})}}),a&&i.jsxs("div",{"data-design-input-notice":"",className:"flex items-center justify-between gap-2 border-t bg-amber-500/10 px-2.5 py-1.5 text-[11px]",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("span",{className:"font-semibold text-amber-600 dark:text-amber-400",children:"Discard comment?"})," ",i.jsx("span",{className:"text-muted-foreground",children:"This comment isn't saved yet."})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[i.jsx("button",{type:"button",onClick:()=>l(!1),className:"rounded border bg-background px-2 py-0.5 text-[10px] font-medium hover:bg-muted",children:"Keep Editing"}),i.jsx("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.browser.previewDesignCss(e,"draft",{}),We?h():u()},className:"rounded bg-destructive px-2 py-0.5 text-[10px] font-medium text-white hover:opacity-90",children:"Discard"})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-2 border-t border-border/50 bg-muted/20 px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2.5",children:[i.jsx("input",{ref:G,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:U=>{kt(Array.from(U.target.files??[])),U.target.value=""}}),i.jsx("button",{type:"button",onClick:()=>G.current?.click(),"aria-label":"Attach image to annotation",title:"Attach image",className:"flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(ph,{className:"h-3.5 w-3.5"})}),i.jsxs("label",{htmlFor:de,className:"group flex cursor-pointer items-center gap-1.5 text-[11px] text-muted-foreground transition-colors hover:text-foreground",children:[i.jsx("input",{id:de,type:"checkbox",checked:!x,onChange:U=>v(!U.target.checked),className:"sr-only"}),i.jsx("span",{"aria-hidden":"true",className:q("relative inline-flex h-3.5 w-6 shrink-0 items-center rounded-full transition-colors duration-150",x?"bg-muted-foreground/30":"bg-[#3a96dd]"),children:i.jsx("span",{className:q("inline-block h-2.5 w-2.5 rounded-full bg-white shadow-2xs transition-transform duration-150",x?"translate-x-0.5":"translate-x-3")})}),i.jsx("span",{children:"Batch edits"})]})]}),i.jsxs("button",{type:"button",disabled:oe||!Lt,"aria-label":Mt,title:`${Mt} (Enter)`,onClick:()=>{se()},className:"flex h-7 items-center gap-1.5 rounded-lg bg-[#3a96dd] px-3 text-[11px] font-medium text-white shadow-xs transition-all hover:bg-[#3286c9] active:scale-[0.98] disabled:bg-muted disabled:text-muted-foreground disabled:opacity-50",children:[Bt==="add-to-stack"?i.jsx(ds,{className:"h-3 w-3"}):Bt==="save-note"?i.jsx(Un,{className:"h-3 w-3"}):i.jsx(wd,{className:"h-3 w-3"}),i.jsx("span",{children:Mt})]})]})]})]})}function xq({tabId:e,conversationId:t,url:n,designMode:s,onDesignModeState:o}){const{t:r}=Q(),[a,l]=m.useState(!1),[d,c]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),[g,x]=m.useState(!1),[v,y]=m.useState(!1),[w,b]=m.useState(!1),_=Wn(z=>z.annotationsFor(t,e)),j=Wn(z=>z.annotationsFor(t)),N=m.useRef(n);m.useEffect(()=>{n&&Wn.getState().setBrowserUrl(e,n),N.current!==n&&(N.current=n,c(null),h(null),y(!1),l(!1),x(!1))},[e,n]);const C=m.useCallback(async z=>{z?Wn.getState().markEntered():(c(null),h(null),f(null),y(!1),l(!1));const $=await window.electronAPI.browser.setDesignMode(e,z);o($)},[e,o]);m.useEffect(()=>{if(!s||!n)return;const z=Mk(n),$=_.filter(R=>R.pageKey===z).map(YM);window.electronAPI.browser.setAnnotationPins(e,z,$)},[s,n,_,e]);const S=m.useCallback(z=>{if(f(z),z!==null&&d&&d.region===null&&d.elements.length>0){const $=d.elements.map(J=>J.rect.x),R=d.elements.map(J=>J.rect.y),B=d.elements.map(J=>J.rect.x+J.rect.width),H=d.elements.map(J=>J.rect.y+J.rect.height),oe=Math.max(0,Math.min(...$)-12),te=Math.max(0,Math.min(...R)-12),O=Math.max(24,Math.max(...B)-oe+12),V=Math.max(24,Math.max(...H)-te+12);c({...d,region:{left:oe,top:te,width:O,height:V}})}},[d]);m.useEffect(()=>window.electronAPI.browser.onDesignMode(z=>{if(z.tabId===e){if(z.type==="cancelled"){c(null),h(null),f(null),l(!1);return}if(z.type==="drawing"){l(z.drawing);return}if(z.type==="pins"){Wn.getState().setPinnedIds(e,z.ids);return}if(z.type==="pin-click"){c(null),y(!1),z.pin&&h({id:z.id,badge:z.pin});return}if(z.type==="select"){if(l(!1),h(null),y(!1),z.addToChat&&z.description.elements.length>0){z.description.elements.forEach(($,R)=>{const B=`ui-${Date.now()}-${R}`,H=gf($),oe=R===0&&z.description.image?{data:z.description.image.data,mimeType:z.description.image.mimeType}:void 0;Vx({kind:"ui-element",id:B,label:H,path:$.path||$.tagName.toLowerCase(),text:($.innerText||"").replace(/\s+/g," ").trim().slice(0,200)||Rk($),imageId:`img-${B}`},oe)}),wo(),window.electronAPI.browser.clearSelection(e);return}c({elements:z.elements,region:z.region?{left:z.region.x,top:z.region.y,width:z.region.width,height:z.region.height}:null,viewportWidth:z.viewportWidth,description:z.description,markup:[],redoMarkup:[]})}}}),[e]);const A=m.useCallback(()=>{c(null),f(null),y(!1),window.electronAPI.browser.clearSelection(e)},[e]),E=m.useCallback(()=>{h(null),y(!1),window.electronAPI.browser.openAnnotationPin(e,null,!1)},[e]),I=m.useCallback(async z=>{const $=await window.electronAPI.browser.moveSelection(e,z);$.elements.length!==0&&c(R=>R?{...R,elements:$.elements,description:$.description}:null)},[e]),D=m.useCallback(async z=>{if(z.browserId!==e){Be({type:"info",title:r("Turn on design mode in this note's browser tab to open it")});return}s||await C(!0);const $=await window.electronAPI.browser.openAnnotationPin(e,z.id,!0);$&&(c(null),h({id:z.id,badge:$}))},[e,s,C,r]),T=m.useCallback(z=>{const $=Wn.getState(),R=$.annotationsFor(t),B=z?R.filter(O=>z.has(O.id)):[...R];if(B.length===0)return;const H=XM(B,O=>O.pageKey),oe=H.ordered.map(O=>O.id);if($.removeAnnotations(t,oe),!h7({text:H.text,images:H.images,mentions:[]})){$.restoreAnnotations(t,H.ordered),Be({type:"warning",title:r("Note not sent"),description:r("The note stays in the queue.")});return}$.annotationsFor(t).length===0&&s&&C(!1)},[t,s,C,r]);return m.useEffect(()=>{const z=$=>{if((Qr?$.metaKey:$.ctrlKey)&&$.shiftKey&&!$.altKey&&$.key.toLowerCase()==="d"){$.preventDefault(),$.stopPropagation(),C(!s);return}if(!s||$.key!=="Escape")return;const B=$.target instanceof Element?$.target:null,H=B?.closest('[role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"], [aria-expanded="true"], [data-design-owns-escape]')!==null&&B?.closest("[data-design-owns-escape]")!==null,oe=B?.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')!==null;if(w){$.preventDefault(),$.stopPropagation(),b(!1);return}switch(bR({queueOwnsEscape:w,targetOwnsEscape:H,targetIsInput:oe,markupStrokeActive:g,markupToolHeld:p!==null,warningShown:v,draftOpen:d!==null,editorOpen:u!==null})){case"pass-through":return;case"cancel-stroke":$.preventDefault(),$.stopPropagation(),x(!1);return;case"put-down-tool":$.preventDefault(),$.stopPropagation(),f(null);return;case"dismiss-warning":$.preventDefault(),$.stopPropagation(),y(!1);return;case"cancel-draft":$.preventDefault(),$.stopPropagation(),A();return;case"close-editor":$.preventDefault(),$.stopPropagation(),E();return;case"exit":$.preventDefault(),$.stopPropagation(),C(!1);return}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[s,w,g,p,v,d,u,C,A,E]),{drawing:a,draftPick:d,openPin:u,markupTool:p,warningShown:v,queueOpen:w,allConversationAnnotations:j,setQueueOpen:b,setWarningShown:y,setDraftPick:c,setDesignMode:C,handleMarkupToolChange:S,moveSelection:I,cancelDraft:A,closeOpenPin:E,openPinFromQueue:D,sendQueue:T,setMarkupStrokeActive:x}}const vq=(e,t)=>e.width>0&&e.height>0&&t.width>0&&t.height>0&&e.x<t.x+t.width&&t.x<e.x+e.width&&e.y<t.y+t.height&&t.y<e.y+e.height,My=(e,t)=>t.some(n=>vq(e,n)),bq=new Set(["dialog-popup","dialog-viewport","dialog-backdrop","alert-dialog-popup","alert-dialog-viewport","alert-dialog-backdrop"]);function wq(e){if(e.getAttribute("data-enso-float")!==null)return!0;const t=e.getAttribute("data-slot");return t?bq.has(t)||t.endsWith("-popup")||t.endsWith("-positioner"):!1}function Ry(e,t){const n=[];for(const s of Array.from(e.querySelectorAll("*"))){if(!wq(s))continue;const o=s.getBoundingClientRect();o.width>0&&o.height>0&&n.push({x:o.left,y:o.top,width:o.width,height:o.height})}return n}const yq={tabId:null,url:"",title:"",favicon:null,loading:!1,canGoBack:!1,canGoForward:!1,locked:!1,devtoolsOpen:!1,designMode:!1,holder:null},Rp=(e,t)=>e===t||e!==null&&t!==null&&e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height&&e.radius===t.radius,Ly=80,Sq=.42;function Oy(e){if(!e?.isConnected)return null;const t=e.getBoundingClientRect();if(t.width<1||t.height<1)return null;const n={x:Math.round(t.left),y:Math.round(t.top),width:Math.round(t.width),height:Math.round(t.height)},s=Cq(e,t.bottom);return s>0?{...n,radius:s}:n}function Cq(e,t){const n=e.closest('[data-slot="side-panel"]');if(!n||Math.abs(n.getBoundingClientRect().bottom-t)>1)return 0;const s=getComputedStyle(n);return Number.parseFloat(s.borderBottomLeftRadius)||Number.parseFloat(s.borderBottomRightRadius)||0}function kq(){const{t:e}=Q();return i.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-6 text-center text-muted-foreground text-sm",children:[i.jsx(fo,{className:"h-6 w-6"}),i.jsx("p",{children:e("The built-in browser is not available in full view. Check it on the computer.")})]})}function ZT(e){return window.electronAPI.remote?i.jsx(kq,{}):i.jsx(jq,{...e})}function jq({conversationId:e,panelApi:t,active:n}){const{t:s}=Q(),o=re(O=>yR(O.conversations,e)),r=gn(O=>O.uiByConversation[o]?.open??!1),a=re(O=>O.activeId===o),l=n??(r&&a),[d,c]=m.useState(yq),[u,h]=m.useState(""),[p,f]=m.useState(!1),[g,x]=m.useState(null),[v,y]=m.useState(Sq),[w,b]=m.useState({width:800,height:600}),_=m.useRef(null),j=m.useRef(null),N=m.useRef(null),C=m.useRef(void 0),S=m.useRef(!1),A=m.useRef(void 0),E=m.useRef(!1),I=m.useRef(!1);I.current=d.locked;const D=m.useRef(!1);D.current=d.devtoolsOpen;const T=(d.url.startsWith("http")||d.url.startsWith("file:"))&&!d.loading,z=m.useRef(!1);z.current=T;const $=m.useRef(null),R=t.id,B=xq({tabId:R,conversationId:e,url:d.url,designMode:d.designMode,onDesignModeState:c});m.useEffect(()=>{const O=_.current;if(!O)return;const V=()=>{const pe=O.getBoundingClientRect();pe.width>0&&pe.height>0&&b({width:Math.round(pe.width),height:Math.round(pe.height)})};V();const J=new ResizeObserver(V);return J.observe(O),()=>J.disconnect()},[]),m.useEffect(()=>window.electronAPI.browser.onState(O=>{O.tabId===R&&c(O.state)}),[R]),m.useEffect(()=>window.electronAPI.browser.onDesignMode(O=>{if(O.tabId!==R||O.type==="cancelled"||O.type==="select"||O.type==="drawing"||O.type==="pin-click"||O.type==="pins")return;let V=!1;if(O.type==="annotated")V=O.image?m7(O.image):!1;else{const J=typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`ui-${Date.now()}`;V=Vx({kind:"ui-element",id:J,label:O.payload.label||O.payload.tag||"element",path:O.payload.path||O.payload.tag||"element",text:O.payload.text||O.payload.label||O.payload.tag||"element",imageId:`img-${J}`},O.image)}V?wo():Be({type:"warning",title:s("No Composer for this selection")})}),[R,s]),m.useEffect(()=>{p||h(d.url)},[d.url,p]),m.useEffect(()=>{const O=d.title.trim()||s("Browser");t.setTitle(O),t.updateParameters({...t.getParameters(),favicon:d.favicon})},[t,d.title,d.favicon,s]),m.useEffect(()=>{let O=0,V=!1;document.getElementById("root"),zk();const J=()=>{if(V)return;const pe=l&&t.isActive&&t.isVisible&&document.visibilityState==="visible",fe=pe?Oy(_.current):null,_e=fe!==null&&(I.current||My(fe,Ry(document)));(C.current===void 0||!Rp(C.current,fe)||_e!==S.current)&&(C.current=fe,S.current=_e,window.electronAPI.browser.setViewport(R,e,fe,_e).then(c));const Ee=z.current?fe:null;Rp($.current,Ee)||($.current=Ee,gn.getState().setBrowserHole(`${R}:guest`,Ee));const me=pe&&D.current?Oy(j.current):null,W=me!==null&&My(me,Ry(document));(A.current===void 0||!Rp(A.current,me)||W!==E.current)&&(gn.getState().setBrowserHole(`${R}:devtools`,me),A.current=me,E.current=W,window.electronAPI.browser.setDevToolsViewport(R,e,me,W).then(c)),O=requestAnimationFrame(J)};return O=requestAnimationFrame(J),()=>{V=!0,cancelAnimationFrame(O);const{setBrowserHole:pe}=gn.getState();pe(`${R}:guest`,null),pe(`${R}:devtools`,null),$.current=null,C.current!==null&&(C.current=null,window.electronAPI.browser.setViewport(R,e,null)),A.current!==null&&(A.current=null,window.electronAPI.browser.setDevToolsViewport(R,e,null))}},[e,R,t,l]);const H=async()=>{f(!1);const O=u.trim();if(!O)return;const V=await window.electronAPI.browser.navigate(R,e,O);x(V.ok?null:V.error??s("Navigation failed"))},oe=O=>{const V=_.current,J=j.current;if(!V||!J)return;O.currentTarget.setPointerCapture(O.pointerId);const pe=O.clientY,fe=V.getBoundingClientRect().height,_e=J.getBoundingClientRect().height,Ee=fe+_e,me=G=>{const de=Math.min(Ee-Ly,Math.max(Ly,_e-(G.clientY-pe)));y(de/Ee)},W=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",W)};window.addEventListener("pointermove",me),window.addEventListener("pointerup",W)},te="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40 disabled:hover:bg-transparent";return i.jsxs("div",{className:"flex h-full flex-col",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b bg-background px-2",children:[i.jsx("button",{type:"button",className:te,disabled:d.locked||!d.canGoBack,onClick:()=>{window.electronAPI.browser.goBack(R)},"aria-label":s("Back"),children:i.jsx(ad,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:te,disabled:d.locked||!d.canGoForward,onClick:()=>{window.electronAPI.browser.goForward(R)},"aria-label":s("Forward"),children:i.jsx(Ok,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",className:te,disabled:d.locked||!d.tabId,onClick:()=>{window.electronAPI.browser.reload(R)},"aria-label":s("Reload"),children:i.jsx(ak,{className:q("h-3.5 w-3.5",d.loading&&"animate-spin")})}),i.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1.5 rounded-md border bg-background px-2 py-0.5 text-xs focus-within:border-ring",onSubmit:O=>{O.preventDefault(),H()},children:[i.jsx(fo,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("input",{value:u,onChange:O=>h(O.target.value),onFocus:O=>{f(!0),O.target.select()},onBlur:()=>f(!1),placeholder:s("Enter a URL"),spellCheck:!1,disabled:d.locked,className:"min-w-0 flex-1 bg-transparent outline-none placeholder:text-muted-foreground disabled:opacity-60"})]}),i.jsx(fq,{tabId:R,conversationId:e,active:d.designMode,disabled:!d.tabId||d.locked||d.devtoolsOpen,queueOpen:B.queueOpen,onQueueOpenChange:B.setQueueOpen,onToggleDesignMode:O=>{B.setDesignMode(O)},onOpenPinFromQueue:O=>{B.openPinFromQueue(O)},onSendQueue:B.sendQueue}),i.jsx("button",{type:"button",className:q(te,d.devtoolsOpen&&"bg-muted text-foreground"),disabled:!d.tabId,onClick:()=>{window.electronAPI.browser.setDevTools(R,!d.devtoolsOpen).then(c)},"aria-label":s("Toggle Developer Tools"),"aria-pressed":d.devtoolsOpen,children:i.jsx(X1,{className:"h-3.5 w-3.5"})}),d.locked&&i.jsxs("span",{className:"flex shrink-0 items-center gap-1 rounded bg-amber-500/15 px-1.5 py-0.5 text-[10px] text-amber-600 dark:text-amber-400",children:[i.jsx(Yb,{className:"h-3 w-3"}),s("Enso is in control")]})]}),d.designMode&&i.jsx(pq,{drawing:B.drawing,pick:B.draftPick,markupTool:B.markupTool,editorOpen:B.openPin!==null,onMarkupToolChange:B.handleMarkupToolChange,onExit:()=>{B.setDesignMode(!1)}}),g&&i.jsx("div",{className:"border-b bg-destructive/10 px-3 py-1 text-xs text-destructive",children:g}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col","data-slot":"browser-native-stack",children:[i.jsxs("div",{ref:_,className:q("relative min-h-0",d.devtoolsOpen?"shrink-0":"flex-1",T?"bg-transparent":"bg-background"),style:d.devtoolsOpen?{flex:`${1-v} 1 0`}:void 0,children:[i.jsx(hq,{active:d.designMode}),d.designMode&&i.jsx(gq,{tabId:R,conversationId:e,stageSize:w,draftPick:B.draftPick,openPin:B.openPin,markupTool:B.markupTool,warningShown:B.warningShown,onWarningShownChange:B.setWarningShown,onDraftPickChange:B.setDraftPick,onMoveSelection:O=>{B.moveSelection(O)},onCancelDraft:B.cancelDraft,onCloseOpenPin:B.closeOpenPin,onSendQueue:B.sendQueue,onStrokeStateChange:B.setMarkupStrokeActive}),!d.url.startsWith("http")&&!d.url.startsWith("file:")&&i.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-center text-sm text-muted-foreground",children:[i.jsx(fo,{className:"h-6 w-6 opacity-40"}),i.jsx("p",{children:s("Enter a URL above, or let the agent open a page with browser_navigate.")})]}),d.locked&&i.jsxs("div",{className:"group absolute inset-0 z-10 flex cursor-default items-center justify-center",children:[i.jsx("div",{className:"absolute inset-0 bg-black/0 transition-colors group-hover:bg-black/40"}),i.jsxs("button",{type:"button",className:"relative flex items-center gap-1.5 rounded-full border bg-background px-4 py-2 text-sm shadow-lg opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted",onClick:()=>{window.electronAPI.browser.setLocked(e,!1)},children:[i.jsx(Yb,{className:"h-3.5 w-3.5"}),s("Take control")]})]})]}),d.devtoolsOpen&&i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:N,className:"h-1.5 shrink-0 cursor-row-resize bg-border hover:bg-ring",onPointerDown:oe}),i.jsx("div",{ref:j,className:"min-h-0 bg-transparent",style:{flex:`${v} 1 0`}})]})]})]})}function _q({chatId:e,visible:t}){const{t:n}=Q(),s=ce(p=>p.browserTabs[e]),o=ce(p=>p.browserTitles),r=ce(p=>p.browserHolders),{openBrowserTab:a,selectBrowserTab:l,closeBrowserTab:d,setBrowserTitle:c}=ce.getState(),u=s?.active;m.useEffect(()=>{u||a(e)},[u,e,a]);const h=m.useMemo(()=>u?{id:u,isActive:!0,isVisible:!0,setTitle:p=>c(u,p),getParameters:()=>{},updateParameters:()=>{}}:null,[u,c]);return i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex h-8 shrink-0 items-center gap-0.5 overflow-x-auto border-b px-1.5",children:[s?.tabs.map(p=>{const f=r[p],g=o[p]||n("Browser");return i.jsxs("div",{className:q("flex h-6 min-w-0 max-w-44 shrink items-center rounded-md text-xs",p===u?"bg-brand/10 text-foreground dark:bg-brand/15":"text-muted-foreground hover:bg-muted/60 hover:text-foreground"),children:[i.jsxs("button",{type:"button",title:f?`${g}
|
|
74
|
-
${n("{{name}} is using this tab",{name:f.name})}`:g,onClick:()=>l(e,p),className:"flex h-full min-w-0 items-center gap-1.5 pl-2",children:[i.jsx(fo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:g}),f&&i.jsxs("span",{className:"max-w-16 shrink-0 truncate text-muted-foreground",children:["· ",f.name]})]}),i.jsx("button",{type:"button","aria-label":n("Close"),title:n("Close"),onClick:()=>{d(e,p)},className:"mx-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded opacity-60 hover:bg-foreground/10 hover:opacity-100",children:i.jsx(an,{className:"h-3 w-3"})})]},p)}),i.jsx("button",{type:"button","aria-label":n("New tab"),title:n("New tab"),onClick:()=>a(e),className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground",children:i.jsx(ds,{className:"h-3.5 w-3.5"})})]}),h&&i.jsx(ZT,{conversationId:SR(e),panelApi:h,active:t},h.id)]})}const Nq=[[0,59],[0,23],[1,31],[1,12],[0,7]],nr=6e4,Tq=60*nr,Dq=5e4;function Lp(e,t,n){if(!/^\d+$/u.test(e))return;const s=Number(e);return s>=t&&s<=n?s:void 0}function Iq(e,t,n){const s=new Set;for(const o of e.split(",")){const[r,a,l]=o.split("/");if(l!==void 0)return;const d=a===void 0?1:Lp(a,1,n);if(d===void 0)return;let c,u;if(r==="*")c=t,u=n;else{const[h,p,f]=r.split("-");if(f!==void 0)return;c=Lp(h,t,n),u=p===void 0?a===void 0?c:n:Lp(p,t,n)}if(c===void 0||u===void 0||c>u)return;for(let h=c;h<=u;h+=d)s.add(h)}return[...s].sort((o,r)=>o-r)}function kh(e){const t=e.trim().split(/\s+/u);if(t.length!==5)return;const n=t.map((d,c)=>Iq(d,...Nq[c]));if(n.some(d=>d===void 0))return;const[s,o,r,a,l]=n;return{source:t.join(" "),minute:s,hour:o,dayOfMonth:r,month:a,dayOfWeek:[...new Set(l.map(d=>d%7))].sort((d,c)=>d-c),domStar:t[2].startsWith("*"),dowStar:t[4].startsWith("*")}}function Eq(e,t){const n=e.dayOfMonth.includes(t.getDate()),s=e.dayOfWeek.includes(t.getDay());return e.domStar||e.dowStar?n&&s:n||s}function Pq(e,t){let n=Math.floor(t/nr)*nr+nr;for(let s=0;s<Dq;s+=1){const o=new Date(n);let r;if(!e.month.includes(o.getMonth()+1))r=new Date(o.getFullYear(),o.getMonth()+1,1).getTime();else if(!Eq(e,o))r=new Date(o.getFullYear(),o.getMonth(),o.getDate()+1).getTime();else if(!e.hour.includes(o.getHours()))r=n-o.getMinutes()*nr+Tq;else if(!e.minute.includes(o.getMinutes()))r=n+nr;else return n;n=Math.max(r,n+nr)}}const Op=e=>String(e).padStart(2,"0"),Aq=["日","一","二","三","四","五","六"],Mq=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Ux(e,t){const n=typeof e=="string"?kh(e):e;if(!n)return String(e);const[s,o,r,a,l]=n.source.split(" "),d=t==="zh";if(a!=="*")return n.source;const c=/^\*\/(\d+)$/u.exec(s);if(o==="*"&&r==="*"&&l==="*"){if(s==="*")return d?"每分钟":"Every minute";if(c)return d?`每 ${c[1]} 分钟`:`Every ${c[1]} minutes`;if(n.minute.length===1&&/^\d+$/u.test(s)){const h=Op(n.minute[0]);return d?`每小时 ${h} 分`:`Every hour at :${h}`}return n.source}if(!/^\d+$/u.test(s)||!/^\d+$/u.test(o))return n.source;const u=`${Op(n.hour[0])}:${Op(n.minute[0])}`;if(r==="*"&&l==="*")return d?`每天 ${u}`:`Every day at ${u}`;if(r==="*"&&l==="1-5")return d?`工作日 ${u}`:`Weekdays at ${u}`;if(r==="*"&&/^\d+(,\d+)*$/u.test(l)){const h=[...new Set(n.dayOfWeek.map(p=>p%7))].sort((p,f)=>p-f);return d?`每周${h.map(p=>Aq[p]).join("、")} ${u}`:`Every ${h.map(p=>Mq[p]).join(", ")} at ${u}`}if(l==="*"&&/^\d+$/u.test(r)){const h=n.dayOfMonth[0];return d?`每月 ${h} 日 ${u}`:`Monthly on day ${h} at ${u}`}return n.source}const Rq=/[A-Za-z0-9._%+-]/,zy=/[A-Za-z0-9_-]/,Lq=/```[\s\S]*?(?:```|$)|`[^`\n]*`/g;function JT(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&typeof t.id=="string"&&typeof t.name=="string"&&t.name.length>0):[]}function Oq(e,t){if(typeof e!="string")return{ids:[],all:!1};const n=e.normalize("NFC").replace(Lq,a=>" ".repeat(a.length)),s=[...t.map(a=>({key:Kc(a.name),id:a.id})),...Gk.map(a=>({key:Kc(a),id:null}))].sort((a,l)=>l.key.length-a.key.length),o=[];let r=!1;for(let a=n.indexOf("@");a!==-1;a=n.indexOf("@",a+1)){if(a>0&&Rq.test(n[a-1]))continue;const l=s.find(({key:d})=>{const c=a+1+d.length;if(n.slice(a+1,c).toLowerCase()!==d)return!1;const u=n[c];return!(u&&zy.test(d.at(-1)??"")&&zy.test(u))});l&&(l.id===null?r=!0:o.includes(l.id)||o.push(l.id))}return{ids:o,all:r}}function zq(e,t){const n=JT(t),{ids:s,all:o}=Oq(e,n);return o?{ids:[...new Set(n.map(r=>r.id))],all:o}:{ids:s,all:o}}function Gq(e,t){const n=Kc(typeof e=="string"?e.replace(/^@/,""):"");return JT(t).filter(s=>Kc(s.name).startsWith(n))}function Nm(e,t){return/(?:^|\s)\$([^\s$]*)$/.exec(e.slice(0,t))?.[1]??null}function QT(e){const t=new Set,n=[];for(const s of e){const o=s.name.trim().toLowerCase();!o||t.has(o)||(t.add(o),n.push(s))}return n}function Fq(e,t,n){const s=n??t;if(s===null)return[];const o=s.toLowerCase();return QT(e.filter(r=>n!==null?r.name.startsWith("/skill:")&&r.name.slice(7).toLowerCase().includes(o):r.name.toLowerCase().includes(o))).slice(0,10)}const Hq=500,Bq=72,Cl=28;function eD({phase:e,heldMs:t,cancelZone:n}){return e!=="recording"&&e!=="starting"?"none":n?"cancel":e==="starting"||t<Hq?"too-short":"finish"}function Gy(e,t){return e-t>=Bq}function jh(e,t){const n=[...e,t].slice(-Cl);return n.length<Cl?[...new Array(Cl-n.length).fill(0),...n]:n}const Vq=300,$q=12,Wq=-50,Uq=3;function tD(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s]*e[s];const n=Math.sqrt(t/Math.max(1,e.length));return n>0?Math.max(-100,20*Math.log10(n)):-100}function Kq(){let e=Number.POSITIVE_INFINITY;return t=>{const n=t.length/qc*1e3,s=tD(t);return e=Math.min(s,e+Uq*n/1e3),s>Math.max(e+$q,Wq)}}function qq(e){if(e===qc)return r=>r;const t=e/qc;let n=new Float32Array(0),s=0,o=0;return r=>{const a=new Float32Array(n.length+r.length);a.set(n),a.set(r,n.length);const l=s+a.length,d=[];for(;;){const u=Math.floor(o*t),h=Math.floor((o+1)*t);if(h>l)break;let p=0;for(let f=u;f<h;f++)p+=a[f-s];d.push(h>u?p/(h-u):a[u-s]??0),o++}const c=Math.floor(o*t);return n=a.slice(c-s),s=c,Float32Array.from(d)}}function Yq(e){return Math.min(1,Math.max(0,(tD(e)+55)/45))}const Xq=2e3;function Zq(e=Xq){const t=Kq();let n=0,s=0;return o=>{const r=o.length/qc*1e3;return t(o)?(n+=r,s=0):s+=r,n>=Vq&&s>=e}}class nD extends Error{}let li=null;function Tm(){return(!li||li.state==="closed")&&(li=new AudioContext),li.state!=="running"&&li.resume().catch(()=>{}),li}async function Jq(){try{if((await navigator.permissions?.query({name:"microphone"}))?.state==="granted")return}catch{}const e=await navigator.mediaDevices.getUserMedia({audio:!0});for(const t of e.getTracks())t.stop()}function Fy(){const e=li;li=null,e?.close().catch(()=>{})}const zp={channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0};async function Qq(e){const t=navigator.mediaDevices;if(!e||e===CR)return t.getUserMedia({audio:zp});try{return await t.getUserMedia({audio:{...zp,deviceId:{exact:e}}})}catch(n){const s=n instanceof Error?n.name:"";if(s==="NotAllowedError"||s==="SecurityError")throw n;return t.getUserMedia({audio:zp})}}const eY=5e3;async function tY(e,t={}){const n=!t.context,s=t.context??new AudioContext,o=t.context!=null&&t.context===li,r=s.resume(),a=()=>{!n&&!o||(li===s&&(li=null),s.close().catch(()=>{}))};let l;try{l=await Qq(t.deviceId),await Promise.race([r,new Promise((b,_)=>setTimeout(()=>_(new Error("audio context stayed suspended")),3e3))])}catch(b){for(const _ of l?.getTracks()??[])_.stop();throw a(),b}const d=l.getTracks();if(s.state==="closed"){for(const b of d)b.stop();throw new Error("audio context closed")}const c=s.createMediaStreamSource(l),u=s.createScriptProcessor(4096,1,1),h=qq(s.sampleRate);let p=0,f=()=>{};const g=new Promise(b=>{f=b}),x=setTimeout(f,eY),v=()=>{clearTimeout(x),f()};u.onaudioprocess=b=>{const _=b.inputBuffer.getChannelData(0);for(let N=0;N<_.length;N++)p=Math.max(p,Math.abs(_[N]));p>0&&v(),t.onLevel?.(Yq(_));const j=h(new Float32Array(_));j.length>0&&e(j)},c.connect(u),u.connect(s.destination);let y=!1;const w=()=>{if(!y){y=!0,v(),u.onaudioprocess=null,u.disconnect(),c.disconnect();for(const b of d)b.stop();a()}};return{live:g,cancel:w,stop:async()=>{if(w(),p===0)throw new nD("silent recording")}}}const sD="Microphone access denied. Allow it in system settings.",nY={disabled:"Voice input is turned off.","not-ready":"The speech model is not downloaded yet.","invalid-audio":"The recording was empty or too long.",failed:"Voice input failed."};function iD(e){const t=e?.name;return t==="NotFoundError"||t==="OverconstrainedError"?"No microphone found.":t==="NotAllowedError"||t==="SecurityError"?sD:"Voice input failed."}function oD({startSession:e,requestMicAccess:t,onText:n}){const{t:s}=Q(),[o,r]=m.useState("idle"),[a,l]=m.useState(0),[d,c]=m.useState(null),[u,h]=m.useState(""),[p,f]=m.useState(!1),g=m.useRef(null),x=m.useRef(null),v=m.useRef(async()=>{}),y=m.useRef(0);m.useEffect(()=>()=>{y.current++,g.current?.cancel(),x.current?.cancel()},[]),m.useEffect(()=>{if(!d)return;const j=setTimeout(()=>c(null),4e3);return()=>clearTimeout(j)},[d]);const w=m.useCallback(()=>{y.current++,g.current?.cancel(),x.current?.cancel(),g.current=null,x.current=null,h(""),f(!1),r("idle")},[]),b=m.useCallback(async()=>{const j=g.current,N=x.current;if(!(!j||!N)){g.current=null,r("transcribing");try{await j.stop();const C=await N.finish();C.ok?C.text?n(C.text):c(s("No speech detected.")):c(s(nY[C.error]))}catch(C){N.cancel(),c(s(C instanceof nD?sD:"Voice input failed."))}finally{x.current=null,h(""),f(!1),r("idle")}}},[n,s]);return v.current=b,m.useEffect(()=>{if(o!=="recording")return;const j=setInterval(()=>l(N=>N+1),1e3);return()=>clearInterval(j)},[o]),m.useEffect(()=>{o==="recording"&&a>=kR&&b()},[a,b,o]),{phase:o,elapsed:a,error:d,setError:c,partial:u,correcting:p,start:async({autoStop:j=!1,...N}={})=>{if(c(null),!navigator.mediaDevices?.getUserMedia){c(s("Voice input needs a secure (HTTPS) connection."));return}const C=++y.current;h(""),f(!1),l(0),r("starting");let S=null;try{if(t&&!await t())throw new DOMException("microphone denied","NotAllowedError");if(C!==y.current)return;const A=e((D,T)=>{x.current===A&&(h(D),f(T))});S=A,x.current=A;const E=j?Zq():null,I=await tY(D=>{A.push(D),E?.(D)&&x.current===A&&v.current()},N);if(C!==y.current){I.cancel();return}if(g.current=I,await I.live,C!==y.current)return;r("recording")}catch(A){if(C!==y.current)return;S?.cancel(),x.current=null,r("idle"),c(s(iD(A)))}},finish:b,cancel:w}}const sY=6,Hy=8,iY=448;function oY(e,t){const n=Math.min(iY,t.width*.8);return{left:Math.max(Hy,Math.min(e.left,t.width-Hy-n)),bottom:t.height-e.top+sY,maxWidth:n}}const By=120,rD=12,rY=Array.from({length:rD},(e,t)=>`bar-${t}`),Vy=jh([],0),aY=300;function $y(e){const t=e.getBoundingClientRect();return oY(t,{width:window.innerWidth,height:window.innerHeight})}function aD({anchor:e,status:t,children:n}){const[s,o]=m.useState(()=>$y(e));return m.useLayoutEffect(()=>{let r=0;const a=()=>{const l=$y(e);o(d=>d.left===l.left&&d.bottom===l.bottom&&d.maxWidth===l.maxWidth?d:l),r=requestAnimationFrame(a)};return a(),()=>cancelAnimationFrame(r)},[e]),Ws.createPortal(i.jsx("p",{role:t?"status":void 0,"aria-live":"polite","data-testid":t?void 0:"voice-partial",style:{position:"fixed",...s,zIndex:kn.TOOLTIP},className:"w-max rounded-md border bg-popover px-2 py-1 text-popover-foreground text-xs shadow-md",children:n}),document.body)}const Dm="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40";function lD({startSession:e,requestMicAccess:t,disabled:n,holdBinding:s,holdScope:o,onText:r}){const{t:a}=Q(),{phase:l,elapsed:d,error:c,setError:u,partial:h,correcting:p,start:f,finish:g,cancel:x}=oD({startSession:e,requestMicAccess:t,onText:r}),v=m.useRef(null),[y,w]=m.useState(Vy),b=Ce(S=>S.voiceInputDevice),_=(S=!1)=>(w(Vy),f({autoStop:S,deviceId:b,onLevel:A=>w(E=>jh(E,A))})),j=m.useRef({phase:l,start:_,finish:g,cancel:x});j.current={phase:l,start:_,finish:g,cancel:x},m.useEffect(()=>{if(!s||n)return;let S=null,A;const E=()=>{clearTimeout(A),A=void 0},I=()=>{A!==void 0&&(E(),s==="space"&&document.execCommand("insertText",!1," "))},D=()=>{if(E(),S===null)return;const $=j.current,R=eD({phase:$.phase,heldMs:performance.now()-S,cancelZone:!1});S=null,R==="finish"?$.finish():R!=="none"&&$.cancel(),R==="too-short"&&u(a("Speech was too short."))},T=$=>{if($.isComposing||$.keyCode===229)return;if(Il($,{allowBare:!0})!==s){I();return}const R=o.current;if(!R||!($.target instanceof Node)||!R.contains($.target))return;const B=S===null&&A===void 0;B&&($.repeat||j.current.phase!=="idle")||($.preventDefault(),S!==null&&$.stopPropagation(),B&&(A=setTimeout(()=>{A=void 0,S=performance.now(),j.current.start()},aY)))},z=$=>{S===null&&!A||!jR(s,$)||($.preventDefault(),I(),D())};return window.addEventListener("keydown",T,!0),window.addEventListener("keyup",z,!0),window.addEventListener("blur",D),()=>{window.removeEventListener("keydown",T,!0),window.removeEventListener("keyup",z,!0),window.removeEventListener("blur",D),E(),S!==null&&j.current.cancel()}},[n,s,o,u,a]),m.useEffect(()=>{if(l!=="recording")return;const S=A=>{A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),x())};return window.addEventListener("keydown",S,!0),()=>window.removeEventListener("keydown",S,!0)},[x,l]);const N=h.length>By?`…${h.slice(-By)}`:h,C=l==="transcribing"?a(p?"Correcting…":"Transcribing…"):null;return i.jsxs("div",{ref:v,className:"relative flex shrink-0 items-center",children:[l==="recording"?i.jsxs(i.Fragment,{children:[i.jsxs("button",{type:"button",onClick:()=>{g()},"aria-label":a("Stop recording"),title:a("Stop recording"),className:"flex h-7 shrink-0 items-center gap-1.5 rounded-md px-1.5 text-destructive transition-colors hover:bg-destructive/10",children:[i.jsx("span",{"aria-hidden":!0,className:"flex h-3.5 items-center gap-[2px]",children:rY.map((S,A)=>i.jsx("span",{className:"w-[2px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:3+y[Cl-rD+A]*11}},S))}),i.jsxs("span",{className:"text-xs tabular-nums",children:[Math.floor(d/60),":",String(d%60).padStart(2,"0")]}),i.jsx(ld,{className:"h-3 w-3 fill-current"})]}),i.jsx("button",{type:"button",onClick:x,"aria-label":a("Cancel recording"),title:`${a("Cancel recording")} (Esc)`,className:Dm,children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}):i.jsx("button",{type:"button",disabled:n||l!=="idle",onClick:()=>{_(!0)},"aria-label":C??a("Voice input"),title:C??(s?`${a("Voice input")} · ${a("Hold {{key}} to talk",{key:fi(s)})}`:a("Voice input")),className:Dm,children:l==="idle"?i.jsx(Fk,{className:"h-3.5 w-3.5"}):i.jsx(hr,{className:"h-3.5 w-3.5"})}),v.current&&(c||h)?i.jsx(aD,{anchor:v.current,status:!!c,children:c??(p?i.jsxs("span",{className:"flex items-start gap-1.5",children:[i.jsx(hr,{"aria-hidden":!0,className:"mt-0.5 size-3 shrink-0"}),i.jsxs("span",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[a("Correcting…")," "]}),N]})]}):N)}):null]})}const dD=["agents","members","chats"];function lY(e){return[...dD.flatMap(t=>e[t].map(n=>({candidate:n,group:t}))),...e.files.map(t=>({candidate:t,group:"files"}))]}function cD(e,t){const n=dD.filter(s=>e[s].length>0);return!t.trim()&&n.length>0?[...n.map(s=>({type:"folder",id:s})),...e.files.map(s=>({type:"item",candidate:s,group:"files"}))]:lY(e).map(s=>({type:"item",candidate:s.candidate,group:s.group}))}const dY=20;function cY(e,t,n){return e.filter(s=>s.id!==n&&!s.parentId&&!!s.sessionFile).sort((s,o)=>{const r=s.projectId===t?0:1,a=o.projectId===t?0:1;return r!==a?r-a:o.createdAt-s.createdAt}).slice(0,dY).map(s=>({kind:"chat",id:s.id,label:s.title.split(`
|
|
75
|
-
`)[0].trim()||"Untitled chat",sessionFile:s.sessionFile}))}function uY(e){return e.map(t=>({...t,kind:"agent-type",id:t.typeKey,label:t.displayName}))}function hY(e){const t=new Set,n=[];for(const s of e)!s.relativePath||t.has(s.relativePath)||(t.add(s.relativePath),n.push({kind:"file",id:s.relativePath,label:s.name||s.relativePath.split("/").at(-1)||s.relativePath,relativePath:s.relativePath}));return n}function pY(e,t,n,s=[]){const o=e.trim().toLocaleLowerCase(),r=o?t.filter(d=>`${d.label}
|
|
76
|
-
${d.description}
|
|
77
|
-
${d.source}
|
|
78
|
-
${d.typeKey}`.toLocaleLowerCase().includes(o)):[...t],a=o?n.filter(d=>`${d.label}
|
|
79
|
-
${d.relativePath}`.toLocaleLowerCase().includes(o)):[...n],l=o?s.filter(d=>d.label.toLocaleLowerCase().includes(o)):[...s];return{agents:r.filter(d=>d.source!=="bot"),members:r.filter(d=>d.source==="bot"),files:a,chats:l}}function uD(e,t,n=[],s={}){const[o,r]=m.useState([]),[a,l]=m.useState([]),d=t!==null,{searchFiles:c,agents:u=!0}=s;return m.useEffect(()=>{if(!d||!u)return;r([]);let h=!1;return window.electronAPI.agentRegistry.list().then(p=>{const f=Hk(p);h||r(f?uY(f.candidates):[])}).catch(()=>{h||r([])}),()=>{h=!0}},[d,u]),m.useEffect(()=>{if(t===null||!e&&!c){l([]);return}let h=!1;const p=window.setTimeout(()=>{(c?c(t):window.electronAPI.files.search(e,t)).then(f=>{h||l(hY(f))}).catch(()=>{h||l([])})},150);return()=>{h=!0,window.clearTimeout(p)}},[e,t,c]),m.useMemo(()=>t===null?{agents:[],members:[],files:[],chats:[]}:pY(t,o,a,n),[o,a,n,t])}const Wy={bot:"Mention a member",all:"Mention a member",chat:"Reference a chat",file:"Files",skill:"Skills"},fY=e=>{switch(e.kind){case"bot":return`bot:${e.bot.id}`;case"all":return"all";case"chat":return`chat:${e.chat.id}`;case"file":return`file:${e.path}`;case"skill":return`skill:${e.skill.id}`}};function mY({chatId:e,placeholder:t,members:n,chatOptions:s=[],skills:o=[],running:r,disabled:a=!1,toolbar:l,hint:d,voice:c,requestMicAccess:u,onSend:h,onStop:p}){const{t:f}=Q(),g=m.useRef(null),x=m.useRef(null),v=m.useRef(null),y=m.useRef(!1),[w,b]=m.useState(()=>Qv(localStorage,e)),[_,j]=m.useState([]),[N,C]=m.useState(null),[S,A]=m.useState(0),[E,I]=m.useState(!1),D=Ce(X=>X.keybindings),{"voice-hold":T,"send-message":z}=Ai(D),{text:$}=w,R=X=>b(ie=>({...ie,...X}));m.useEffect(()=>{x.current?.focus()},[]),m.useEffect(()=>{_R(localStorage,e,w)},[e,w]),m.useEffect(()=>NR(X=>{X===e&&b(Qv(localStorage,X))}),[e]),m.useLayoutEffect(()=>{const X=x.current;X&&(X.style.height="auto",X.style.height=`${Math.min(X.scrollHeight,220)}px`)},[$]);const B=m.useCallback(X=>window.electronAPI.bots.searchFiles({chatId:e,query:X}).then(ie=>ie.ok?ie.files:[]),[e]),H=uD(void 0,N?.kind==="at"?N.query:null,[],{searchFiles:B,agents:!1}).files,oe=(()=>{if(!N)return[];const X=N.query.toLowerCase();if(N.kind==="skill")return o.filter(Z=>Z.name.toLowerCase().includes(X)).slice(0,10).map(Z=>({kind:"skill",skill:Z}));const ie=n?Gq(N.query,n).map(Z=>({kind:"bot",bot:Z})):[];return n&&Gk.some(Z=>Z.startsWith(X))&&ie.push({kind:"all"}),w.chats.length<TR&&ie.push(...s.filter(Z=>!w.chats.includes(Z.id)&&Z.title.toLowerCase().includes(X)).slice(0,6).map(Z=>({kind:"chat",chat:Z}))),ie.push(...H.slice(0,8).map(Z=>({kind:"file",path:Z.relativePath,name:Z.label}))),ie})(),te=(X,ie)=>{const Z=o.length?Nm(X,ie):null;if(Z!==null){C({kind:"skill",start:ie-Z.length-1,query:Z}),A(0);return}const le=/(^|[^A-Za-z0-9._%+-])@([^\s@]*)$/u.exec(X.slice(0,ie));if(!le)return C(null);C({kind:"at",start:ie-le[2].length-1,query:le[2]}),A(0)},O=X=>{if(!N)return;const ie=x.current,Z=ie?.selectionStart??$.length,le=$.slice(0,N.start),be=$.slice(Z);let Fe="";const Je={};X.kind==="bot"||X.kind==="all"?Fe=`@${X.kind==="all"?f("everyone"):X.bot.name} `:X.kind==="file"?(Fe=`@${X.path} `,Je.files=[...new Set([...w.files,X.path])]):X.kind==="chat"?Je.chats=[...w.chats,X.chat.id]:Je.skill=X.skill.id,R({...Je,text:le+Fe+be}),C(null);const We=le.length+Fe.length;requestAnimationFrame(()=>{ie?.focus(),ie?.setSelectionRange(We,We)})},V=X=>{const ie=x.current,Z=ie?.selectionStart??$.length,le=ie?.selectionEnd??$.length;R({text:$.slice(0,Z)+X+$.slice(le)}),requestAnimationFrame(()=>{ie?.focus(),ie?.setSelectionRange(Z+X.length,Z+X.length)})},J=X=>{for(const ie of X){if(!ie.type.startsWith("image/"))continue;const Z=new FileReader;Z.onload=()=>{const le=Z.result;j(be=>[...be,{data:le.slice(le.indexOf(",")+1),mimeType:ie.type}])},Z.readAsDataURL(ie)}},pe=X=>{const ie=x.current,Z=ie?.selectionStart??$.length,le=ie?.selectionEnd??$.length;window.electronAPI.bots.savePastedText({chatId:e,text:X}).catch(()=>({ok:!1,error:"unavailable"})).then(be=>{const Fe=be.ok?`@${be.path} `:X;b(Je=>({...Je,text:Je.text.slice(0,Z)+Fe+Je.text.slice(le)})),requestAnimationFrame(()=>{ie?.focus(),ie?.setSelectionRange(Z+Fe.length,Z+Fe.length)})})},fe=new Map(s.map(X=>[X.id,X])),_e=w.skill?o.find(X=>X.id===w.skill||X.name===w.skill):void 0,Ee=_e&&n?n.filter(X=>zq($,n).ids.includes(X.id)&&!_e.owners.includes(X.id)):[],me=!a&&!E&&($.trim().length>0||_.length>0||w.chats.length>0||!!w.skill),W=async()=>{if(!me)return;const X=w,ie=_,Z=X.text.trim();b(DR),j([]),C(null),I(!0);try{await h({text:Z,images:ie,files:X.files.filter(be=>Z.includes(`@${be}`)),chats:X.chats,...X.skill?{skill:_e?.id??X.skill}:{}})||(b(be=>be.text||be.chats.length||be.skill?be:X),j(be=>be.length?be:ie))}finally{I(!1)}},G=X=>{const ie=X.nativeEvent.isComposing||y.current;if(N&&oe.length>0&&!ie){if(X.key==="ArrowDown"||X.key==="ArrowUp"){X.preventDefault();const Z=X.key==="ArrowDown"?1:-1;A(le=>(le+Z+oe.length)%oe.length);return}if(X.key==="Enter"||X.key==="Tab"){X.preventDefault(),O(oe[Math.min(S,oe.length-1)]);return}if(X.key==="Escape"){X.preventDefault(),C(null);return}}!ie&&Vk(X,z)&&(X.preventDefault(),W())},de=X=>(n??[]).filter(ie=>X.includes(ie.id)).map(ie=>ie.name).join(", ");return i.jsxs("div",{ref:g,"data-slot":"composer",className:"relative rounded-2xl border bg-background shadow-float",onDragOver:X=>X.preventDefault(),onDrop:X=>{X.preventDefault(),J([...X.dataTransfer.files])},children:[N&&oe.length>0&&i.jsx("div",{className:"absolute bottom-full left-3 z-10 mb-1.5 max-h-80 w-80 overflow-y-auto rounded-xl border bg-popover p-1 shadow-lg",children:oe.map((X,ie)=>{const Z=Wy[X.kind],le=ie===0||Wy[oe[ie-1].kind]!==Z;return i.jsxs("div",{children:[le&&i.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:f(Z)}),i.jsx("button",{type:"button",onMouseDown:be=>{be.preventDefault(),O(X)},onMouseEnter:()=>A(ie),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",ie===S&&"bg-muted"),children:i.jsx(gY,{item:X,ownerNames:de,grouped:!!n})})]},fY(X))})}),(w.chats.length>0||w.skill)&&i.jsxs("div",{className:"flex flex-wrap gap-1.5 px-3 pt-3",children:[w.skill&&i.jsx(Uy,{icon:i.jsx(zs,{className:"h-3 w-3"}),label:_e?.name??w.skill,tone:"skill",onRemove:()=>R({skill:void 0})}),w.chats.map(X=>i.jsx(Uy,{icon:i.jsx(ca,{className:"h-3 w-3"}),label:fe.get(X)?.title??f("Unavailable chat"),onRemove:()=>R({chats:w.chats.filter(ie=>ie!==X)})},X))]}),Ee.length>0&&i.jsx("div",{className:"px-4 pt-1.5 text-warning text-xs",children:f("{{names}} cannot use this skill; they will be told it is unavailable",{names:Ee.map(X=>X.name).join(", ")})}),_.length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:_.map((X,ie)=>i.jsxs("div",{className:"group relative h-14 w-14 overflow-hidden rounded-lg border",children:[i.jsx("img",{src:`data:${X.mimeType};base64,${X.data}`,alt:"",className:"h-full w-full object-cover"}),i.jsx("button",{type:"button","aria-label":f("Remove"),onClick:()=>j(Z=>Z.filter((le,be)=>be!==ie)),className:"absolute top-0.5 right-0.5 hidden rounded-full bg-background/90 p-0.5 group-hover:block",children:i.jsx(an,{className:"h-3 w-3"})})]},ie))}),i.jsx("textarea",{ref:x,value:$,rows:1,disabled:a,placeholder:t,onChange:X=>{R({text:X.target.value}),te(X.target.value,X.target.selectionStart)},onSelect:X=>te(X.currentTarget.value,X.currentTarget.selectionStart),onBlur:()=>C(null),onKeyDown:G,onCompositionStart:()=>{y.current=!0},onCompositionEnd:()=>{y.current=!1},onPaste:X=>{const ie=[...X.clipboardData.files].filter(Z=>Z.type.startsWith("image/"));if(ie.length===0){const Z=X.clipboardData.getData("text/plain");if(!Bk(Z))return;X.preventDefault(),pe(Z);return}X.preventDefault(),J(ie)},className:"block max-h-56 min-h-12 w-full resize-none bg-transparent px-4 pt-3 pb-1 text-sm outline-none placeholder:text-muted-foreground disabled:opacity-60"}),i.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 pb-2",children:[i.jsx("button",{type:"button",onClick:()=>v.current?.click(),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground",title:f("Attach image"),"aria-label":f("Attach image"),children:i.jsx(ph,{className:"h-4 w-4"})}),i.jsx("input",{ref:v,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:X=>{J([...X.target.files??[]]),X.target.value=""}}),c&&i.jsx(lD,{startSession:c,requestMicAccess:u,disabled:a,holdBinding:T||void 0,holdScope:g,onText:V}),l,i.jsx("div",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:d}),r&&p&&!me?i.jsx("button",{type:"button",onClick:p,className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground",title:f("Stop"),"aria-label":f("Stop"),children:i.jsx(ld,{className:"h-3 w-3 fill-current"})}):i.jsx("button",{type:"button",disabled:!me,onClick:()=>{W()},className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground disabled:opacity-40",title:f("Send"),"aria-label":f("Send"),children:i.jsx(wd,{className:"h-4 w-4"})})]})]})}function gY({item:e,ownerNames:t,grouped:n}){const{t:s}=Q();switch(e.kind){case"all":return i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"grid h-6 w-6 place-items-center rounded-full bg-muted text-[11px]",children:"@"}),i.jsx("span",{children:s("everyone")})]});case"bot":return i.jsxs(i.Fragment,{children:[i.jsx(tn,{bot:e.bot,size:"sm"}),i.jsx("span",{className:"min-w-0 truncate",children:e.bot.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.bot.title})]});case"chat":return i.jsxs(i.Fragment,{children:[i.jsx(ca,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 truncate",children:e.chat.title}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:e.chat.kind==="group"?s("Group chat"):s("Direct chat")})]});case"file":return i.jsxs(i.Fragment,{children:[i.jsx(bo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0",children:e.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:e.path})]});case"skill":return i.jsxs(i.Fragment,{children:[i.jsx(zs,{className:"h-4 w-4 shrink-0 text-info"}),i.jsx("span",{className:"shrink-0",children:e.skill.name}),i.jsx("span",{className:"min-w-0 truncate text-muted-foreground text-xs",children:n?t(e.skill.owners):e.skill.description})]})}}function Uy({icon:e,label:t,tone:n,onRemove:s}){const{t:o}=Q();return i.jsxs("span",{className:q("inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs",n==="skill"?"bg-info/15 text-info":"bg-muted text-foreground"),children:[e,i.jsx("span",{className:"min-w-0 truncate",children:t}),i.jsx("button",{type:"button","aria-label":o("Remove"),onClick:s,className:"rounded opacity-70 hover:opacity-100",children:i.jsx(an,{className:"h-3 w-3"})})]})}const xY={thinking:"Thinking",typing:"Writing reply",tool:"Calling tools",retrying:"Retrying"},Ky={turn:"Queued · waiting for the current turn to finish",capacity:"Queued · concurrency limit reached","member-check":"Queued · checking whether tasks can run in parallel","member-serial":"Queued · waiting for the member's current task to finish","member-fifo":"Queued · waiting for the member's earlier tasks","member-stopping":"Queued · waiting for the member to stop"},vY={running:"Running",done:"Done",error:"Error",denied:"Denied",timeout:"Timed out · denied"},bY={running:"text-primary",done:"text-success",error:"text-destructive",denied:"text-warning",timeout:"text-warning"},wY=e=>e<1e4?`${(Math.max(0,e)/1e3).toFixed(1)}s`:mo(e);function hD({conversationId:e,leading:t,trailing:n,className:s}){const{t:o}=Q(),r=ce(p=>e?p.sessions[e]:void 0),a=ce(p=>e?p.queue.find(f=>f.conversationId===e):void 0),l=m.useMemo(()=>IR(r,!!a),[r,a]),d=!!(l&&l.state!=="queued"),[c,u]=m.useState(()=>Date.now());m.useEffect(()=>{if(!d)return;u(Date.now());const p=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(p)},[d]);const h=l?l.state!=="queued"?o(xY[l.state]):o(a?.reason&&Object.hasOwn(Ky,a.reason)?Ky[a.reason]:"Queued"):null;return i.jsxs("div",{className:q("min-w-0 text-muted-foreground text-xs",s),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[t,h&&i.jsx("span",{className:"truncate",children:h}),d&&l?.startedAt!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:mo(c-l.startedAt)}),n]}),l&&l.steps.length>0&&i.jsxs("div",{className:"mt-1 flex flex-col gap-0.5",children:[l.more>0&&i.jsxs("span",{children:["+",l.more]}),l.steps.map(p=>{const f=p.durationMs??(p.startedAt!==void 0?c-p.startedAt:void 0);return i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-medium text-foreground",children:ha(p.name,o)}),p.detail&&i.jsx("span",{className:"truncate font-mono",children:p.detail}),i.jsx("span",{className:q("shrink-0",bY[p.status]),children:o(p.status==="timeout"&&p.name==="ask_user"?"Timed out · no answer":vY[p.status])}),f!==void 0&&i.jsx("span",{className:"shrink-0 tabular-nums",children:wY(f)})]},p.id)})]})]})}const yY=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),SY=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),CY=[],kY={auto:"Automatic",delegator:"By delegator",human:"Manual"};function _h({state:e,interrupted:t,autoRetry:n}){const{t:s}=Q();if(n&&e==="failed")return i.jsx("span",{className:"rounded bg-warning/25 px-1.5 text-[11px] text-warning-foreground dark:bg-warning/15 dark:text-warning",children:s("Will retry automatically")});const o=e==="running"||e==="queued"?"bg-info/15 text-info":e==="completed"?"bg-success/15 text-success":e==="failed"?"bg-destructive/15 text-destructive":e==="blocked"?"bg-warning/15 text-warning":"bg-muted text-muted-foreground",r={queued:s("Queued"),running:s("In progress"),completed:s("Completed"),failed:s(t?"Interrupted":"Failed"),canceled:s("Canceled"),blocked:s("Stuck run")};return i.jsx("span",{className:q("rounded px-1.5 text-[11px]",o),children:r[e]??e})}function pD({check:e,className:t}){const{t:n}=Q();return i.jsxs("div",{className:q("flex min-w-0 items-center gap-1.5 text-muted-foreground text-xs",t),children:[i.jsx("span",{className:"shrink-0",children:n("Acceptance check")}),i.jsx("code",{className:"min-w-0 truncate rounded bg-muted px-1",title:e.text,children:e.text}),e.passed!==void 0&&i.jsx("span",{className:q("shrink-0 rounded px-1.5 text-[11px]",e.passed?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:e.passed?n("Passed"):n("Not passed")})]})}function Td(e,t){switch(e.failure){case"interrupted":return t("The app restarted before this task finished. It was stopped and will not rerun.");case"timeout":return t("Timed out after {{n}} minutes.",{n:e.timeoutMinutes??240});case"denied":return t("Denied.");case"check":return t('Acceptance check failed: "{{text}}" not found in tool outputs.',{text:e.check?.text??""});default:return e.error==="budget-exceeded"?t("The member's daily budget is used up."):e.error==="turn-token-limit"?t("Stopped: the member's per-turn token limit was exceeded."):e.error}}function jY(e,t){window.electronAPI.bots.cancelDelegation(e).then(n=>{n.ok||Be({type:"error",title:t("Cancel failed"),description:n.error}),ce.getState().refreshDelegations()})}function kl(e,t,n){window.electronAPI.bots.retryDelegation(e,n).then(s=>{s.ok?s.warning&&Be({type:"warning",title:s.warning}):Be({type:"error",title:t("Retry failed"),description:s.error}),ce.getState().refreshDelegations()})}function Nh(e){const[t,n]=m.useState(()=>Date.now());return m.useEffect(()=>{if(!e)return;n(Date.now());const s=setInterval(()=>n(Date.now()),3e4);return()=>clearInterval(s)},[e]),t}function _Y({record:e,delegations:t}){const{t:n}=Q(),s=PR(e);if(!s)return null;const o=Uk(e,t);return i.jsx("span",{className:"rounded border px-1 py-px text-[10px]",title:e.retryNote?n("Delegator note: {{note}}",{note:e.retryNote}):void 0,children:AR(e)?n("Retrying automatically · attempt {{n}}",{n:o}):n("Retry #{{n}} · {{source}}",{n:o,source:n(kY[s])})})}function Th({record:e,entry:t,retried:n,append:s,taskSeq:o,fill:r,bots:a,onOpenConversation:l}){const{t:d}=Q(),c=ce(z=>z.delegations)??CY,u=e?.state??t?.state??"queued",h=Nh(!s&&El(u)),p=a.get(e?.parentBotId??t?.from??""),f=a.get(e?.targetBotId??t?.to??""),g=MR(s?"completed":u),x=ER(e),v=!s&&x&&El(u),y=!s&&u==="blocked"?e?.blocked:void 0,w=ce(z=>y&&e?.taskId?z.delegations.some($=>$.taskId===e.taskId&&$.createdAt>e.createdAt):!1),b=ce(z=>z.openTask),_=!!t?.taskId&&!s,[j,N]=m.useState(!_),C=e?$k(e,c):!1,S=!s&&e?.chatId&&e.resultSeq!==void 0?{chatId:e.chatId,seq:e.resultSeq}:void 0,A=s||S?void 0:e?u==="completed"?e.result:u==="blocked"?void 0:Td(e,d):t?.summary,E=d("{{from}} → {{to}} · Delegation",{from:p?.name??d("Deleted member"),to:f?.name??d("Deleted member")}),I=i.jsxs(i.Fragment,{children:[_&&i.jsx(bn,{"aria-hidden":!0,className:q("size-3.5 shrink-0 transition-transform",j&&"rotate-90")}),i.jsx(tn,{bot:p,size:"xs"}),i.jsx("span",{className:"min-w-0 truncate text-foreground",title:p?.name,children:p?.name??d("Deleted member")}),i.jsx("span",{children:"→"}),i.jsx(tn,{bot:f,size:"xs",presence:x?.state}),i.jsx("span",{className:"min-w-0 truncate text-foreground",title:f?.name,children:f?.name??d("Deleted member")}),i.jsxs("span",{children:["· ",d("Delegation")]}),s?i.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:o===void 0?d("Merged into the current run"):d("Merged into the current run of #{{n}}",{n:o})}):v?i.jsx(Wk,{info:x}):i.jsx(_h,{state:u,interrupted:e?.failure==="interrupted",autoRetry:C}),e&&!s&&i.jsx(_Y,{record:e,delegations:c}),e&&!s&&i.jsx("span",{children:mo((e.finishedAt??h)-e.createdAt)}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:yY(s?.at??t?.at??e?.createdAt??h)})]}),D="flex flex-wrap items-center gap-1.5 whitespace-nowrap text-muted-foreground text-xs",T=s?.text??e?.task;return i.jsxs("div",{"data-slot":"bot-card",className:q("rounded-xl border bg-card px-3 py-2.5",r?"w-full min-w-0":"max-w-lg"),children:[_?i.jsx("button",{type:"button","aria-expanded":j,"aria-label":d(j?"Collapse delegation result":"Expand delegation result"),className:q(D,"w-full rounded text-left hover:text-foreground"),onClick:()=>N(z=>!z),children:I}):i.jsx("div",{className:D,children:I}),!j&&T&&i.jsx("div",{className:"mt-1 truncate text-muted-foreground text-xs",children:T}),j&&T&&i.jsx("div",{className:"mt-1.5 line-clamp-3 text-sm [overflow-wrap:anywhere]",children:T}),j&&i.jsxs(i.Fragment,{children:[e?.check&&!s&&i.jsx(pD,{check:e.check,className:"mt-1.5"}),A&&i.jsx("div",{className:"mt-1.5 line-clamp-4 whitespace-pre-wrap text-muted-foreground text-xs [overflow-wrap:anywhere]",children:A}),y&&e&&i.jsxs("div",{className:"mt-1.5 rounded-md bg-warning/10 px-2 py-1 text-xs",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap",children:d("Blocked · needs: {{need}}",{need:y.need})}),i.jsx("div",{className:"text-muted-foreground",children:w?d("Answered; the work continues"):y.waitFor==="parent"?d("Waiting for {{name}} to reply",{name:p?.name??d("Deleted member")}):d("Waiting for your reply")})]}),C&&e?.autoRetryAt!==void 0&&i.jsx("div",{className:"mt-1 text-warning-foreground text-xs dark:text-warning",children:d("Retrying automatically at {{time}} (attempt {{n}})",{time:SY(e.autoRetryAt),n:Uk(e,c)+1})}),S&&i.jsx("button",{type:"button",onClick:()=>ce.getState().focusSeq(S.chatId,S.seq),className:"mt-1.5 text-muted-foreground text-xs underline-offset-2 hover:text-foreground hover:underline",children:d("Result posted to the group · View")}),e&&i.jsxs("div",{className:"mt-2 flex flex-wrap justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>l(e.childConversationId,E),children:d("View process")}),y&&!w&&e.chatId&&e.taskId&&i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>e.chatId&&e.taskId&&b(e.chatId,e.taskId),children:d("Reply")}),g.cancel&&i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>jY(e.id,d),children:d("Cancel")}),g.retry&&!n&&i.jsx(ge,{size:"xs",variant:"outline",title:C?d("Skip the wait and retry now. The scheduled automatic retry is canceled."):void 0,onClick:()=>kl(e.id,d),children:d(C?"Retry now":"Retry")}),g.resumeOrRestart&&!n&&i.jsxs(i.Fragment,{children:[i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>kl(e.id,d,"resume"),children:d("Continue")}),i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>kl(e.id,d,"restart"),children:d("Start over")})]})]})]})]})}function fD(e){const t=ce(c=>c.chats.find(u=>u.id===e)),n=ce(c=>c.sessions),s=ce(c=>c.queue),o=ce(c=>c.silences),r=ce(c=>c.delegations),a=ce(c=>c.browserHolders),l=ce(c=>c.browserTabs[t?.parentId??e]?.tabs),d=ce(c=>LR(c.timelines[e]?.entries??[]));return m.useMemo(()=>({chat:t??{id:e,sessions:{}},delegations:r,sessions:n,queue:s,silences:o,clearedAt:d,holders:a,tabIds:l??[]}),[t,e,r,n,s,o,d,a,l])}function NY(e,t){const n=fD(e);return m.useMemo(()=>RR(t,n),[t,n])}function TY(e,t){const n=e.wait;switch(n?.kind){case"approval":return t("Your approval: {{title}}",{title:n.title});case"ask":return t("Your answer: {{title}}",{title:n.title});case"file":return t("{{holder}} is editing {{file}}",{holder:n.holder,file:n.file});case"workspace":return t("{{holder}} is running a workspace-wide command",{holder:n.holder});case"capacity":return t("A free slot (concurrency limit, not a person)");case"turn":return t("Its previous turn to finish");case"member-check":return t("Queued · checking whether tasks can run in parallel");case"member-serial":return t("Queued · waiting for the member's current task to finish");case"member-fifo":return t("Queued · waiting for the member's earlier tasks");case"member-stopping":return t("Queued · waiting for the member to stop");default:return}}function mD(e){const t=document.querySelector(`[data-pending-conversation="${CSS.escape(e)}"]`);t?.scrollIntoView({block:"nearest"}),t?.animate([{backgroundColor:"var(--color-warning)"},{backgroundColor:"transparent"}],{duration:1200})}function Oa({label:e,children:t}){return i.jsxs("div",{className:"flex gap-2",children:[i.jsx("span",{className:"w-12 shrink-0 text-muted-foreground",children:e}),i.jsx("span",{className:"min-w-0 flex-1 break-words",children:t})]})}function gD({info:e,bot:t}){const{t:n}=Q(),s=ce(d=>e.delegation?d.bots.find(c=>c.id===e.delegation?.parentBotId):void 0),o=e.delegation,r=TY(e,n),a=ce(d=>e.browserTab?d.browserTitles[e.browserTab]||n("Browser"):void 0),l=e.wait&&"conversationId"in e.wait?e.wait.conversationId:void 0;return i.jsxs(kT,{align:"start",className:"w-72 flex-col gap-1.5 p-3 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"font-semibold text-sm",children:t?.name??n("Deleted member")}),i.jsx(Wk,{info:e})]}),e.state==="idle"?i.jsx("div",{className:"text-muted-foreground",children:n("Nothing in progress")}):i.jsxs(i.Fragment,{children:[o&&i.jsxs(i.Fragment,{children:[i.jsx(Oa,{label:n("Task"),children:i.jsx("span",{className:"line-clamp-2",children:o.task})}),i.jsx(Oa,{label:n("From"),children:s?.name??n("Deleted member")}),i.jsx(Oa,{label:n("Time"),children:mo((o.finishedAt??Date.now())-o.createdAt)})]}),r&&i.jsx(Oa,{label:n("Waiting on"),children:r}),a&&i.jsx(Oa,{label:n("Browser"),children:i.jsx("span",{className:"line-clamp-1",children:a})}),e.quietSince!==void 0&&i.jsx("div",{className:"text-muted-foreground",children:n("Still running, no output for {{time}}",{time:mo(Date.now()-e.quietSince)})}),o&&e.state==="stuck"&&o.state==="failed"&&i.jsx("div",{className:"text-muted-foreground",children:Td(o,n)}),o&&e.state==="done"&&o.result&&i.jsx("div",{className:"line-clamp-3 text-muted-foreground",children:o.result}),l&&i.jsx(ge,{size:"xs",className:"mt-1 self-start",onClick:()=>mD(l),children:n("Go handle it")})]})]})}function xD({chatId:e,botId:t,bot:n,size:s="sm"}){const{t:o}=Q(),r=NY(e,t);return i.jsxs(Hx,{children:[i.jsxs(Bx,{render:i.jsx("span",{className:"relative inline-flex shrink-0"}),children:[i.jsx(tn,{bot:n,size:s,presence:r.state}),i.jsx("span",{className:"sr-only",children:bf(r,o)})]}),i.jsx(gD,{info:r,bot:n})]})}function DY({chatId:e,memberIds:t,bots:n,onOpenLive:s}){const{t:o}=Q(),r=fD(e),a=m.useMemo(()=>OR(t,r),[t,r]);return a.length===0?null:i.jsx("div",{className:"mb-1.5 flex flex-wrap items-center gap-1",children:a.map(({botId:l,info:d})=>{const c=n.get(l),u=c?.name??o("Deleted member"),h=zR(d),p=GR(d);return i.jsxs(Hx,{children:[i.jsxs(Bx,{render:i.jsx("button",{type:"button",onClick:()=>p?.kind==="pending"?mD(p.conversationId):p&&s(p.conversationId,l),className:"flex h-7 min-w-0 items-center gap-1.5 rounded-full px-1 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground"}),children:[i.jsx(tn,{bot:c,size:"xs",presence:d.state}),h?i.jsx("span",{className:"max-w-56 truncate pr-1.5",children:[u,bf(d,o),h].join(" · ")}):i.jsx("span",{className:"sr-only",children:`${u} · ${bf(d,o)}`})]}),i.jsx(gD,{info:d,bot:c})]},l)})})}const vD=[137,80,78,71,13,10,26,10];function pa(e){let t="";for(let n=0;n<e.length;n+=8192)t+=String.fromCharCode(...e.subarray(n,n+8192));return t}let Xd=null;function IY(e){if(!Xd){Xd=new Uint32Array(256);for(let n=0;n<256;n+=1){let s=n;for(let o=0;o<8;o+=1)s=s&1?3988292384^s>>>1:s>>>1;Xd[n]=s>>>0}}let t=4294967295;for(const n of e)t=Xd[(t^n)&255]^t>>>8;return(t^4294967295)>>>0}function bD(e){return vD.every((t,n)=>e[n]===t)?"png":e[0]===255&&e[1]===216&&e[2]===255?"jpeg":pa(e.subarray(0,4))==="RIFF"&&pa(e.subarray(8,12))==="WEBP"?"webp":null}function wD(e){if(bD(e)!=="png")return null;const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=[];for(let s=8;s+12<=e.length;){const o=t.getUint32(s),r=s+12+o;if(r>e.length)return null;const a=pa(e.subarray(s+4,s+8));if(n.push({type:a,data:e.subarray(s+8,s+8+o),raw:e.subarray(s,r)}),s=r,a==="IEND")return n}return null}const yD=e=>{if(e.type!=="tEXt")return null;const t=e.data.indexOf(0);return t>0?pa(e.data.subarray(0,t)):null};function qy(e,t){const n=wD(e)?.find(s=>yD(s)===t);return n?pa(n.data.subarray(t.length+1)):null}function Yy(e,t){const n=new Uint8Array(12+t.length),s=new DataView(n.buffer);s.setUint32(0,t.length);for(let o=0;o<4;o+=1)n[4+o]=e.charCodeAt(o);return n.set(t,8),s.setUint32(8+t.length,IY(n.subarray(4,8+t.length))),n}function EY(e,t,n,s=[]){const o=wD(e);if(!o)return null;const r=new Set([t,...s]),a=o.filter(h=>{const p=yD(h);return h.type!=="IEND"&&!(p&&r.has(p))}),l=Uint8Array.from(`${t}\0${n}`,h=>h.charCodeAt(0)&255),d=[Uint8Array.from(vD),...a.map(h=>h.raw),Yy("tEXt",l),Yy("IEND",new Uint8Array)],c=new Uint8Array(d.reduce((h,p)=>h+p.length,0));let u=0;for(const h of d)c.set(h,u),u+=h.length;return c}function PY(e){return btoa(pa(new TextEncoder().encode(e)))}function AY(e){try{const t=Uint8Array.from(atob(e.trim()),n=>n.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{return null}}function MY(e){return{budgetCost:e?.dailyCostUsd!==void 0?String(e.dailyCostUsd):"",budgetTokens:e?.dailyTokens!==void 0?String(e.dailyTokens):""}}function SD(e){const t={},n=e.budgetCost.trim();if(n){const o=Number(n);if(!Number.isFinite(o)||o<=0)return{ok:!1};t.dailyCostUsd=o}const s=e.budgetTokens.trim();if(s){const o=Number(s);if(!Number.isSafeInteger(o)||o<=0)return{ok:!1};t.dailyTokens=o}return{ok:!0,budget:Object.keys(t).length>0?t:null}}function RY(e){return{delegationTimeout:e.delegationTimeoutMinutes!==void 0?String(e.delegationTimeoutMinutes):"",maxTurnTokens:e.maxTokensPerTurn!==void 0?String(e.maxTokensPerTurn):""}}function Kx(e){const t=e.delegationTimeout.trim()?Number(e.delegationTimeout):null,n=e.maxTurnTokens.trim()?Number(e.maxTurnTokens):null;return t!==null&&!FR(t)||n!==null&&!HR(n)?{ok:!1}:{ok:!0,delegationTimeoutMinutes:t,maxTokensPerTurn:n}}function Xy(e){return[...e.normalize("NFC").trim().replace(/\s+/gu,"_").replace(/[^\p{L}\p{N}_-]/gu,"").replace(/_+/gu,"_").replace(/^_+|_+$/gu,"")].slice(0,VR).join("")}const Do=e=>typeof e=="string"?e.trim():"",Gp=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function Zy(e){const t=e.split(`
|
|
80
|
-
`).find(s=>s.trim())??"",n=/^.*?[.!?。!?](?=\s|$)/u.exec(t.trim());return(n?n[0]:t.trim()).slice(0,80)}function LY(e,t){return{spec:"chara_card_v2",spec_version:"2.0",data:{name:e.name,description:t,personality:"",scenario:e.scope,first_mes:"",mes_example:"",creator_notes:e.title,system_prompt:"",post_history_instructions:"",alternate_greetings:[],tags:[],creator:"EnsoCode",character_version:"",extensions:{enso:{title:e.title,scope:e.scope,color:e.avatar.color,tools:e.tools,approvalMode:e.approvalMode,memory:e.memory.enabled}}}}}function OY(e){return{...typeof e.title=="string"?{title:e.title.trim()}:{},...Do(e.scope)?{scope:Do(e.scope)}:{},...typeof e.color=="string"&&/^#[0-9a-f]{6}$/iu.test(e.color)?{color:e.color}:{},...e.tools==="all"||e.tools==="readonly"?{tools:e.tools}:{},...BR.includes(e.approvalMode)?{approvalMode:e.approvalMode}:{},...typeof e.memory=="boolean"?{memoryEnabled:e.memory}:{}}}function zY(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:"invalid-json"}}if(!t||typeof t!="object"||Array.isArray(t))return{ok:!1,error:"not-a-card"};const n=t,s=Gp(n.data)?n.data:n,o=Do(s.name);if(!o)return{ok:!1,error:"not-a-card"};const r=Gp(s.extensions)?s.extensions.enso:void 0;if(Gp(r)){const c=typeof s.description=="string"?s.description:"";return{ok:!0,draft:{name:Xy(o),title:"",scope:Zy(c),persona:c,...OY(r)}}}const a=c=>c.replace(/\{\{char\}\}/giu,o).replace(/\{\{user\}\}/giu,"the user"),l=a(Do(s.description)),d=[l,Do(s.personality)&&`Personality: ${a(Do(s.personality))}`,Do(s.scenario)&&`Scenario: ${a(Do(s.scenario))}`].filter(Boolean);return{ok:!0,draft:{name:Xy(o),title:"",scope:Zy(l),persona:d.join(`
|
|
81
|
-
|
|
82
|
-
`)}}}const Dr=256,Jy=4;function CD({hasImage:e,nested:t=!1,disabled:n=!1,onPick:s,onRemove:o}){const{t:r}=Q(),a=m.useRef(null),[l,d]=m.useState(null);return i.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[i.jsxs(ge,{size:"xs",variant:"outline",disabled:n,onClick:()=>a.current?.click(),children:[i.jsx(ph,{}),r("Upload avatar")]}),e&&i.jsxs(ge,{size:"xs",variant:"ghost",disabled:n,onClick:o,children:[i.jsx(an,{}),r("Remove avatar")]}),i.jsx("input",{ref:a,type:"file",accept:"image/png,image/jpeg,image/webp",hidden:!0,onChange:c=>{const u=c.target.files?.[0];c.target.value="",u&&$R(u).then(d,()=>Be({type:"error",title:r("This image cannot be used as an avatar.")}))}}),i.jsx(GY,{source:l,nested:t,onCancel:()=>d(null),onDone:c=>{d(null),s(c)}})]})}function GY({source:e,nested:t=!1,onCancel:n,onDone:s}){const{t:o}=Q(),r=m.useRef(null),a=m.useRef(null),[l,d]=m.useState(null),[c,u]=m.useState({zoom:1,x:0,y:0});m.useEffect(()=>{d(null),u({zoom:1,x:0,y:0})},[e]);const h=v=>l?Dr/Math.min(l.w,l.h)*v:1,p=v=>{if(!l)return v;const y=h(v.zoom),w=(l.w*y-Dr)/2,b=(l.h*y-Dr)/2;return{zoom:v.zoom,x:Math.max(-w,Math.min(w,v.x)),y:Math.max(-b,Math.min(b,v.y))}},f=v=>u(y=>p({...y,zoom:Math.max(1,Math.min(Jy,v))})),g=()=>{const v=r.current;if(!v||!l)return;const y=h(c.zoom),w=Dr/y;s(UR(v,l.w/2-w/2-c.x/y,l.h/2-w/2-c.y/y,w))},x=h(c.zoom);return i.jsx(wn,{open:e!==null,onOpenChange:v=>!v&&n(),children:i.jsxs(yn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:o("Crop avatar")}),i.jsx(Bs,{children:o("Drag to move, scroll to zoom.")})]}),i.jsxs(On,{className:"flex flex-col items-center gap-4",children:[i.jsxs("div",{"data-avatar-crop":!0,className:"relative cursor-grab touch-none select-none overflow-hidden rounded-lg bg-muted active:cursor-grabbing",style:{width:Dr,height:Dr},onPointerDown:v=>{v.currentTarget.setPointerCapture(v.pointerId),a.current={id:v.pointerId,x:v.clientX,y:v.clientY}},onPointerMove:v=>{const y=a.current;!y||y.id!==v.pointerId||(a.current={...y,x:v.clientX,y:v.clientY},u(w=>p({...w,x:w.x+v.clientX-y.x,y:w.y+v.clientY-y.y})))},onPointerUp:()=>{a.current=null},onWheel:v=>f(c.zoom*(v.deltaY<0?1.1:1/1.1)),children:[e&&i.jsx("img",{ref:r,src:e,alt:"",draggable:!1,onLoad:v=>d({w:v.currentTarget.naturalWidth,h:v.currentTarget.naturalHeight}),onError:()=>{Be({type:"error",title:o("This image cannot be used as an avatar.")}),n()},className:"pointer-events-none absolute top-1/2 left-1/2 max-w-none",style:l?{width:l.w*x,height:l.h*x,transform:`translate(-50%, -50%) translate(${c.x}px, ${c.y}px)`}:{visibility:"hidden"}}),i.jsx("span",{className:"pointer-events-none absolute inset-0 rounded-full shadow-[0_0_0_9999px_rgb(0_0_0/0.55)] ring-2 ring-white/80"})]}),i.jsx(WR,{min:1,max:Jy,step:.01,value:c.zoom,"aria-label":o("Zoom"),onValueChange:v=>f(Array.isArray(v)?v[0]:v)})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(ge,{size:"sm",disabled:!l,onClick:g,children:o("Use this avatar")})]})]})})}const FY=["tools","approvalMode","skillIds","mcpServerIds","canDelegateTo","acceptFrom"],HY=(e,t)=>Array.isArray(e)&&Array.isArray(t)?e.length===t.length&&e.every(n=>t.includes(n)):e===t;function Qy(e,t){return FY.flatMap(n=>{const s=t[n];return!s||HY(e[n],s.value)?[]:[{field:n,from:e[n],to:s.value,reason:s.reason}]})}function BY(e,t,n){const s={...e};for(const o of t)n.includes(o.field)&&Object.assign(s,{[o.field]:o.to});return s}const kD={tools:"all",approvalMode:"auto-edits",skillIds:[],mcpServerIds:[],canDelegateTo:"any",acceptFrom:"any",memoryEnabled:!0,budgetCost:"",budgetTokens:"",delegationTimeout:"",maxTurnTokens:""};function jD({value:e,onChange:t,profile:n,botId:s,zIndex:o}){const{t:r}=Q(),l=ce(d=>d.bots).filter(d=>d.id!==s&&!d.archivedAt);return i.jsxs("div",{className:"space-y-4",children:[i.jsx(VY,{value:e,onApply:t,profile:n,botId:s}),i.jsxs("div",{children:[i.jsx(Kt,{children:r("Tools")}),i.jsx(hg,{value:e.tools,options:[{value:"all",label:r("All tools")},{value:"readonly",label:r("Read-only")}],onChange:d=>t({tools:d})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:r("Approval mode")}),i.jsx(Kk,{value:e.approvalMode,onChange:d=>t({approvalMode:d}),zIndex:o})]}),i.jsx(_D,{value:e,onChange:t}),i.jsx(eS,{label:r("Can delegate to"),value:e.canDelegateTo,bots:l,onChange:d=>t({canDelegateTo:d})}),i.jsx(eS,{label:r("Accepts delegation from"),value:e.acceptFrom,bots:l,onChange:d=>t({acceptFrom:d})}),i.jsxs("label",{className:"flex items-center justify-between gap-2 text-sm",children:[i.jsx("span",{children:r("Long-term memory")}),i.jsx(Di,{checked:e.memoryEnabled,onCheckedChange:d=>t({memoryEnabled:d})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:r("Daily budget")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsx(Xt,{type:"number",min:0,step:"0.01",inputMode:"decimal",value:e.budgetCost,placeholder:r("Cost (USD), empty = unlimited"),"aria-label":r("Daily cost limit (USD)"),onChange:d=>t({budgetCost:d.target.value})}),i.jsx(Xt,{type:"number",min:0,step:"1",inputMode:"numeric",value:e.budgetTokens,placeholder:r("Tokens, empty = unlimited"),"aria-label":r("Daily token limit"),onChange:d=>t({budgetTokens:d.target.value})})]}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("Resets at local midnight. Once reached, new messages to this member are refused and a running reply is stopped.")})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:r("Per-turn token limit")}),i.jsx(Xt,{type:"number",min:1,step:"1",inputMode:"numeric",value:e.maxTurnTokens,placeholder:r("Tokens, empty = unlimited"),"aria-label":r("Per-turn token limit"),onChange:d=>t({maxTurnTokens:d.target.value})}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("A single reply that uses more tokens than this (counted while streaming) is stopped.")})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:r("Delegation time limit (minutes)")}),i.jsx(Xt,{type:"number",min:1,max:1440,step:"1",inputMode:"numeric",value:e.delegationTimeout,placeholder:r("Empty = 240"),"aria-label":r("Delegation time limit (minutes)"),onChange:d=>t({delegationTimeout:d.target.value})}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:r("When other members delegate to this one, the task fails with a timeout after this long. A delegator can ask for less, not more.")})]})]})}function Dh(e,t){switch(e.error){case"no-model":return t("No model is available. Set a default model or a Bot assistant model first.");case"timeout":return t("The model did not answer in time. Try again.");case"invalid-reply":return t("The model reply could not be understood. Try again.");case"invalid":return t("Fill in a name, title or responsibilities first.");default:return t("Could not get suggestions")}}function VY({value:e,onApply:t,profile:n,botId:s}){const{t:o,locale:r}=Q(),[a,l]=m.useState(!1),[d,c]=m.useState(null),[u,h]=m.useState([]),p=d?Qy(e,d):[],f=async()=>{if(![n.name,n.title,n.scope,n.persona].some(x=>x.trim())){Be({type:"warning",title:o("Fill in a name, title or responsibilities first.")});return}l(!0);try{const x=await window.electronAPI.bots.suggestAbilities({name:n.name,title:n.title,scope:n.scope,persona:n.persona,language:r==="zh"?"zh":"en",...s?{botId:s}:{}});if(!x.ok){Be({type:"error",title:Dh(x,o),...x.detail?{description:x.detail}:{}});return}if(Qy(e,x.suggestion).length===0){Be({type:"info",title:o("Current abilities already match the suggestion.")});return}h([]),c(x.suggestion)}finally{l(!1)}},g=()=>{const x=p.map(y=>y.field).filter(y=>!u.includes(y)),v=BY(e,p,x);t(Object.fromEntries(x.map(y=>[y,v[y]]))),c(null)};return i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Let a model suggest abilities from the name, title, responsibilities and persona.")}),i.jsxs(ge,{size:"xs",variant:"outline",disabled:a,onClick:()=>{f()},children:[a?i.jsx(qt,{className:"animate-spin"}):i.jsx(zs,{}),o("Auto-configure abilities")]})]}),d&&p.length>0&&i.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/40 p-2.5",children:[i.jsx("p",{className:"font-medium text-xs",children:o("Suggested changes")}),p.map(x=>i.jsxs("label",{className:"flex items-start gap-2 text-xs",children:[i.jsx(dd,{className:"mt-0.5",checked:!u.includes(x.field),onCheckedChange:v=>h(y=>v?y.filter(w=>w!==x.field):[...y,x.field])}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5",children:[i.jsx("span",{className:"font-medium",children:$Y(x.field,o)}),i.jsx(WY,{change:x})]}),x.reason&&i.jsx("p",{className:"text-muted-foreground",children:x.reason})]})]},x.field)),i.jsxs("div",{className:"flex justify-end gap-2",children:[i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>c(null),children:o("Cancel")}),i.jsx(ge,{size:"xs",disabled:p.every(x=>u.includes(x.field)),onClick:g,children:o("Apply")})]})]})]})}function $Y(e,t){switch(e){case"tools":return t("Tools");case"approvalMode":return t("Approval mode");case"skillIds":return t("Skills");case"mcpServerIds":return t("MCP Servers");case"canDelegateTo":return t("Can delegate to");case"acceptFrom":return t("Accepts delegation from")}}function WY({change:e}){const{t}=Q(),n=Ce(p=>p.skills),s=Ce(p=>p.mcpServers),o=ce(p=>p.bots),r=(p,f)=>i.jsxs("span",{className:"text-muted-foreground",children:[p," → ",i.jsx("span",{className:"text-foreground",children:f})]});if(e.field==="tools"){const p=f=>t(f==="all"?"All tools":"Read-only");return r(p(e.from),p(e.to))}if(e.field==="approvalMode"){const p=f=>t(Pl[f].labelKey);return r(p(e.from),p(e.to))}const a=e.field==="skillIds"?n:e.field==="mcpServerIds"?s:o,l=p=>a.find(f=>f.id===p)?.name??p,d=e.from,c=e.to;if(d==="any"||c==="any"){const p=f=>f==="any"?t("All members"):f.length===0?t("None selected"):f.map(l).join(", ");return r(p(d),p(c))}const u=c.filter(p=>!d.includes(p)),h=d.filter(p=>!c.includes(p));return i.jsxs("span",{className:"space-x-1.5",children:[u.map(p=>i.jsxs("span",{className:"text-success",children:["+",l(p)]},`+${p}`)),h.map(p=>i.jsx("span",{className:"text-destructive line-through",children:l(p)},`-${p}`))]})}function _D({value:e,onChange:t}){const{t:n}=Q(),s=Ce(a=>a.skills),o=Ce(a=>a.mcpServers),r=(a,l)=>a.includes(l)?a.filter(d=>d!==l):[...a,l];return i.jsxs(i.Fragment,{children:[i.jsx(e0,{title:n("Skills"),emptyText:n("No skills yet"),items:s,getName:a=>a.name,getSource:a=>a.source,isChecked:a=>e.skillIds.includes(a.id),onToggle:a=>t({skillIds:r(e.skillIds,a.id)}),onSetFiltered:(a,l)=>t({skillIds:n0(e.skillIds,a,l)}),placeholder:n("Filter skills..."),renderDetail:a=>i.jsx(t0,{rows:[[n("Source"),a.source],[n("Path"),a.path],[n("Description"),a.description]]})}),i.jsx(e0,{title:n("MCP Servers"),emptyText:n("No MCP servers yet"),items:o,getName:a=>a.name,getSource:a=>a.source,isChecked:a=>e.mcpServerIds.includes(a.id),onToggle:a=>t({mcpServerIds:r(e.mcpServerIds,a.id)}),onSetFiltered:(a,l)=>t({mcpServerIds:n0(e.mcpServerIds,a,l)}),placeholder:n("Filter MCP servers..."),renderDetail:a=>i.jsx(t0,{rows:[[n("Source"),a.source],["Transport",a.transport],["URL",a.url]]})})]})}function eS({label:e,value:t,bots:n,onChange:s}){const{t:o}=Q();return i.jsxs("div",{children:[i.jsx(Kt,{children:e}),i.jsx(hg,{value:t==="any"?"any":"some",options:[{value:"any",label:o("All members")},{value:"some",label:o("Selected members")}],onChange:r=>s(r==="any"?"any":[])}),t!=="any"&&i.jsxs("div",{className:"mt-1.5 space-y-1",children:[n.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:o("No other members")}),n.map(r=>i.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[i.jsx(dd,{checked:t.includes(r.id),onCheckedChange:a=>s(a?[...t,r.id]:t.filter(l=>l!==r.id))}),i.jsx(tn,{bot:r,size:"xs"}),r.name]},r.id))]})]})}function UY({bot:e}){const{t}=Q(),n=ce(r=>r.usage?.bots[e.id]);if(m.useEffect(()=>{ce.getState().refreshUsage()},[]),!n)return null;const s=[[t("Today"),n.today],[t("Last 7 days"),n.week],[t("Last 30 days"),n.month]],o=e.budget;return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card p-3",children:[i.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.map(([r,a])=>i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"text-muted-foreground text-xs",children:r}),i.jsx("div",{className:"truncate font-medium text-sm tabular-nums",children:Kh(a.tokens)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs tabular-nums",children:qh(a.cost)})]},r))}),o&&i.jsxs("div",{className:n.exhausted?"mt-2 text-destructive text-xs":"mt-2 text-muted-foreground text-xs",children:[[o.dailyTokens!==void 0&&`${Kh(n.today.tokens)} / ${Kh(o.dailyTokens)} tokens`,o.dailyCostUsd!==void 0&&`${qh(n.today.cost??0)} / ${qh(o.dailyCostUsd)}`].filter(Boolean).join(" · "),n.exhausted&&` · ${t("Today's budget is used up")}`]})]})}function ND({spaceId:e,emptyText:t}){const[n,s]=m.useState(null),o=m.useCallback(async()=>{const r=await window.electronAPI.memory.list({spaceId:e,limit:100,offset:0});s(r.items)},[e]);return m.useEffect(()=>(s(null),o(),window.electronAPI.memory.onChanged(()=>{o()})),[o]),n===null?i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):n.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:t}):i.jsx("div",{className:"space-y-1.5",children:n.map(r=>i.jsx(KY,{item:r,onDeleted:()=>s(a=>a?.filter(l=>l.id!==r.id)??null)},r.id))})}function KY({item:e,onDeleted:t}){const{t:n}=Q(),[s,o]=m.useState(null),[r,a]=m.useState(!1),l=async()=>{a(!0);const c=await window.electronAPI.memory.detail(e.id);a(!1),c?o({title:c.title,content:c.content}):Be({type:"error",title:n("Memory not found")})},d=async()=>{if(!s)return;a(!0);const c=await window.electronAPI.memory.update(e.id,s);a(!1),c.ok?o(null):Be({type:"error",title:n("Save failed"),description:c.error})};return s?i.jsxs("div",{"data-slot":"bot-card",className:"space-y-1.5 rounded-lg border bg-card px-2.5 py-2",children:[i.jsx(Xt,{size:"sm",value:s.title,placeholder:n("Memory title"),onChange:c=>o({...s,title:c.target.value})}),i.jsx(ei,{rows:5,value:s.content,placeholder:n("Memory content"),onChange:c=>o({...s,content:c.target.value})}),i.jsxs("div",{className:"flex justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",disabled:r,onClick:()=>o(null),children:n("Cancel")}),i.jsxs(ge,{size:"xs",disabled:r||!s.content.trim(),onClick:()=>{d()},children:[r&&i.jsx(qt,{className:"animate-spin"}),n("Save")]})]})]}):i.jsxs("div",{"data-slot":"bot-card",className:"group flex items-start gap-2 rounded-lg border bg-card px-2.5 py-2",children:[i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("div",{className:"truncate font-medium text-xs",children:e.title}),i.jsx("div",{className:"line-clamp-3 text-muted-foreground text-xs",children:e.contentSummary})]}),i.jsxs("div",{className:"flex shrink-0 opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100",children:[i.jsx("button",{type:"button",title:n("Edit"),"aria-label":n("Edit"),disabled:r,onClick:()=>{l()},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:r?i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin"}):i.jsx(Fs,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",title:n("Delete"),"aria-label":n("Delete"),onClick:()=>{window.electronAPI.memory.delete(e.id).then(c=>{c.ok?t():Be({type:"error",title:c.error??n("Delete failed")})})},className:"rounded p-1 text-muted-foreground hover:bg-muted hover:text-destructive",children:i.jsx(Gs,{className:"h-3.5 w-3.5"})})]})]})}function TD({target:e,emptyText:t}){const{t:n}=Q(),s="botId"in e?e.botId:void 0,o="chatId"in e?e.chatId:void 0,[r,a]=m.useState(null),[l,d]=m.useState(null),[c,u]=m.useState(!1),h=m.useRef(!1);h.current=l!==null;const p=m.useCallback(async()=>{const g=await window.electronAPI.bots.notes.get(s?{botId:s}:{chatId:o??""});g.ok&&a(g.notes)},[s,o]);m.useEffect(()=>(a(null),d(null),p(),window.electronAPI.bots.onEvent(g=>{g.kind!=="notes"||h.current||(s?!g.chatId:g.chatId===o)&&p()})),[p,s,o]);const f=async()=>{if(!r||l===null)return;u(!0);const g=await window.electronAPI.bots.notes.save({...s?{botId:s}:{chatId:o??""},content:l,version:r.version});if(u(!1),g.ok){a(g.notes),d(null);return}Be({type:"error",title:g.error==="conflict"?n("Notes were updated elsewhere; reloaded the latest version"):n("Save failed")}),g.error==="conflict"&&(d(null),p())};return r?l!==null?i.jsxs("div",{className:"space-y-1.5",children:[i.jsx(ei,{rows:8,value:l,maxLength:r.maxChars,onChange:g=>d(g.target.value)}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsxs("span",{className:"mr-auto text-muted-foreground text-xs",children:[l.length," / ",r.maxChars]}),i.jsx(ge,{size:"xs",variant:"ghost",disabled:c,onClick:()=>d(null),children:n("Cancel")}),i.jsx(ge,{size:"xs",disabled:c,onClick:()=>{f()},children:n("Save")})]})]}):i.jsxs("div",{className:"group space-y-1.5",children:[r.content?i.jsx("div",{"data-slot":"bot-card",className:"max-h-64 overflow-y-auto whitespace-pre-wrap rounded-lg border bg-card px-2.5 py-2 text-xs",children:r.content}):i.jsx("p",{className:"text-muted-foreground text-xs",children:t}),i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>d(r.content),children:n("Edit notes")})]}):i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}function DD({value:e,onApply:t}){const{t:n,locale:s}=Q(),[o,r]=m.useState(!1),a=async()=>{if(!e.name.trim()||!e.title.trim()){Be({type:"warning",title:n("Fill in a name and title first.")});return}r(!0);try{const l=await window.electronAPI.bots.suggestPersona({name:e.name,title:e.title,scope:e.scope,persona:e.persona,language:s==="zh"?"zh":"en"});if(!l.ok){Be({type:"error",title:Dh(l,n),...l.detail?{description:l.detail}:{}});return}const{persona:d,scope:c}=l.suggestion,u={persona:e.persona,scope:e.scope};t({persona:d,...c?{scope:c}:{}}),Be({type:"success",title:n(c?"Persona and responsibilities generated":"Persona generated"),timeout:1e4,actions:[{label:n("Undo"),onClick:()=>t(u)}]})}finally{r(!1)}};return i.jsxs(ge,{size:"xs",variant:"ghost",className:"-my-1 h-6 text-muted-foreground",disabled:o,onClick:()=>{a()},children:[o?i.jsx(qt,{className:"animate-spin"}):i.jsx(zs,{}),n("Generate with AI")]})}function tS(e){const t=kh(e);if(!t)return;const[n,s,o,r,a]=t.source.split(" ");if(!/^\d+$/u.test(n)||!/^\d+$/u.test(s)||o!=="*"||r!=="*")return;const l={hour:t.hour[0],minute:t.minute[0]};return a==="*"?{kind:"daily",days:[],...l}:a==="1-5"?{kind:"weekdays",days:[],...l}:/^\d+(,\d+)*$/u.test(a)?{kind:"weekly",days:[...new Set(t.dayOfWeek.map(c=>c%7))].sort((c,u)=>c-u),...l}:void 0}function qY(e){const{kind:t,hour:n,minute:s}=e;if(!Number.isInteger(n)||n<0||n>23||!Number.isInteger(s)||s<0||s>59)return;const o=[...new Set(e.days)].filter(a=>Number.isInteger(a)&&a>=0&&a<=6);if(t==="weekly"&&!o.length)return;const r=t==="daily"?"*":t==="weekdays"?"1-5":o.sort().join(",");return`${s} ${n} * * ${r}`}function YY(e){const t={todo:[],doing:[],review:[],done:[],canceled:[],blocked:[]};for(const n of e)t[n.status].push(n);return t.todo.sort((n,s)=>n.seq-s.seq),t.doing.sort((n,s)=>n.seq-s.seq),t.blocked.sort((n,s)=>n.seq-s.seq),t.review.sort((n,s)=>n.seq-s.seq),t.done.sort((n,s)=>s.updatedAt-n.updatedAt),t.canceled.sort((n,s)=>s.updatedAt-n.updatedAt),t}function XY(e){return e.status==="review"&&!!(e.delegationId&&e.assigneeBotId)}function ZY(e,t){return e.filter(n=>n.chatId===t).sort((n,s)=>n.createdAt-s.createdAt)}const Zd=e=>e.finishedAt??e.createdAt;function JY(e,t){const n=e.filter(o=>o.chatId===t),s=o=>El(o.state)||$k(o,e);return{active:n.filter(s).sort((o,r)=>o.createdAt-r.createdAt),completed:n.filter(o=>o.state==="completed").sort((o,r)=>Zd(r)-Zd(o)),failed:n.filter(o=>["failed","canceled","blocked"].includes(o.state)&&!s(o)).sort((o,r)=>Zd(r)-Zd(o))}}function QY(e,t,n){const s=new Map(t.map(o=>[o.id,o]));return[...e].sort((o,r)=>o.createdAt-r.createdAt).map(o=>({run:o,record:s.get(o.id),time:o.state==="queued"&&o.startedAt===void 0?{queued:!0,ms:n-o.createdAt}:{queued:!1,ms:(o.finishedAt??n)-(o.startedAt??o.createdAt)}}))}function eX(e,t){const n=KR(e);if(!n)return;const s=t.find(r=>r.id===e.delegationId);if(n.reason==="failed"){const r=qk(e);return{reason:"failed",...s?{record:s}:{},since:r?.finishedAt??s?.finishedAt??e.updatedAt}}const o=(e.blockedStreak?.[e.assigneeBotId??""]??0)>=qR;return{reason:"need",need:n.need||s?.blocked?.need||"",waitFor:!o&&s?.blocked?.waitFor==="parent"?s.parentBotId:"human",...o?{humanOnly:!0}:{},since:s?.finishedAt??s?.blocked?.at??e.updatedAt}}const tX=["0 9 * * *","0 9 * * 1-5","0 9 * * 1","0 * * * *"];function nX(e,t,n){const s=kh(e);if(s)return{source:s.source,description:Ux(s,t),next:Pq(s,n)}}function sX(e,t){return e.filter(n=>n.archivedAt===void 0&&!n.parentId&&n.members.includes(t)).sort((n,s)=>+(n.kind==="group")-+(s.kind==="group"))}function iX(e){return e.title.trim()?e.prompt.trim()?kh(e.schedule)?e.chatId?null:"chat":"schedule":"prompt":"title"}function Du(e,t,n){switch(e){case"invalid":return t("Check the title, prompt and schedule, and that the member is still in the target chat.");case"not-found":return t("This routine no longer exists.");case"unavailable":return t("The member or target chat is archived or unavailable.");case"disabled":return t("Bot mode is off.");case"acl":return fa("acl",t);case"not-approved":return t("Approve this routine before running it. You can still do a dry run.");case"busy":return t("This routine is already running.");case"blocked":return n?fa(n,t):t("This routine is blocked. Fix the problem and enable it again.");default:return e}}function fa(e,t){switch(e){case"executor-missing":return t("The member who runs it was deleted.");case"executor-archived":return t("The member who runs it is archived.");case"chat-missing":return t("The target chat no longer exists.");case"chat-archived":return t("The target chat is archived.");case"not-in-chat":return t("The member who runs it is no longer in the target chat.");case"acl":return t("Delegation permissions do not allow that member to run it.");default:return t("This routine is blocked. Fix the problem and enable it again.")}}function ID(e,t){switch(e){case"ok":return"✓";case"error":return t("Error");case"budget":return t("Over budget");case"skipped-busy":return t("Skipped (still running)");case"interrupted":return t("Interrupted");case"blocked":return t("Blocked");case"skipped":return t("Skipped");default:return t("Running")}}function qx(){const{t:e}=Q(),[t,n]=m.useState(!1),s=async(r,a,l)=>{n(!0);try{const d=await a();d.ok?l&&Be({type:"success",title:l}):Be({type:"error",title:r,description:Du(d.error,e,d.reason)})}finally{n(!1)}},o=window.electronAPI.bots.routines;return{busy:t,review:(r,a)=>s(e("Routine not saved"),()=>o.review({botId:r.botId,id:r.id,approve:a})),resume:r=>s(e("Routine not saved"),async()=>{const a=await o.save({botId:r.botId,id:r.id,title:r.title,prompt:r.prompt,schedule:r.schedule,chatId:r.chatId,enabled:!0});return a.ok&&a.routine.status==="blocked"?{ok:!1,error:"blocked",reason:a.routine.blockedReason}:a}),run:(r,a)=>s(e("Routine did not run"),()=>o.runNow({botId:r.botId,id:r.id,dryRun:a}),e(a?"Dry run started":"Routine started"))}}function ED({routine:e}){const{t,locale:n}=Q(),s=ce(r=>r.bots),o=e.doneBy?s.find(r=>r.id===e.doneBy):void 0;return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground text-xs",children:[Ux(e.schedule,n),e.doneBy?` · ${t("Done by {{name}}",{name:o?.name??t("Deleted member")})}`:""]}),i.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-xs",children:e.prompt})]})}function oX({alert:e}){const{t}=Q(),n=ce(p=>p.bots),s=ce(p=>p.chats),o=ce(p=>p.setView),{busy:r,review:a,resume:l,run:d}=qx(),{routine:c}=e,u=n.find(p=>p.id===c.botId),h=s.find(p=>p.id===c.chatId);return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:u,size:"sm"}),i.jsx("span",{className:"text-foreground",children:u?.name??t("Deleted member")}),h?.kind==="group"&&i.jsxs("span",{children:["· ",ys(h,n,t)]}),i.jsx(Yx,{routine:c})]}),i.jsx(ED,{routine:c}),e.kind==="blocked"&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:fa(c.blockedReason,t)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[h&&i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>o({kind:"chat",chatId:h.id}),children:t("Go to chat")}),e.kind==="approval"?i.jsxs(i.Fragment,{children:[i.jsx(ge,{size:"xs",variant:"outline",disabled:r,onClick:()=>d(c,!0),children:t("Dry run")}),i.jsx(ge,{size:"xs",variant:"outline",disabled:r,onClick:()=>a(c,!1),children:t("Reject")}),i.jsx(ge,{size:"xs",disabled:r,onClick:()=>a(c,!0),children:t("Approve")})]}):i.jsx(ge,{size:"xs",disabled:r,onClick:()=>l(c),children:t("Enable again")})]})]})}function Yx({routine:e}){const{t}=Q(),[n,s]=e.status==="draft"?[t("Pending approval"),"bg-warning/20 text-warning"]:e.status==="blocked"?[t("Blocked"),"bg-destructive/15 text-destructive"]:e.status==="paused"?[t("Paused"),"bg-muted text-muted-foreground"]:[t("Enabled"),"bg-success/15 text-success"];return i.jsx("span",{className:q("rounded px-1.5 text-[11px]",s),children:n})}function rX({text:e,target:t}){const{t:n}=Q(),s=ce(l=>l.routines.find(d=>d.id===t.id&&d.botId===t.botId)),{busy:o,review:r,run:a}=qx();return i.jsxs("div",{"data-slot":"bot-card",className:"w-full max-w-md self-center rounded-xl border bg-card px-3 py-2 text-xs",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[i.jsx("span",{className:"min-w-0 flex-1",children:e}),s?i.jsx(Yx,{routine:s}):i.jsx("span",{className:"text-[11px]",children:n("Routine removed")})]}),s&&i.jsx(ED,{routine:s}),s?.status==="draft"&&i.jsxs("div",{className:"mt-2 flex justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",disabled:o,onClick:()=>a(s,!0),children:n("Dry run")}),i.jsx(ge,{size:"xs",variant:"outline",disabled:o,onClick:()=>r(s,!1),children:n("Reject")}),i.jsx(ge,{size:"xs",disabled:o,onClick:()=>r(s,!0),children:n("Approve")})]})]})}const Xx=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function PD(e,t){switch(e){case"title":return t("Enter a title.");case"prompt":return t("Enter what the member should do.");case"schedule":return t("Invalid cron expression (minute hour day month weekday).");case"chat":return t("Choose a target chat.")}}function aX(e,t){switch(e){case"scheduled":return t("Scheduled");case"manual":return t("Manual");case"catchup":return t("Catch-up");case"dry-run":return t("Dry run")}}function lX(e){if(e.finishedAt===void 0)return"";const t=Math.max(0,Math.round((e.finishedAt-e.startedAt)/1e3));return t<60?` · ${t}s`:` · ${Math.floor(t/60)}m ${t%60}s`}function AD({botId:e,chatId:t}){const{t:n,locale:s}=Q(),o=ce(b=>b.chats),r=ce(b=>b.bots),[a,l]=m.useState(null),[d,c]=m.useState(null),[u,h]=m.useState(null),[p,f]=m.useState(null),g=qx(),x=m.useCallback(async()=>{const b=await window.electronAPI.bots.routines.list(e?{botId:e}:{}).catch(()=>null),_=b?.ok?b.routines:[];l(t?ZY(_,t):_)},[e,t]);m.useEffect(()=>(l(null),x(),window.electronAPI.bots.onEvent(b=>{b.kind==="routine"&&x()})),[x]);const v=async(b,_)=>{const{id:j,title:N,prompt:C,schedule:S}=b,A=await window.electronAPI.bots.routines.save({botId:b.botId,id:j,title:N,prompt:C,schedule:S,chatId:b.chatId,enabled:_});A.ok?A.routine.status==="blocked"&&Be({type:"error",title:n("Routine blocked"),description:fa(A.routine.blockedReason,n)}):Be({type:"error",title:n("Routine not saved"),description:Du(A.error,n)}),x()},y=async b=>{h(null);const _=await window.electronAPI.bots.routines.remove({botId:b.botId,id:b.id});_.ok||Be({type:"error",title:n("Routine not deleted"),description:Du(_.error,n)}),x()};if(a===null)return i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const w=b=>r.find(_=>_.id===b)?.name??n("Deleted member");return i.jsxs("div",{className:"space-y-1.5",children:[i.jsxs(ge,{size:"xs",variant:"outline",onClick:()=>c("new"),children:[i.jsx(ds,{}),n("New routine")]}),a.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No routines yet")}),a.map(b=>{const _=o.find(S=>S.id===b.chatId),j=b.status==="draft",N=YR(b)&&(b.status==="enabled"||b.status==="paused"),C=_?n("Posts to {{chat}}",{chat:ys(_,r,n)}):n("Target chat missing");return i.jsxs("div",{"data-slot":"bot-card",className:q("rounded-lg border bg-card px-2.5 py-2 text-xs",b.status==="paused"&&"opacity-70"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:b.title}),i.jsx(Yx,{routine:b}),!j&&i.jsx(Di,{checked:b.status==="enabled",onCheckedChange:S=>{v(b,S)},title:b.status==="enabled"?n("Enabled"):n("Paused")})]}),i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:[t?w(b.botId):"",Ux(b.schedule,s),b.doneBy?n("Done by {{name}}",{name:w(b.doneBy)}):"",t?"":C].filter(Boolean).join(" · ")}),b.proposedBy&&j&&i.jsx("div",{className:"mt-0.5 text-warning",children:n("Proposed by {{name}}, waiting for your approval",{name:w(b.proposedBy)})}),b.status==="blocked"&&i.jsx("div",{className:"mt-0.5 text-destructive",children:fa(b.blockedReason,n)}),i.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[i.jsx("span",{children:b.lastRunAt?n("Last run {{time}} · {{result}}",{time:Xx(b.lastRunAt),result:ID(b.lastResult,n)}):n("Never run")}),b.missed?i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-warning",children:n("Missed {{n}} times",{n:b.missed})}):null,!b.catchUp&&i.jsx("span",{children:n("No catch-up")})]}),i.jsxs("div",{className:"mt-1.5 flex flex-wrap justify-end gap-1",children:[j?i.jsxs(i.Fragment,{children:[i.jsx(ge,{size:"xs",variant:"ghost",disabled:g.busy,onClick:()=>{g.review(b,!1)},children:n("Reject")}),i.jsx(ge,{size:"xs",disabled:g.busy,onClick:()=>{g.review(b,!0)},children:n("Approve")})]}):i.jsxs(ge,{size:"xs",variant:"ghost",disabled:!N||g.busy,onClick:()=>{g.run(b,!1)},children:[i.jsx(pg,{}),n("Run now")]}),i.jsxs(ge,{size:"xs",variant:"ghost",disabled:g.busy,title:n("Run once without affecting the schedule"),onClick:()=>{g.run(b,!0)},children:[i.jsx(Pk,{}),n("Dry run")]}),i.jsxs(ge,{size:"xs",variant:p===b.id?"secondary":"ghost",onClick:()=>f(p===b.id?null:b.id),children:[i.jsx(Bo,{}),n("History")]}),i.jsxs(ge,{size:"xs",variant:"ghost",onClick:()=>c(b),children:[i.jsx(Fs,{}),n("Edit")]}),i.jsxs(ge,{size:"xs",variant:"ghost",onClick:()=>h(b),children:[i.jsx(Gs,{}),n("Delete")]})]}),p===b.id&&i.jsx(dX,{routine:b})]},b.id)}),d&&i.jsx(hX,{botId:e,chatId:t,routine:d==="new"?void 0:d,onClose:b=>{c(null),b&&x()}}),i.jsx(fs,{open:u!==null,onOpenChange:b=>!b&&h(null),title:n('Delete routine "{{title}}"?',{title:u?.title??""}),description:n("It will no longer run. This cannot be undone."),confirmLabel:n("Delete"),onConfirm:()=>u&&void y(u)})]})}function dX({routine:e}){const{t}=Q(),n=ce(l=>l.setView),[s,o]=m.useState(null),{botId:r,id:a}=e;return m.useEffect(()=>{let l=!0;const d=()=>{window.electronAPI.bots.routines.runs({botId:r,id:a}).then(u=>l&&o(u.ok?u.runs:[])).catch(()=>l&&o([]))};d();const c=window.electronAPI.bots.onEvent(u=>{u.kind==="routine"&&d()});return()=>{l=!1,c()}},[r,a]),s===null?i.jsx(qt,{className:"mt-2 h-3.5 w-3.5 animate-spin"}):s.length===0?i.jsx("p",{className:"mt-2 text-muted-foreground",children:t("No runs yet")}):i.jsx("ul",{className:"mt-2 space-y-1 border-t pt-2",children:s.map(l=>i.jsxs("li",{className:"flex flex-wrap items-center gap-x-2 text-muted-foreground",children:[i.jsx("span",{className:"tabular-nums",children:Xx(l.startedAt)}),i.jsx("span",{children:aX(l.trigger,t)}),i.jsxs("span",{className:q(l.result==="ok"&&"text-success",(l.result==="error"||l.result==="blocked"||l.result==="budget")&&"text-destructive"),children:[ID(l.result,t),lX(l)]}),l.conversationId&&i.jsx("button",{type:"button",className:"text-primary hover:underline",onClick:()=>n({kind:"chat",chatId:l.chatId}),children:t("Open chat")}),l.error&&i.jsx("span",{className:"w-full truncate text-destructive",title:l.error,children:l.result==="blocked"?fa(l.error,t):l.error})]},l.runId))})}const cX=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],nS=e=>String(e).padStart(2,"0");function uX({value:e,onChange:t}){const{t:n,locale:s}=Q(),o=tS(e),[r,a]=m.useState(!o),[l,d]=m.useState(o??{kind:"daily",days:[1],hour:9,minute:0}),c=nX(e,s,Date.now()),u=f=>{d(f);const g=qY(f);g&&t(g)},h=[{value:"daily",label:n("Every day")},{value:"weekdays",label:n("Weekdays")},{value:"weekly",label:n("Every week on")}],p=()=>{if(!r)return a(!0);const f=tS(e);f?d(f):u(l),a(!1)};return i.jsxs("div",{children:[i.jsx(Kt,{hint:r?n("cron: minute hour day month weekday, local time"):void 0,action:i.jsx(ge,{size:"xs",variant:"ghost",onClick:p,children:n(r?"Simple":"Advanced (cron)")}),children:n("Schedule")}),r?i.jsx(Xt,{className:"font-mono",value:e,placeholder:"0 9 * * 1-5",onChange:f=>t(f.target.value)}):i.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[i.jsxs(xs,{items:h,value:l.kind,onValueChange:f=>u({...l,kind:f,days:l.days.length?l.days:[1]}),children:[i.jsx(vs,{className:"w-32",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:h.map(f=>i.jsx(ns,{value:f.value,children:f.label},f.value))})]}),l.kind==="weekly"&&cX.map((f,g)=>{const x=l.days.includes(g);return i.jsx(ge,{size:"xs",variant:x?"default":"outline",onClick:()=>{const v=x?l.days.filter(y=>y!==g):[...l.days,g].sort();v.length&&u({...l,days:v})},children:n(f)},f)}),i.jsx(Xt,{type:"time",className:"w-28",value:`${nS(l.hour)}:${nS(l.minute)}`,onChange:f=>{const[g,x]=f.target.value.split(":").map(Number);Number.isInteger(g)&&Number.isInteger(x)&&u({...l,hour:g,minute:x})}})]}),i.jsx("p",{className:q("mt-1 text-xs",c?"text-muted-foreground":"text-destructive"),children:c?`${c.description} · ${c.next?n("Next run {{time}}",{time:Xx(c.next)}):n("Never runs")}`:PD("schedule",n)})]})}function hX({botId:e,chatId:t,routine:n,onClose:s}){const{t:o}=Q(),r=ce(B=>B.chats),a=ce(B=>B.bots),l=m.useMemo(()=>(r.find(H=>H.id===t)?.members??[]).flatMap(H=>{const oe=a.find(te=>te.id===H&&te.archivedAt===void 0);return oe?[oe]:[]}),[r,a,t]),[d,c]=m.useState(n?.botId??e??l[0]?.id??""),u=m.useMemo(()=>sX(r,d),[r,d]),[h,p]=m.useState(n?.title??""),[f,g]=m.useState(n?.prompt??""),[x,v]=m.useState(n?.schedule??tX[0]),[y,w]=m.useState(n?.chatId??t??u[0]?.id??""),[b,_]=m.useState(n?.doneBy??""),[j,N]=m.useState(n?.catchUp??!0),[C,S]=m.useState(null),[A,E]=m.useState(!1),I=B=>{const H=r.find(oe=>oe.id===B);return H?`${ys(H,a,o)} · ${H.kind==="group"?o("Group chat"):o("Private chat")}`:o("Target chat missing")},D=u.some(B=>B.id===y)||!y?u.map(B=>B.id):[y,...u.map(B=>B.id)],T=m.useMemo(()=>(r.find(H=>H.id===y)?.members??[]).flatMap(H=>{const oe=a.find(te=>te.id===H&&te.archivedAt===void 0);return oe&&oe.id!==d?[oe]:[]}),[r,a,y,d]),z=[{value:"",label:o("The member itself")},...T.map(B=>({value:B.id,label:B.name}))],$=T.some(B=>B.id===b)?b:"",R=async()=>{if(!d)return S(o("Choose a member."));const B=iX({title:h,prompt:f,schedule:x,chatId:y});if(B)return S(PD(B,o));E(!0),S(null);try{const H=await window.electronAPI.bots.routines.save({botId:d,title:h,prompt:f,schedule:x,chatId:y,catchUp:j,doneBy:$||null,...n?{id:n.id,enabled:n.status!=="paused"}:{}});H.ok?s(!0):S(Du(H.error,o))}finally{E(!1)}};return i.jsx(wn,{open:!0,onOpenChange:B=>!B&&s(!1),children:i.jsxs(yn,{className:"max-h-[85vh] max-w-lg",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:o(n?"Edit routine":"New routine")})}),i.jsxs(On,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:o("Routine title")}),i.jsx(Xt,{value:h,onChange:B=>p(B.target.value)})]}),i.jsxs("div",{children:[i.jsx(Kt,{hint:o("Sent to the member as the task each time it runs"),children:o("Prompt")}),i.jsx(ei,{rows:4,value:f,onChange:B=>g(B.target.value)})]}),i.jsx(uX,{value:x,onChange:v}),t?i.jsxs("div",{children:[i.jsx(Kt,{children:o("Member")}),i.jsxs(xs,{items:l.map(B=>({value:B.id,label:B.name})),value:d,disabled:!!n,onValueChange:B=>c(B),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:l.map(B=>i.jsx(ns,{value:B.id,children:B.name},B.id))})]})]}):i.jsxs("div",{children:[i.jsx(Kt,{children:o("Target chat")}),D.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:o("This member is not in any chat yet. Start a private chat first.")}):i.jsxs(xs,{items:D.map(B=>({value:B,label:I(B)})),value:y,onValueChange:B=>w(B),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:D.map(B=>i.jsx(ns,{value:B,children:I(B)},B))})]})]}),T.length>0&&i.jsxs("div",{children:[i.jsx(Kt,{hint:o("Another member of the target chat runs it, as a delegation"),children:o("Done by")}),i.jsxs(xs,{items:z,value:$,onValueChange:B=>_(B),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:z.map(B=>i.jsx(ns,{value:B.value,children:B.label},B.value||"self"))})]})]}),i.jsxs("div",{className:"flex items-center justify-between gap-3",children:[i.jsx(Kt,{hint:o("If the app was closed at the scheduled time, run the latest missed one once on startup"),children:o("Catch up missed runs")}),i.jsx(Di,{checked:j,onCheckedChange:N})]}),C&&i.jsx("p",{className:"text-destructive text-sm",children:C})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>s(!1),children:o("Cancel")}),i.jsxs(ge,{size:"sm",disabled:A,onClick:()=>{R()},children:[A&&i.jsx(qt,{className:"animate-spin"}),o("Save")]})]})]})})}function Fp(e,t){return{name:e.name,title:e.title,scope:e.scope,persona:t,color:e.avatar.color,engine:e.engine??null,tools:e.tools,approvalMode:e.approvalMode,skillIds:e.skillIds,mcpServerIds:e.mcpServerIds,canDelegateTo:e.delegation.canDelegateTo,acceptFrom:e.delegation.acceptFrom,memoryEnabled:e.memory.enabled,...MY(e.budget),...RY(e)}}function pX(e){const t=SD(e),n=Kx(e);return!t.ok||!n.ok?null:{name:e.name.trim(),title:e.title.trim(),scope:e.scope.trim(),persona:e.persona,avatar:{color:e.color},engine:e.engine,tools:e.tools,approvalMode:e.approvalMode,skillIds:e.skillIds,mcpServerIds:e.mcpServerIds,delegation:{canDelegateTo:e.canDelegateTo,acceptFrom:e.acceptFrom},memory:{enabled:e.memoryEnabled},budget:t.budget,delegationTimeoutMinutes:n.delegationTimeoutMinutes,maxTokensPerTurn:n.maxTokensPerTurn}}async function fX(e,t){const n=Yc(e),s=n?await fetch(n).then(r=>r.blob()).then(Jk).catch(()=>null):null,o=EY(XR(s??await ZR(e.name,e.avatar.color)),"chara",PY(JSON.stringify(LY(e,t))),["ccv3"]);if(!o)throw new Error("png");JR(new Blob([new Uint8Array(o)],{type:"image/png"}),`${e.name}.png`)}function mX({botId:e,chat:t,onOpenHistory:n}){const{t:s}=Q(),o=ce(I=>I.bots.find(D=>D.id===e)),r=ce(I=>I.bots),[a,l]=m.useState(null),[d,c]=m.useState(null),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[g,x]=m.useState(!1),[v,y]=m.useState(null),w=m.useCallback(async()=>{const I=await window.electronAPI.bots.get(e);I.ok&&(ce.getState().upsertBot(I.bot),l(I.persona),c(Fp(I.bot,I.persona)),h(!1))},[e]);m.useEffect(()=>{l(null),c(null),w()},[w]);const b=m.useMemo(()=>o&&a!==null?Fp(o,a):null,[o,a]),_=u&&!!(d&&b&&JSON.stringify(d)!==JSON.stringify(b));if(m.useEffect(()=>{!u&&b&&c(b)},[o?.version]),!o||!d)return i.jsx("div",{className:"flex flex-1 items-center justify-center",children:i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"})});const j=I=>{c(D=>D&&{...D,...I}),h(!0)},N=fg(d.name,r,s,o.id),C=async I=>{x(!0);try{await Zk(o.id,I)||Be({type:"error",title:s("Avatar update failed")})}finally{x(!1)}},S=()=>{fX(o,a??"").then(()=>Be({type:"success",title:s('Persona embedded in the PNG. Restore it in a new member via "Import character card".')})).catch(()=>Be({type:"error",title:s("Export failed")}))},A=async()=>{const I=pX(d);if(!I){Be({type:"error",title:Kx(d).ok?s("Budget must be a positive number"):s("Check the per-turn token limit and delegation time limit")});return}f(!0);try{const D=await window.electronAPI.bots.update({botId:o.id,expectedVersion:o.version,draft:I});if(D.ok){ce.getState().upsertBot(D.bot),l(d.persona),c(Fp(D.bot,d.persona)),h(!1);return}Be({type:"error",title:sl(D.reason,D.error,s),...D.reason==="conflict"?{actions:[{label:s("Refresh"),onClick:()=>{w()}}]}:{}})}finally{f(!1)}},E=async()=>{const I=v;if(y(null),I==="archive"){const T=await window.electronAPI.bots.archive(o.id,!0);T.ok?ce.getState().upsertBot(T.bot):Be({type:"error",title:sl(T.reason,T.error,s)});return}const D=await window.electronAPI.bots.remove(o.id);if(D.ok){ce.getState().setView(null),await Promise.all([ce.getState().refreshCatalog(),ce.getState().refreshChats()]);return}if(D.reason==="boss"){const T=ce.getState().chats,z=(D.chatIds??[]).map($=>T.find(R=>R.id===$)).filter($=>!!$).map($=>ys($,r,s));Be({type:"warning",title:s("{{name}} owns group chats",{name:o.name}),description:s("Choose another owner in {{groups}} first.",{groups:z.join("、")})});return}Be({type:"error",title:sl(D.reason,D.error,s)})};return i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex items-center gap-3 px-4 pt-4",children:[i.jsx(tn,{bot:{id:o.id,name:d.name||o.name,avatar:{...o.avatar,color:d.color}},size:"lg"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-semibold text-base",children:o.name}),i.jsx("div",{className:"truncate text-muted-foreground text-sm",children:o.title}),i.jsxs("div",{className:"mt-1 flex flex-wrap gap-1.5",children:[i.jsxs(wf,{children:[i.jsxs(yf,{render:i.jsx(ge,{size:"xs",variant:"outline",onClick:S}),children:[i.jsx(sd,{}),s("Export character card")]}),i.jsx(Sf,{className:"max-w-72",children:s('Exports a SillyTavern V2 PNG: the avatar as image, persona embedded. Restore it in a new member via "Import character card".')})]}),i.jsx(CD,{hasImage:!!o.avatar.image,disabled:g,onPick:I=>{C(I)},onRemove:()=>{C(null)}})]})]})]}),i.jsxs(Wu,{defaultValue:"profile",className:"mt-3 flex min-h-0 flex-1 flex-col",children:[i.jsxs(Uu,{variant:"underline",className:"shrink-0 px-2",children:[i.jsx(Ds,{value:"profile",children:s("Profile")}),i.jsx(Ds,{value:"abilities",children:s("Abilities")}),i.jsx(Ds,{value:"memory",children:s("Memory")}),i.jsx(Ds,{value:"routines",children:s("Routines")}),i.jsx(Ds,{value:"history",children:s("History")})]}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-3",children:[i.jsxs(oo,{value:"profile",className:"space-y-3",children:[i.jsx(UY,{bot:o}),i.jsxs("div",{children:[i.jsx(Kt,{hint:s("Used for @ in groups; must be unique"),children:s("Name")}),i.jsx(Xt,{value:d.name,onChange:I=>j({name:I.target.value})}),N&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:N})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:s("Title")}),i.jsx(Xt,{value:d.title,onChange:I=>j({title:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Kt,{hint:s("Used for routing and the delegation directory"),children:s("Responsibilities")}),i.jsx(ei,{rows:2,value:d.scope,onChange:I=>j({scope:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Kt,{action:i.jsx(DD,{value:d,onApply:j}),children:s("Persona")}),i.jsx(ei,{rows:8,value:d.persona,onChange:I=>j({persona:I.target.value})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:s("Avatar color")}),i.jsx(Yk,{value:d.color,onChange:I=>j({color:I})})]}),i.jsxs("div",{className:"flex gap-2 border-t pt-3",children:[i.jsxs(ge,{size:"xs",variant:"outline",onClick:()=>y("archive"),children:[i.jsx(Ii,{}),s("Archive member")]}),i.jsxs(ge,{size:"xs",variant:"destructive-outline",onClick:()=>y("delete"),children:[i.jsx(Gs,{}),s("Delete permanently")]})]})]}),i.jsxs(oo,{value:"abilities",className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:s("Model")}),i.jsx(Xk,{engine:d.engine,onChange:I=>j({engine:I})})]}),i.jsx(jD,{value:d,onChange:j,profile:d,botId:o.id})]}),i.jsxs(oo,{value:"memory",children:[i.jsxs("div",{className:"mb-4",children:[i.jsx(Kt,{hint:s("Injected into every new conversation"),children:s("Core notes")}),i.jsx(TD,{target:{botId:o.id},emptyText:s("No notes yet. Key preferences and facts are summarized here automatically after memories are organized.")})]}),i.jsx(ND,{spaceId:`bot:${o.id}`,emptyText:s("No memories yet")})]}),i.jsx(oo,{value:"routines",children:i.jsx(AD,{botId:o.id})}),i.jsx(oo,{value:"history",children:i.jsx(gX,{chat:t,botId:o.id,onOpen:I=>n(I,o.name)})})]})]}),_&&i.jsxs("div",{className:"flex shrink-0 justify-end gap-2 border-t bg-muted/50 px-4 py-2.5",children:[i.jsx(ge,{size:"sm",variant:"outline",onClick:()=>{b&&c(b),h(!1)},children:s("Discard")}),i.jsxs(ge,{size:"sm",disabled:p||!!N,onClick:()=>{A()},children:[p&&i.jsx(qt,{className:"animate-spin"}),s("Save")]})]}),i.jsx(fs,{open:v!==null,onOpenChange:I=>!I&&y(null),title:v==="delete"?s("Delete {{name}}?",{name:o.name}):s("Archive {{name}}?",{name:o.name}),description:s(v==="delete"?"The member, their private chats, persona, memories and workspace are deleted. This cannot be undone.":"Archived members stop replying and are hidden from the list. You can restore them later."),confirmLabel:s(v==="delete"?"Delete permanently":"Archive member"),onConfirm:()=>{E()}})]})}function gX({chat:e,botId:t,onOpen:n}){const{t:s}=Q(),[o,r]=m.useState(null);return m.useEffect(()=>{let a=!0;return window.electronAPI.bots.chatSessions(e.id).then(l=>{a&&r(l.ok?l.sessions.filter(d=>d.botId===t):[])}),()=>{a=!1}},[e.id,t]),o===null?i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):o.length===0?i.jsx("p",{className:"text-muted-foreground text-xs",children:s("No conversations yet")}):i.jsx("div",{className:"space-y-1",children:o.map((a,l)=>i.jsxs("button",{type:"button",onClick:()=>n(a.conversationId),"data-slot":"bot-card-button",className:"flex w-full items-center justify-between rounded-lg border bg-card px-2.5 py-2 text-left text-xs hover:bg-muted",children:[i.jsx("span",{children:s("Conversation {{n}}",{n:o.length-l})}),i.jsx("span",{className:"text-muted-foreground",children:a.current?s("Current"):s("Read-only")})]},a.conversationId))})}function Iu(e,t){switch(e){case"invalid":return t("Check the title and details.");case"disabled":return t("Bot mode is off.");default:return e}}async function MD(e,t,n,s){const o=await window.electronAPI.bots.tasks.reply({chatId:e,id:t,text:n}),r=ce.getState();return r.refreshTasks(e),r.refreshDelegations(),r.refreshInbox(),o.ok||Be({type:"error",title:s("Reply not sent"),description:Iu(o.error,s)}),o.ok}function Zx({placeholder:e,onSend:t,className:n}){const{t:s}=Q(),[o,r]=m.useState(""),[a,l]=m.useState(!1),d=Ai(Ce(u=>u.keybindings))["send-message"],c=async()=>{const u=o.trim();if(!(!u||a)){l(!0);try{await t(u)&&r("")}finally{l(!1)}}};return i.jsxs("div",{className:q("mt-1.5 flex items-end gap-1",n),children:[i.jsx(ei,{value:o,rows:1,size:"sm",maxLength:mg,placeholder:e,"aria-label":e,title:d?`${s("Send")} ${fi(d)}`:void 0,disabled:a,className:"text-xs [&_textarea]:max-h-32 [&_textarea]:min-h-0 [&_textarea]:resize-none",onChange:u=>r(u.target.value),onKeyDown:u=>{!u.nativeEvent.isComposing&&Vk(u,d)&&(u.preventDefault(),c())}}),i.jsx(ge,{size:"icon-sm",variant:o.trim()?"default":"ghost","aria-label":s("Send reply"),disabled:!o.trim()||a,onClick:()=>{c()},children:a?i.jsx(qt,{className:"animate-spin"}):i.jsx(yx,{})})]})}function RD(e,t){switch(e){case"append":return t("Appended");case"reply":return t("Resumed after reply");case"rework":return t("Rework");case"retry":return t("Retry");default:return t("Delegated")}}const LD=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),OD=(e,t)=>e.ok===void 0?t("Processing"):e.ok?t("Delivered"):t("Not delivered");function xX({appends:e}){const{t}=Q();return i.jsx("ul",{className:"mt-0.5 ml-6 space-y-0.5",children:e.map(n=>i.jsxs("li",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx("span",{className:"shrink-0 tabular-nums",children:LD(n.at)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-foreground",title:n.text,children:n.text}),i.jsx("span",{className:q("shrink-0 rounded px-1.5 text-[11px]",n.ok===void 0?"bg-info/15 text-info":n.ok?"bg-success/15 text-success":"bg-destructive/15 text-destructive"),children:OD(n,t)})]},n.deliveryId))})}function vX({runs:e,bots:t,onOpenConversation:n}){const{t:s}=Q(),o=ce(f=>f.delegations),r=Nh(e.some(f=>El(f.state))),[a,l]=m.useState(!1),[d,c]=m.useState(null),u=QY(e,o,r),h=a?u:u.slice(-5),p=f=>t.get(f)?.name??s("Deleted member");return i.jsxs("section",{className:"mt-1.5 border-t pt-1.5",children:[i.jsxs("h5",{className:"mb-1 text-[11px] text-muted-foreground",children:[s("Run history")," · ",u.length]}),i.jsx("ul",{className:"space-y-1",children:h.map(({run:f,record:g,time:x})=>{const v=f.state==="failed"?Td(g??f,s):void 0,y=g?.appends??[];return i.jsxs("li",{className:q(f.nested&&"ml-3 border-l pl-2"),children:[i.jsxs("div",{className:"flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-muted-foreground",children:[i.jsx(tn,{bot:t.get(f.botId),size:"xs"}),i.jsx("span",{className:"text-foreground",children:p(f.botId)}),i.jsxs("span",{children:["· ",f.nested?s("Sub-delegation"):RD(f.trigger,s)]}),x.queued?i.jsx("span",{className:"rounded bg-info/15 px-1.5 text-[11px] text-info",children:s("Queued {{time}}",{time:mo(x.ms)})}):i.jsxs(i.Fragment,{children:[i.jsx(_h,{state:f.state,interrupted:f.failure==="interrupted"}),i.jsx("span",{children:mo(x.ms)})]}),f.appends&&i.jsx("button",{type:"button","aria-expanded":d===f.id,disabled:!y.length,title:y.map(w=>`${LD(w.at)} ${w.text} · ${OD(w,s)}`).join(`
|
|
83
|
-
`),onClick:()=>c(d===f.id?null:f.id),className:"rounded px-1 text-info hover:bg-info/10 disabled:hover:bg-transparent",children:s("+{{n}} appended",{n:f.appends})}),i.jsx("span",{className:"flex-1"}),g&&i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>n(g.childConversationId,s("{{from}} → {{to}} · Delegation",{from:p(g.parentBotId),to:p(g.targetBotId)})),children:s("View process")})]}),d===f.id&&y.length>0&&i.jsx(xX,{appends:y}),v&&i.jsx("div",{className:"mt-0.5 line-clamp-2 whitespace-pre-wrap text-destructive",children:v})]},f.id)})}),u.length>h.length&&i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>l(!0),children:s("Show all ({{n}})",{n:u.length})})]})}const Im=5,bX=e=>new Date(e).toLocaleString([],{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"});function io({title:e,count:t,limit:n,children:s}){const{t:o}=Q(),[r,a]=m.useState(!1),l=n&&!r?Math.min(n,t):t;return i.jsxs("section",{className:"mt-4 first:mt-0",children:[i.jsxs("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:[e," · ",t]}),i.jsx("div",{className:"space-y-1.5",children:s(l)}),t>l&&i.jsx(ge,{size:"xs",variant:"ghost",className:"mt-1",onClick:()=>a(!0),children:o("Show all ({{n}})",{n:t})})]})}function wX({chat:e,onOpenConversation:t}){const{t:n}=Q(),s=ce(S=>S.tasks[e.id]),o=ce(S=>S.bots),r=ce(S=>S.delegations),[a,l]=m.useState(null),[d,c]=m.useState(null),[u,h]=m.useState(null),p=ce(S=>S.taskFocus),[f,g]=m.useState(null),x=m.useRef(null),v=Nh(!!s?.some(S=>S.status==="blocked")),y=m.useMemo(()=>new Map(o.map(S=>[S.id,S])),[o]),w=e.members.flatMap(S=>{const A=y.get(S);return A&&A.archivedAt===void 0?[A]:[]});m.useEffect(()=>{ce.getState().refreshTasks(e.id)},[e.id]),m.useEffect(()=>{!p||p.chatId!==e.id||!s||(ce.getState().clearTaskFocus(p.nonce),s.some(S=>S.id===p.taskId)&&(g(p.taskId),requestAnimationFrame(()=>x.current?.querySelector(`[data-task-id="${CSS.escape(p.taskId)}"]`)?.scrollIntoView({block:"center",behavior:"smooth"}))))},[p,s,e.id]),m.useEffect(()=>{if(!f)return;const S=setTimeout(()=>g(null),2e3);return()=>clearTimeout(S)},[f]);const b=async(S,A)=>{const E=await S();E.ok||Be({type:"error",title:A,description:Iu(E.error??"",n)}),ce.getState().refreshTasks(e.id)},_=window.electronAPI.bots.tasks,j=S=>({chatId:e.id,id:S.id});if(!s)return i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"});const N=YY(s),C=S=>i.jsx(yX,{task:S,bots:y,members:w,onOpenConversation:t,block:eX(S,r),now:v,highlighted:f===S.id,onEdit:()=>l(S),onAssign:A=>{b(()=>_.assign({...j(S),botId:A}),n("Task not assigned"))},onComplete:()=>{b(()=>_.complete(j(S)),n("Task not updated"))},onAccept:()=>{b(()=>_.review({...j(S),accept:!0}),n("Task not updated"))},onReturn:A=>h({task:S,rework:A}),onCancel:()=>{b(()=>_.cancel(j(S)),n("Task not updated"))},onDelete:()=>c(S),onReply:A=>MD(e.id,S.id,A,n)},S.id);return i.jsxs("div",{ref:x,children:[i.jsxs(ge,{size:"xs",variant:"outline",className:"mb-3",onClick:()=>l("new"),children:[i.jsx(ds,{}),n("New task")]}),s.length===0&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No tasks yet. Members can also add and claim tasks with the board tool.")}),N.todo.length>0&&i.jsx(io,{title:n("To do"),count:N.todo.length,children:()=>N.todo.map(C)}),N.doing.length>0&&i.jsx(io,{title:n("Doing"),count:N.doing.length,children:()=>N.doing.map(C)}),N.blocked.length>0&&i.jsx(io,{title:n("Stuck tasks"),count:N.blocked.length,children:()=>N.blocked.map(C)}),N.review.length>0&&i.jsx(io,{title:n("Awaiting review"),count:N.review.length,children:()=>N.review.map(C)}),N.done.length>0&&i.jsx(io,{title:n("Completed"),count:N.done.length,limit:Im,children:S=>N.done.slice(0,S).map(C)}),N.canceled.length>0&&i.jsx(io,{title:n("Canceled"),count:N.canceled.length,limit:0,children:S=>N.canceled.slice(0,S).map(C)}),a&&i.jsx(kX,{chatId:e.id,task:a==="new"?void 0:a,onClose:S=>{l(null),S&&ce.getState().refreshTasks(e.id)}}),u&&i.jsx(CX,{task:u.task,assignee:y.get(u.task.assigneeBotId??"")?.name??n("Deleted member"),rework:u.rework,onClose:()=>h(null),onReturn:S=>_.review({...j(u.task),accept:!1,reason:S,...u.rework?{rework:!0}:{}}).then(A=>(A.ok&&(h(null),ce.getState().refreshTasks(e.id)),A.ok?null:Iu(A.error,n)))}),i.jsx(fs,{open:d!==null,onOpenChange:S=>!S&&c(null),title:n("Delete task #{{n}}?",{n:d?.seq??""}),description:n("The task is removed from the board. This cannot be undone."),confirmLabel:n("Delete"),onConfirm:()=>{const S=d;c(null),S&&b(()=>_.remove(j(S)),n("Task not deleted"))}})]})}function yX({task:e,bots:t,members:n,onOpenConversation:s,onEdit:o,onAssign:r,onComplete:a,onAccept:l,onReturn:d,onCancel:c,onDelete:u,onReply:h,block:p,now:f,highlighted:g}){const{t:x}=Q(),v=e.status==="todo"||e.status==="doing"||e.status==="blocked",y=e.status==="review",w=qk(e),b=e.assigneeBotId?t.get(e.assigneeBotId):void 0,_=e.createdBy==="human"?x("You"):t.get(e.createdBy)?.name??x("Deleted member");return i.jsxs("div",{"data-slot":"bot-card","data-task-id":e.id,className:q("group rounded-lg border bg-card px-2.5 py-2 text-xs transition-shadow",!v&&!y&&"opacity-75",g&&"ring-2 ring-brand/60"),children:[i.jsxs("div",{className:"flex items-start gap-1.5",children:[i.jsxs("span",{className:"shrink-0 text-muted-foreground",children:["#",e.seq]}),i.jsx("span",{className:"min-w-0 flex-1 break-words font-medium text-sm",children:e.title}),i.jsxs(Hi,{children:[i.jsx(Bi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:i.jsx(hh,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",children:[i.jsxs(pn,{onClick:o,children:[i.jsx(Fs,{}),x("Edit")]}),v&&(!e.delegationId||e.status==="blocked"||w)&&n.length>0&&i.jsxs(ej,{children:[i.jsxs(tj,{children:[i.jsx(Hl,{}),e.assigneeBotId?x("Reassign to"):x("Assign to")]}),i.jsx(nj,{children:n.map(j=>i.jsxs(pn,{disabled:j.id===e.assigneeBotId,onClick:()=>r(j.id),children:[i.jsx(tn,{bot:j,size:"xs"}),j.name]},j.id))})]}),v&&!w&&i.jsxs(pn,{onClick:a,children:[i.jsx(Un,{}),x("Mark done")]}),(v||y)&&i.jsxs(pn,{onClick:c,children:[i.jsx(an,{}),x("Cancel task")]}),i.jsx(va,{}),i.jsxs(pn,{variant:"destructive",onClick:u,children:[i.jsx(Gs,{}),x("Delete")]})]})]})]}),e.detail&&i.jsx("div",{className:"mt-1 line-clamp-3 whitespace-pre-wrap text-muted-foreground",children:e.detail}),e.result&&i.jsx("div",{className:q("mt-1 rounded px-1.5 py-1 text-foreground",e.status!=="done"&&e.check?.passed===!1?"bg-destructive/10":"bg-success/10"),children:i.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:e.result})}),e.returnReason&&i.jsx("div",{className:"mt-1 rounded bg-warning/10 px-1.5 py-1 text-foreground",children:i.jsx("div",{className:"line-clamp-3 whitespace-pre-wrap",children:x("Returned: {{reason}}",{reason:e.returnReason})})}),p&&i.jsx(SX,{block:p,now:f,assignee:b,bots:t,members:n,assigneeBotId:e.assigneeBotId,onRetry:()=>w&&kl(w.id,x),onAssign:r,onCancel:c,onReply:h}),!p&&(y||e.status==="doing"&&e.delegationId)&&i.jsx(Zx,{placeholder:x(y?"Comment…":"Add to the current run…"),onSend:h}),e.check&&i.jsx(pD,{check:e.check,className:"mt-1"}),y&&i.jsxs("div",{className:"mt-1.5 flex gap-1.5",children:[i.jsxs(ge,{size:"xs",onClick:l,children:[i.jsx(Un,{}),x("Accept result")]}),i.jsxs(ge,{size:"xs",variant:"outline",onClick:()=>d(!1),children:[i.jsx(ua,{}),x("Return")]}),XY(e)&&i.jsxs(ge,{size:"xs",variant:"outline",onClick:()=>d(!0),children:[i.jsx(gg,{}),x("Return for rework")]})]}),i.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-muted-foreground",children:[b||e.assigneeBotId?i.jsxs("span",{className:"flex items-center gap-1",children:[i.jsx(tn,{bot:b,size:"xs"}),b?.name??x("Deleted member")]}):i.jsx("span",{children:x("Unassigned")}),e.delegationId&&i.jsxs("span",{children:["· ",x("Delegation")]}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{title:x("Created by {{name}}",{name:_}),children:bX(e.updatedAt)})]}),e.runs&&e.runs.length>0&&i.jsx(vX,{runs:e.runs,bots:t,onOpenConversation:s})]})}function SX({block:e,now:t,assignee:n,assigneeBotId:s,bots:o,members:r,onRetry:a,onAssign:l,onCancel:d,onReply:c}){const{t:u}=Q(),h=n?.name??u("Deleted member"),p=u("Stuck for {{time}}",{time:mo(t-e.since)});if(e.reason==="need"){const g=e.waitFor==="human"?u("Waiting for your reply"):u("Waiting for {{name}} to reply",{name:o.get(e.waitFor)?.name??u("Deleted member")});return i.jsxs("div",{className:"mt-1.5 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-foreground",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · needs: {{need}}",{need:e.need})}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[g," · ",p]}),e.humanOnly&&i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:u("Stuck several times in a row; only you can answer now.")}),i.jsx(Zx,{placeholder:u("Answer {{name}}; they continue after your reply…",{name:h}),onSend:c})]})}const f=e.record?.state==="failed"&&Td(e.record,u)||u("Failed");return i.jsxs("div",{className:"mt-1.5 rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1.5 text-foreground",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:u("Blocked · run failed: {{reason}}",{reason:f})}),i.jsxs("div",{className:"mt-0.5 text-muted-foreground",children:[u("Waiting for you to handle it")," · ",p]}),i.jsxs("div",{className:"mt-1.5 flex flex-wrap gap-1.5",children:[i.jsxs(ge,{size:"xs",variant:"outline",onClick:a,children:[i.jsx(na,{}),u("Retry")]}),r.length>0&&i.jsxs(Hi,{children:[i.jsxs(Bi,{render:i.jsx(ge,{size:"xs",variant:"outline"}),children:[i.jsx(Hl,{}),u("Reassign")]}),i.jsx(Vi,{align:"start",children:r.map(g=>i.jsxs(pn,{disabled:g.id===s,onClick:()=>l(g.id),children:[i.jsx(tn,{bot:g,size:"xs"}),g.name]},g.id))})]}),i.jsxs(ge,{size:"xs",variant:"outline",onClick:d,children:[i.jsx(an,{}),u("Cancel task")]})]})]})}function CX({task:e,assignee:t,rework:n,onClose:s,onReturn:o}){const{t:r}=Q(),[a,l]=m.useState(""),[d,c]=m.useState(null),[u,h]=m.useState(!1),p=async()=>{if(!a.trim())return c(r("Enter a reason."));h(!0);try{c(await o(a.trim()))}finally{h(!1)}};return i.jsx(wn,{open:!0,onOpenChange:f=>!f&&s(),children:i.jsxs(yn,{className:"max-w-lg",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:n?r("Return task #{{n}} for rework",{n:e.seq}):r("Return task #{{n}}",{n:e.seq})})}),i.jsxs(On,{className:"space-y-2",children:[i.jsx(Kt,{children:r("Reason for returning")}),i.jsx(ei,{rows:4,autoFocus:!0,value:a,maxLength:mg,onChange:f=>l(f.target.value)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:n?r("{{name}} continues in the same conversation with this reason, and the result comes back for review.",{name:t}):r("The task goes back to To do with this reason and can be reassigned.")}),d&&i.jsx("p",{className:"text-destructive text-sm",children:d})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:s,children:r("Cancel")}),i.jsxs(ge,{size:"sm",disabled:u,onClick:()=>{p()},children:[u&&i.jsx(qt,{className:"animate-spin"}),r(n?"Return for rework":"Return")]})]})]})})}function kX({chatId:e,task:t,onClose:n}){const{t:s}=Q(),[o,r]=m.useState(t?.title??""),[a,l]=m.useState(t?.detail??""),[d,c]=m.useState(t?.check?.text??""),[u,h]=m.useState(null),[p,f]=m.useState(!1),g=async()=>{if(!o.trim())return h(s("Enter a title."));f(!0);try{const x=await window.electronAPI.bots.tasks.save({chatId:e,title:o.trim(),detail:a.trim(),check:d.trim(),...t?{id:t.id}:{}});x.ok?n(!0):h(Iu(x.error,s))}finally{f(!1)}};return i.jsx(wn,{open:!0,onOpenChange:x=>!x&&n(!1),children:i.jsxs(yn,{className:"max-w-lg",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:t?s("Edit task #{{n}}",{n:t.seq}):s("New task")})}),i.jsxs(On,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:s("Task title")}),i.jsx(Xt,{value:o,maxLength:QR,onChange:x=>r(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:s("Details")}),i.jsx(ei,{rows:4,value:a,maxLength:mg,onChange:x=>l(x.target.value)})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:s("Acceptance check (optional)")}),i.jsx(Xt,{value:d,maxLength:e2,onChange:x=>c(x.target.value)}),i.jsx("p",{className:"mt-1 text-muted-foreground text-xs",children:s("Done only when the member's tool output contains this text, e.g. a command printing ALL_TESTS_PASS.")})]}),u&&i.jsx("p",{className:"text-destructive text-sm",children:u})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsxs(ge,{size:"sm",disabled:p,onClick:()=>{g()},children:[p&&i.jsx(qt,{className:"animate-spin"}),s("Save")]})]})]})})}function jX({chat:e,onOpenConversation:t}){const{t:n}=Q(),s=ce(d=>d.delegations),o=ce(d=>d.bots),r=m.useMemo(()=>new Map(o.map(d=>[d.id,d])),[o]),a=m.useMemo(()=>JY(s,e.id),[s,e.id]),l=d=>i.jsx(Th,{record:d,retried:Qk(d,s),bots:r,onOpenConversation:t},d.id);return!a.active.length&&!a.completed.length&&!a.failed.length?i.jsx("p",{className:"text-muted-foreground text-xs",children:n("No delegations in this group yet")}):i.jsxs("div",{children:[a.active.length>0&&i.jsx(io,{title:n("In progress"),count:a.active.length,children:()=>a.active.map(l)}),a.completed.length>0&&i.jsx(io,{title:n("Completed"),count:a.completed.length,limit:Im,children:d=>a.completed.slice(0,d).map(l)}),a.failed.length>0&&i.jsx(io,{title:n("Failed · interrupted · canceled"),count:a.failed.length,limit:Im,children:d=>a.failed.slice(0,d).map(l)})]})}const _X=(e,t)=>e.workspace.kind===t.kind&&(t.kind!=="project"||e.workspace.kind==="project"&&e.workspace.projectId===t.projectId);function zD({chat:e,className:t}){const{t:n}=Q(),s=Ce(f=>f.projects),o=ce(f=>f.bots),r=ce(f=>f.upsertChat),[a,l]=m.useState(!1),[d,c]=m.useState(null),u=sj(e,s,o,n),h=[e.kind==="direct"?{input:{kind:"member-home"},label:n("Member's own workspace")}:{input:{kind:"chat-home"},label:n("Standalone workspace")},...Ku(s).map(f=>({input:{kind:"project",projectId:f.id},label:f.alias||f.name}))],p=async f=>{const g=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,workspace:f});g.ok?r(g.chat):Be({type:"error",title:_s(g.error,n)})};return i.jsxs(i.Fragment,{children:[i.jsxs(Ri,{open:a,onOpenChange:l,children:[i.jsxs(Li,{className:q("flex h-7 min-w-0 max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24 items-center gap-1.5 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground",t),title:n("Workspace"),children:[i.jsx(yd,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"truncate",children:u}),i.jsx(Vn,{className:"h-3 w-3 shrink-0 opacity-60"})]}),i.jsxs(Oi,{side:"bottom",align:"end",className:"w-64 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsxs("button",{type:"button",onClick:()=>{l(!1),window.electronAPI.bots.openWorkspace({chatId:e.id}).then(f=>{f.ok||Be({type:"error",title:_s(f.error,n)})})},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[i.jsx(ni,{className:"h-3.5 w-3.5 shrink-0"}),n("Open folder")]}),i.jsx("div",{className:"my-1 border-t"}),i.jsx("div",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Change workspace")}),i.jsx("div",{className:"max-h-64 overflow-y-auto",children:h.map(f=>{const g=_X(e,f.input);return i.jsxs("button",{type:"button",onClick:()=>{l(!1),g||c(f.input)},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:f.label}),g&&i.jsx(Un,{className:"h-3.5 w-3.5 shrink-0 text-brand"})]},f.input.kind==="project"?f.input.projectId:f.input.kind)})})]})]}),i.jsx(fs,{open:d!==null,onOpenChange:f=>!f&&c(null),title:n("Change workspace?"),description:n("Members start new conversations in the new workspace. Earlier conversations stay readable in history."),confirmLabel:n("Change"),onConfirm:()=>{const f=d;c(null),f&&p(f)}})]})}function Xo({title:e,children:t}){return i.jsxs("section",{className:"mt-5",children:[i.jsx("h4",{className:"mb-1.5 font-medium text-[11px] text-muted-foreground uppercase tracking-wide",children:e}),t]})}function Hp({label:e,value:t}){return i.jsxs("div",{className:"flex justify-between gap-3 border-b border-dashed py-1.5 text-xs",children:[i.jsx("span",{className:"shrink-0 text-muted-foreground",children:e}),i.jsx("span",{className:"min-w-0 truncate text-right",children:t})]})}async function GD(e,t){const n={};for(const s of e.members){const o=await window.electronAPI.bots.get(s);if(!o.ok)return null;n[s]=o.persona}return i2(e,t,n,new Date().toISOString())}async function NX(e,t){const n=await GD(e,t);if(!n)return!1;const s=URL.createObjectURL(new Blob([JSON.stringify(n,null,2)],{type:"application/json"})),o=document.createElement("a");return o.href=s,o.download=`${e.title||"team"}.team.json`,o.click(),URL.revokeObjectURL(s),!0}async function TX(e,t){const n=await GD(e,t),s=n&&t2(n2(n.team));return s?s2(o=>({...o,teams:o2(o.teams,s,crypto.randomUUID())})):!1}function DX({chat:e,thread:t=e,onOpenConversation:n}){const{t:s}=Q(),o=ce(T=>T.bots),r=ce(T=>T.runtime[t.id]),a=ce(T=>T.upsertChat),l=ce(T=>T.openDirect),d=Ce(T=>T.projects),c=m.useMemo(()=>new Map(o.map(T=>[T.id,T])),[o]),[u,h]=m.useState(e.title),[p,f]=m.useState(String(e.routing.maxHops)),[g,x]=m.useState(String(e.routing.maxTurnsPerBot)),[v,y]=m.useState(!1),[w,b]=m.useState("info"),_=ce(T=>T.taskFocus);m.useEffect(()=>{_?.chatId===e.id&&b("board")},[_,e.id]),m.useEffect(()=>{h(e.title),f(String(e.routing.maxHops)),x(String(e.routing.maxTurnsPerBot))},[e.title,e.routing.maxHops,e.routing.maxTurnsPerBot]);const j=async T=>{const z=await window.electronAPI.bots.updateChat({chatId:e.id,expectedVersion:e.version,...T});z.ok?a(z.chat):(Be({type:"error",title:_s(z.error,s)}),ce.getState().refreshChats())},N=e.members.map(T=>({id:T,bot:c.get(T)})),C=e.routing.muted??[],S=o.filter(T=>!T.archivedAt&&!e.members.includes(T.id)),A=T=>T?c.get(T)?.name??"?":"—",E=e.workspace.kind==="project"?d.find(T=>e.workspace.kind==="project"&&T.id===e.workspace.projectId):void 0,I=p!==String(e.routing.maxHops)||g!==String(e.routing.maxTurnsPerBot),D=[{value:"boss",label:s("Group owner replies")},{value:"smart",label:s("Smart pick")}];return i.jsxs(Wu,{value:w,onValueChange:T=>b(String(T)),className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs(Uu,{variant:"underline",className:"shrink-0 px-2 pt-2",children:[i.jsx(Ds,{value:"info",children:s("Group info")}),i.jsx(Ds,{value:"board",children:s("Task board")}),i.jsx(Ds,{value:"delegations",children:s("Delegations")}),i.jsx(Ds,{value:"routines",children:s("Routines")})]}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:[i.jsx(oo,{value:"board",children:i.jsx(wX,{chat:e,onOpenConversation:n})}),i.jsx(oo,{value:"delegations",children:i.jsx(jX,{chat:t,onOpenConversation:n})}),i.jsx(oo,{value:"routines",children:i.jsx(AD,{chatId:e.id})}),i.jsxs(oo,{value:"info",children:[i.jsx(Xt,{className:"mt-2",value:u,placeholder:s("Group name"),onChange:T=>h(T.target.value),onBlur:()=>u.trim()!==e.title&&void j({title:u.trim()}),onKeyDown:T=>T.key==="Enter"&&T.currentTarget.blur()}),i.jsxs(Xo,{title:s("Members"),children:[N.map(({id:T,bot:z})=>i.jsxs("div",{className:"group flex items-center gap-2 rounded-lg py-1.5",children:[i.jsxs("button",{type:"button",onClick:()=>{l(T)},className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(xD,{chatId:t.id,botId:T,bot:z}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[i.jsx("span",{className:"truncate",children:z?.name??s("Deleted member")}),e.bossBotId===T&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:s("Owner")}),C.includes(T)&&i.jsxs("span",{title:s("Replies only when @-mentioned by name"),className:"flex shrink-0 items-center gap-0.5 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:[i.jsx(Kb,{className:"h-2.5 w-2.5"}),s("Muted")]})]}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:z?.scope||z?.title})]})]}),i.jsxs(Hi,{children:[i.jsx(Bi,{className:"rounded p-1 text-muted-foreground opacity-0 hover:bg-muted group-hover:opacity-100 data-popup-open:opacity-100",children:i.jsx(hh,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",children:[i.jsxs(pn,{disabled:e.bossBotId===T,onClick:()=>{j({bossBotId:T})},children:[i.jsx(ij,{}),s("Make owner")]}),i.jsxs(pn,{disabled:e.bossBotId===T,onClick:()=>{j({routing:{muted:C.includes(T)?C.filter($=>$!==T):[...C,T]}})},children:[i.jsx(Kb,{}),C.includes(T)?s("Unmute"):s("Mute")]}),i.jsxs(pn,{disabled:e.bossBotId===T||e.members.length<=2,onClick:()=>{j({members:e.members.filter($=>$!==T)})},children:[i.jsx(x6,{}),s("Remove from group")]})]})]})]},T)),i.jsxs(Ri,{open:v,onOpenChange:y,children:[i.jsxs(Li,{disabled:S.length===0,className:"mt-1 flex h-7 items-center gap-1 rounded-md border px-2 text-muted-foreground text-xs hover:bg-muted hover:text-foreground disabled:opacity-50",children:[i.jsx(ds,{className:"h-3.5 w-3.5"}),s("Add member")]}),i.jsx(Oi,{side:"bottom",align:"start",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:S.map(T=>i.jsxs("button",{type:"button",onClick:()=>{y(!1),j({members:[...e.members,T.id]})},className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted",children:[i.jsx(tn,{bot:T,size:"sm"}),i.jsx("span",{className:"min-w-0 truncate",children:T.name})]},T.id))})]})]}),i.jsxs(Xo,{title:s("Reply queue"),children:[i.jsx(Hp,{label:s("Current"),value:r?.current?`${A(r.current)}(${s("relay {{n}}/{{max}}",{n:r.hops,max:e.routing.maxHops})})`:r?.routing?s("Choosing who replies…"):"—"}),i.jsx(Hp,{label:s("Waiting"),value:r?.queue.length?r.queue.map(T=>A(T)).join("、"):"—"}),i.jsx(Hp,{label:s("Per-member limit"),value:s("{{n}} replies",{n:e.routing.maxTurnsPerBot})})]}),i.jsx(Xo,{title:s("Workspace"),children:i.jsxs("div",{"data-slot":"bot-card",className:"rounded-lg border bg-card px-2.5 py-2",children:[i.jsx(zD,{chat:e,className:"w-full max-w-none"}),i.jsxs("p",{className:"mt-1.5 text-muted-foreground text-xs",children:[E?`${E.path} · `:"",s("Shared by all members")]})]})}),i.jsxs(Xo,{title:s("Routing limits"),children:[i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("Without @")}),i.jsxs(xs,{items:D,value:e.routing.mode,onValueChange:T=>{T!==e.routing.mode&&j({routing:{mode:T}})},children:[i.jsx(vs,{size:"sm",className:"w-40",children:i.jsx(bs,{})}),i.jsx(ws,{children:D.map(T=>i.jsx(ns,{value:T.value,children:T.label},T.value))})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("@ relay limit")}),i.jsx(Xt,{type:"number",min:1,max:20,value:p,onChange:T=>f(T.target.value)})]}),i.jsxs("label",{className:"space-y-1",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:s("Replies per member")}),i.jsx(Xt,{type:"number",min:1,max:10,value:g,onChange:T=>x(T.target.value)})]})]}),I&&i.jsx(ge,{size:"xs",className:"mt-2",onClick:()=>{j({routing:{maxHops:Math.round(Number(p))||e.routing.maxHops,maxTurnsPerBot:Math.round(Number(g))||e.routing.maxTurnsPerBot}})},children:s("Save")})]}),i.jsx(Xo,{title:s("Group notes"),children:i.jsx(TD,{target:{chatId:e.id},emptyText:s("No group notes yet. Group conventions and decisions are summarized here automatically after memories are organized.")})}),i.jsx(Xo,{title:s("Group memory"),children:i.jsx(ND,{spaceId:`chat:${e.id}`,emptyText:s("No group memories yet")})}),i.jsxs(Xo,{title:s("Team"),children:[i.jsxs(ge,{size:"xs",variant:"outline",onClick:()=>{NX(e,o).then(T=>T||Be({type:"error",title:s("Export failed")}))},children:[i.jsx(sd,{}),s("Export team")]}),i.jsxs(ge,{size:"xs",variant:"outline",className:"ml-1.5",onClick:()=>{TX(e,o).then(T=>Be(T?{type:"success",title:s("Saved as team template")}:{type:"error",title:s("Could not save as team template")}))},children:[i.jsx(SV,{}),s("Save as team template")]}),i.jsx("p",{className:"mt-1.5 text-muted-foreground text-xs",children:s("Group settings and member personas only. Memory, sessions, timeline, tasks, routines, models, skills and MCP are not included.")})]})]})]})]})}function IX(e,t=0){const n=new Map;for(const s of e)if(!(s.seq<=t)&&((s.kind==="human"||s.newConversation)&&n.clear(),s.kind==="bot"&&s.botId&&n.delete(s.botId),s.failure&&n.set(s.failure.botId,s.id),s.retryOf))for(const[o,r]of n)r===s.retryOf&&n.delete(o);return new Set(n.values())}function EX(e,t){const n=new RegExp(`#${t}(?!\\d)`).exec(e);if(!n)return;const s=n.index+n[0].length;return[e.slice(0,n.index),n[0],e.slice(s)]}function PX(e,t){const n=String(t),s=`${n}-`;return e.find(o=>o.key===n||o.key.startsWith(s))?.key}function AX(e){return e.earliest===void 0?"wait":e.target>=e.earliest?"scroll":e.loading?"wait":e.hasOlder?"load":"give-up"}function MX(e){return e.range===void 0||e.loading?"wait":e.range&&e.target>=e.range[0]&&e.target<=e.range[1]?"scroll":e.jumped?"give-up":"jump"}function RX(e,t){const n=[];let s=0;for(const[o,r]of t)o<s||r<=o||r>e.length||(o>s&&n.push({text:e.slice(s,o),match:!1}),n.push({text:e.slice(o,r),match:!0}),s=r);return s<e.length&&n.push({text:e.slice(s),match:!1}),n}function LX({chatId:e,bots:t}){const{t:n}=Q(),s=ce(a=>a.queue),[o,r]=m.useState(null);return s.filter(a=>a.chatId===e&&a.deliveryId).map(a=>{const l=t.get(a.botId)?.name??n("Deleted member");return i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsxs("span",{children:[l," · ",n("Queued")]}),a.canInterject&&i.jsx(ge,{size:"sm",variant:"ghost",disabled:o!==null,onClick:async()=>{if(a.deliveryId){r(a.deliveryId);try{const d=await window.electronAPI.bots.interjectQueued(e,a.deliveryId);d.ok||Be({type:"error",title:d.error})}catch{Be({type:"error",title:n("Failed to send")})}finally{r(null)}}},children:n("Insert into {{name}}’s current task",{name:l})})]},a.deliveryId)})}const OX=(e,t)=>t?e.find(n=>n.conversationId===t):void 0,zX=(e,t)=>Math.max(0,Math.floor((t-e)/1e3));function FD({since:e}){const{t}=Q(),[n,s]=m.useState(()=>Date.now());return m.useEffect(()=>{const o=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(o)},[]),i.jsx(i.Fragment,{children:t("Quiet for {{n}}s",{n:zX(e,n)})})}function HD({conversationId:e,className:t}){const n=ce(s=>OX(s.silences,e)?.since);return n===void 0?null:i.jsx("span",{className:t??"shrink-0 text-warning",children:i.jsx(FD,{since:n})})}const Hc=e=>new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),GX={smart:"Smart pick","smart:build":"Smart pick · build","smart:answer":"Smart pick · answer","smart:discuss":"Smart pick · discuss",summary:"Owner summary","wrap-up":"Owner wrap-up"};function FX({chat:e,bots:t,timeline:n,runtime:s,delegations:o,focus:r,onFocusDone:a,onLoadOlder:l,onLoadNewer:d,onLoadAround:c,onJumpLatest:u,onOpenConversation:h,onOpenLive:p}){const{t:f}=Q(),g=m.useRef(null),x=m.useRef(!0),v=m.useRef(h);v.current=h;const y=m.useCallback((le,be)=>v.current(le,be),[]),w=m.useRef(null),b=m.useRef(!1),_=n?.entries??[],j=m.useRef({chatId:e.id,loaded:_,delegations:o});j.current={chatId:e.id,loaded:_,delegations:o};const N=m.useCallback(le=>{const{chatId:be,loaded:Fe,delegations:Je}=j.current,We=d2(Fe,le);if(We!==void 0)return ce.getState().focusSeq(be,We);const et=Je.find(qe=>qe.id===le);Be({type:"info",title:et&&et.deliveredAt===void 0?f("The delegation card is posted after the delegator receives the result."):f("The delegation card is not in the loaded messages.")})},[f]),C=IX(_,e.epochSeq??0),S=n?.history,A=e.epochSeq??0,[E,I]=m.useState(!1);m.useEffect(()=>I(!1),[e.id,A]);const D=A>0&&!E&&!S,T=m.useMemo(()=>D?_.filter(le=>le.seq>=A):_,[_,D,A]),z=m.useMemo(()=>c2(T),[T]),$=()=>{D&&n?.hasOlder&&!n.loading&&!_.some(le=>le.seq<A)&&(_e(),l()),I(D)},R=m.useMemo(()=>{const le=new Map;if(!S)for(const be of z)be.kind==="entry"&&be.entry.kind==="bot"&&!be.continued&&le.set(be.entry.botId,be.entry.id);return new Set(le.values())},[z,S]),B=m.useMemo(()=>new Map(o.map(le=>[le.id,{record:le,retried:Qk(le,o)}])),[o]),H=m.useMemo(()=>rj(o,e.id),[o,e.id]),oe=m.useMemo(()=>u2(T,h2(H)),[T,H]),te=ce(le=>le.tasks[e.id]),O=H.some(le=>le.appends?.length);m.useEffect(()=>{O&&!te&&ce.getState().refreshTasks(e.id)},[O,te,e.id]);const V=({key:le,record:be,append:Fe})=>i.jsx(Th,{record:be,append:Fe,taskSeq:Fe&&te?.find(Je=>Je.id===be.taskId)?.seq,fill:!0,bots:t,onOpenConversation:h},le),J=s?.current?t.get(s.current):void 0,pe=s?.current?e.sessions[s.current]?.conversationId:void 0,fe=ce(le=>pe?le.sessions[pe]?.messages.length:void 0);m.useLayoutEffect(()=>{const le=g.current;le&&(le.scrollTop=le.scrollHeight),x.current=!0},[e.id]);const _e=()=>{const le=g.current;if(!le)return;const be=le.getBoundingClientRect().top;for(const Fe of le.querySelectorAll("[data-seq]")){const Je=Fe.getBoundingClientRect();if(!(Je.bottom<=be)){w.current={seq:Number(Fe.dataset.seq),top:Je.top-be};return}}};m.useLayoutEffect(()=>{const le=g.current;if(!le)return;const be=w.current;!n?.loading&&!n?.loadingNewer&&(w.current=null);const Je=b.current&&!S;b.current=!!S;const We=be&&le.querySelector(`[data-seq="${be.seq}"]`);if(be&&We){le.scrollTop+=We.getBoundingClientRect().top-le.getBoundingClientRect().top-be.top;return}Je&&(x.current=!0),x.current&&!S&&(le.scrollTop=le.scrollHeight)},[T,S,n?.loading,n?.loadingNewer,H.length,J?.id,fe,s?.routing]);const Ee=()=>{const le=g.current;if(!le||!n)return;const be=le.scrollHeight-le.scrollTop-le.clientHeight;x.current=be<40,w.current&&_e(),!(T.length===0||D&&(_[0]?.seq??0)<=A)&&(le.scrollTop<80&&n.hasOlder&&!n.loading&&(_e(),l()),be<80&&S&&!n.loadingNewer&&(_e(),d()))},[me,W]=m.useState(null),G=m.useRef(null),[de,X]=m.useState(null);m.useLayoutEffect(()=>{if(!r||G.current===r.nonce)return;if(D&&r.seq<A){I(!0);return}const le=T[0]?.seq,be=T.at(-1)?.seq,Fe=de?.nonce===r.nonce?de:null,Je=MX({target:r.seq,range:n?le===void 0||be===void 0?null:[le,be]:void 0,loading:!!(Fe&&!Fe.done),jumped:!!Fe?.done});if(Je!=="wait"){if(Je==="jump"){const We=r.nonce;x.current=!1,w.current=null,X({nonce:We,done:!1}),c(r.seq).finally(()=>X(et=>et?.nonce===We?{nonce:We,done:!0}:et));return}G.current=r.nonce,a?.(r.nonce),Je==="scroll"&&(x.current=!1,w.current=null,W(r.seq),g.current?.querySelector(`[data-seq="${r.seq}"]`)?.scrollIntoView({block:"center"}))}},[r,T,n===void 0,de,D]),m.useEffect(()=>{if(me===null)return;const le=window.setTimeout(()=>W(null),2500);return()=>window.clearTimeout(le)},[me]);const ie=()=>{x.current=!0,w.current=null,u()},Z=S&&n?n.lastSeq-S.sinceSeq:0;return i.jsxs("div",{className:"relative flex min-h-0 flex-1 flex-col",children:[i.jsx("div",{ref:g,onScroll:Ee,className:"min-h-0 flex-1 select-text overflow-y-auto",children:i.jsx("div",{className:"@container",children:i.jsxs("div",{"data-slot":"bot-timeline",className:q(yi,"flex flex-col gap-3 py-4"),children:[n?.loading&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(qt,{className:"h-4 w-4 animate-spin"})}),n&&!n.hasOlder&&!D&&T.length>0&&i.jsx("div",{className:"text-center text-[11px] text-muted-foreground",children:f("Beginning of the chat")}),!n&&i.jsx("div",{className:"flex justify-center py-6 text-muted-foreground",children:i.jsx(qt,{className:"h-4 w-4 animate-spin"})}),n&&T.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:f("Say something. Mention a member with @, or the group owner replies.")}),oe.head.map(V),z.map(le=>le.kind==="day"?i.jsx("div",{className:"py-1 text-center text-[11px] text-muted-foreground",children:new Date(le.at).toLocaleDateString()},le.key):i.jsxs(m.Fragment,{children:[A>0&&!S&&le.entry.seq===A&&i.jsxs("button",{type:"button",onClick:$,className:"flex items-center gap-1 self-center rounded-md px-2 py-1 text-muted-foreground text-xs hover:bg-muted hover:text-foreground",children:[D?i.jsx(bn,{className:"h-3.5 w-3.5"}):i.jsx(Vn,{className:"h-3.5 w-3.5"}),D?f("Earlier conversation · {{n}} messages",{n:A-1}):f("Collapse earlier conversation")]}),i.jsx("div",{"data-seq":le.entry.seq,className:q("-mx-2 flex flex-col rounded-lg px-2 transition-colors duration-500",me===le.entry.seq&&"bg-brand/10"),children:i.jsx(HX,{chatId:e.id,entry:le.entry,continued:le.continued,latest:R.has(le.entry.id),retryable:C.has(le.entry.id)&&e.archivedAt===void 0,retryBusy:!!(s?.current||s?.routing),bots:t,records:B,onOpenConversation:y,onLocateDelegation:N})}),oe.after.get(le.entry.id)?.map(V)]},le.key)),n?.loadingNewer&&i.jsx("div",{className:"flex justify-center py-1 text-muted-foreground",children:i.jsx(qt,{className:"h-4 w-4 animate-spin"})}),!S&&!J&&s?.routing&&i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(sS,{}),f("Choosing who replies…")]}),!S&&i.jsx(LX,{chatId:e.id,bots:t}),!S&&J&&i.jsxs("button",{type:"button",disabled:!pe,title:f("View live"),onClick:()=>pe&&p(pe,J.id),className:"-mx-2 flex gap-2.5 rounded-lg px-2 py-1 text-left hover:bg-muted/60 disabled:pointer-events-none",children:[i.jsx(tn,{bot:J,size:"sm",busy:!0}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("div",{className:"text-muted-foreground text-xs",children:[i.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:J.name}),f("Replying")]}),i.jsx(hD,{conversationId:pe,leading:i.jsx(sS,{}),trailing:i.jsxs(i.Fragment,{children:[i.jsx(HD,{conversationId:pe}),pe&&i.jsx("span",{className:"shrink-0 underline-offset-2 hover:underline",children:f("View live")})]})})]})]})]})})}),S&&i.jsxs("button",{type:"button",onClick:ie,className:"absolute bottom-4 left-1/2 z-10 inline-flex h-7 -translate-x-1/2 items-center gap-1.5 rounded-full border bg-card px-3 text-muted-foreground text-xs shadow-float transition-colors hover:text-foreground",children:[i.jsx(uh,{className:"h-3 w-3"}),Z>0?f("Back to latest · {{n}} new",{n:Z}):f("Back to latest")]})]})}function sS(){return i.jsx("span",{className:"flex gap-0.5",children:[0,1,2].map(e=>i.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-muted-foreground",style:{animationDelay:`${e*.2}s`}},e))})}const HX=m.memo(function({chatId:t,entry:n,continued:s,latest:o,bots:r,records:a,onOpenConversation:l,onLocateDelegation:d,retryable:c,retryBusy:u}){const{t:h}=Q(),[p,f]=m.useState(!1),g=async()=>{if(!p){f(!0);try{const x=await window.electronAPI.bots.retry(t,n.id);x.ok||Be({type:"error",title:h("Retry failed"),description:_s(x.error,h)})}catch{Be({type:"error",title:h("Retry failed")})}finally{f(!1)}}};switch(n.kind){case"system":return n.newConversation?i.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground text-xs",children:[i.jsx("div",{className:"h-px flex-1 bg-border"}),h("New conversation")," · ",Hc(n.at),i.jsx("div",{className:"h-px flex-1 bg-border"})]}):n.routine?i.jsx(rX,{text:n.text,target:n.routine}):i.jsxs("div",{"data-slot":"bot-notice",className:"self-center rounded-full bg-muted px-2.5 py-0.5 text-center text-muted-foreground text-xs",children:[n.text,c&&i.jsx(ge,{size:"xs",variant:"outline",className:"ml-2",disabled:u||p,onClick:g,children:h("Retry")})]});case"human":return i.jsxs("div",{className:"flex w-full flex-col items-end",children:[n.text&&i.jsx("div",{className:q(Za,"whitespace-pre-wrap break-words"),children:i.jsx(Bc,{text:n.text,bots:r})}),n.images?.length?i.jsx(Tu,{target:{chatId:t,entryId:n.id}}):null,(n.refs?.skill||n.refs?.chats?.length)&&i.jsx(WX,{refs:n.refs}),!s&&i.jsx("span",{className:"mt-0.5 text-[11px] text-muted-foreground",children:Hc(n.at)})]});case"progress":return i.jsx(VX,{chatId:t,entry:n,bots:r,failed:a.get(n.delegationId)?.record.state==="failed"});case"delegation":return i.jsx(Th,{record:a.get(n.delegationId)?.record,retried:a.get(n.delegationId)?.retried,entry:n,fill:!0,bots:r,onOpenConversation:l});case"bot":{const x=r.get(n.botId);return i.jsxs("div",{className:q("flex w-full gap-2.5",s&&"-mt-1.5"),children:[s?i.jsx("span",{className:"w-6 shrink-0"}):o?i.jsx(xD,{chatId:t,botId:n.botId,bot:x}):i.jsx(tn,{bot:x,size:"sm"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[!s&&i.jsxs("div",{className:"mb-0.5 text-muted-foreground text-xs",children:[i.jsx("span",{className:"mr-1.5 font-semibold text-foreground",children:x?.name??h("Deleted member")}),x?.title?`${x.title} · `:"",Hc(n.at),n.model&&i.jsx("span",{className:"ml-1.5 rounded-md bg-muted px-1.5 py-0.5 font-mono text-[10px]",children:n.model}),n.delegationId&&i.jsx("button",{type:"button",title:h("Locate the delegation card"),onClick:()=>n.delegationId&&d(n.delegationId),className:"ml-1.5 rounded bg-info/15 px-1 py-px text-[10px] text-info hover:bg-info/25",children:h("Delegation result")}),n.routedBy&&i.jsx("span",{title:h(n.routedBy==="summary"?"Asked to sum up after the assigned members replied":"Picked automatically because nobody was @-mentioned"),className:"ml-1.5 rounded border px-1 py-px text-[10px]",children:h(GX[n.routedBy])})]}),i.jsx("div",{className:"text-sm",children:i.jsx(js,{text:n.text})}),i.jsx(Tu,{target:{chatId:t,entryId:n.id}}),i.jsx($X,{entry:n,onOpen:()=>l(n.conversationId,x?.name??"")})]})]})}}}),BX={started:{icon:DV,className:"border-brand/50 text-brand"},blocked:{icon:gr,className:"border-warning/60 text-warning"},failed:{icon:r2,className:"border-destructive/60 text-destructive"},delivered:{icon:ag,className:"border-success/60 text-success"}};function VX({chatId:e,entry:t,bots:n,failed:s}){const{t:o}=Q(),r=ce(u=>u.openTask),a=n.get(t.botId),l=BX[t.phase==="blocked"&&s?"failed":t.phase],d=l.icon,c=EX(t.text,t.taskSeq);return i.jsxs("div",{"data-slot":"bot-progress","data-phase":t.phase,className:"flex w-full gap-2.5",children:[i.jsx(tn,{bot:a,size:"sm"}),i.jsxs("div",{className:q("flex min-w-0 max-w-lg items-start gap-1.5 rounded-md border-l-2 bg-muted/50 px-2 py-1 text-xs",l.className),children:[i.jsx(d,{"aria-hidden":!0,className:"mt-px size-3.5 shrink-0"}),i.jsxs("div",{className:"line-clamp-2 min-w-0 break-words text-muted-foreground",children:[i.jsx("span",{className:"font-medium text-foreground",children:a?.name??o("Deleted member")})," ",c?i.jsxs(i.Fragment,{children:[i.jsx(Bc,{text:c[0],bots:n}),i.jsx("button",{type:"button","aria-label":o("Open task card #{{n}}",{n:t.taskSeq}),className:"rounded px-0.5 font-medium text-foreground underline decoration-dotted underline-offset-2 hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>r(e,t.taskId),children:c[1]}),i.jsx(Bc,{text:c[2],bots:n})]}):i.jsx(Bc,{text:t.text,bots:n})]}),i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:Hc(t.at)})]})]})}function Bc({text:e,bots:t}){const n=m.useMemo(()=>{const s=[...t.values()].map(a=>a.name).sort((a,l)=>l.length-a.length),o=s.map(a=>a.replace(/[.*+?^${}()|[\]\\]/gu,"\\$&")),r=s.length?new RegExp(`(@(?:${o.join("|")}|所有人|everyone|all))`,"giu"):null;return ok(e).flatMap(a=>a.type==="file"?[a]:(r?a.text.split(r):[a.text]).map((l,d)=>l.startsWith("@")&&d%2===1?{type:"mention",part:l}:l))},[e,t]);return i.jsx(i.Fragment,{children:n.map((s,o)=>typeof s=="string"?s:s.type==="file"?i.jsxs("span",{className:q(Gx("file"),"mx-0.5 leading-4"),title:s.path,children:[i.jsx(bo,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:oj})]},o):i.jsx("span",{className:"font-medium underline underline-offset-2",children:s.part},o))})}function $X({entry:e,onOpen:t}){const{t:n}=Q(),[s,o]=m.useState(!1),[r,a]=m.useState(null);m.useEffect(()=>{if(!s||r)return;let d=!0;const c=h=>{const p=a2(h,e.text);if(d){if(!p)return a({error:n("No process recorded.")});a({steps:l2(h.slice(p.start,p.end)),exact:p.exact})}},u=ce.getState().sessions[e.conversationId]?.messages;return u?.some(h=>h.role==="assistant")?c(u):window.electronAPI.bots.sessionHistory({conversationId:e.conversationId}).then(h=>h.ok?c(h.messages):d&&a({error:h.error})),()=>{d=!1}},[s,r,e.conversationId,e.text,n]);const l=s?Vn:bn;return i.jsxs("div",{className:"mt-1",children:[i.jsxs("button",{type:"button",onClick:()=>o(d=>!d),className:"flex items-center gap-1 text-muted-foreground text-xs hover:text-foreground",children:[i.jsx(l,{className:"h-3 w-3"}),n("View process"),r&&"steps"in r&&` · ${n("{{n}} steps",{n:r.steps.length})}`]}),s&&i.jsxs("div",{"data-slot":"bot-card",className:"mt-1.5 rounded-lg border bg-card px-3 py-2 font-mono text-muted-foreground text-xs leading-relaxed",children:[!r&&i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin"}),r&&"error"in r&&i.jsx("span",{children:r.error}),r&&"steps"in r&&i.jsxs(i.Fragment,{children:[!r.exact&&i.jsx("div",{className:"mb-1 font-sans italic",children:n("Could not locate this reply; showing the latest turn.")}),r.steps.length===0&&i.jsx("div",{className:"font-sans",children:n("No tool calls in this turn.")}),r.steps.map(d=>i.jsxs("div",{className:q("truncate",d.error&&"text-destructive"),children:[d.error?"✗":"·"," ",ha(d.name,n),d.detail&&i.jsxs("span",{className:"text-foreground/80",children:[" ",d.detail]})]},d.id))]}),i.jsx("button",{type:"button",onClick:t,className:"mt-1.5 font-sans text-foreground underline-offset-2 hover:underline",children:n("Open full conversation")})]})]})}function WX({refs:e}){const{t}=Q(),n=ce(a=>a.chats),s=ce(a=>a.bots),o=Ce(a=>a.skills),r="inline-flex h-6 max-w-56 items-center gap-1 rounded-md px-1.5 text-xs";return i.jsxs("div",{className:"mt-1 flex flex-wrap justify-end gap-1.5",children:[e.skill&&i.jsxs("span",{className:q(r,"bg-info/15 text-info"),children:[i.jsx(zs,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:o.find(a=>a.id===e.skill)?.name??e.skill})]}),e.chats?.map(a=>{const l=n.find(d=>d.id===a);return i.jsxs("span",{className:q(r,"bg-muted"),title:t("Referenced chat"),children:[i.jsx(ca,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:l?ys(l,s,t):t("Unavailable chat")})]},a)})]})}function Ih({retry:e,onCancel:t}){const{t:n}=Q(),[s,o]=m.useState(()=>Date.now());m.useEffect(()=>{const a=setInterval(()=>o(Date.now()),500);return()=>clearInterval(a)},[]);const r=Math.max(0,Math.ceil((e.at+e.delayMs-s)/1e3));return i.jsxs("div",{className:"mb-1 flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-2.5 py-1.5 text-xs",children:[i.jsx(Fo,{className:"h-3.5 w-3.5 shrink-0 animate-spin text-amber-500 [animation-duration:2s]"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",title:e.error,children:[e.maxAttempts>0?n("Auto-retrying ({{attempt}}/{{max}})",{attempt:e.attempt,max:e.maxAttempts}):n("Auto-retrying ({{attempt}})",{attempt:e.attempt}),i.jsxs("span",{className:"text-muted-foreground",children:[" · ",r>0?n("retrying in {{seconds}}s",{seconds:r}):n("retrying…")," — ",e.error]})]}),t&&i.jsx("button",{type:"button",title:n("Cancel auto-retry"),onClick:t,className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]})}function BD(e){const{t}=Q(),n=ce(r=>r.delegations),s=e?p2(n,e):[],o=s.map(r=>`${r.key}:${r.at}:${r.trigger}`).join("|");return m.useMemo(()=>s.map(r=>({key:r.key,at:r.at,text:t("Run {{n}} · {{source}}",{n:r.n,source:RD(r.trigger,t)})})),[o,t])}const UX=2500;function VD({focus:e,timelineRef:t,items:n,baseIndex:s,hasMessages:o,loading:r,loadOlder:a,onDone:l}){const[d,c]=m.useState(null),u=m.useRef(null);return m.useEffect(()=>{if(!e||u.current===e.nonce)return;const h=AX({target:e.messageIndex,earliest:o?s:void 0,hasOlder:s>0,loading:r});if(h==="wait")return;if(h==="load"){a();return}u.current=e.nonce,l?.(e.nonce);const p=h==="scroll"?PX(n,e.messageIndex):void 0;p&&(window.setTimeout(()=>t.current?.scrollToKey(p),60),c({key:p,query:e.query}))},[e,n,s,o,r,a,l,t]),m.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>c(null),UX);return()=>window.clearTimeout(h)},[d]),{searchQuery:d?.query??"",activeHit:d?{key:d.key,nth:0}:null}}function $D({conversationId:e,speaker:t,emptyTitle:n,emptyDescription:s,className:o,focus:r,onFocusDone:a,turnFooter:l,controls:d,runDividers:c,dataSlot:u}){const h=ce(C=>C.sessions[e]),p=ce(C=>!!C.sessionHistoryLoading[e]),f=m.useRef(null),g=h?.status==="running",x=m.useMemo(()=>h?xr(h.messages,g,h.customEntries,void 0,{historyBaseIndex:h.historyBaseIndex,toolOutputs:h.toolOutputs,pendingApprovals:h.pendingApprovals,toolStartedAt:h.toolStartedAt,runDividers:c}):[],[h,g,c]);m.useEffect(()=>{f.current?.isAtBottom()&&f.current.pinToBottom()},[x]);const v=m.useMemo(()=>()=>{ce.getState().loadOlderSession(e)},[e]),y=VD({focus:r,timelineRef:f,items:x,baseIndex:h?.historyBaseIndex??0,hasMessages:(h?.messages.length??0)>0,loading:p,loadOlder:v,onDone:a}),{name:w,color:b,image:_}=t,j=m.useMemo(()=>({sessionId:e,canRewind:!!d,canRetry:!!d,canFork:!1,speaker:{name:w,color:b,image:_},turnFooter:l,...d?{botControls:d}:{}}),[e,w,b,_,l,d]),N=(h?.historyBaseIndex??0)>0;return i.jsx(bh.Provider,{value:j,children:i.jsxs("div",{"data-slot":u,className:q("@container flex min-h-0 flex-1 flex-col",o),children:[i.jsx(Ch,{ref:f,items:x,busy:g,loading:!1,running:g,runStartedAt:h?.runStartedAt,lastOutputAt:h?.lastOutputAt,error:h?.status==="failed"?h.error:void 0,emptyTitle:n,emptyDescription:s,historyLoading:p,hasOlder:N,olderCursor:h?.historyBaseIndex,onStartReached:N?()=>{ce.getState().loadOlderSession(e)}:void 0,searchQuery:y.searchQuery,activeHit:y.activeHit},e),h?.retry&&i.jsx("div",{className:yi,children:i.jsx(Ih,{retry:h.retry})})]})})}function KX({conversationId:e,title:t,speaker:n,emptyTitle:s,emptyDescription:o,footer:r,onClose:a}){const l=BD(e);return i.jsx(wn,{open:e!==null,onOpenChange:d=>!d&&a(),children:i.jsxs(yn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:t})}),e&&i.jsx($D,{className:"border-t",conversationId:e,speaker:n,emptyTitle:s??t,emptyDescription:o,runDividers:l}),r&&i.jsx("div",{className:yi,children:r})]})})}function Jx({conversationId:e,title:t,speaker:n,focus:s,turnFooter:o,read:r,botSession:a=!0,onClose:l}){const{t:d}=Q(),[c,u]=m.useState(null),[h,p]=m.useState(),[f,g]=m.useState(!1),x=m.useRef(!1),v=m.useRef(null),y=m.useCallback(I=>r?r(I):window.electronAPI.bots.sessionHistory({conversationId:e??"",...I!==void 0?{beforeIndex:I}:{}}),[e,r]);m.useEffect(()=>{if(u(null),p(void 0),!e)return;let I=!0;return y().then(D=>{I&&(D.ok?u({messages:D.messages,baseIndex:D.baseIndex}):p(D.code==="not-found"?d("This conversation has no history yet."):D.error))}),()=>{I=!1}},[e,y,d]);const w=m.useCallback(async()=>{if(!(!e||!c||c.baseIndex<=0||x.current)){x.current=!0,g(!0);try{const I=await y(c.baseIndex);I.ok&&I.baseIndex+I.messages.length===c.baseIndex&&u({messages:[...I.messages,...c.messages],baseIndex:I.baseIndex})}finally{x.current=!1,g(!1)}}},[e,y,c]),b=BD(e),_=m.useMemo(()=>c?xr(c.messages,!1,[],void 0,{historyBaseIndex:c.baseIndex,runDividers:b}):[],[c,b]),j=m.useCallback(()=>{w()},[w]),N=VD({focus:s,timelineRef:v,items:_,baseIndex:c?.baseIndex??0,hasMessages:!!c?.messages.length,loading:f||c===null,loadOlder:j}),C=n?.name,S=n?.color,A=n?.image,E=m.useMemo(()=>({sessionId:e,canRewind:!1,canRetry:!1,botSession:a,speaker:C&&S?{name:C,color:S,image:A}:void 0,turnFooter:o}),[a,e,C,S,A,o]);return i.jsx(wn,{open:e!==null,onOpenChange:I=>!I&&l(),children:i.jsxs(yn,{className:"flex h-[80vh] max-w-3xl flex-col",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:t})}),i.jsx(bh.Provider,{value:E,children:i.jsx("div",{className:"@container flex min-h-0 flex-1 flex-col border-t",children:h?i.jsx("p",{className:"p-6 text-muted-foreground text-sm",children:h}):i.jsx(Ch,{ref:v,items:_,busy:c===null,loading:c===null,running:!1,emptyTitle:t,hasOlder:!!(c&&c.baseIndex>0),historyLoading:f,olderCursor:c?.baseIndex,onStartReached:c&&c.baseIndex>0?()=>{w()}:void 0,searchQuery:N.searchQuery,activeHit:N.activeHit})})})]})})}function Oo(e,t,n=Date.now()){const s=new Intl.RelativeTimeFormat(t,{numeric:"auto"}),o=e-n,r=Math.abs(o);return r<6e4?s.format(0,"second"):r<36e5?s.format(Math.trunc(o/6e4),"minute"):r<864e5?s.format(Math.trunc(o/36e5),"hour"):r<30*864e5?s.format(Math.trunc(o/864e5),"day"):r<365*864e5?s.format(Math.trunc(o/(30*864e5)),"month"):s.format(Math.trunc(o/(365*864e5)),"year")}const Em="flex h-7 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50";function qX({group:e,thread:t}){const{t:n}=Q(),s=ce(S=>S.chats),o=ce(S=>S.sessions),r=ce(S=>S.timelines),a=ce(S=>S.queue),l=ce(S=>S.reads),d=ce(S=>S.bots),[c,u]=m.useState(!1),[h,p]=m.useState(null),[f,g]=m.useState(null),x=e.archivedAt!==void 0,v=m.useMemo(()=>Object.fromEntries(d.map(S=>[S.id,S.name])),[d]),y=S=>S.threadTitle??(S.parentId?n("New topic"):n("Main topic")),w=J6(s,e).map(S=>{const A=xg(S,{sessions:o,timeline:r[S.id],queue:a,names:v});return{id:S.id,title:y(S),preview:A.preview,activityAt:Math.max(A.activityAt,S.createdAt),unread:S.id!==t.id&&Ya(A.marker,l[A.key]),running:A.running,canRename:!x,canDelete:!!S.parentId}}),b=gN(w,{currentId:t.id,rootId:e.id}),_=w.length-b.length,j=S=>ce.getState().openThread(e.id,S),N=async()=>{await ce.getState().createThread(e.id)||Be({type:"error",title:n("Could not create topic")})},C=async S=>{const A=await window.electronAPI.bots.deleteThread(S);A.ok||Be({type:"error",title:_s(A.error,n)}),ce.getState().refreshChats()};return i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{children:[i.jsxs(Bi,{className:q(Em,"max-w-56 @max-[28rem]:max-w-32 @max-[21rem]:max-w-24"),children:[i.jsx("span",{className:"truncate",children:y(t)}),w.some(S=>S.unread)&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),i.jsx(Vn,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Vi,{align:"end",className:"w-72",children:[i.jsxs(vg,{children:[i.jsx(bg,{children:n("Topics")}),b.map(S=>i.jsxs(pn,{onClick:()=>j(S.id),children:[i.jsx(Un,{className:q(S.id!==t.id&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:S.title}),i.jsx(Qx,{entry:S})]},S.id))]}),i.jsx(va,{}),_>0&&i.jsxs(pn,{onClick:()=>u(!0),children:[i.jsx(bx,{}),n("All topics ({{n}})",{n:w.length})]}),i.jsxs(pn,{disabled:x,onClick:()=>{N()},children:[i.jsx(Ro,{}),n("New topic")]}),i.jsxs(pn,{disabled:x,onClick:()=>p({id:t.id,title:y(t)}),children:[i.jsx(Fs,{}),n("Rename topic")]}),t.parentId&&i.jsxs(pn,{variant:"destructive",onClick:()=>g(t.id),children:[i.jsx(Gs,{}),n("Delete topic")]})]})]}),i.jsxs("button",{type:"button",disabled:x,onClick:()=>{N()},className:q(Em,"shrink-0"),title:n("New topic"),"aria-label":n("New topic"),children:[i.jsx(Ro,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New topic")})]}),c&&i.jsx(WD,{heading:n("Topics"),placeholder:n("Search topics..."),empty:n("No matching topics"),filters:!0,entries:w,currentId:t.id,onClose:()=>u(!1),onOpen:S=>{j(S),u(!1)},onRename:S=>p({id:S.id,title:S.title}),onDelete:S=>g(S.id)}),i.jsx(fs,{open:f!==null,onOpenChange:S=>!S&&g(null),title:n("Delete this topic?"),description:n("Its messages and member sessions are removed; replies in progress are stopped. Group notes, memory and the task board stay."),confirmLabel:n("Delete"),onConfirm:()=>f&&void C(f),zIndexLevel:c?"nested":"base"}),h!==null&&i.jsx(YX,{initial:h.title,nested:c,onClose:()=>p(null),onSave:async S=>{const A=await window.electronAPI.bots.renameThread(h.id,S);if(!A.ok){Be({type:"error",title:_s(A.error,n)});return}ce.getState().upsertChat(A.chat),p(null)}})]})}function Qx({entry:e}){const{locale:t}=Q();return i.jsxs(i.Fragment,{children:[e.running&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-warning"}),e.unread&&i.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-info"}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Oo(e.activityAt,t)})]})}function WD({heading:e,placeholder:t,empty:n,filters:s=!1,entries:o,currentId:r,onClose:a,onOpen:l,onRename:d,onDelete:c}){const{t:u}=Q(),[h,p]=m.useState(""),[f,g]=m.useState("all"),x=rw(o,h,f),v=w=>rw(o,"",w).length,y="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100";return i.jsx(wn,{open:!0,onOpenChange:w=>!w&&a(),children:i.jsxs(yn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(Sn,{children:[i.jsxs(Cn,{className:"flex items-baseline gap-2",children:[e,i.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:o.length})]}),i.jsxs(qu,{"data-size":"sm",className:"mt-1",children:[i.jsx(Yu,{children:i.jsx(ti,{})}),i.jsx(Xu,{autoFocus:!0,value:h,placeholder:t,onChange:w=>p(w.target.value)})]}),s&&i.jsx(Wu,{value:f,onValueChange:w=>g(w),children:i.jsxs(Uu,{children:[i.jsx(Ds,{value:"all",children:u("All")}),i.jsxs(Ds,{value:"unread",children:[u("Unread"),v("unread")>0&&i.jsx("span",{className:"tabular-nums",children:v("unread")})]}),i.jsxs(Ds,{value:"running",children:[u("In progress"),v("running")>0&&i.jsx("span",{className:"tabular-nums",children:v("running")})]})]})})]}),i.jsxs(On,{className:"flex flex-col gap-y-0.5 border-t pt-3!",children:[x.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:n}),x.map(w=>i.jsxs("div",{className:"group flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[i.jsxs("button",{type:"button",onClick:()=>l(w.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[i.jsx(Un,{className:q("h-3.5 w-3.5 shrink-0",w.id!==r&&"invisible")}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm",children:w.title}),w.preview&&i.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:w.preview})]}),i.jsx(Qx,{entry:w})]}),d&&w.canRename&&i.jsx("button",{type:"button",className:y,onClick:()=>d(w),title:u("Rename topic"),"aria-label":u("Rename topic"),children:i.jsx(Fs,{className:"h-3.5 w-3.5"})}),c&&w.canDelete?i.jsx("button",{type:"button",className:q(y,"hover:text-destructive"),onClick:()=>c(w),title:u("Delete topic"),"aria-label":u("Delete topic"),children:i.jsx(Gs,{className:"h-3.5 w-3.5"})}):c?i.jsx("span",{className:"w-5.5 shrink-0","aria-hidden":!0}):null]},w.id))]})]})})}function YX({initial:e,nested:t,onClose:n,onSave:s}){const{t:o}=Q(),[r,a]=m.useState(e),l=()=>{r.trim()&&s(r.trim())};return i.jsx(wn,{open:!0,onOpenChange:d=>!d&&n(),children:i.jsxs(yn,{className:"max-w-sm",zIndexLevel:t?"nested":"base",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:o("Rename topic")})}),i.jsx(On,{children:i.jsx(Xt,{value:r,autoFocus:!0,maxLength:80,onChange:d=>a(d.target.value),onKeyDown:d=>d.key==="Enter"&&l()})}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:n,children:o("Cancel")}),i.jsx(ge,{size:"sm",disabled:!r.trim(),onClick:l,children:o("Save")})]})]})})}function XX({chat:e,botId:t,running:n,onView:s}){const{t:o}=Q(),[r,a]=m.useState([]),[l,d]=m.useState(!1),[c,u]=m.useState(null),h=e.sessions[t]?.conversationId,p=m.useCallback(()=>{window.electronAPI.bots.chatSessions(e.id).then(b=>{b.ok&&a(b.sessions.filter(_=>_.botId===t))})},[e.id,t]);m.useEffect(p,[p,h,n]);const f=r.map(b=>{const _=b.conversationId===h;return{id:b.conversationId,title:b.title??o(_?"New conversation":"Untitled conversation"),preview:_||b.resumable?"":o("Workspace changed; view only"),activityAt:b.activityAt??(_?Date.now():0),unread:!1,running:_&&n,resumable:b.resumable}}),g=gN(f,{currentId:h??"",rootId:h??""}),x=f.length-g.length,v=f.find(b=>b.id===h)?.title??o("New conversation"),y=async b=>{const _=await window.electronAPI.bots.switchSession(e.id,b);_.ok||Be({type:"error",title:_s(_.error,o)}),await ce.getState().refreshChats(),p()},w=b=>{const _=f.find(j=>j.id===b);!_||b===h||(_.resumable?n?u(b):y(b):s(b,_.title))};return f.length<2?null:i.jsxs(i.Fragment,{children:[i.jsxs(Hi,{onOpenChange:b=>b&&p(),children:[i.jsxs(Bi,{className:q(Em,"max-w-56"),children:[i.jsx("span",{className:"truncate",children:v}),i.jsx(Vn,{className:"h-3.5 w-3.5 shrink-0"})]}),i.jsxs(Vi,{align:"end",className:"w-72",children:[i.jsxs(vg,{children:[i.jsx(bg,{children:o("Conversations")}),g.map(b=>i.jsxs(pn,{onClick:()=>w(b.id),children:[i.jsx(Un,{className:q(b.id!==h&&"invisible")}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:b.title}),!b.resumable&&b.id!==h&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:o("Read-only")}),i.jsx(Qx,{entry:b})]},b.id))]}),x>0&&i.jsxs(i.Fragment,{children:[i.jsx(va,{}),i.jsxs(pn,{onClick:()=>d(!0),children:[i.jsx(bx,{}),o("All conversations ({{n}})",{n:f.length})]})]})]})]}),l&&i.jsx(WD,{heading:o("Conversations"),placeholder:o("Search conversations..."),empty:o("No matching conversations"),entries:f,currentId:h??"",onClose:()=>d(!1),onOpen:b=>{d(!1),w(b)}}),i.jsx(fs,{open:c!==null,onOpenChange:b=>!b&&u(null),title:o("Switch conversation?"),description:o("The reply in progress will be stopped."),confirmLabel:o("Switch"),onConfirm:()=>c&&void y(c)})]})}function UD(e){const{t}=Q(),n=wa(),s=Ce(d=>d.virtualModels);if(!e?.engine)return t("Default model");const{providerId:o,modelId:r}=e.engine,a=hj(s,e.engine);return a?a.name:n.find(d=>d.id===o)?.models.find(d=>d.id===r)?.label??r}function ZX({chat:e,group:t=e}){const{t:n}=Q(),s=ce(ke=>ke.bots),o=ce(ke=>ke.chats),r=ce(ke=>ke.sessions),a=ce(ke=>ke.queue),l=ce(ke=>ke.delegations),d=ce(ke=>ke.timelines[e.id]),c=ce(ke=>ke.runtime[e.id]),u=ce(ke=>ke.markRead),h=ce(ke=>ke.panelOpen),p=ce(ke=>ke.panelTab),f=ce(ke=>ke.browserTabs[t.id]?.tabs.length??0),g=ce(ke=>ke.panelWidth),x=Ce(ke=>ke.skills),v=Ce(ke=>ke.voiceInputEnabled),y=Ce(ke=>ke.voiceModel),{status:w}=aj(v),b=v&&w?.state!=="unsupported"&&w?.models.find(ke=>ke.id===y)?.state==="ready",[_,j]=m.useState(!1),[N,C]=m.useState(0),S=ba(),A=m.useRef(null);m.useEffect(()=>{const ke=A.current?.parentElement;if(!ke)return;const ut=()=>C(ke.clientWidth);ut();const ft=new ResizeObserver(ut);return ft.observe(ke),()=>ft.disconnect()},[]);const E=S?N:uj(g,N),I=h?E:0,D=m.useCallback(ke=>{const ut=A.current?.parentElement;ut&&ce.getState().nudgePanelWidth(-ke,ut.clientWidth)},[]),[T,z]=m.useState(null),[$,R]=m.useState(),[B,H]=m.useState(null),oe=ce(ke=>ke.focus?.chatId===e.id?ke.focus:null),te=ce(ke=>ke.clearFocus),O=m.useMemo(()=>new Map(s.map(ke=>[ke.id,ke])),[s]),V=m.useMemo(()=>Object.fromEntries(s.map(ke=>[ke.id,ke.name])),[s]),J=e.members.map(ke=>O.get(ke)).filter(ke=>!!ke),pe=J.map(ke=>`${ke.id}:${ke.skillIds.join(",")}`).join("|"),fe=m.useMemo(()=>x.flatMap(ke=>{const ut=J.filter(ft=>ft.skillIds.includes(ke.id)).map(ft=>ft.id);return ut.length?[{id:ke.id,name:ke.name,description:ke.description,owners:ut}]:[]}),[x,pe]),_e=m.useMemo(()=>o.filter(ke=>ke.id!==t.id&&!ke.parentId&&ke.archivedAt===void 0).map(ke=>({id:ke.id,title:ys(ke,s,n),kind:ke.kind})),[o,t.id,s,n]),Ee=xg(e,{sessions:r,timeline:d,queue:a,names:V}),me=ce(ke=>ke.reads[Ee.key]),W=e.kind==="group"?f2(d,me):Ee.marker,G=m.useMemo(()=>l.filter(ke=>ke.chatId===e.id),[l,e.id]),de=m.useMemo(()=>lj(r,dj(o,l),e.id),[r,o,l,e.id]),ie=T?(ke=>{const ut=G.find(wt=>wt.childConversationId===ke);if(ut)return O.get(ut.targetBotId);const ft=Object.entries(e.sessions).find(([,wt])=>wt.conversationId===ke)?.[0],ze=d?.entries.find(wt=>wt.kind==="bot"&&wt.conversationId===ke);return O.get(ft??(ze?.kind==="bot"?ze.botId:e.kind==="direct"?e.members[0]:""))})(T.id):void 0,Z=B?O.get(B.botId):void 0,le=B?de.filter(ke=>ke.conversationId===B.id):[],be=B?.title??Z?.name??n("Deleted member"),Fe=B&&l.find(ke=>ke.childConversationId===B.id)?.state==="queued",Je=m.useCallback((ke,ut)=>{const ft=m2(ce.getState().delegations,ke);ft?(ce.getState().sessions[ke]||ce.getState().trackSession(ke),H({id:ke,botId:ft.botId,title:ut})):z({id:ke,title:ut})},[]);m.useEffect(()=>{u(Ee.key,W)},[u,Ee.key,W]),m.useEffect(()=>{if(e.kind==="group"){const ke=ce.getState();ke.timelines[e.id]?.history&&ke.focus?.chatId!==e.id?ke.jumpLatest(e.id):ke.loadLatest(e.id),ce.getState().refreshRuntime(e.id)}},[e.id,e.kind]);const We=e.kind==="direct"?J[0]:void 0,et=We?e.sessions[We.id]?.conversationId:void 0,qe=oe?.locator,Lt=oe&&qe?.kind==="session"&&qe.conversationId===et?{messageIndex:qe.messageIndex,query:oe.query,nonce:oe.nonce}:void 0,Bt=oe&&qe?.kind==="timeline"?{seq:qe.seq,query:oe.query,nonce:oe.nonce}:void 0;m.useEffect(()=>{oe?.locator.kind==="session"&&oe.locator.conversationId!==et&&(z({id:oe.locator.conversationId,title:n("History")}),R({messageIndex:oe.locator.messageIndex,query:oe.query,nonce:oe.nonce}),te(oe.nonce))},[oe,et,te,n]);const Mt=T?.id,ne=m.useCallback(ke=>e.kind==="direct"&&Mt?i.jsx(Tu,{target:{chatId:e.id,conversationId:Mt,messageIndex:ke}}):null,[e.id,e.kind,Mt]),se=e.archivedAt!==void 0,He=c?.current?O.get(c.current):void 0,kt=(()=>{if(se)return n("This chat is archived. Restore it before sending.");if(e.kind==="group"){const ke=e.routing.mode==="smart"?n("Without @, the best-fit member is picked to reply"):n("Without @, the group owner replies");return He?`${ke} · ${n("{{name}} is replying; new messages are routed after they finish",{name:He.name})}`:ke}return Ee.running&&We?n("{{name}} is working; your message joins the current turn",{name:We.name}):null})(),st=async({text:ke,images:ut,...ft})=>{const ze=await ce.getState().send(e.id,ke,ut,ft);return ze.ok?(ze.queued&&Be({type:"info",title:n("Queued until a session slot frees up")}),ce.getState().timelines[e.id]?.history&&ce.getState().jumpLatest(e.id),!0):(Be({type:"error",title:n("Message not sent"),description:_s(ze.error,n)}),!1)};return i.jsxs("div",{className:"relative flex min-h-0 min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"@container flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[We?i.jsx(tn,{bot:We,busy:Ee.running}):i.jsx(il,{bots:J,busy:Ee.running}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-semibold text-sm",children:ys(e,s,n)}),i.jsx("div",{className:"truncate text-muted-foreground text-xs",children:We?i.jsx(QX,{bot:We,running:Ee.running,queued:Ee.queued,conversationId:e.sessions[We.id]?.conversationId}):n("{{n}} members · Owner {{name}}",{n:J.length,name:O.get(e.bossBotId??"")?.name??"—"})})]}),i.jsx("div",{className:"flex-1"}),i.jsx(zD,{chat:t}),We?i.jsxs(i.Fragment,{children:[i.jsx(XX,{chat:e,botId:We.id,running:Ee.running,onView:(ke,ut)=>z({id:ke,title:ut})}),i.jsxs("button",{type:"button",disabled:se,onClick:()=>{window.electronAPI.bots.newSession(e.id).then(ke=>{ke.ok?ce.getState().refreshChats():Be({type:"error",title:_s(ke.error,n)})})},className:"flex h-7 shrink-0 items-center gap-1 whitespace-nowrap rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",title:n("New conversation"),"aria-label":n("New conversation"),children:[i.jsx(Ro,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"@min-[28rem]:inline hidden",children:n("New conversation")})]})]}):i.jsx(qX,{group:t,thread:e})]}),We?i.jsxs(i.Fragment,{children:[i.jsx(JX,{items:rj(G,e.id),bots:O,onOpenConversation:Je}),i.jsx(tZ,{chat:e,bot:We,focus:Lt,onFocusDone:te})]}):i.jsx(FX,{chat:e,bots:O,timeline:d,runtime:c,delegations:G,focus:Bt,onFocusDone:te,onLoadOlder:()=>{ce.getState().loadOlder(e.id)},onLoadNewer:()=>{ce.getState().loadNewer(e.id)},onLoadAround:ke=>ce.getState().loadAround(e.id,ke),onJumpLatest:()=>{ce.getState().jumpLatest(e.id)},onOpenConversation:Je,onOpenLive:(ke,ut)=>H({id:ke,botId:ut,title:O.get(ut)?.name??n("Deleted member")})}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:q(yi,"pb-4"),children:[We&&(Ee.running||Ee.queued)&&i.jsx(hD,{conversationId:e.sessions[We.id]?.conversationId,className:"mb-2 rounded-lg border bg-muted/30 px-3 py-2"}),i.jsx(iS,{items:de,bots:O,showNames:e.kind==="group"}),e.kind==="group"&&i.jsx(DY,{chatId:e.id,memberIds:e.members,bots:O,onOpenLive:(ke,ut)=>H({id:ke,botId:ut,title:O.get(ut)?.name??n("Deleted member")})}),i.jsx(mY,{chatId:e.id,placeholder:We?n("Message {{name}}…",{name:We.name}):n("@ a member, or just say it…"),members:e.kind==="group"?J:void 0,chatOptions:_e,skills:fe,voice:b?$T:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,running:Ee.running||!!(c?.current||c?.routing),disabled:se,hint:kt,toolbar:We?i.jsx(eZ,{bot:We}):null,onSend:st,onStop:()=>{ce.getState().stop(e.id)}},e.id)]})})]}),h&&!S&&i.jsx(wu,{onResize:D,onResizingChange:j}),i.jsx(Ms.aside,{ref:A,initial:!1,animate:{width:I},style:S?void 0:{maxWidth:`max(0px, calc(100% - ${cj+yg}px))`},transition:VT({skip:_,cover:S,targetW:I}),className:q("flex min-h-0 shrink-0 flex-col overflow-hidden bg-background",S?"absolute inset-y-0 right-0 z-10":"relative"),children:i.jsxs("div",{className:q("flex h-full min-h-0 flex-col",!h&&"invisible"),style:{width:E},children:[i.jsx("div",{className:"flex h-10 shrink-0 items-center gap-1 border-b px-2",children:["info","browser"].map(ke=>i.jsxs("button",{type:"button",onClick:()=>ce.getState().setPanelTab(ke),className:q("flex h-7 items-center gap-1.5 rounded-md px-2.5 text-xs transition-colors",p===ke?"bg-brand/10 font-medium text-foreground dark:bg-brand/15":"text-muted-foreground hover:text-foreground"),children:[ke==="info"?i.jsx(wg,{className:"h-3.5 w-3.5"}):i.jsx(fo,{className:"h-3.5 w-3.5"}),n(ke==="info"?We?"Member":"Group info":"Browser"),ke==="browser"&&f>0&&i.jsx("span",{className:"text-muted-foreground tabular-nums",children:f})]},ke))}),p==="browser"?i.jsx(_q,{chatId:t.id,visible:h}):We?i.jsx(mX,{botId:We.id,chat:e,onOpenHistory:Je}):i.jsx(DX,{chat:t,thread:e,onOpenConversation:Je})]})}),i.jsx(Jx,{conversationId:T?.id??null,title:T?.title??"",speaker:ie?{name:ie.name,color:ie.avatar.color,image:Yc(ie)}:void 0,focus:$,turnFooter:ne,onClose:()=>{z(null),R(void 0)}}),i.jsx(KX,{conversationId:B?.id??null,title:be,speaker:{name:Z?.name??be,color:Z?.avatar.color??"#64748b",image:Z?Yc(Z):void 0},emptyTitle:Fe?n("Queued and has not started yet"):void 0,emptyDescription:Fe?"":void 0,footer:Z&&le.length>0?i.jsx(iS,{items:le,bots:O,showNames:!1}):void 0,onClose:()=>H(null)})]})}function JX({items:e,bots:t,onOpenConversation:n}){const{t:s}=Q();return e.length===0?null:i.jsx("div",{className:"shrink-0 border-b bg-muted/30",children:i.jsxs("div",{className:q(yi,"py-2"),children:[i.jsx("div",{className:"mb-1.5 text-muted-foreground text-xs",children:s("Delegations in progress · {{n}}",{n:e.length})}),i.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto",children:e.map(o=>i.jsx(Th,{record:o,bots:t,onOpenConversation:n},o.id))})]})})}function QX({bot:e,running:t,queued:n,conversationId:s}){const{t:o}=Q(),r=UD(e),a=o(t?"Working":n?"Queued":"Idle");return i.jsxs(i.Fragment,{children:[[e.title,r,a].filter(Boolean).join(" · "),t&&i.jsx(HD,{conversationId:s,className:"ml-1.5 text-warning"})]})}function eZ({bot:e}){const{t}=Q(),n=UD(e),s=Pl[e.approvalMode];return i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"flex h-6 min-w-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[i.jsx(zs,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-32 truncate",children:n})]}),i.jsxs("span",{className:"flex h-6 shrink-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs",children:[i.jsx(Bu,{className:"h-3 w-3"}),t(s.labelKey)]})]})}function tZ({chat:e,bot:t,focus:n,onFocusDone:s}){const{t:o}=Q(),r=e.sessions[t.id]?.conversationId,a=e.archivedAt!==void 0,l=m.useMemo(()=>{if(a||!r)return;const c=u=>{u.ok||Be({type:"error",title:_s(u.error??"unavailable",o)})};return{subscribe:ce.subscribe,projection:()=>ce.getState().sessions[r],rewind:(u,h)=>{ce.getState().rewind(e.id,u,h).then(c)},retry:()=>{ce.getState().retry(e.id).then(c)}}},[e.id,r,a,o]),d=m.useCallback(c=>r?i.jsx(Tu,{target:{chatId:e.id,conversationId:r,messageIndex:c}}):null,[e.id,r]);return r?i.jsx($D,{conversationId:r,speaker:{name:t.name,color:t.avatar.color,image:Yc(t)},emptyTitle:o("Say hi to {{name}}",{name:t.name}),focus:n,onFocusDone:s,turnFooter:d,controls:l,dataSlot:"bot-timeline"}):i.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center",children:[i.jsx(tn,{bot:t,size:"lg"}),i.jsx("p",{className:"font-medium text-lg",children:t.name}),i.jsx("p",{className:"max-w-sm text-muted-foreground text-sm",children:t.scope||t.title})]})}function iS({items:e,bots:t,showNames:n}){const{t:s}=Q(),o=new Map;for(const r of e)o.set(r.conversationId,[...o.get(r.conversationId)??[],r]);return i.jsx(i.Fragment,{children:[...o.entries()].map(([r,a])=>{const l=t.get(a[0].botId),d=a[0].delegation,c=l?.name??s("Deleted member"),u=a.flatMap(p=>p.kind==="approval"?[p.request]:[]),h=a.flatMap(p=>p.kind==="ask"?[p.request]:[]);return i.jsxs("div",{"data-pending-conversation":r,children:[(n||d)&&i.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:l,size:"xs"}),d?s("{{name}} (on behalf of {{owner}}) needs you",{name:c,owner:t.get(d.parentBotId)?.name??s("Deleted member")}):s("{{name}} needs you",{name:c})]}),i.jsx(Bl,{approvals:u,onRespond:(p,f)=>{window.electronAPI.agent.respondApproval(r,p,f)}}),i.jsx(mh,{asks:h,onAnswer:(p,f)=>{window.electronAPI.agent.respondAsk(r,p,f)}})]},r)})})}function nZ(e,t){const n={pending:[],budgets:[],routines:[],silences:[],interrupted:[],blocked:[],count:0};for(const s of g2(e)){const o={chatId:s.chatId??"",botId:s.botId??"",...s.delegationId&&s.ownerBotId?{delegation:{id:s.delegationId,parentBotId:s.ownerBotId}}:{}};if(s.kind==="approval"&&s.approval&&s.conversationId)n.pending.push({kind:"approval",conversationId:s.conversationId,request:s.approval,...o});else if(s.kind==="ask"&&s.ask&&s.conversationId)n.pending.push({kind:"ask",conversationId:s.conversationId,request:s.ask,...o});else if(s.kind==="budget")n.budgets.push(s);else if(s.kind==="silence")n.silences.push(s);else if(s.kind==="routine-draft"||s.kind==="routine-blocked"){const r=t.routines.find(a=>a.id===s.routine?.id&&a.botId===s.routine.botId);r&&n.routines.push({kind:s.kind==="routine-draft"?"approval":"blocked",routine:r})}else if(s.kind==="delegation-interrupted"||s.kind==="task-blocked"){const r=t.delegations.find(a=>a.id===s.delegationId);r&&n[s.kind==="task-blocked"?"blocked":"interrupted"].push({item:s,record:r})}}return n.count=n.pending.length+n.budgets.length+n.routines.length+n.silences.length+n.interrupted.length+n.blocked.length,n}function sZ({write:e,bot:t,chatName:n}){const{t:s}=Q(),o=x2(u=>u.review),[r,a]=m.useState(!1),[l,d]=m.useState(null),c=u=>{a(!0),d(null),o(e.id,u).then(h=>{h.ok||d(h.error??s("Failed"))}).finally(()=>a(!1))};return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:t?.name??s("Deleted member")}),n&&i.jsxs("span",{children:["· ",n]}),i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:s("Memory write")}),i.jsxs("span",{children:["→ ",e.spaceLabel]}),e.redacted&&i.jsxs("span",{children:["· ",s("Secrets redacted")]})]}),e.title&&i.jsx("div",{className:"mt-2 font-medium text-sm",children:e.title}),i.jsx("pre",{className:"mt-1 max-h-32 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1.5 text-xs",children:e.content}),l&&i.jsx("div",{className:"mt-1 text-destructive text-xs",children:l}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"outline",disabled:r,onClick:()=>c("reject"),children:s("Reject")}),i.jsx(ge,{size:"xs",disabled:r,onClick:()=>c("approve"),children:s("Approve")})]})]})}function iZ(){const{t:e}=Q(),t=ce(p=>p.inbox),n=ce(p=>p.chats),s=ce(p=>p.bots),o=ce(p=>p.delegations),r=ce(p=>p.routines),[a,l]=m.useState(null),d=m.useMemo(()=>nZ(t,{routines:r,delegations:o}),[t,r,o]),c=v2(),u=m.useMemo(()=>new Map(s.map(p=>[p.id,p])),[s]),h=p=>{const f=n.find(g=>g.id===p);return f?ys(f,s,e):""};return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"flex h-[52px] shrink-0 items-center gap-2.5 border-b px-4",children:[i.jsx("div",{className:"font-semibold text-sm",children:e("Inbox")}),i.jsx("div",{className:"text-muted-foreground text-xs",children:e("Everything members are waiting on you for")})]}),i.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:i.jsxs("div",{className:"mx-auto w-full max-w-2xl space-y-2.5 px-6 py-4",children:[d.count===0&&c.length===0&&i.jsxs("div",{className:"flex flex-col items-center gap-2 py-16 text-muted-foreground",children:[i.jsx(vx,{className:"h-6 w-6"}),i.jsx("p",{className:"text-sm",children:e("Nothing needs your attention")})]}),d.pending.map(p=>i.jsx(dZ,{item:p,bot:u.get(p.botId),owner:p.delegation?u.get(p.delegation.parentBotId):void 0,chatName:h(p.chatId)},`${p.conversationId}:${p.request.requestId}`)),d.budgets.map(p=>i.jsx(rZ,{item:p,bot:u.get(p.botId??"")},p.key)),c.map(p=>i.jsx(sZ,{write:p,bot:p.botId?u.get(p.botId):void 0,chatName:h(p.chatId)},p.id)),d.routines.map(p=>i.jsx(oX,{alert:p},p.routine.id)),d.silences.map(p=>i.jsx(oZ,{item:p,bot:u.get(p.botId??""),chatName:h(p.chatId)},p.key)),d.blocked.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Stuck delegated tasks")}),d.blocked.map(({item:p,record:f})=>i.jsx(aZ,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId)},p.key)),d.interrupted.length>0&&i.jsx("div",{className:"pt-3 font-medium text-muted-foreground text-xs",children:e("Interrupted delegations")}),d.interrupted.map(({item:p,record:f})=>i.jsx(lZ,{inboxKey:p.key,record:f,bots:u,chatName:h(f.chatId),onOpen:g=>l({id:f.childConversationId,title:g,bot:u.get(f.targetBotId)})},p.key))]})}),i.jsx(Jx,{conversationId:a?.id??null,title:a?.title??"",speaker:a?.bot?{name:a.bot.name,color:a.bot.avatar.color}:void 0,onClose:()=>l(null)})]})}function oZ({item:e,bot:t,chatName:n}){const{t:s}=Q(),o=ce(l=>l.setView),r=ce(l=>l.dismissInbox),a=t?.name??s("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm",busy:!0}),i.jsx("span",{className:"text-foreground",children:a}),n&&i.jsxs("span",{children:["· ",n]}),e.delegationId&&i.jsxs("span",{children:["· ",s("Delegation")]}),i.jsx("span",{className:"rounded bg-warning/20 px-1.5 text-[11px] text-warning",children:i.jsx(FD,{since:e.since??e.createdAt})})]}),i.jsx("div",{className:"mt-2 text-sm",children:s("{{name}} is still running but has produced no output for a while",{name:a})}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>{r(e.key)},children:s("Dismiss")}),e.chatId&&i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>e.chatId&&o({kind:"chat",chatId:e.chatId}),children:s("Go to chat")})]})]})}function rZ({item:e,bot:t}){const{t:n}=Q(),s=ce(a=>a.dismissInbox),o=ce(a=>a.openDirect),r=t?.name??n("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:r}),i.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:n("Budget")})]}),i.jsx("div",{className:"mt-2 text-sm",children:n("{{name}}'s budget for today is used up",{name:r})}),i.jsx("div",{className:"mt-1 text-muted-foreground text-xs",children:e.budget?.reason==="cost"?n("Daily cost limit reached. New messages are refused until local midnight."):n("Daily token limit reached. New messages are refused until local midnight.")}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>{s(e.key)},children:n("Dismiss")}),t&&i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>{o(t.id)},children:n("Go to chat")})]})]})}function aZ({inboxKey:e,record:t,bots:n,chatName:s}){const{t:o}=Q(),r=ce(g=>g.openTask),a=ce(g=>g.dismissInbox),l=Nh(!0),d=n.get(t.targetBotId),c=d?.name??o("Deleted member"),u=t.finishedAt??t.blocked?.at??t.createdAt,h=t.blocked?.waitFor==="parent"?o("Waiting for {{name}} to reply",{name:n.get(t.parentBotId)?.name??o("Deleted member")}):o("Waiting for your reply"),{chatId:p,taskId:f}=t;return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:c}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(_h,{state:t.state}),i.jsx("span",{className:"flex-1"}),i.jsx("span",{children:o("Stuck for {{time}}",{time:mo(l-u)})})]}),i.jsx("div",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:t.task}),i.jsxs("div",{className:"mt-2 rounded-md border border-warning/30 bg-warning/10 px-2 py-1.5 text-xs",children:[i.jsx("div",{className:"line-clamp-4 whitespace-pre-wrap font-medium",children:o("Blocked · needs: {{need}}",{need:t.blocked?.need??""})}),i.jsx("div",{className:"mt-0.5 text-muted-foreground",children:h}),p&&f&&i.jsx(Zx,{placeholder:o("Answer {{name}}; they continue after your reply…",{name:c}),onSend:g=>MD(p,f,g,o)})]}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>{a(e)},children:o("Dismiss")}),p&&f&&i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>r(p,f),children:o("Open task card")})]})]})}function lZ({inboxKey:e,record:t,bots:n,chatName:s,onOpen:o}){const{t:r}=Q(),a=ce(p=>p.setView),l=ce(p=>p.dismissInbox),d=n.get(t.parentBotId),c=n.get(t.targetBotId),u=d?.name??r("Deleted member"),h=c?.name??r("Deleted member");return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:d,size:"xs"}),i.jsx("span",{className:"text-foreground",children:u}),i.jsx("span",{children:"→"}),i.jsx(tn,{bot:c,size:"xs"}),i.jsx("span",{className:"text-foreground",children:h}),i.jsxs("span",{children:["· ",r("Delegation")]}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx(_h,{state:t.state,interrupted:!0})]}),i.jsx("div",{className:"mt-2 line-clamp-3 text-sm",children:t.task}),i.jsx("div",{className:"mt-1 text-muted-foreground text-xs",children:Td(t,r)}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>{l(e)},children:r("Dismiss")}),t.chatId&&i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>t.chatId&&a({kind:"chat",chatId:t.chatId}),children:r("Go to chat")}),i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>o(r("{{from}} → {{to}} · Delegation",{from:u,to:h})),children:r("View conversation")}),i.jsx(ge,{size:"xs",onClick:()=>kl(t.id,r),children:r("Retry")})]})]})}function dZ({item:e,bot:t,owner:n,chatName:s}){const{t:o}=Q(),r=ce(g=>g.setView),[a,l]=m.useState(""),[d,c]=m.useState(!1),u=g=>{c(!0),g.finally(()=>c(!1))},h=g=>u(window.electronAPI.agent.respondApproval(e.conversationId,e.request.requestId,g)),p=g=>g.trim()&&u(window.electronAPI.agent.respondAsk(e.conversationId,e.request.requestId,g.trim())),f=e.kind==="approval"&&e.request.phase==="reviewing";return i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs",children:[i.jsx(tn,{bot:t,size:"sm"}),i.jsx("span",{className:"text-foreground",children:e.delegation?o("{{name}} on behalf of {{owner}}",{name:t?.name??o("Deleted member"),owner:n?.name??o("Deleted member")}):t?.name??o("Deleted member")}),s&&i.jsxs("span",{children:["· ",s]}),i.jsx("span",{className:e.kind==="approval"?"rounded bg-warning/20 px-1.5 text-[11px] text-warning":"rounded bg-info/15 px-1.5 text-[11px] text-info",children:e.kind==="approval"?o("Approval"):o("Question")}),e.kind==="approval"&&e.request.protected&&i.jsx("span",{className:"rounded bg-destructive/15 px-1.5 text-[11px] text-destructive",children:xN(e.request.protected,o)})]}),e.kind==="approval"?i.jsxs("div",{className:"mt-2 text-sm",children:[ha(e.request.tool,o),i.jsx("pre",{className:"mt-1 max-h-24 overflow-auto whitespace-pre-wrap rounded-md bg-muted/60 px-2 py-1.5 font-mono text-xs",children:e.request.summary})]}):i.jsx("div",{className:"mt-2 whitespace-pre-wrap text-sm",children:e.request.question}),i.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center justify-end gap-1.5",children:[i.jsx(ge,{size:"xs",variant:"ghost",onClick:()=>r({kind:"chat",chatId:e.chatId}),children:o("Go to chat")}),e.kind==="approval"?f?i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Assistant reviewing…")}):i.jsxs(i.Fragment,{children:[i.jsx(ge,{size:"xs",variant:"outline",disabled:d,onClick:()=>h("deny"),children:o("Deny")}),!e.request.protected&&i.jsx(ge,{size:"xs",variant:"outline",disabled:d,onClick:()=>h("allowSession"),children:o("Always allow in this session")}),i.jsx(ge,{size:"xs",disabled:d,onClick:()=>h("allow"),children:o("Allow")})]}):i.jsxs(i.Fragment,{children:[e.request.options?.map(g=>i.jsx(ge,{size:"xs",variant:"outline",disabled:d,onClick:()=>p(g),children:g},g)),i.jsx(Xt,{className:"h-7 w-48",value:a,placeholder:o("Custom answer…"),onChange:g=>l(g.target.value),onKeyDown:g=>g.key==="Enter"&&p(a)}),i.jsx(ge,{size:"xs",disabled:d||!a.trim(),onClick:()=>p(a),children:o("Reply")})]})]})]})}function cZ(e){const{openOnInputClick:t=!1,value:n,defaultValue:s,onValueChange:o,mode:r="list",itemToStringValue:a,...l}=e,d=r==="inline"||r==="both",c=r==="inline"||r==="none",u=n!==void 0,[h,p]=m.useState(s??""),[f,g]=m.useState("");m.useEffect(()=>{u&&g("")},[n,u]);let x;d&&f!==""?x=f:u?x=n??"":x=h;const v=b2({locale:l.locale}),y=m.useMemo(()=>l.filter!==void 0?l.filter:v.contains,[l.filter,v]),w=String(u?n:h).trim(),b=m.useMemo(()=>r!=="both"?c?null:y:y===null?null:(N,C,S)=>y(N,w,S),[y,r,w,c]);function _(N,C){g(""),u||p(N),o?.(N,C)}function j(N,C){e.onItemHighlighted?.(N,C),C.reason!==y2&&g(d&&N!=null?S2(N,a):"")}return i.jsx(w2,{...l,itemToStringLabel:a,openOnInputClick:t,selectionMode:"none",fillInputOnItemPress:!0,filter:b,autoComplete:r,inputValue:x,defaultInputValue:s,onInputValueChange:_,onItemHighlighted:j})}const uZ=C2,hZ="",pZ=200;function fZ(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let n=null;for(;t.nextNode();){const s=t.currentNode;s.nodeValue!==""&&(n=s)}return n}function mZ(){const e=k2(),t=m.useRef(null);return m.useEffect(()=>{if(j2)return;const n=t.current;if(n==null)return;const s=fZ(n);if(s==null)return;const o=s.data,r=`${o}${hZ}`;return s.nodeValue=r,e.start(pZ,()=>{s.nodeValue===r&&(s.nodeValue=o)}),()=>{e.clear(),s.nodeValue===r&&(s.nodeValue=o)}},[t,e]),t}const KD=m.createContext(void 0);function gZ(){const e=m.useContext(KD);if(e===void 0)throw new Error(od(18));return e}const xZ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,items:a,...l}=t,[d,c]=m.useState(),u=m.useMemo(()=>({labelId:d,setLabelId:c,items:a}),[d,c,a]),h=rd("div",t,{ref:n,props:[{role:"group","aria-labelledby":d},l]}),p=i.jsx(KD.Provider,{value:u,children:h});return a?i.jsx(_2,{items:a,children:p}):p}),vZ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,id:a,...l}=t,{setLabelId:d}=gZ(),c=Sk(a);return lg(()=>(d(c),()=>{d(h=>h===c?void 0:h)}),[c,d]),rd("div",t,{ref:n,props:[{id:c},l]})}),bZ=N2,wZ=m.forwardRef(function(t,n){const{render:s,className:o,style:r,children:a,...l}=t,{filteredItems:d}=T2(),c=D2(),u=mZ(),h=d.length===0?a:null;return rd("div",t,{ref:[n,c.state.emptyRef,u],props:[{children:h,role:"status","aria-live":"polite","aria-atomic":!0},l]})}),ev=cZ,Bp=new WeakMap;function Ir(e,t){const n=Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue(e));return Number.isFinite(n)?n:t}function Pm(e){if(e.classList.contains("is-clearing"))return;const t=e.querySelector("input"),n=e.querySelector(".t-clear-mirror");if(!t||!n)return;const s=t.value.length>0;e.classList.toggle("has-value",s),n.textContent=s?t.value.replace(/ /g," "):""}function yZ(e){const t=e.closest(".t-clear"),n=t?.querySelector("input"),s=t?.querySelector(".t-clear-mirror"),o=t?.querySelector(".t-clear-placeholder");if(!t||!n||!s||!o||!n.value)return;const r=Bp.get(t);if(r!==void 0&&window.clearTimeout(r),s.textContent=n.value.replace(/ /g," "),o.textContent=n.placeholder,t.classList.remove("has-value"),t.classList.add("is-clearing"),window.matchMedia("(prefers-reduced-motion: reduce)").matches){t.classList.remove("is-clearing"),s.textContent="";return}const a=getComputedStyle(document.documentElement),l=Ir("--clear-dur",1e3),d=Ir("--clear-out-dur",400),c=Ir("--clear-in-dur",400),u=Ir("--clear-out-fly",12),h=Ir("--clear-in-fly",12),p=Ir("--clear-blur",2),f=a.getPropertyValue("--clear-out-ease").trim()||"ease-out",g=a.getPropertyValue("--clear-in-ease").trim()||"ease-out",x=s.animate([{transform:"translateY(0)",opacity:1,filter:"blur(0)"},{transform:`translateY(${u}px)`,opacity:0,filter:`blur(${p}px)`}],{duration:d,easing:f,fill:"forwards"}),v=o.animate([{transform:`translateY(-${h}px)`,opacity:.9,filter:`blur(${p}px)`},{transform:"translateY(0)",opacity:1,filter:"blur(0)"}],{duration:c,easing:g,fill:"forwards"}),y=window.setTimeout(()=>{x.cancel(),v.cancel(),t.classList.remove("is-clearing"),s.textContent="",Bp.delete(t),Pm(t)},Math.max(l,d,c));Bp.set(t,y)}function tv({className:e,showTrigger:t=!1,showClear:n=!1,startAddon:s,size:o,...r}){const a=o??"default",l=m.useRef(null);return m.useLayoutEffect(()=>{l.current&&Pm(l.current)},[r.value]),i.jsxs("div",{ref:l,className:"t-clear autocomplete-clear-dissolve relative w-full",onInput:d=>Pm(d.currentTarget),children:[s&&i.jsx("div",{"aria-hidden":"true",className:"[&_svg]:-mx-0.5 pointer-events-none absolute inset-y-0 start-px z-10 flex items-center ps-[calc(--spacing(3)-1px)] opacity-80 has-[+[data-size=sm]]:ps-[calc(--spacing(2.5)-1px)] [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4","data-slot":"autocomplete-start-addon",children:s}),i.jsx(I2,{className:q(s&&"data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7.5)-1px)] *:data-[slot=autocomplete-input]:ps-[calc(--spacing(8.5)-1px)] sm:data-[size=sm]:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(7)-1px)] sm:*:data-[slot=autocomplete-input]:ps-[calc(--spacing(8)-1px)]",a==="sm"?"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-6.5":"has-[+[data-slot=autocomplete-trigger],+[data-slot=autocomplete-clear]]:*:data-[slot=autocomplete-input]:pe-7",e),"data-slot":"autocomplete-input",render:i.jsx(Xt,{size:a}),...r}),i.jsx("div",{"aria-hidden":"true",className:q("t-clear-mirror px-[calc(--spacing(3)-1px)] text-base sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]"))}),i.jsx("div",{"aria-hidden":"true",className:q("t-clear-placeholder px-[calc(--spacing(3)-1px)] text-base text-muted-foreground/72 opacity-0 sm:text-sm",a==="sm"&&"px-[calc(--spacing(2.5)-1px)]",s&&(a==="sm"?"ps-[calc(--spacing(7.5)-1px)] sm:ps-[calc(--spacing(7)-1px)]":"ps-[calc(--spacing(8.5)-1px)] sm:ps-[calc(--spacing(8)-1px)]")),children:r.placeholder}),i.jsx("div",{"aria-hidden":"true",className:"t-clear-glow"}),t&&i.jsx(jZ,{className:q("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:i.jsx(pj,{})}),n&&i.jsx(kZ,{className:q("-translate-y-1/2 absolute top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-colors pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 has-[+[data-slot=autocomplete-clear]]:hidden sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",a==="sm"?"end-0":"end-0.5"),children:i.jsx(an,{})})]})}function qD({className:e,children:t,sideOffset:n=4,zIndex:s,...o}){return i.jsx(E2,{children:i.jsx(P2,{className:"z-[55] select-none",style:s?{zIndex:s}:void 0,"data-slot":"autocomplete-positioner",sideOffset:n,children:i.jsx("span",{className:q("relative flex max-h-full origin-(--transform-origin) rounded-lg border bg-popover bg-clip-padding transition-[scale,opacity] before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-lg)-1px)] before:shadow-lg has-data-starting-style:scale-98 has-data-starting-style:opacity-0 dark:not-in-data-[slot=group]:bg-clip-border",e),children:i.jsx(A2,{className:"flex max-h-[min(var(--available-height),23rem)] w-(--anchor-width) max-w-(--available-width) flex-col","data-slot":"autocomplete-popup",...o,children:t})})})})}function nv({className:e,children:t,...n}){return i.jsx(bZ,{className:q("flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",e),"data-slot":"autocomplete-item",...n,children:t})}function SZ({className:e,...t}){return i.jsx(xZ,{className:q("[[role=group]+&]:mt-1.5",e),"data-slot":"autocomplete-group",...t})}function CZ({className:e,...t}){return i.jsx(vZ,{className:q("px-2 py-1.5 font-medium text-muted-foreground text-xs",e),"data-slot":"autocomplete-group-label",...t})}function sv({className:e,...t}){return i.jsx(wZ,{className:q("not-empty:p-2 text-center text-base text-muted-foreground sm:text-sm",e),"data-slot":"autocomplete-empty",...t})}function iv({className:e,...t}){return i.jsx(M2,{scrollbarGutter:!0,scrollFade:!0,children:i.jsx(R2,{className:q("not-empty:scroll-py-1 not-empty:p-1 in-data-has-overflow-y:pe-3",e),"data-slot":"autocomplete-list",...t})})}function kZ({className:e,onClickCapture:t,onPointerDownCapture:n,...s}){return i.jsx(L2,{className:q("-translate-y-1/2 absolute end-0.5 top-1/2 inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-md border border-transparent opacity-80 outline-none transition-[color,background-color,box-shadow,opacity] pointer-coarse:after:absolute pointer-coarse:after:min-h-11 pointer-coarse:after:min-w-11 hover:opacity-100 sm:size-7 [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",e),"data-slot":"autocomplete-clear",onClickCapture:o=>{t?.(o),o.defaultPrevented||yZ(o.currentTarget)},onPointerDownCapture:o=>{n?.(o);const r=o.currentTarget.closest(".t-clear")?.querySelector("input");!o.defaultPrevented&&document.activeElement===r&&o.preventDefault()},...s,children:i.jsx(an,{})})}function jZ({className:e,...t}){return i.jsx(uZ,{className:e,"data-slot":"autocomplete-trigger",...t})}const YD=m.createContext({inputRef:null}),XD=O2,_Z=z2;function NZ({className:e,...t}){return i.jsx(H2,{className:q("fixed inset-0 z-50 bg-black/32 backdrop-blur-sm transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0",e),"data-slot":"command-dialog-backdrop",...t})}function TZ({className:e,...t}){return i.jsx(B2,{className:q("fixed inset-0 z-50 flex flex-col items-center px-4 py-[max(--spacing(4),4vh)] sm:py-[10vh]",e),"data-slot":"command-dialog-viewport",...t})}function ZD({className:e,children:t,...n}){const s=m.useRef(null);return i.jsxs(_Z,{children:[i.jsx(G2,{}),i.jsx(NZ,{}),i.jsx(TZ,{children:i.jsx(F2,{className:q("-translate-y-[calc(1.25rem*var(--nested-dialogs))] relative row-start-2 flex max-h-100 min-h-0 w-full min-w-0 max-w-xl scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border bg-popover bg-clip-padding text-popover-foreground opacity-[calc(1-0.1*var(--nested-dialogs))] shadow-lg transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:bg-muted/50 before:shadow-[0_1px_--theme(--color-black/4%)] data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0 **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",e),"data-slot":"command-dialog-popup",initialFocus:s,...n,children:i.jsx(YD.Provider,{value:{inputRef:s},children:t})})})]})}function JD({autoHighlight:e="always",keepHighlight:t=!0,open:n=!0,...s}){return i.jsx(ev,{autoHighlight:e,keepHighlight:t,open:n,...s})}function QD({className:e,placeholder:t=void 0,endAddon:n,...s}){const{inputRef:o}=m.useContext(YD);return i.jsxs("div",{className:"flex items-center gap-2 px-2.5 py-1.5",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(tv,{className:q("border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0",e),placeholder:t,ref:o,size:"lg",startAddon:i.jsx(ti,{}),...s})}),n]})}function eI({className:e,...t}){return i.jsx(iv,{className:q("not-empty:scroll-py-2 not-empty:p-2",e),"data-slot":"command-list",...t})}function tI({className:e,...t}){return i.jsx(sv,{className:q("not-empty:py-6",e),"data-slot":"command-empty",...t})}function nI({className:e,...t}){return i.jsx("div",{className:"-mx-px relative min-h-0 rounded-t-xl border bg-popover bg-clip-padding shadow-xs [clip-path:inset(0_1px)] before:pointer-events-none before:absolute before:inset-0 before:rounded-t-[calc(var(--radius-xl)-1px)] **:data-[slot=scroll-area-scrollbar]:mt-2 dark:bg-clip-border dark:before:shadow-[0_-1px_--theme(--color-white/8%)]",...t})}function Er({className:e,...t}){return i.jsx(SZ,{className:e,"data-slot":"command-group",...t})}function Pr({className:e,...t}){return i.jsx(CZ,{className:e,"data-slot":"command-group-label",...t})}function sr({className:e,...t}){return i.jsx(nv,{className:q("py-1.5",e),"data-slot":"command-item",...t})}function oS({className:e,...t}){return i.jsx("span",{className:q("ms-auto font-medium text-muted-foreground/72 text-xs tracking-widest",e),"data-slot":"command-shortcut",...t})}function sI({className:e,...t}){return i.jsx("div",{className:q("flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] px-5 py-3 text-muted-foreground text-xs",e),"data-slot":"command-footer",...t})}const rS=e=>e.locator.kind==="timeline"?`${e.chatId}:${e.locator.seq}`:`${e.chatId}:${e.locator.conversationId}:${e.locator.messageIndex}`;function iI({className:e}){const{t}=Q(),n=Ce(r=>r.keybindings),s=Ai(n)["search-workspace"],o=t("Search messages");return i.jsx("button",{type:"button",className:e,onClick:()=>ce.getState().setSearchOpen(!0),title:s?`${o} (${fi(s)})`:o,children:i.jsx(ti,{className:"h-4 w-4"})})}function DZ(){const{t:e,locale:t}=Q(),n=ce(v=>v.searchOpen),s=ce(v=>v.setSearchOpen),o=ce(v=>v.bots),r=ce(v=>v.chats),[a,l]=m.useState(""),[d,c]=m.useState(),u=a.trim(),h=m.useMemo(()=>new Map(o.map(v=>[v.id,v])),[o]),p=m.useMemo(()=>new Map(r.map(v=>[v.id,v])),[r]),f=d?.key===u?d:void 0;m.useEffect(()=>{n||(l(""),c(void 0))},[n]),m.useEffect(()=>{if(!n||!u)return;let v=!1;const y=window.setTimeout(()=>{window.electronAPI.bots.search({query:u}).then(w=>{v||c(w.ok?{key:u,hits:w.hits,truncated:w.truncated}:{key:u,hits:[],truncated:!1})}).catch(()=>{v||c({key:u,hits:[],truncated:!1})})},150);return()=>{v=!0,window.clearTimeout(y)}},[n,u]);const g=v=>{v.key==="Escape"&&(v.preventDefault(),v.stopPropagation(),s(!1))},x=Date.now();return i.jsx(XD,{open:n,onOpenChange:s,children:i.jsx(ZD,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:g,children:i.jsxs(JD,{children:[i.jsx(QD,{placeholder:e("Search group and direct messages…"),value:a,onChange:v=>l(v.currentTarget.value),onKeyDown:v=>{g(v);const y=f?.hits[0];v.key==="Enter"&&!v.nativeEvent.isComposing&&y&&!document.querySelector('[data-slot="command-dialog-popup"] [data-highlighted]')&&(v.preventDefault(),ce.getState().focusHit(y,u))}}),i.jsxs(nI,{children:[u&&f&&f.hits.length===0&&i.jsx(tI,{children:e("No matching messages")}),i.jsxs(eI,{children:[f?.hits.map(v=>{const y=p.get(v.chatId),w=(y?.members??[]).map(j=>h.get(j)).filter(j=>j!==void 0),b=v.speaker.kind==="human"?e("You"):h.get(v.speaker.botId)?.name??e("Deleted member"),_=v.locator.kind==="session"&&!v.locator.current?` · ${e("History")}`:"";return i.jsxs(sr,{value:rS(v),className:"items-start gap-2.5",onClick:()=>ce.getState().focusHit(v,u),children:[i.jsx("span",{className:"mt-0.5 shrink-0",children:v.chatKind==="direct"?i.jsx(tn,{bot:w[0]}):i.jsx(il,{bots:w})}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 text-xs",children:[i.jsx("span",{className:"truncate font-medium",children:y?ys(y,o,e):e("Deleted chat")}),i.jsxs("span",{className:"shrink-0 text-muted-foreground",children:[b,_]})]}),i.jsx("p",{className:"line-clamp-2 break-words text-muted-foreground text-xs",children:RX(v.snippet,v.ranges).map((j,N)=>j.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:j.text},N):i.jsx("span",{children:j.text},N))})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:v.at?Oo(v.at,t,x):""})]},rS(v))}),f?.truncated&&i.jsx("p",{className:"px-2 py-1.5 text-center text-muted-foreground text-xs",children:e("Showing the latest {{n}} matches",{n:f.hits.length})})]})]}),i.jsxs(sI,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(fj,{children:[i.jsx(ai,{children:"↑"}),i.jsx(ai,{children:"↓"})]}),e("Navigate")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(ai,{children:"↵"}),e("Open")]})]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(ai,{children:"esc"}),e("Close")]})]})]})})})}function IZ({chat:e,onOpenChange:t}){const{t:n}=Q(),s=ce(f=>f.bots),o=ce(f=>f.chats),r=Ce(f=>f.projects),[a,l]=m.useState(""),[d,c]=m.useState(!1);if(m.useEffect(()=>{if(!e)return;const f=o.filter(g=>g.kind==="group").map(g=>g.title);l(V2(n("{{title}} copy",{title:ys(e,s,n)}),f)),c(!1)},[e?.id]),!e)return null;const u=f=>s.find(g=>g.id===f)?.name??"—",h=`${e.routing.mode==="smart"?n("Smart pick"):n("Group owner replies")} · ${n("Relay {{hops}} · {{turns}} replies each",{hops:e.routing.maxHops,turns:e.routing.maxTurnsPerBot})}`,p=async()=>{const f=a.trim();if(f){c(!0);try{const g=await window.electronAPI.bots.cloneChat({chatId:e.id,title:f});if(!g.ok){Be({type:"error",title:_s(g.error,n)});return}const x=ce.getState();x.upsertChat(g.chat),x.setView({kind:"chat",chatId:g.chat.id}),x.loadLatest(g.chat.id),Be({type:"success",title:n("Cloned. The chat history is empty.")}),t(!1)}finally{c(!1)}}};return i.jsx(wn,{open:!0,onOpenChange:t,children:i.jsxs(yn,{className:"max-w-md",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:n("Clone group chat")}),i.jsx(Bs,{children:n("Copies the setup of “{{title}}”. The original stays as is; replies in progress are not stopped.",{title:ys(e,s,n)})})]}),i.jsxs(On,{className:"space-y-4 text-sm",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:n("Group name")}),i.jsx(Xt,{value:a,autoFocus:!0,onChange:f=>l(f.target.value),onKeyDown:f=>f.key==="Enter"&&void p()})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(Kt,{children:n("Will copy")}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Members"),":"]}),e.members.map(u).join("、")]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Owner"),":"]}),u(e.bossBotId)]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Routing"),":"]}),h]}),i.jsxs("p",{children:[i.jsxs("span",{className:"text-muted-foreground",children:[n("Workspace"),":"]}),e.workspace.kind==="project"?n("Same project: {{name}}",{name:sj(e,r,s,n)}):n("A new empty folder, separate from the original")]})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx(Kt,{children:n("Not copied")}),i.jsx("p",{className:"text-muted-foreground",children:n("Chat history, group notes, routines, task board and group memory")})]})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsx(ge,{size:"sm",disabled:!a.trim()||d,onClick:()=>{p()},children:n("Clone")})]})]})})}const Zo="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function EZ({width:e,onCollapse:t,onNewMember:n,onNewGroup:s,onNewTeam:o,onStartFromGoal:r}){const{t:a,locale:l}=Q(),d=[{label:a("Start from a goal"),icon:Na,onClick:r},{label:a("New member"),icon:Hl,onClick:n},{label:a("New group chat"),icon:ra,onClick:s},{label:a("Create team from template"),icon:Cf,onClick:o}],c=ce(ne=>ne.bots),u=ce(ne=>ne.chats),h=ce(ne=>ne.queue),p=ce(ne=>ne.sessions),f=ce(ne=>ne.delegations),g=ce(ne=>ne.timelines),x=ce(ne=>ne.reads),v=ce(ne=>ne.view),y=ce(ne=>ne.setView),w=ce(ne=>ne.openDirect),b=ce(ne=>ne.upsertChat),_=ce(ne=>ne.upsertBot),[j,N]=m.useState(!1),[C,S]=m.useState(""),[A,E]=m.useState(null),[I,D]=m.useState(null),T=m.useMemo(()=>new Map(c.map(ne=>[ne.id,ne])),[c]),z=m.useMemo(()=>Object.fromEntries(c.map(ne=>[ne.id,ne.name])),[c]),$=m.useMemo(()=>lj(p,dj(u,f)),[p,u,f]),R=m.useMemo(()=>{const ne=new Set,se=new Set;for(const He of f)El(He.state)&&(He.chatId&&ne.add(He.chatId),se.add(He.targetBotId));return{chatIds:ne,botIds:se}},[f]),B=m.useMemo(()=>$2(u.map(ne=>{const se=xg(ne,{sessions:p,timeline:g[ne.id],queue:h,names:z});return{chat:ne,summary:{...se,running:se.running||(ne.kind==="group"?R.chatIds.has(ne.id):R.botIds.has(ne.members[0])),pending:$.filter(He=>He.chatId===ne.id).length}}}),x),[u,p,g,h,z,$,R,x]),H=B.filter(ne=>!ne.chat.archivedAt),oe=W2(H.filter(ne=>ne.chat.kind==="group"&&ne.chat.settledAt===void 0)),te=new Map(H.filter(ne=>ne.chat.kind==="direct").map(ne=>[ne.chat.members[0],ne])),O=c.filter(ne=>ne.archivedAt===void 0&&te.get(ne.id)?.chat.settledAt===void 0).map(ne=>({bot:ne,row:te.get(ne.id)})).sort((ne,se)=>{const He=Number(se.row?.chat.pinned??!1)-Number(ne.row?.chat.pinned??!1),kt=(ne.row?.chat.pinOrder??Number.POSITIVE_INFINITY)-(se.row?.chat.pinOrder??Number.POSITIVE_INFINITY);return He||(ne.row?.chat.pinned&&kt?kt:0)||(se.row?.summary.activityAt??se.bot.updatedAt)-(ne.row?.summary.activityAt??ne.bot.updatedAt)}),V=H.filter(ne=>ne.chat.settledAt!==void 0&&(ne.chat.kind==="group"||T.get(ne.chat.members[0])?.archivedAt===void 0)).sort((ne,se)=>(se.chat.settledAt??0)-(ne.chat.settledAt??0)),J=oe.filter(ne=>ne.chat.pinned).map(ne=>ne.chat.id),pe=O.flatMap(({row:ne})=>ne?.chat.pinned?[ne.chat.id]:[]),[fe,_e]=m.useState(null),[Ee,me]=m.useState(!0),W=B.filter(ne=>ne.chat.archivedAt!==void 0),G=c.filter(ne=>ne.archivedAt!==void 0),de=W.length+G.length,X=C.trim().toLowerCase(),ie=(...ne)=>!X||ne.some(se=>se.toLowerCase().includes(X)),Z=W.filter(({chat:ne,summary:se})=>ie(ys(ne,c,a),se.preview??"")).sort((ne,se)=>(se.chat.archivedAt??0)-(ne.chat.archivedAt??0)),le=G.filter(ne=>ie(ne.name,ne.title,ne.scope)).sort((ne,se)=>(se.archivedAt??0)-(ne.archivedAt??0)),be=Sg(),Fe=v?.kind==="chat"?v.chatId:null,Je=async(ne,se)=>{const He=await window.electronAPI.bots.updateChat({chatId:ne.id,...se});He.ok?b(He.chat):Be({type:"error",title:_s(He.error,a)})},We=ne=>Je(ne,ne.pinned?{pinned:!1}:{pinned:!0,pinOrder:Math.max(-1,...u.filter(se=>se.pinned).map(se=>se.pinOrder??0))+1}),et=(ne,se,He)=>{const kt=Object.fromEntries(u.map(st=>[st.id,st.pinOrder]));for(const st of q2(ne,se,He,kt)){const ke=u.find(ut=>ut.id===st.chatId);ke&&Je(ke,{pinOrder:st.pinOrder})}},qe=(ne,se)=>{const He=se.indexOf(ne.id),kt=B.find(st=>st.chat.id===ne.id)?.summary;return{onSettle:()=>{Je(ne,{settled:ne.settledAt===void 0})},onSnooze:st=>{Je(ne,{snoozedUntil:st})},onMarkUnread:kt&&Fe!==ne.id&&!Ya(kt.marker,x[kt.key])&&U2(kt.marker)!==void 0?()=>ce.getState().markUnread(ne.id):void 0,onMoveUp:He>0?()=>et(se,ne.id,He-1):void 0,onMoveDown:He>=0&&He<se.length-1?()=>et(se,ne.id,He+1):void 0}},Lt=(ne,se)=>ne?.pinned?{draggable:!0,onDragStart:He=>{He.dataTransfer.effectAllowed="move",_e(ne.id)},onDragEnd:()=>_e(null),onDragOver:He=>{fe&&fe!==ne.id&&se.includes(fe)&&He.preventDefault()},onDrop:He=>{He.preventDefault(),fe&&se.includes(fe)&&et(se,fe,se.indexOf(ne.id)),_e(null)}}:{},Bt=async(ne,se)=>{const He=await window.electronAPI.bots.archive(ne.id,se);He.ok?_(He.bot):Be({type:"error",title:He.error})},Mt=ne=>ne?ne.running?a("Working"):ne.queued?a("Queued"):ne.activityAt?Oo(ne.activityAt,l):null:null;return i.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-2 pb-2",children:[i.jsx(Vp,{title:a("Group chats"),onAdd:s,addLabel:a("New group chat")}),oe.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No group chats yet")}),oe.map(({chat:ne,summary:se})=>i.jsx(Wp,{chat:ne,onPin:()=>{We(ne)},onArchive:()=>{Je(ne,{archived:!0})},onDelete:()=>E(ne),onClone:()=>D(ne),manage:qe(ne,J),children:i.jsx($p,{...Lt(ne,J),active:Fe===ne.id,avatar:i.jsx(il,{bots:ne.members.map(He=>T.get(He)),busy:se.running}),title:ys(ne,c,a),pinned:ne.pinned,meta:Mt(se),preview:se.preview,unread:Ya(se.marker,x[se.key]),pending:se.pending,onClick:()=>y({kind:"chat",chatId:ne.id})})},ne.id)),i.jsx(Vp,{title:a("Members"),onAdd:n,addLabel:a("New member")}),O.length===0&&i.jsx("p",{className:"px-4 py-1 text-muted-foreground text-xs",children:a("No members yet")}),O.map(({bot:ne,row:se})=>i.jsx(Wp,{chat:se?.chat,onPin:se?()=>{We(se.chat)}:void 0,onArchive:se?()=>{Je(se.chat,{archived:!0})}:void 0,onArchiveMember:()=>{Bt(ne,!0)},manage:se?qe(se.chat,pe):void 0,children:i.jsx($p,{...Lt(se?.chat,pe),active:!!(se&&Fe===se.chat.id),avatar:i.jsx(tn,{bot:ne,busy:se?.summary.running||R.botIds.has(ne.id)}),title:ne.name,pinned:se?.chat.pinned,meta:R.botIds.has(ne.id)?a("Working"):Mt(se?.summary),preview:se?.summary.preview||ne.title||ne.scope,unread:!!(se&&Ya(se.summary.marker,x[se.summary.key])&&Fe!==se.chat.id),pending:se?.summary.pending??0,onClick:()=>{w(ne.id)}})},ne.id)),V.length>0&&i.jsx(Vp,{title:`${a("Settled")} · ${V.length}`,onToggle:()=>me(ne=>!ne)}),Ee&&V.map(({chat:ne,summary:se})=>{const He=ne.kind==="direct"?T.get(ne.members[0]):void 0;return i.jsx(Wp,{chat:ne,onPin:()=>{We(ne)},onArchive:()=>{Je(ne,{archived:!0})},onClone:ne.kind==="group"?()=>D(ne):void 0,manage:qe(ne,[]),children:i.jsx($p,{className:"opacity-75",active:Fe===ne.id,avatar:He?i.jsx(tn,{bot:He,busy:se.running}):i.jsx(il,{bots:ne.members.map(kt=>T.get(kt)),busy:se.running}),title:He?He.name:ys(ne,c,a),meta:ne.snoozedUntil!==void 0?a("Remind {{time}}",{time:Oo(ne.snoozedUntil,l)}):Mt(se),preview:se.preview,unread:Ya(se.marker,x[se.key])&&(ne.kind==="group"||Fe!==ne.id),pending:se.pending,onClick:()=>He?void w(He.id):y({kind:"chat",chatId:ne.id})})},ne.id)})]}),i.jsxs("div",{className:"@container flex shrink-0 items-center justify-between border-t p-2",children:[t?i.jsx("button",{type:"button",onClick:t,className:Zo,title:a("Collapse sidebar"),children:i.jsx(wx,{className:"h-4 w-4"})}):i.jsx("span",{}),i.jsxs("div",{className:"flex items-center",children:[i.jsx(iI,{className:Zo}),d.map(({label:ne,icon:se,onClick:He})=>i.jsx("button",{type:"button",className:q(Zo,"hidden @min-[18.5rem]:flex"),onClick:He,title:ne,children:i.jsx(se,{className:"h-4 w-4"})},ne)),i.jsxs(Hi,{children:[i.jsx(Bi,{className:q(Zo,"@min-[18.5rem]:hidden"),title:a("More actions"),children:i.jsx(hh,{className:"h-4 w-4"})}),i.jsx(Vi,{align:"end",side:"top",children:d.map(({label:ne,icon:se,onClick:He})=>i.jsxs(pn,{onClick:He,children:[i.jsx(se,{}),ne]},ne))})]}),(be>0||v?.kind==="inbox")&&i.jsxs("button",{type:"button",className:q(Zo,v?.kind==="inbox"&&"bg-brand/10 text-foreground hover:bg-brand/10 dark:bg-brand/15 dark:hover:bg-brand/15"),onClick:()=>y({kind:"inbox"}),title:a("Inbox"),children:[i.jsx(vx,{className:"h-4 w-4"}),be>0&&i.jsx(Eh,{count:be,className:"-top-0.5 -right-1 absolute"})]}),de>0&&i.jsx("button",{type:"button",className:Zo,onClick:()=>{S(""),N(!0)},title:`${a("Archived")} (${de})`,children:i.jsx(Ii,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Zo,onClick:()=>{window.electronAPI.window.openSettings()},title:a("Settings"),children:i.jsx(ui,{className:"h-4 w-4"})})]})]}),i.jsx(wn,{open:j,onOpenChange:N,children:i.jsxs(yn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(Sn,{children:[i.jsxs(Cn,{className:"flex items-baseline gap-2",children:[a("Archived"),i.jsx("span",{className:"font-sans text-muted-foreground text-sm tabular-nums",children:de})]}),i.jsxs(qu,{"data-size":"sm",className:"mt-1",children:[i.jsx(Yu,{children:i.jsx(ti,{})}),i.jsx(Xu,{value:C,placeholder:a("Search conversations..."),onChange:ne=>S(ne.target.value)})]})]}),i.jsxs(On,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[Z.length+le.length===0&&i.jsx("p",{className:"py-10 text-center text-muted-foreground text-sm",children:C.trim()?a("No matching conversations"):a("Nothing archived")}),Z.length>0&&i.jsx(aS,{title:a("Chat threads"),count:Z.length,children:Z.map(({chat:ne,summary:se})=>i.jsx(lS,{avatar:ne.kind==="group"?i.jsx(il,{bots:ne.members.map(He=>T.get(He))}):i.jsx(tn,{bot:T.get(ne.members[0])}),title:ys(ne,c,a),preview:se.preview,onOpen:()=>{y({kind:"chat",chatId:ne.id}),N(!1)},onRestore:()=>{Je(ne,{archived:!1})},onDelete:ne.kind==="group"?()=>E(ne):void 0},ne.id))}),le.length>0&&i.jsx(aS,{title:a("Members"),count:le.length,children:le.map(ne=>i.jsx(lS,{avatar:i.jsx(tn,{bot:ne}),title:ne.name,preview:ne.title||ne.scope,onRestore:()=>{Bt(ne,!1)}},ne.id))})]})]})}),i.jsx(fs,{open:A!==null,onOpenChange:ne=>!ne&&E(null),title:a("Delete group chat?"),description:a("The group timeline and its standalone workspace are deleted. Member sessions stay readable in their history."),confirmLabel:a("Delete"),onConfirm:()=>{const ne=A;E(null),ne&&window.electronAPI.bots.deleteChat(ne.id).then(se=>{se.ok?(Fe===ne.id&&y(null),ce.getState().refreshChats()):Be({type:"error",title:_s(se.error,a)})})}}),i.jsx(IZ,{chat:I,onOpenChange:ne=>!ne&&D(null)})]})}function Eh({count:e,className:t}){return i.jsx("span",{className:q("min-w-4 rounded-full bg-destructive px-1 text-center font-medium text-[10px] text-white leading-4",t),children:e>99?"99+":e})}function aS({title:e,count:t,children:n}){return i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-2 pr-0.5 pl-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate py-1 font-medium text-[10px] text-muted-foreground uppercase tracking-wide",children:e}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:t})]}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:n})]})}function lS({avatar:e,title:t,preview:n,onOpen:s,onRestore:o,onDelete:r}){const{t:a}=Q(),l="shrink-0 rounded p-1 text-muted-foreground opacity-0 hover:bg-muted hover:text-foreground group-hover:opacity-100";return i.jsxs("div",{className:"group flex items-center gap-2.5 rounded-md px-2 py-1.5 hover:bg-muted/60",children:[i.jsxs("button",{type:"button",disabled:!s,onClick:s,className:"flex min-w-0 flex-1 items-center gap-2.5 text-left disabled:cursor-default",children:[e,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate text-sm",children:t}),n&&i.jsx("span",{className:"block truncate text-muted-foreground text-xs",children:n})]})]}),i.jsx("button",{type:"button",className:l,onClick:o,title:a("Unarchive"),children:i.jsx(Fl,{className:"h-3.5 w-3.5"})}),r&&i.jsx("button",{type:"button",className:q(l,"hover:text-destructive"),onClick:r,title:a("Delete"),children:i.jsx(Gs,{className:"h-3.5 w-3.5"})})]})}function Vp({title:e,onAdd:t,addLabel:n,onToggle:s}){return i.jsxs("div",{className:"flex items-center justify-between px-4 pt-3 pb-1 text-[11px] text-muted-foreground",children:[s?i.jsx("button",{type:"button",onClick:s,className:"hover:text-foreground",children:e}):i.jsx("span",{children:e}),t&&i.jsx("button",{type:"button",onClick:t,title:n,"aria-label":n,className:"rounded p-0.5 transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(ds,{className:"h-3.5 w-3.5"})})]})}function $p({active:e,avatar:t,title:n,pinned:s,meta:o,preview:r,unread:a,pending:l=0,action:d,className:c,...u}){return i.jsxs("div",{role:"button",tabIndex:0,...u,onKeyDown:h=>{h.key==="Enter"&&u.onClick?.(h)},className:q("mx-1.5 flex cursor-default items-center gap-2.5 rounded-lg px-2.5 py-1.5 transition-colors",e?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted",c),children:[t,i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 truncate font-medium text-sm",children:n}),s&&i.jsx(di,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"flex-1"}),l>0?i.jsx(Eh,{count:l}):o&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:o})]}),i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",children:r}),a&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full bg-info"}),d&&i.jsx("button",{type:"button",onClick:h=>{h.stopPropagation(),d.onClick()},className:"shrink-0 rounded px-1.5 text-[11px] text-muted-foreground hover:bg-background hover:text-foreground",children:d.label})]})]})]})}function Wp({chat:e,children:t,onPin:n,onArchive:s,onDelete:o,onArchiveMember:r,onClone:a,manage:l}){const{t:d}=Q(),c=u=>l?.onSnooze(K2(Date.now())[u]);return i.jsxs(uo,{children:[i.jsx(ho,{render:t}),i.jsxs(po,{className:"min-w-40",children:[n&&i.jsxs(Ut,{onClick:n,children:[e?.pinned?i.jsx(vu,{}):i.jsx(di,{}),e?.pinned?d("Unpin"):d("Pin")]}),l?.onMoveUp&&i.jsxs(Ut,{onClick:l.onMoveUp,children:[i.jsx(wd,{}),d("Move up")]}),l?.onMoveDown&&i.jsxs(Ut,{onClick:l.onMoveDown,children:[i.jsx(uh,{}),d("Move down")]}),l&&i.jsxs(Ut,{onClick:l.onSettle,children:[e?.settledAt!==void 0?i.jsx(na,{}):i.jsx(ag,{}),e?.settledAt!==void 0?d("Back to in progress"):d("Settle")]}),l&&i.jsxs(mj,{children:[i.jsxs(gj,{children:[i.jsx(dV,{}),d("Remind me later")]}),i.jsxs(xj,{className:"min-w-36",children:[i.jsx(Ut,{onClick:()=>c("hour"),children:d("In 1 hour")}),i.jsx(Ut,{onClick:()=>c("later"),children:d("In 3 hours")}),i.jsx(Ut,{onClick:()=>c("tomorrow"),children:d("Tomorrow 9:00")})]})]}),l?.onMarkUnread&&i.jsxs(Ut,{onClick:l.onMarkUnread,children:[i.jsx(M$,{}),d("Mark as unread")]}),a&&i.jsxs(Ut,{onClick:a,children:[i.jsx(Vu,{}),d("Clone group chat")]}),s&&i.jsxs(Ut,{onClick:s,children:[i.jsx(Ii,{}),d("Archive chat")]}),r&&i.jsxs(Ut,{onClick:r,children:[i.jsx(Fl,{}),d("Archive member")]}),o&&i.jsxs(i.Fragment,{children:[i.jsx(Cg,{}),i.jsxs(Ut,{variant:"destructive",onClick:o,children:[i.jsx(Gs,{}),d("Delete group chat")]})]})]})]})}const PZ=30;function dS({onPick:e}){const{t,locale:n}=Q(),s=n==="zh"?"zh":"en",o=vj(),r=ce(_=>_.bots),[a,l]=m.useState(""),[d,c]=m.useState(!1),[u,h]=m.useState(null),[p,f]=m.useState(null),[g,x]=m.useState(""),v=async()=>{if(!(!a.trim()||d)){c(!0),h(null);try{const _=await window.electronAPI.bots.suggestGoal({goal:a.trim(),language:s,...r.length?{members:r.map(({id:j,name:N,title:C,scope:S})=>({id:j,name:N,title:C,scope:S}))}:{},templates:o.slice(0,PZ).map(({id:j,data:N})=>({id:j,title:N.title,summary:N.summary}))});if(!_.ok){h(Dh(_,t));return}f(_.suggestion),x(_.suggestion.firstMessage)}finally{c(!1)}}},y=async _=>{if(!d){c(!0),h(null);try{await e(_)}catch{h(t("Could not open chat. Try again."))}finally{c(!1)}}};if(!p)return i.jsxs("div",{className:"w-full max-w-lg space-y-2 text-left",children:[i.jsx(ei,{value:a,autoFocus:!0,rows:3,placeholder:t("e.g. Track competitor news every week and send me a summary"),onChange:_=>l(_.target.value),onKeyDown:_=>{_.key==="Enter"&&(_.metaKey||_.ctrlKey)&&v()}}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u}),i.jsx("div",{className:"flex justify-end",children:i.jsxs(ge,{size:"sm",disabled:!a.trim()||d,onClick:()=>{v()},children:[d?i.jsx(qt,{className:"animate-spin"}):i.jsx(zs,{}),t("Recommend")]})})]});const w=p.kind==="team"?o.find(_=>_.id===p.templateId)?.data:void 0,b=p.kind==="existing"?r.find(_=>_.id===p.botId):p.kind==="member"?{...p.member,avatar:{color:er[0]}}:void 0;return i.jsxs("div",{className:"w-full max-w-lg space-y-3 text-left",children:[i.jsxs("div",{"data-slot":"bot-card",className:"rounded-xl border bg-card p-3",children:[i.jsxs("p",{className:"mb-2 flex items-center gap-1.5 text-muted-foreground text-xs",children:[i.jsx(Na,{className:"h-3.5 w-3.5"}),p.kind==="team"?t("Recommended: a team"):t("Recommended: one member")]}),b?i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(tn,{bot:b}),i.jsxs("div",{className:"min-w-0",children:[i.jsxs("p",{className:"font-medium text-sm",children:[b.name,i.jsx("span",{className:"ml-2 font-normal text-muted-foreground text-xs",children:b.title})]}),b.scope&&i.jsx("p",{className:"text-muted-foreground text-xs",children:b.scope})]})]}):w&&i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("div",{className:"-space-x-1.5 flex",children:w.members.map(_=>i.jsx(tn,{size:"sm",bot:{name:_.name,avatar:{color:_.color}}},_.key))}),i.jsx("p",{className:"font-medium text-sm",children:w.title}),i.jsx("p",{className:"text-muted-foreground text-xs",children:w.summary})]}),p.reason&&i.jsx("p",{className:"mt-2 text-muted-foreground text-xs",children:p.reason})]}),i.jsxs("div",{className:"space-y-1",children:[i.jsx("p",{className:"text-muted-foreground text-xs",children:t("First message (put into the input box, not sent)")}),i.jsx(ei,{value:g,rows:3,onChange:_=>x(_.target.value)})]}),u&&i.jsx("p",{className:"text-destructive text-xs",children:u}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsxs(ge,{size:"sm",variant:"ghost",disabled:d,onClick:()=>{f(null),h(null)},children:[i.jsx(ad,{}),t("Back")]}),i.jsxs("div",{className:"flex gap-2",children:[p.kind==="existing"&&i.jsx(ge,{size:"sm",variant:"outline",disabled:d,onClick:()=>{y({firstMessage:g})},children:t("Create new instead")}),i.jsx(ge,{size:"sm",disabled:d||p.kind==="existing"&&!b,onClick:()=>{y(p.kind==="existing"?{firstMessage:g,botId:p.botId}:p.kind==="member"?{firstMessage:g,member:p.member}:{firstMessage:g,templateId:p.templateId})},children:p.kind==="existing"?t("Use this member"):p.kind==="member"?t("Create this member"):t("Create this team")})]})]})]})}const Jd=e=>({...kD,name:"",title:"",scope:"",persona:"",color:e,engine:null});function AZ({open:e,onOpenChange:t,seed:n,onCreated:s}){const{t:o}=Q(),r=ce(D=>D.bots),a=Y2(),l=m.useRef(null),[d,c]=m.useState({kind:"template",id:"pm"}),[u,h]=m.useState(()=>Jd(er[0])),[p,f]=m.useState(null),[g,x]=m.useState(null),[v,y]=m.useState(!1),[w,b]=m.useState(!1),[_,j]=m.useState(!1),N=()=>{c({kind:"blank"}),h(Jd(er[r.length%er.length])),f(null),x(null)},C=D=>{if(!D)return N();const T=X2(D.data);c({kind:"template",id:D.id}),h({...kD,name:T.name??"",title:T.title??"",scope:T.scope??"",persona:T.persona??"",color:T.avatar?.color??er[0],engine:null,approvalMode:T.approvalMode??"auto-edits",tools:T.tools??"all"}),f(null),x(null)};m.useEffect(()=>{e&&(n?(c({kind:"blank"}),h({...Jd(er[r.length%er.length]),...n}),f(null),x(null)):C(a[0]),y(!1),b(!1),j(!1))},[e]);const S=D=>{h(T=>({...T,...D})),x(null)},A=async D=>{const T=new Uint8Array(await D.arrayBuffer()),z=bD(T)==="png",$=z?AY(qy(T,"chara")??qy(T,"ccv3")??""):new TextDecoder().decode(T),R=$?zY($):{ok:!1,error:"not-a-card"};if(!R.ok){x(R.error==="invalid-json"&&!z?o("This file is not valid JSON."):o("This file is not a SillyTavern character card."));return}const{color:B,memoryEnabled:H,...oe}=R.draft;c({kind:"import"}),h({...Jd(B??u.color),...oe,...H!==void 0?{memoryEnabled:H}:{}}),f(z?await Jk(D).catch(()=>null):null),y(!0),x(null)},E=fg(u.name,r,o),I=async()=>{if(y(!0),E)return;const D=SD(u);if(!D.ok){x(o("Budget must be a positive number"));return}const T=Kx(u);if(!T.ok){x(o("Check the per-turn token limit and delegation time limit"));return}b(!0);try{const z=await window.electronAPI.bots.create({name:u.name.trim(),title:u.title.trim(),scope:u.scope.trim(),...T.delegationTimeoutMinutes?{delegationTimeoutMinutes:T.delegationTimeoutMinutes}:{},...T.maxTokensPerTurn?{maxTokensPerTurn:T.maxTokensPerTurn}:{},persona:u.persona,avatar:{color:u.color},engine:u.engine,approvalMode:u.approvalMode,tools:u.tools,skillIds:u.skillIds,mcpServerIds:u.mcpServerIds,delegation:{canDelegateTo:u.canDelegateTo,acceptFrom:u.acceptFrom},memory:{enabled:u.memoryEnabled},...D.budget?{budget:D.budget}:{}});if(!z.ok){x(sl(z.reason,z.error,o));return}ce.getState().upsertBot(z.bot),p&&!await Zk(z.bot.id,p)&&Be({type:"error",title:o("Avatar update failed")}),t(!1);const $=await ce.getState().openDirect(z.bot.id);$&&s?.($)}finally{b(!1)}};return i.jsx(wn,{open:e,onOpenChange:t,children:i.jsxs(yn,{className:"max-h-[85vh] max-w-3xl",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:o("New member")}),i.jsx(Bs,{children:o("Members have their own persona, model, tools and memory. Their name is how you @ them in groups.")})]}),i.jsxs(On,{className:"space-y-4",children:[i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ge,{size:"sm",variant:d.kind==="template"?"default":"outline",disabled:a.length===0,onClick:()=>C(a[0]),children:o("From template")}),i.jsx(ge,{size:"sm",variant:d.kind==="blank"?"default":"outline",onClick:N,children:o("Blank")}),i.jsxs(ge,{size:"sm",variant:d.kind==="import"?"default":"outline",onClick:()=>l.current?.click(),children:[i.jsx(ug,{}),o("Import character card")]}),i.jsx("input",{ref:l,type:"file",accept:".json,.png,application/json,image/png",hidden:!0,onChange:D=>{const T=D.target.files?.[0];D.target.value="",T&&A(T)}})]}),d.kind==="template"&&i.jsxs("div",{className:"grid grid-cols-3 gap-2.5",children:[a.map(D=>i.jsxs("button",{type:"button",onClick:()=>C(D),className:q("flex flex-col items-start gap-1 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted",d.id===D.id&&"ring-2 ring-info"),children:[i.jsx(tn,{bot:{name:D.data.title,avatar:{color:D.data.color}}}),i.jsx("span",{className:"font-medium text-sm",children:D.data.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:D.data.summary})]},D.id)),i.jsxs("button",{type:"button",onClick:N,className:"flex items-center justify-center gap-1 rounded-xl border border-dashed p-3 text-muted-foreground text-sm hover:bg-muted",children:[i.jsx(ds,{className:"h-4 w-4"}),o("Blank member")]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(Kt,{hint:o("Used for @ in groups; must be unique"),children:o("Name")}),i.jsx(Xt,{value:u.name,onChange:D=>S({name:D.target.value}),onBlur:()=>y(!0)}),v&&E&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:E})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:o("Title")}),i.jsx(Xt,{value:u.title,onChange:D=>S({title:D.target.value})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:o("Model")}),i.jsx(Xk,{engine:u.engine,onChange:D=>S({engine:D}),zIndex:kn.DROPDOWN_IN_MODAL})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:o("Avatar color")}),i.jsxs("div",{className:"flex items-start gap-2.5",children:[i.jsx(tn,{bot:{name:u.name||"?",avatar:{color:u.color}},src:p??void 0,size:"md"}),i.jsxs("div",{className:"min-w-0 space-y-1.5",children:[i.jsx(Yk,{value:u.color,onChange:D=>S({color:D})}),i.jsx(CD,{nested:!0,hasImage:!!p,onPick:f,onRemove:()=>f(null)})]})]})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Kt,{hint:o("Used for routing and the delegation directory"),children:o("Responsibilities")}),i.jsx(Xt,{value:u.scope,onChange:D=>S({scope:D.target.value})})]}),i.jsxs("div",{className:"col-span-2",children:[i.jsx(Kt,{action:i.jsx(DD,{value:u,onApply:S}),children:o("Persona")}),i.jsx(ei,{rows:4,value:u.persona,onChange:D=>S({persona:D.target.value})})]}),i.jsxs("div",{className:"col-span-2 rounded-lg border",children:[i.jsxs("button",{type:"button",className:"flex w-full items-center gap-1.5 px-3 py-2 text-left text-sm","aria-expanded":_,onClick:()=>j(D=>!D),children:[i.jsx(bn,{className:q("h-4 w-4 transition-transform",_&&"rotate-90")}),i.jsx("span",{className:"font-medium",children:o("Abilities")}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:o("Tools, approval, skills, MCP, delegation and memory")})]}),_&&i.jsx("div",{className:"border-t px-3 py-3",children:i.jsx(jD,{value:u,onChange:S,profile:u,zIndex:kn.DROPDOWN_IN_MODAL})})]})]}),g&&i.jsx("p",{className:"text-destructive text-sm",children:g})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),i.jsxs(ge,{size:"sm",disabled:w||v&&!!E,onClick:()=>{I()},children:[w&&i.jsx(qt,{className:"animate-spin"}),o("Create and start chatting")]})]})]})})}function oI({projectId:e,onChange:t}){const{t:n}=Q(),s=Ce(p=>p.projects),o=Ce(p=>p.addProject),r=m.useMemo(()=>Ku(s),[s]),[a,l]=m.useState([]),[d,c]=m.useState(()=>r.find(p=>p.id===e)?.path??"");m.useEffect(()=>{window.electronAPI.projects.getRecent().then(l).catch(()=>l([]))},[]),m.useEffect(()=>{const p=r.find(f=>f.id===e)?.path;p&&c(p)},[e,r]);const u=m.useMemo(()=>{const p=new Set(r.map(f=>f.path));return[...r.map(f=>({path:f.path,label:f.alias||f.name,detail:f.path,projectId:f.id})),...a.filter(f=>!p.has(f.path)).map(f=>({path:f.path,label:bj(f.path),detail:`${f.displayPath} · ${f.sourceName}`}))]},[r,a]),h=async p=>{c(p);const f=r.find(g=>g.path===p);if(f)return t(f.id);try{const g=await o(p);if(!g)throw new Error;t(g.id)}catch(g){Be({type:"error",title:n("Failed to add project"),description:g instanceof Error&&g.message||void 0})}};return i.jsxs(ev,{value:d,onValueChange:(p,f)=>{c(p??""),f.reason==="item-press"&&p?h(p):e&&t("")},items:u,filter:(p,f)=>{if(!f)return!0;const g=f.toLowerCase();return[p.label,p.path,p.detail].some(x=>x.toLowerCase().includes(g))},itemToStringValue:p=>p.path,children:[i.jsxs("div",{className:"mt-2 flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(tv,{placeholder:n("Search Code projects or recent folders..."),showClear:!!d,showTrigger:!0})}),i.jsx(ge,{type:"button",variant:"outline",onClick:()=>{window.electronAPI.dialog.selectDirectory().then(p=>{p&&h(p)})},children:n("Browse")})]}),i.jsxs(qD,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(sv,{children:n("No matching projects found")}),i.jsx(iv,{children:p=>i.jsxs(nv,{value:p,className:"gap-2",children:[i.jsx("span",{className:"shrink-0",children:p.label}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground text-xs",title:p.path,children:p.detail}),!p.projectId&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n("Add")})]},p.path)})]})]})}function MZ({open:e,onOpenChange:t}){const{t:n}=Q(),s=ce(I=>I.bots),o=m.useMemo(()=>s.filter(I=>I.archivedAt===void 0),[s]),r=Ku(Ce(I=>I.projects)),[a,l]=m.useState(""),[d,c]=m.useState([]),[u,h]=m.useState(null),[p,f]=m.useState("project"),[g,x]=m.useState(""),[v,y]=m.useState(String(Nr.maxHops)),[w,b]=m.useState(String(Nr.maxTurnsPerBot)),[_,j]=m.useState(!1),[N,C]=m.useState(null);m.useEffect(()=>{e&&(l(""),c([]),h(null),f(r.length>0?"project":"chat-home"),x(r[0]?.id??""),y(String(Nr.maxHops)),b(String(Nr.maxTurnsPerBot)),j(!1),C(null))},[e]);const S=(I,D)=>{const T=D?[...d,I]:d.filter(z=>z!==I);c(T),T.includes(u??"")?!u&&T.length&&h(T[0]):h(T[0]??null)},A=d.length>=2&&u!==null&&(p==="chat-home"||!!g),E=async()=>{if(A){j(!0);try{const I=await window.electronAPI.bots.createChat({kind:"group",title:a.trim(),members:d,bossBotId:u,workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},routing:{maxHops:Math.round(Number(v))||Nr.maxHops,maxTurnsPerBot:Math.round(Number(w))||Nr.maxTurnsPerBot}});if(!I.ok){C(_s(I.error,n));return}const D=ce.getState();D.upsertChat(I.chat),D.setView({kind:"chat",chatId:I.chat.id}),D.loadLatest(I.chat.id),t(!1)}finally{j(!1)}}};return i.jsx(wn,{open:e,onOpenChange:t,children:i.jsxs(yn,{className:"max-h-[85vh] max-w-xl",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:n("New group chat")}),i.jsx(Bs,{children:n("One member replies at a time. Without @, the best-fit member is picked to reply.")})]}),i.jsxs(On,{className:"space-y-4",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:n("Group name")}),i.jsx(Xt,{value:a,onChange:I=>l(I.target.value)})]}),i.jsxs("div",{children:[i.jsx(Kt,{hint:n("Pick at least two, and one owner"),children:n("Members")}),o.length<2&&i.jsx("p",{className:"text-muted-foreground text-xs",children:n("Create at least two members first.")}),i.jsx("div",{className:"space-y-0.5",children:o.map(I=>{const D=d.includes(I.id);return i.jsxs("div",{className:"flex items-center gap-2.5 rounded-md px-1.5 py-1 hover:bg-muted",children:[i.jsx(dd,{checked:D,onCheckedChange:T=>S(I.id,T===!0)}),i.jsx(tn,{bot:I,size:"sm"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-sm",children:[I.name,I.title&&i.jsx("span",{className:"ml-1.5 text-muted-foreground text-xs",children:I.title})]}),D&&i.jsxs("label",{className:"flex shrink-0 items-center gap-1 text-muted-foreground text-xs",children:[i.jsx("input",{type:"radio",name:"group-owner",checked:u===I.id,onChange:()=>h(I.id),className:"accent-primary"}),n("Owner")]})]},I.id)})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:n("Shared workspace")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[i.jsxs("button",{type:"button",onClick:()=>f("project"),className:q("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:n("Based on a Code project")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:n("Members read and write directly in the project folder")})]}),i.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:q("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:n("Standalone workspace")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:n("A new empty folder for this group, removed with the group")})]})]}),p==="project"&&i.jsx(oI,{projectId:g,onChange:x}),i.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-warning/40 bg-warning/8 px-3 py-2 text-xs",children:[i.jsx(wg,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),i.jsx("span",{children:n("All members share this folder: anyone who can talk to a member can reach its contents through them. You can change it later in group info (members start new conversations).")})]})]}),i.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:n("@ relay limit (per message of yours)")}),i.jsx(Xt,{type:"number",min:1,max:20,value:v,onChange:I=>y(I.target.value)})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:n("Max replies per member")}),i.jsx(Xt,{type:"number",min:1,max:10,value:w,onChange:I=>b(I.target.value)})]})]}),N&&i.jsx("p",{className:"text-destructive text-sm",children:N})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>t(!1),children:n("Cancel")}),i.jsxs(ge,{size:"sm",disabled:!A||_,onClick:()=>{E()},children:[_&&i.jsx(qt,{className:"animate-spin"}),n("Create")]})]})]})})}const cS={skillIds:[],mcpServerIds:[]};function RZ({open:e,onOpenChange:t,seedTemplateId:n,onCreated:s}){const{t:o,locale:r}=Q(),a=ce(V=>V.bots),l=vj(),d=Ku(Ce(V=>V.projects)),c=m.useRef(null),[u,h]=m.useState(null),[p,f]=m.useState("chat-home"),[g,x]=m.useState(""),[v,y]=m.useState(!1),[w,b]=m.useState(null),[_,j]=m.useState({}),[N,C]=m.useState(null),[S,A]=m.useState(!1);m.useEffect(()=>{if(!e)return;h(null),x(d[0]?.id??""),y(!1),b(null),j({}),C(null);const V=l.find(J=>J.id===n);V&&E({team:s0(V.data)})},[e]);const E=async V=>{y(!0),b(null);try{const J=await window.electronAPI.bots.previewTeam(V);if(!J.ok){b(Z2(J.error,o));return}h({team:J.team,renamed:J.renamed,picked:J.team.members.map(pe=>pe.key)}),j({}),C(null),f(J.team.workspace==="project"&&d.length>0?"project":"chat-home")}finally{y(!1)}},I=V=>h(J=>J&&{...J,team:V(J.team)}),D=(V,J)=>I(pe=>({...pe,members:pe.members.map(fe=>fe.key===V?{...fe,...J}:fe)})),T=m.useMemo(()=>u?J2(u.team,u.picked):null,[u]),z=m.useMemo(()=>{const V=new Map;if(!T)return V;const J=[...a,...T.members.map(pe=>({id:`team:${pe.key}`,name:pe.name}))];for(const pe of T.members){const fe=fg(pe.name,J,o,`team:${pe.key}`);fe&&V.set(pe.key,fe)}return V},[T,a,o]),$=T!==null&&z.size===0&&(p==="chat-home"||!!g)&&!v&&!S,R=V=>_[V]??cS,B=(V,J)=>j(pe=>({...pe,[V]:{...pe[V]??cS,...J}})),H=async()=>{if(T){A(!0);try{const V=r==="zh"?"zh":"en",J=await Promise.all(T.members.map(async W=>{try{const G=await window.electronAPI.bots.suggestAbilities({name:W.name,title:W.title,scope:W.scope,persona:W.persona,language:V});return{key:W.key,result:G}}catch{return{key:W.key,result:null}}}));let pe=0,fe=0,_e;const Ee={..._},me=new Map;for(const{key:W,result:G}of J){if(!G?.ok){fe++,G&&!_e&&(_e=Dh(G,o));continue}const{suggestion:de}=G,X={};de.tools&&(X.tools=de.tools.value),de.approvalMode&&(X.approvalMode=de.approvalMode.value),Object.keys(X).length>0&&me.set(W,X);const ie=de.skillIds?.value??R(W).skillIds,Z=de.mcpServerIds?.value??R(W).mcpServerIds;Ee[W]={skillIds:[...ie],mcpServerIds:[...Z]},(ie.length+Z.length>0||me.has(W))&&pe++}j(Ee),me.size>0&&I(W=>({...W,members:W.members.map(G=>({...G,...me.get(G.key)}))})),fe>0&&Be({type:"error",title:o("Suggestions failed for {{n}} members",{n:fe}),..._e?{description:_e}:{}}),fe<J.length&&Be({type:pe>0?"success":"info",title:pe>0?o("Configured abilities for {{n}} members",{n:pe}):o("Current abilities already match the suggestion.")})}finally{A(!1)}}},oe=async()=>{if(!(!T||!$)){y(!0),b(null);try{const V=Object.fromEntries(T.members.map(fe=>[fe.key,R(fe.key)]).filter(([,fe])=>fe.skillIds.length+fe.mcpServerIds.length>0)),J=await window.electronAPI.bots.createTeam({team:{...T,title:T.title.trim()},workspace:p==="project"?{kind:"project",projectId:g}:{kind:"chat-home"},...Object.keys(V).length>0?{assets:V}:{}});if(!J.ok){b(sl(J.error,_s(J.error,o),o));return}const pe=ce.getState();for(const fe of J.bots)pe.upsertBot(fe);pe.upsertChat(J.chat),pe.setView({kind:"chat",chatId:J.chat.id}),pe.loadLatest(J.chat.id),t(!1),s?.(J.chat.id)}finally{y(!1)}}},te=r==="zh"?"zh":"en",O=V=>u?.team.members.find(J=>J.key===V)?.name??V;return i.jsx(wn,{open:e,onOpenChange:t,children:i.jsxs(yn,{className:"max-h-[85vh] max-w-2xl",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:o("Create team from template")}),i.jsx(Bs,{children:o("Creates the members and their group chat in one go. Members follow the default model; expand a member to set tools, approval, delegation, skills and MCP, or let AI set them.")})]}),i.jsxs(On,{className:"space-y-4",children:[u?i.jsxs(i.Fragment,{children:[i.jsxs("div",{children:[i.jsx(Kt,{children:o("Group name")}),i.jsx(Xt,{value:u.team.title,onChange:V=>{const J=V.target.value;I(pe=>({...pe,title:J}))}})]}),i.jsxs("div",{children:[i.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[i.jsxs("span",{className:"flex items-baseline gap-2",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:o("Members")}),i.jsx("span",{className:"text-[11px] text-muted-foreground/70",children:o("Uncheck members you do not need; the owner stays")})]}),i.jsxs(ge,{size:"xs",variant:"outline",disabled:!T||S||v,onClick:()=>{H()},children:[S?i.jsx(qt,{className:"animate-spin"}):i.jsx(zs,{}),o("AI auto-configure")]})]}),i.jsx("div",{className:"space-y-1.5",children:u.team.members.map(V=>{const J=u.picked.includes(V.key),pe=V.key===u.team.bossKey,fe=u.renamed.find(de=>de.key===V.key),_e=J?z.get(V.key):void 0,Ee=V.delegation.canDelegateTo,me=Ee==="any"?[]:Ee.filter(de=>u.picked.includes(de)),W=R(V.key),G=J&&N===V.key;return i.jsxs("div",{className:q("flex items-start gap-2.5 rounded-lg border px-2.5 py-2",!J&&"opacity-60"),children:[i.jsx(dd,{className:"mt-1.5",checked:J,disabled:pe,onCheckedChange:de=>h({...u,picked:de===!0?[...u.picked,V.key]:u.picked.filter(X=>X!==V.key)})}),i.jsx(tn,{bot:V,size:"sm"}),i.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Xt,{className:"h-7 w-36",value:V.name,disabled:!J,onChange:de=>{const X=de.target.value;I(ie=>({...ie,members:ie.members.map(Z=>Z.key===V.key?{...Z,name:X}:Z)}))}}),i.jsx("span",{className:"truncate text-muted-foreground text-xs",children:V.title}),pe&&i.jsxs("span",{className:"flex shrink-0 items-center gap-0.5 rounded bg-muted px-1.5 text-[10px] text-muted-foreground",children:[i.jsx(ij,{className:"h-3 w-3"}),o("Owner")]})]}),i.jsx("p",{className:"text-muted-foreground text-xs",children:V.scope}),fe&&fe.to===V.name&&i.jsx("p",{className:"text-warning text-xs",children:o('"{{from}}" is taken, renamed to "{{to}}"',fe)}),_e&&i.jsx("p",{className:"text-destructive text-xs",children:_e}),i.jsxs("button",{type:"button",disabled:!J,onClick:()=>C(G?null:V.key),className:"flex items-start gap-1 text-left text-[11px] text-muted-foreground hover:text-foreground disabled:pointer-events-none",children:[G?i.jsx(Vn,{className:"mt-px h-3 w-3 shrink-0"}):i.jsx(bn,{className:"mt-px h-3 w-3 shrink-0"}),i.jsxs("span",{children:[V.tools==="readonly"?o("Read-only"):o("All tools")," · ",o(Pl[V.approvalMode].labelKey),me.length>0&&` · ${o("Delegates to {{names}}",{names:me.map(O).join(te==="zh"?"、":", ")})}`," · ",W.skillIds.length+W.mcpServerIds.length===0?o("No skills or MCP"):o("{{n}} skills · {{m}} MCP",{n:W.skillIds.length,m:W.mcpServerIds.length})]})]}),G&&i.jsxs("div",{className:"space-y-3 rounded-lg bg-muted/40 p-2.5",children:[i.jsxs("div",{children:[i.jsx(Kt,{children:o("Tools")}),i.jsx(hg,{value:V.tools,options:[{value:"all",label:o("All tools")},{value:"readonly",label:o("Read-only")}],onChange:de=>D(V.key,{tools:de})})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:o("Approval mode")}),i.jsx(Kk,{value:V.approvalMode,onChange:de=>D(V.key,{approvalMode:de}),zIndex:kn.DROPDOWN_IN_MODAL})]}),i.jsx(i0,{label:o("Can delegate to"),value:V.delegation.canDelegateTo,options:u.picked.filter(de=>de!==V.key),nameOf:O,onChange:de=>D(V.key,{delegation:{...V.delegation,canDelegateTo:de}})}),i.jsx(i0,{label:o("Accepts delegation from"),value:V.delegation.acceptFrom,options:u.picked.filter(de=>de!==V.key),nameOf:O,onChange:de=>D(V.key,{delegation:{...V.delegation,acceptFrom:de}})}),i.jsx(_D,{value:W,onChange:de=>B(V.key,de)})]})]})]},V.key)})}),!T&&i.jsx("p",{className:"mt-1 text-destructive text-xs",children:o("Keep the owner and at least one other member.")})]}),i.jsxs("div",{children:[i.jsx(Kt,{children:o("Shared workspace")}),i.jsxs("div",{className:"grid grid-cols-2 gap-2.5",children:[i.jsxs("button",{type:"button",onClick:()=>f("chat-home"),className:q("rounded-xl border bg-card p-3 text-left",p==="chat-home"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:o("Standalone workspace")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:o("A new empty folder for this group, removed with the group")})]}),i.jsxs("button",{type:"button",onClick:()=>f("project"),className:q("rounded-xl border bg-card p-3 text-left disabled:opacity-50",p==="project"&&"ring-2 ring-info"),children:[i.jsx("div",{className:"font-medium text-sm",children:o("Based on a Code project")}),i.jsx("div",{className:"mt-0.5 text-muted-foreground text-xs",children:o("Members read and write directly in the project folder")})]})]}),p==="project"&&i.jsx(oI,{projectId:g,onChange:x}),i.jsxs("div",{className:"mt-2 flex gap-2 rounded-lg border border-info/40 bg-info/8 px-3 py-2 text-xs",children:[i.jsx(wg,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-info"}),i.jsx("span",{children:o(u.team.routing.mode==="smart"?"Without @, the best-fit member replies; @ relay limit {{n}}.":"Without @, the owner replies; @ relay limit {{n}}.",{n:u.team.routing.maxHops})})]})]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"grid grid-cols-3 gap-2.5",children:l.map(({id:V,data:J})=>i.jsxs("button",{type:"button",disabled:v,onClick:()=>{E({team:s0(J)})},className:"flex flex-col items-start gap-1.5 rounded-xl border bg-card p-3 text-left transition-colors hover:bg-muted disabled:opacity-50",children:[i.jsx("div",{className:"-space-x-1.5 flex",children:J.members.map(pe=>i.jsx(tn,{size:"sm",bot:{name:pe.name,avatar:{color:pe.color}}},pe.key))}),i.jsx("span",{className:"font-medium text-sm",children:J.title}),i.jsx("span",{className:"text-muted-foreground text-xs",children:J.summary})]},V))}),i.jsxs(ge,{size:"sm",variant:"outline",disabled:v,onClick:()=>c.current?.click(),children:[i.jsx(ug,{}),o("Import team (JSON)")]}),i.jsx("input",{ref:c,type:"file",accept:".json,application/json",hidden:!0,onChange:V=>{const J=V.target.files?.[0];V.target.value="",J&&J.text().then(pe=>E({text:pe}))}})]}),w&&i.jsx("p",{className:"text-destructive text-sm",children:w})]}),i.jsxs(cs,{children:[u&&i.jsxs(ge,{variant:"ghost",size:"sm",className:"mr-auto",onClick:()=>{h(null),b(null)},children:[i.jsx(ad,{}),o("Back")]}),i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>t(!1),children:o("Cancel")}),u&&i.jsxs(ge,{size:"sm",disabled:!$,onClick:()=>{oe()},children:[v&&i.jsx(qt,{className:"animate-spin"}),o("Create team")]})]})]})})}const jo="relative flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function LZ({sidebarWidth:e,collapsed:t,onToggleCollapse:n,onResize:s}){const o=Zu()==="mobile",{t:r}=Q(),a=ce(T=>T.view),l=ce(T=>T.chats),d=ce(T=>T.bots),c=ce(T=>T.loaded),u=ce(T=>T.setView),[h,p]=m.useState(!1),[f,g]=m.useState(!1),[x,v]=m.useState(!1),[y,w]=m.useState(!1),[b,_]=m.useState(null),j=m.useRef(""),N=Sg(),C=a?.kind==="chat"?l.find(T=>T.id===a.chatId):void 0,S=C?.kind==="group"?Q6(l,C):void 0;m.useEffect(()=>{c&&a?.kind==="chat"&&!C&&u(null)},[c,a,C,u]);const A=async T=>{if(T.botId){const z=ce.getState();if(!z.bots.some(R=>R.id===T.botId))throw new Error("Member not found");const $=await z.openDirect(T.botId);if(!$)throw new Error("Could not open chat");o0($,T.firstMessage.trim()),w(!1);return}w(!1),_(T),j.current=T.firstMessage.trim(),T.templateId?v(!0):p(!0)},E=T=>{j.current&&o0(T,j.current),j.current=""},I=()=>{_(null),j.current="",p(!0)},D=()=>{_(null),j.current="",v(!0)};return i.jsxs(i.Fragment,{children:[t?i.jsxs("aside",{className:"flex w-12 shrink-0 flex-col items-center gap-1 border-r bg-background py-2",children:[i.jsx(iI,{className:jo}),i.jsx("button",{type:"button",className:jo,onClick:()=>w(!0),title:r("Start from a goal"),children:i.jsx(Na,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:jo,onClick:I,title:r("New member"),children:i.jsx(Hl,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:jo,onClick:()=>g(!0),title:r("New group chat"),children:i.jsx(ra,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:jo,onClick:D,title:r("Create team from template"),children:i.jsx(Cf,{className:"h-4 w-4"})}),(N>0||a?.kind==="inbox")&&i.jsxs("button",{type:"button",className:q(jo,a?.kind==="inbox"&&"bg-brand/10 text-foreground hover:bg-brand/10 dark:bg-brand/15 dark:hover:bg-brand/15"),onClick:()=>u({kind:"inbox"}),title:r("Inbox"),children:[i.jsx(vx,{className:"h-4 w-4"}),N>0&&i.jsx(Eh,{count:N,className:"-top-0.5 -right-1 absolute"})]}),i.jsx("div",{className:"flex-1"}),i.jsx("button",{type:"button",className:jo,onClick:()=>{window.electronAPI.window.openSettings()},title:r("Settings"),children:i.jsx(ui,{className:"h-4 w-4"})}),o&&i.jsx("button",{type:"button",className:jo,onClick:n,title:r("Expand sidebar"),children:i.jsx(tN,{className:"h-4 w-4"})})]}):i.jsxs(i.Fragment,{children:[i.jsx(EZ,{width:e,onCollapse:o?n:void 0,onNewMember:I,onNewGroup:()=>g(!0),onNewTeam:D,onStartFromGoal:()=>w(!0)}),i.jsx(wu,{onResize:s})]}),a?.kind==="inbox"?i.jsx(iZ,{}):C?i.jsx(ZX,{chat:S??C,group:C},S?.id??C.id):i.jsxs("div",{className:"flex min-w-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[i.jsx(Hs,{className:"h-8 w-8 text-muted-foreground"}),i.jsx("p",{className:"font-medium text-lg",children:r("Bot mode")}),i.jsx("p",{className:"max-w-md text-muted-foreground text-sm",children:d.length===0?r("Tell us in one sentence what you want done; we will recommend a member or a team and draft your first message."):r("Pick a member or a group chat on the left.")}),d.length===0&&c&&i.jsx(dS,{onPick:A}),i.jsxs("div",{className:"flex gap-2",children:[i.jsxs(ge,{size:"sm",variant:d.length===0?"outline":"default",onClick:I,children:[i.jsx(Hl,{}),r("New member")]}),d.length>=2&&i.jsxs(ge,{size:"sm",variant:"outline",onClick:()=>g(!0),children:[i.jsx(ra,{}),r("New group chat")]}),i.jsxs(ge,{size:"sm",variant:"outline",onClick:D,children:[i.jsx(Cf,{}),r("Create team from template")]})]})]}),i.jsx(AZ,{open:h,onOpenChange:p,seed:b?.member,onCreated:E}),i.jsx(MZ,{open:f,onOpenChange:g}),i.jsx(DZ,{}),i.jsx(RZ,{open:x,onOpenChange:v,seedTemplateId:b?.templateId,onCreated:E}),i.jsx(wn,{open:y,onOpenChange:w,children:i.jsxs(yn,{className:"max-w-xl",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:r("Start from a goal")}),i.jsx(Bs,{children:r("Tell us in one sentence what you want done; we will recommend a member or a team and draft your first message.")})]}),i.jsx(On,{className:"flex justify-center pb-4",children:y&&i.jsx(dS,{onPick:A})})]})})]})}const uS="enso-mode",lo=rg()(e=>({mode:localStorage.getItem(uS)==="bot"?"bot":"code",setMode:t=>{localStorage.setItem(uS,t),e({mode:t})}}));function Qd(){return Ce.getState().botModeEnabled&&ts.getState().activeNodeId==="local"&&lo.getState().mode==="bot"}function OZ(){const e=Ce(s=>s.botModeEnabled),t=ts(s=>s.activeNodeId==="local"),n=lo(s=>s.mode);return e&&t&&n==="bot"}async function zZ(e){if(!Ce.getState().botModeEnabled)return;const t=typeof e.chatId=="string"?e.chatId:void 0,n=typeof e.conversationId=="string"?e.conversationId:void 0,s=ce.getState();t||await s.refreshDelegations(),ts.getState().activeNodeId!=="local"&&ts.getState().switchNode("local"),lo.getState().setMode("bot");const o=Q2({chatId:t,conversationId:n},ce.getState().delegations);if(o.kind==="chat"){const r=s.chats.find(a=>a.id===o.chatId);r?.kind==="group"&&s.openThread(r.parentId??r.id,r.id)}s.setView(o)}function GZ(){ts.getState().activeNodeId!=="local"&&ts.getState().switchNode("local"),lo.getState().setMode("code")}const za=[{value:"code",label:"Code",Icon:Go},{value:"bot",label:"Bot",Icon:eL}],FZ={ArrowLeft:-1,ArrowUp:-1,ArrowRight:1,ArrowDown:1},HZ={duration:.26,ease:[.22,1,.36,1]},BZ={duration:.5,ease:[.34,1.36,.64,1]},VZ={duration:.18,ease:[.4,0,.2,1]};function $Z({className:e}){const{t}=Q(),n=lo(h=>h.mode),s=lo(h=>h.setMode),o=Sg(),r=Ai(Ce(h=>h.keybindings))["toggle-app-mode"],a=r?`${t("Switch between Code and Bot")} (${fi(r)})`:void 0,l=aV()??!1,d=m.useId(),c=m.useRef({}),u=h=>{const p=FZ[h.key];if(!p)return;h.preventDefault();const f=za.findIndex(x=>x.value===n),g=za[(f+p+za.length)%za.length].value;s(g),c.current[g]?.focus()};return i.jsx("div",{role:"radiogroup","aria-label":t("Switch mode"),onKeyDown:u,className:q("flex h-7 shrink-0 rounded-lg bg-muted/60 p-0.5 text-xs",e),children:za.map(({value:h,label:p,Icon:f})=>{const g=n===h,x=h==="bot"&&n==="code"&&o>0;return i.jsxs("button",{ref:v=>{c.current[h]=v},type:"button",role:"radio","aria-checked":g,tabIndex:g?0:-1,title:a,onClick:()=>s(h),className:q("relative flex items-center gap-1.5 rounded-md px-2.5 font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",g?"text-foreground":"text-muted-foreground hover:text-foreground"),children:[g&&i.jsx(Ms.span,{layoutId:d,"aria-hidden":!0,className:"absolute inset-0 rounded-md bg-background shadow-xs",transition:l?{duration:0}:Jr}),i.jsx(f,{className:"relative h-3.5 w-3.5"}),i.jsx("span",{className:"relative",children:p}),i.jsx(hl,{children:x&&i.jsx(Ms.span,{className:"-top-1.5 -right-1.5 pointer-events-none absolute",initial:l?!1:{x:-8,y:12},animate:{x:0,y:0},transition:HZ,children:i.jsx(Ms.span,{className:"block",initial:l?!1:{scale:0,opacity:0,filter:"blur(2px)"},animate:{scale:1,opacity:1,filter:"blur(0px)"},exit:l?{opacity:0,transition:{duration:0}}:{scale:0,opacity:0,filter:"blur(2px)",transition:VZ},transition:BZ,children:i.jsx(Eh,{count:o,className:"block"})})})})]},h)})})}const Zl="enso:open-chat-find";let Am;function rI(e){Am=e,window.dispatchEvent(new Event(Zl))}function hS(){const e=Am;return Am=void 0,e}function WZ({query:e,onQueryChange:t,current:n,total:s,onPrev:o,onNext:r,onClose:a}){const{t:l}=Q(),d=m.useRef(null);return m.useEffect(()=>{const c=()=>{d.current?.focus(),d.current?.select()};return c(),window.addEventListener(Zl,c),()=>window.removeEventListener(Zl,c)},[]),i.jsxs("div",{className:"flex shrink-0 items-center gap-1.5 border-b px-3 py-1.5",children:[i.jsxs("div",{className:"relative min-w-0 flex-1",children:[i.jsx(ti,{className:"pointer-events-none absolute top-1/2 left-2.5 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Xt,{ref:d,value:e,onChange:c=>t(c.target.value),onKeyDown:c=>{if(c.key==="Escape"){c.preventDefault(),a();return}c.key==="Enter"&&(c.preventDefault(),c.shiftKey?o():r())},placeholder:l("Search messages..."),className:"h-8 text-xs [&_input]:pl-8"})]}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:s===0?l("No results"):`${n}/${s}`}),i.jsx(ge,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:o,"aria-label":l("Previous match"),children:i.jsx(wj,{className:"h-3.5 w-3.5"})}),i.jsx(ge,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",disabled:s===0,onClick:r,"aria-label":l("Next match"),children:i.jsx(Vn,{className:"h-3.5 w-3.5"})}),i.jsx(ge,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:a,children:i.jsx(an,{className:"h-3.5 w-3.5"})})]})}function UZ(e,t,n,s){return e.host?.kind==="oauth-login"&&s?.host?.kind==="oauth-login"&&e.child.sessionId===t&&e.child.generation===n&&e.turnId===s.turnId&&e.requestId===s.requestId&&sL(e.child,s.child)}function KZ({request:e,conversationId:t}){const{t:n}=Q(),s=re(l=>l.conversations[t]),o=tL({onDone:()=>{iL()}}),r=e.host,a=UZ(e,t,s?.generation,s?.activeOauthAsk);return m.useEffect(()=>{if(!(!a||r?.kind!=="oauth-login"))return o.attach(r.providerId,{host:"agent-child-tab",child:e.child,turnId:e.turnId,requestId:e.requestId}),o.reset},[a,o.attach,o.reset,r,e.child,e.requestId,e.turnId]),!a||r?.kind!=="oauth-login"?null:i.jsxs("section",{className:"mb-1 space-y-3 rounded-lg border border-primary/20 bg-primary/5 p-3",children:[i.jsxs("div",{children:[i.jsx("p",{className:"text-sm font-medium",children:n("Subscription authorization")}),i.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:r.providerLabel})]}),i.jsx(nL,{flow:o,providerLabel:r.providerLabel})]})}function qZ(e){const{t}=Q(),n=e?.startsWith("bot:")?e.slice(4):void 0,s=ce(a=>n?a.bots.find(l=>l.id===n)?.name:void 0),[o,r]=m.useState();if(m.useEffect(()=>{if(r(void 0),!e||!n||s)return;let a=!0;return window.electronAPI.agentRegistry.list().then(l=>{const d=Hk(l)?.candidates.find(c=>c.typeKey===e);a&&r(d?.displayName)}).catch(()=>{}),()=>{a=!1}},[e,n,s]),!!n)return s??o??t("Member")}function YZ(e,t){return e?null:t?"empty":"hydrating"}function XZ(e){const t=e.activeId?e.conversations[e.activeId]:void 0;return t?t.activeTabId?e.conversations[t.activeTabId]?.id??t.id:t.id:null}function ZZ(e){const t=e.activeId?e.conversations[e.activeId]:void 0;if(!t)return null;const n=t.activeTabId?e.conversations[t.activeTabId]??t:t;return{id:n.id,parentId:t.id,projectId:n.projectId,parentProjectId:t.projectId,status:n.status,spawning:n.spawning,started:n.started,sessionFile:n.sessionFile,parentStarted:t.started,parentStatus:t.status,parentSessionFile:t.sessionFile,parentWorktreeMissing:t.worktreeMissing,parentWorktreePath:t.worktree?.path,parentWorktreeBranch:t.worktree?.branch,lastProviderId:n.lastProviderId,lastModelId:n.lastModelId,parentLastProviderId:t.lastProviderId,parentLastModelId:t.lastModelId,reasoningEnabled:n.reasoningEnabled,thinkingLevel:n.thinkingLevel,presetId:n.presetId,approvalMode:n.approvalMode,autoRejectApprovals:n.autoRejectApprovals,draftText:n.draftText,draftImages:n.draftImages,draftAppend:n.draftAppend,prefillAgentTypeKey:n.prefillAgentTypeKey,commands:n.commands,compactionError:n.compactionError,agentType:n.agentType,parentHasRunningChild:kg(t,e.conversations),retry:n.retry,pendingApprovals:n.pendingApprovals,pendingAsks:n.pendingAsks,pendingCapabilityAsks:n.pendingCapabilityAsks,backgroundTasks:n.backgroundTasks,subagents:n.subagents,queuedMessages:n.queuedMessages,goal:n.goal,planState:n.planState,rewinding:n.rewinding,restoringFiles:n.restoringFiles,childLockedProfileId:n.child?.lockedProfileId,activeOauthAsk:n.activeOauthAsk,displayedParentId:n.parentId,busy:yj(n)}}function JZ(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt}function QZ(e,t){return{id:e.id??"",title:e.title,status:e.status??"idle",spawning:e.spawning===!0,hasRunningChild:t,pinned:e.pinned,archived:e.archived,archivedAt:e.archivedAt,createdAt:e.createdAt,projectId:e.projectId,lastActiveAt:JZ(e),messages:[],forkedFromConversationId:e.forkedFromConversationId,unread:e.unread,activeRenewedAt:e.activeRenewedAt,pendingAsks:e.pendingAsks,pendingApprovals:e.pendingApprovals,pendingCapabilityAsks:e.pendingCapabilityAsks,coworkerIds:e.coworkerIds,coworkerName:e.coworkerName,child:e.child,subagents:e.subagents,backgroundTasks:e.backgroundTasks?.map(({status:n})=>({status:n})),parentId:e.parentId,sessionFile:e.sessionFile,worktree:e.worktree}}function eJ(e){return JSON.stringify(e)}let Xi=null;function ov(e){if(Xi?.source===e)return Xi.value;const t={},n=[];for(const[s,o]of Object.entries(e)){if(!o||o.btwParentId)continue;const r=QZ(o,kg({status:o.status??"idle",spawning:o.spawning,subagents:o.subagents,coworkerIds:o.coworkerIds,backgroundTasks:o.backgroundTasks},e));t[s]=r,n.push(`${s}:${eJ(r)}`)}return Xi&&Xi.prints.length===n.length&&Xi.prints.every((s,o)=>s===n[o])?(Xi={source:e,prints:n,value:Xi.value},Xi.value):(Xi={source:e,prints:n,value:t},t)}let Ga=null;function tJ(e){if(Ga?.source===e)return Ga.value;const t=[];for(const[o,r]of Object.entries(e))!r||r.parentId||r.btwParentId||!r.sessionFile||t.push({id:r.id??o,title:r.title,projectId:r.projectId,sessionFile:r.sessionFile,createdAt:r.createdAt});const n=JSON.stringify(t),s=Ga?.print===n?Ga.value:t;return Ga={source:e,print:n,value:s},s}const nJ=[],pS=new WeakMap;function sJ(e,t){const n=e[t];if(!n)return nJ;const s=pS.get(n);if(s?.source===e)return s.value;const o=(n.coworkerIds??[]).flatMap(l=>{const d=e[l];return d?[{id:d.id??l,title:d.title,status:d.status??"idle",spawning:d.spawning===!0,pendingApprovalCount:d.pendingApprovals?.length??0,pendingAskCount:d.pendingAsks?.length??0,pendingCapabilityAskCount:d.pendingCapabilityAsks?.length??0,coworkerName:d.coworkerName,child:d.child?.agentInstanceName?{agentInstanceName:d.child.agentInstanceName}:void 0,mode:d.child?.mode==="task"?"task":"coworker",reloading:d.reloading===!0}]:[]}),r=JSON.stringify(o),a=s?.print===r?s.value:o;return pS.set(n,{source:e,print:r,value:a}),a}let aI=[],lI=[];const Mm=new Set,dI=e=>`/${e.pluginId}:${e.id}`;function iJ(e,t){const n=new Set(e.map(s=>s.id));return[...e,...(t??[]).filter(s=>!n.has(s.id))]}function fS(e){aI=e,lI=e.map(t=>({name:dI(t),description:`${t.title} · ${t.pluginName}`}));for(const t of Mm)t()}function mS(){return lI}function oJ(e){return aI.find(t=>dI(t)===e)??null}function rJ(e){return Mm.add(e),()=>Mm.delete(e)}function aJ(){return m.useSyncExternalStore(rJ,mS,mS)}async function lJ(e,t){const n=await window.electronAPI.extensionPlugins.call({pluginId:e.pluginId,method:"command.run",payload:{id:e.id},sessionId:t});return n.ok?null:n.error}function dJ(e){const t=new Set;for(const n of e)if(n.kind==="tool"){if(n.name==="apply_patch"){n.fileChanges?.length&&t.add(n.key);continue}n.state==="ok"&&(n.output===null&&n.durationMs===null||n.name!=="edit"&&n.name!=="write"||n.name==="edit"&&!(n.edits&&n.edits.length>0)||n.name==="write"&&!n.writeContent||t.add(n.key))}return t}function cJ(e,t){const n=Ce(r=>r.openChangesOnFileEdit),s=m.useRef(void 0),o=m.useRef(new Set);m.useEffect(()=>{const r=dJ(e);if(t!==s.current){s.current=t,o.current=r;return}let a=!1;for(const l of r)o.current.has(l)||(a=!0);o.current=r,a&&n&&Dk()},[t,n,e])}function Fa(e,t){const n=e.trim().toLowerCase();return n?t.some(s=>s?.toLowerCase().includes(n)):!0}function uJ(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=[];for(const o of e){if(o.kind!=="user"&&o.kind!=="text")continue;const r=o.text.toLowerCase();let a=0,l=0;for(;;){const d=r.indexOf(n,a);if(d===-1)break;s.push({key:o.key,nth:l}),l+=1,a=d+n.length}}return s}const hJ=[],pJ=[],fJ=typeof window<"u"&&!!window.electronAPI?.remote;function cI({conversationId:e,cwd:t,emptyTitle:n,onSuggestion:s,timelineRef:o}){const r=re(V=>V.conversations[e]?.projectId),a=re(V=>V.conversations[e]?.messages??hJ),l=re(V=>V.conversations[e]?.customEntries??pJ),d=re(V=>V.conversations[e]?.status==="running"),c=re(V=>V.conversations[e]?.compaction),u=re(V=>V.conversations[e]?.compactionNoticeAt),h=re(V=>V.conversations[e]?.historyBaseIndex??0),p=re(V=>V.conversations[e]?.toolOutputs),f=re(V=>V.conversations[e]?.toolStartedAt),g=re(V=>V.conversations[e]?.pendingApprovals),x=re(V=>V.conversations[e]?.runStartedAt),v=re(V=>V.conversations[e]?.lastOutputAt),y=re(V=>V.conversations[e]?.error),w=re(V=>V.conversations[e]?.started===!0),b=re(V=>V.conversations[e]?.sessionFile),_=re(V=>V.conversations[e]?.status),j=re(V=>V.conversations[e]?.spawning===!0),N=re(V=>V.conversations[e]?.historyLoadAttempted),C=re(V=>!!V.conversations[e]?.historyLoading),S=m.useRef({conversationId:"",items:[]}),A=m.useMemo(()=>{S.current.conversationId!==e&&(S.current={conversationId:e,items:[]});const J=oL(S.current.items,a,d,h)??xr(a,d,l,t,{compaction:c,compactionNoticeAt:u,historyBaseIndex:h,toolOutputs:p,toolStartedAt:f,pendingApprovals:g});return S.current.items=J,J},[c,u,e,t,l,h,a,g,d,p,f]);cJ(A,e);const E=rL({started:w,sessionFile:b,messages:a,spawning:j,status:_,historyLoadAttempted:N,historyLoading:C}),[I,D]=m.useState(!1),[T,z]=m.useState(""),[$,R]=m.useState(0),B=m.useMemo(()=>I?uJ(A,T):[],[I,T,A]);m.useEffect(()=>{const V=()=>{const J=hS();D(!0),J&&(z(J),R(0))};return window.addEventListener(Zl,V),()=>window.removeEventListener(Zl,V)},[]),m.useEffect(()=>{const V=hS();if(R(0),V){z(V),D(!0);return}e&&(z(""),D(!1))},[e]),m.useEffect(()=>{if(!I||B.length===0)return;const V=Math.min($,B.length-1);o.current?.scrollToKey(B[V].key)},[I,$,B,o]);const H=m.useCallback(V=>{B.length!==0&&R(J=>(J+V+B.length)%B.length)},[B.length]);m.useEffect(()=>{if(!I)return;const V=J=>{if(J.key==="Escape"){J.preventDefault(),D(!1);return}const pe=Il(J);pe==="mod+g"?(J.preventDefault(),H(1)):pe==="mod+shift+g"&&(J.preventDefault(),H(-1))};return window.addEventListener("keydown",V),()=>window.removeEventListener("keydown",V)},[I,H]);const oe=m.useMemo(()=>r?{conversationId:e,projectId:r,...t?{cwd:t}:{}}:null,[e,t,r]),te=m.useRef(null),O=m.useCallback(()=>{const V=o.current?.getScroller();te.current=V?{height:V.scrollHeight,top:V.scrollTop}:null,re.getState().loadOlderHistory(e)},[e,o]);return m.useLayoutEffect(()=>{const V=o.current?.getScroller(),J=te.current;!V||!J||(te.current=null,V.scrollTop=J.top+(V.scrollHeight-J.height))},[h]),i.jsxs(jg.Provider,{value:oe,children:[I&&i.jsx(WZ,{query:T,onQueryChange:V=>{z(V),R(0)},current:B.length===0?0:Math.min($,B.length-1)+1,total:B.length,onPrev:()=>H(-1),onNext:()=>H(1),onClose:()=>{D(!1),z("")}}),i.jsx(Ch,{virtualize:!fJ,ref:o,items:A,busy:E!==null,loading:E==="loading",running:d,runStartedAt:x,lastOutputAt:v,error:aL(a,y),emptyTitle:n,onSuggestion:s,onRetryResume:!w&&b&&_==="failed"?()=>{re.getState().resumeConversation(e)}:void 0,historyLoading:C,hasOlder:h>0,olderCursor:h,onStartReached:h>0?O:void 0,searchQuery:I?T:"",activeHit:I?B[$]??null:null},e)]})}const mJ=/-([0-9a-f]{8})$/i;function gS(e){const t=e.title?.trim();return t||e.name.replace(mJ,"").trim()||e.name}const gJ={sm:"size-2",md:"size-2.5"},xJ={sm:"h-3 w-3",md:"h-3.5 w-3.5"};function Ph({tone:e,size:t="sm",title:n,className:s}){const{t:o}=Q();if(e==="waiting"){const r=o("Waiting for your answer");return i.jsx("span",{role:"img","aria-label":r,title:r,"data-slot":"conversation-status","data-tone":e,className:q("flex shrink-0 items-center text-amber-500",s),children:i.jsx(EV,{className:q(xJ[t],"stroke-[2.5]"),"aria-hidden":!0})})}return i.jsx("span",{"data-slot":"conversation-status","data-tone":e,title:n,className:q("shrink-0 rounded-full",gJ[t],e==="attention"&&"animate-pulse bg-destructive",e==="running"&&"animate-pulse bg-brand",e==="failed"&&"bg-destructive",e==="unread"&&"bg-green-500",e==="idle"&&"border border-muted-foreground/50",s)})}function vJ({parentId:e,coworkerIds:t}){const{t:n,locale:s}=Q(),o=Ce(y=>y.agentTypes),[r,a]=m.useState([]),[l,d]=m.useState(!1),[c,u]=m.useState(null),h=m.useRef(0),p=t.join("\0"),f=re(y=>y.pendingChildRun),g=m.useCallback(()=>{const y=++h.current;return window.electronAPI.agent.listChildRuns(e).then(w=>{y===h.current&&a(w.ok?w.items:[])})},[e]);m.useEffect(()=>{g()},[g,p]);const x=m.useCallback(y=>{const w=c?.childId;return w?window.electronAPI.agent.readChildRun(e,w,y):Promise.resolve({ok:!1,code:"not-found",error:"No child run."})},[e,c?.childId]),v=y=>{if(y.available){if(d(!1),y.live&&t.includes(y.childId)){re.getState().selectTab(e,y.childId);return}u(y)}};return m.useEffect(()=>{if(!f||f.parentId!==e)return;const y=r.find(w=>w.childId===f.childId);if(y&&(re.setState({pendingChildRun:null}),!!y.available)){if(d(!1),y.live&&t.includes(y.childId)){re.getState().selectTab(e,y.childId);return}u(y)}},[f,r,e,t]),i.jsxs(i.Fragment,{children:[r.length>0&&i.jsxs(Ri,{open:l,onOpenChange:y=>{d(y),y&&g()},children:[i.jsxs(Li,{className:"flex h-6 shrink-0 items-center justify-center gap-1 rounded-full px-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":n("Subagent history"),title:n("Subagent history"),children:[i.jsx(Bo,{className:"size-3.5"}),i.jsx("span",{className:"text-[11px] tabular-nums leading-none",children:r.length})]}),i.jsx(Oi,{align:"end",className:"w-96 [&_[data-slot=popover-viewport]]:p-1",children:i.jsx("ul",{className:"flex flex-col",children:r.map(y=>{const w=gS(y);return i.jsx("li",{children:i.jsxs("button",{type:"button",disabled:!y.available,title:w,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm",y.available?"hover:bg-muted":"cursor-default text-muted-foreground opacity-40"),onClick:()=>v(y),children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:w}),y.agentType&&i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Sj(y.agentType,o)}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:Oo(y.startedAt,s)}),y.live&&i.jsx(Ph,{tone:"running",size:"sm",title:n("Running")})]})},y.childId)})})})]}),i.jsx(Jx,{conversationId:c?.childId??null,title:c?gS(c):"",read:x,botSession:!1,onClose:()=>u(null)})]})}const bJ=[{name:"pause",aliases:[],description:"Pause the current session goal"},{name:"resume",aliases:[],description:"Resume a paused session goal"},{name:"clear",aliases:[],description:"Clear the session goal"}],wJ={"/goal":bJ};function yJ(e,t){if(!e)return null;const n=t.trimStart();return n?n.search(/\s/)>=0?null:n:""}function SJ(e,t){if(!e)return[];const n=wJ[e]??[],s=t.trim().toLowerCase();return s?n.filter(o=>o.name.toLowerCase().startsWith(s)||o.aliases.some(r=>r.toLowerCase().startsWith(s))):n}const uI=50,CJ=64,kJ=120,jJ=32*1024,_J=120,ec=[];function xS(e){return/(?:^|\s)#([^\s#]*)$/.exec(e)?.[1]??null}function NJ(e,t,n){if(!Array.isArray(n))return[];const s=[];for(const o of n){if(s.length>=uI)break;if(typeof o!="object"||o===null)continue;const{id:r,label:a,detail:l}=o;typeof r!="string"||!r||typeof a!="string"||!a||s.push({key:`${e}:${t}:${r}`,pluginId:e,name:t,item:{id:r.slice(0,200),label:a.slice(0,CJ),...typeof l=="string"&&l?{detail:l.slice(0,kJ)}:{}}})}return s}function TJ(e){const t=typeof e=="string"?e:typeof e=="object"&&e!==null?e.text:null;return typeof t=="string"&&t.length<=jJ?t:null}let hI=[];const Rm=new Set;function vS(e){hI=e;for(const t of Rm)t()}function DJ(e){return Rm.add(e),()=>Rm.delete(e)}const bS=()=>hI;function IJ(e,t){const n=m.useSyncExternalStore(DJ,bS,bS),[s,o]=m.useState(ec);return m.useEffect(()=>{if(e===null||n.length===0){o(ec);return}let r=!1;const a=setTimeout(()=>{Promise.all(n.map(async({pluginId:l,name:d})=>{const c=await window.electronAPI.extensionPlugins.call({pluginId:l,method:"trigger.candidates",payload:{name:d,query:e},sessionId:t});return c.ok?NJ(l,d,c.value):ec})).then(l=>{r||o(l.flat().slice(0,uI))})},_J);return()=>{r=!0,clearTimeout(a)}},[e,n,t]),e===null?ec:s}async function EJ(e,t){const n=await window.electronAPI.extensionPlugins.call({pluginId:e.pluginId,method:"trigger.pick",payload:{name:e.name,item:e.item},sessionId:t});return n.ok?TJ(n.value):null}const Vc="composer-drop",pI="pinned-drop",rv="project-group:__ungrouped__",Lm="project:",Om="project-group:",$c="selector-group:",zm="pinned-chat:",fI=e=>`${Lm}${e}`,mI=e=>`${Om}${e}`,av=e=>`${$c}${e}`,PJ=e=>`chat:${e}`,gI=e=>`${zm}${e}`,AJ=e=>`active-chat:${e}`;function MJ(e){return e.split(`
|
|
84
|
-
`)[0].trim()||"Untitled chat"}function wS(e){if(e===rv||e===`${$c}__ungrouped__`)return null;if(e.startsWith(Om)){const t=e.slice(Om.length);return t==="__all__"?void 0:t}if(e.startsWith($c)){const t=e.slice($c.length);return t==="__all__"?void 0:t}}function RJ(e,t,n,s){if(!t)return null;if(e.type==="project-group"){const o=wS(t);return!o||o===e.groupId?null:{kind:"reorder-groups",activeId:e.groupId,overId:o}}if(e.type==="project"){if(t===Vc)return{kind:"insert-file-mention",path:e.path,label:e.name};const o=wS(t);if(o!==void 0)return(s?.projectGroupId?.(e.projectId)??null)===o?null:{kind:"move-project-to-group",projectId:e.projectId,groupId:o};if(t.startsWith(Lm)){const r=t.slice(Lm.length);if(r===e.projectId)return null;const a=s?.projectGroupId?.(e.projectId)??null,l=s?.projectGroupId?.(r)??null;return s?.projectGroupId&&a!==l?{kind:"move-project-to-group",projectId:e.projectId,groupId:l,beforeProjectId:r}:{kind:"reorder-projects",activeId:e.projectId,overId:r}}return null}if(e.type==="workspace-file")return t===Vc?{kind:"insert-file-mention",path:e.relativePath,label:e.name}:null;if(t===Vc)return!e.sessionFile||e.conversationId===n?null:{kind:"insert-chat-mention",conversationId:e.conversationId,label:MJ(e.title),sessionFile:e.sessionFile};if(t===pI)return e.pinned?null:{kind:"pin-conversation",conversationId:e.conversationId};if(t.startsWith(zm)){const o=t.slice(zm.length);return o===e.conversationId?null:e.pinned?{kind:"reorder-pinned",activeId:e.conversationId,overId:o}:{kind:"pin-conversation",conversationId:e.conversationId}}return null}const yS=200,LJ=Array.from({length:Cl},(e,t)=>`bar-${t}`),SS=jh([],0);function OJ({active:e,disabled:t,onChange:n}){const{t:s}=Q(),[o,r]=m.useState(!1),[a,l]=m.useState(null),d=m.useRef(null);m.useEffect(()=>{if(!a)return;const h=setTimeout(()=>l(null),4e3);return()=>clearTimeout(h)},[a]);const c=async()=>{if(l(null),!navigator.mediaDevices?.getUserMedia){l(s("Voice input needs a secure (HTTPS) connection."));return}Tm(),r(!0);try{await Jq(),n(!0)}catch(h){l(s(iD(h)))}finally{r(!1)}},u=s(e?"Switch to keyboard":"Voice input");return i.jsxs("div",{ref:d,className:"flex shrink-0 items-center",children:[i.jsx("button",{type:"button",disabled:t||o,onClick:()=>e?n(!1):void c(),"aria-label":u,title:u,className:Dm,children:o?i.jsx(hr,{className:"h-3.5 w-3.5"}):e?i.jsx(lL,{className:"h-3.5 w-3.5"}):i.jsx(Fk,{className:"h-3.5 w-3.5"})}),a&&d.current?i.jsx(aD,{anchor:d.current,status:!0,children:a}):null]})}let CS;function zJ({startSession:e,disabled:t,onText:n}){const{t:s}=Q(),{phase:o,elapsed:r,error:a,setError:l,partial:d,correcting:c,start:u,finish:h,cancel:p}=oD({startSession:e,onText:n}),[f,g]=m.useState(SS),[x,v]=m.useState(!1),[y,w]=m.useState(!1),b=m.useRef(null);m.useEffect(()=>(clearTimeout(CS),()=>{CS=setTimeout(Fy,0)}),[]),m.useEffect(()=>{const C=window.visualViewport;if(!x||!C)return;const S=()=>{b.current&&(b.current.shifted=!0)};return C.addEventListener("resize",S),C.addEventListener("scroll",S),()=>{C.removeEventListener("resize",S),C.removeEventListener("scroll",S)}},[x]);const _=C=>{t||b.current||o!=="idle"||C.pointerType==="mouse"&&C.button!==0||(C.preventDefault(),document.activeElement?.blur(),C.currentTarget.setPointerCapture(C.pointerId),b.current={id:C.pointerId,y:C.clientY,at:performance.now(),shifted:!1},v(!0),w(!1),g(SS),u({context:Tm(),onLevel:S=>g(A=>jh(A,S))}))},j=(C,S)=>{const A=b.current;if(!A||A.id!==C.pointerId)return;b.current=null,v(!1),w(!1);const E=eD({phase:o,heldMs:performance.now()-A.at,cancelZone:S||!A.shifted&&Gy(A.y,C.clientY)});E==="finish"?h():E!=="none"&&p(),Fy(),Tm(),E==="too-short"&&l(s("Speech was too short."))},N=x&&(o==="starting"||o==="recording")||o==="transcribing";return i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",disabled:t,onPointerDown:_,onPointerMove:C=>{const S=b.current;S?.id===C.pointerId&&(S.shifted&&(S.y=C.clientY,S.shifted=!1),w(Gy(S.y,C.clientY)))},onPointerUp:C=>j(C,!1),onPointerCancel:C=>j(C,!0),onContextMenu:C=>C.preventDefault(),className:q("mt-2 flex h-11 w-full touch-none select-none items-center justify-center rounded-xl border bg-background font-medium text-sm shadow-float transition-[opacity,scale,background-color] duration-200 ease-out [-webkit-touch-callout:none] starting:scale-x-25 starting:opacity-0 disabled:opacity-40",x&&"bg-accent",a&&"text-destructive"),children:a??s(x?"Release to finish":"Hold to talk")}),N?i.jsx(GJ,{phase:o,cancelling:y,elapsed:r,levels:f,partial:d,correcting:c}):null]})}function GJ({phase:e,cancelling:t,elapsed:n,levels:s,partial:o,correcting:r}){const{t:a}=Q(),l=e==="transcribing",d=o.length>yS?`…${o.slice(-yS)}`:o;return Ws.createPortal(i.jsxs("div",{"data-testid":"hold-to-talk",style:{zIndex:kn.TOAST},className:"fixed inset-0 flex touch-none select-none flex-col overflow-hidden bg-black/60 backdrop-blur-[2px]",children:[i.jsx("div",{className:"flex flex-1 items-center justify-center px-6",children:i.jsxs("div",{role:"status","aria-live":"polite",className:q("flex min-w-36 max-w-[85vw] flex-col items-center gap-3 rounded-2xl px-5 py-4 shadow-lg transition-colors duration-150",t?"bg-destructive text-white":"bg-brand text-brand-foreground"),children:[d?i.jsx("p",{"data-testid":"voice-partial",className:"text-[15px] leading-relaxed",children:d}):e==="recording"?i.jsx("p",{className:"text-sm",children:a("Speak now")}):null,l||e==="starting"?i.jsxs("span",{className:"flex items-center gap-1.5 text-xs opacity-85",children:[i.jsx(hr,{"aria-hidden":!0,className:"size-3.5"}),a(e==="starting"?"Getting the microphone ready…":r?"Correcting…":"Transcribing…")]}):i.jsx("span",{"aria-hidden":!0,className:"flex h-8 items-center gap-[3px]",children:LJ.map((c,u)=>i.jsx("span",{className:"w-[3px] rounded-full bg-current transition-[height] duration-100 ease-out",style:{height:4+s[u]*28}},c))})]})}),l?null:i.jsxs("div",{className:"flex flex-col items-center",children:[i.jsx("span",{className:q("mb-3 flex size-14 items-center justify-center rounded-full transition-[scale,background-color,color] duration-150",t?"scale-110 bg-white text-destructive":"bg-white/15 text-white/80"),children:i.jsx(an,{className:"size-6"})}),i.jsx("p",{className:"mb-5 text-white/80 text-xs",children:a(t?"Release to cancel":"Slide up to cancel")}),i.jsxs("div",{className:q("flex h-[calc(7rem+env(safe-area-inset-bottom))] w-[140%] flex-col items-center rounded-t-[50%] pt-8 transition-colors duration-150",t?"bg-neutral-500 text-white/70":"bg-neutral-100 text-neutral-700"),children:[i.jsx("span",{className:"text-sm",children:a("Release to finish")}),i.jsxs("span",{className:"mt-1 text-xs tabular-nums opacity-60",children:[Math.floor(n/60),":",String(n%60).padStart(2,"0")]})]})]})]}),document.body)}const kS=e=>e.startsWith("/skill:");function FJ(e,t){return!kS(t)||!e.every(kS)?[t]:e.includes(t)?[...e]:[...e,t]}function HJ(e){const t=Ek(e);if(t.names.length>0)return{slashes:t.names.map(s=>`/skill:${s}`),rest:t.rest};const n=ju(e);return{slashes:n.slash?[n.slash]:[],rest:n.rest}}function BJ(e,t,n=!1){const s=e.segments.some(r=>r.type!=="text"||r.text.length>0);if(n&&(s||e.slashes.length>0))return{slashes:e.slashes,segments:[...e.segments,...t.text?[{type:"text",text:`${s?`
|
|
85
|
-
|
|
86
|
-
`:""}${t.text}`}]:[]],images:[...e.images,...t.images??[]]};const o=HJ(t.text??"");return{slashes:o.slashes,segments:o.rest?[{type:"text",text:o.rest}]:[],images:[...n?e.images:[],...t.images??[]]}}const VJ={file:'<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>',chat:'<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/></svg>',"ui-element":'<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 3a2 2 0 0 0-2 2"/><path d="M19 3a2 2 0 0 1 2 2"/><path d="M21 19a2 2 0 0 1-2 2"/><path d="M5 21a2 2 0 0 1-2-2"/><path d="M9 3h1"/><path d="M9 21h1"/><path d="M14 3h1"/><path d="M14 21h1"/><path d="M3 9v1"/><path d="M21 9v1"/><path d="M3 14v1"/><path d="M21 14v1"/></svg>'},$J='<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><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"/></svg>',WJ={file:"bg-success/15 text-success",chat:"bg-warning/25 text-warning-foreground dark:bg-warning/15 dark:text-warning","ui-element":"bg-purple-500/15 text-purple-600 dark:text-purple-400"};function Up(e){const t=document.createElement("span");t.contentEditable="false",t.dataset.mentionKind=e.type,e.type==="file"?(t.dataset.path=e.path,e.label&&(t.dataset.label=e.label),t.title=e.path):e.type==="chat"?(t.dataset.label=e.label,t.dataset.sessionFile=e.sessionFile):(t.dataset.id=e.id,t.dataset.label=e.label,t.dataset.path=e.path,t.dataset.text=e.text,t.dataset.imageId=e.imageId,t.title=`${e.path}${e.text?` · ${e.text}`:""}`),t.className=q("mx-0.5 inline-flex max-w-52 items-center gap-1 rounded-md px-1.5 py-0.5 align-middle text-xs font-medium leading-4 select-none",WJ[e.type]);const n=document.createElement("span");n.className="shrink-0 inline-flex",n.innerHTML=e.type==="file"&&/[\\/]$/.test(e.path)?$J:VJ[e.type],t.appendChild(n);const s=document.createElement("span");return s.className="truncate",s.textContent=e.type==="file"?e.label??fh(e.path):e.label,t.appendChild(s),t}function xI(e){return e.dataset.mentionKind==="file"&&e.dataset.path?{type:"file",path:e.dataset.path,...e.dataset.label?{label:e.dataset.label}:{}}:e.dataset.mentionKind==="chat"&&e.dataset.label&&e.dataset.sessionFile?{type:"chat",label:e.dataset.label,sessionFile:e.dataset.sessionFile}:e.dataset.mentionKind==="ui-element"&&e.dataset.label&&e.dataset.path&&e.dataset.text?{type:"ui-element",id:e.dataset.id??"",label:e.dataset.label,path:e.dataset.path,text:e.dataset.text,imageId:e.dataset.imageId??""}:null}function Kp(e){const t=[],n=o=>{if(!o)return;const r=t.at(-1);r?.type==="text"?r.text+=o:t.push({type:"text",text:o})},s=o=>{if(o.nodeType===Node.TEXT_NODE){n(o.textContent??"");return}if(!(o instanceof HTMLElement))return;if(o.dataset.mentionKind){const a=xI(o);a&&t.push(a);return}if(o.tagName==="BR"){n(`
|
|
87
|
-
`);return}(o.tagName==="DIV"||o.tagName==="P")&&t.length>0&&n(`
|
|
88
|
-
`);for(const a of o.childNodes)s(a)};for(const o of e.childNodes)s(o);return t}function qp(e){const t=window.getSelection();if(!t||t.rangeCount===0||!t.isCollapsed)return null;const{anchorNode:n,anchorOffset:s}=t;return!n||!e.contains(n)||n.nodeType!==Node.TEXT_NODE?null:{node:n,offset:s}}function UJ(e,t){if(t.rangeCount===0||!t.isCollapsed)return null;const{anchorNode:n,anchorOffset:s}=t;if(!n||n.nodeType===Node.TEXT_NODE||n!==e&&!e.contains(n))return null;const o=n.childNodes,r=o[s],a=s>0?o[s-1]:void 0,l=r?.nodeType===Node.TEXT_NODE?{node:r,offset:0}:a?.nodeType===Node.TEXT_NODE?{node:a,offset:a.length}:null;if(!l)return null;const d=document.createRange();return d.setStart(l.node,l.offset),d.collapse(!0),d}function tc(e){return e instanceof HTMLElement&&!!e.dataset.mentionKind}function Qa(e){return e instanceof Text&&!/[^\s\u00a0]/.test(e.textContent??"")}function KJ(e,t){const n=window.getSelection();if(!n||n.rangeCount===0||!n.isCollapsed)return null;const{anchorNode:s,anchorOffset:o}=n;if(!s||!e.contains(s))return null;if(s.nodeType===Node.TEXT_NODE){const d=s.textContent??"";if(t==="before"){if(/[^\s\u00a0]/.test(d.slice(0,o)))return null;let u=s.previousSibling;for(;Qa(u);)u=u.previousSibling;return tc(u)?u:null}if(/[^\s\u00a0]/.test(d.slice(o)))return null;let c=s.nextSibling;for(;Qa(c);)c=c.nextSibling;return tc(c)?c:null}const r=s.childNodes;if(t==="before"){let d=o-1;for(;d>=0&&Qa(r[d]);)d-=1;const c=d>=0?r[d]:null;return tc(c)?c:null}let a=o;for(;a<r.length&&Qa(r[a]);)a+=1;const l=r[a];return tc(l)?l:null}function qJ(e,t){const n=e.nextSibling;Qa(n)&&n.remove();const s=e.previousSibling;if(e.remove(),s){vI(s);return}const o=window.getSelection();if(!o)return;const r=document.createRange();r.setStart(t,0),r.collapse(!0),o.removeAllRanges(),o.addRange(r)}function vI(e){const t=window.getSelection();if(!t)return;const n=document.createRange();n.setStartAfter(e),n.collapse(!0),t.removeAllRanges(),t.addRange(n)}const YJ=m.forwardRef(function({placeholder:t,disabled:n,className:s,onStateChange:o,onKeyDown:r,onPaste:a,onPasteText:l,onCompositionStart:d,onCompositionEnd:c,onChipActivate:u,ariaProps:h},p){const f=m.useRef(null),g=m.useRef(null);m.useEffect(()=>{const w=()=>{const b=f.current;if(!b||document.activeElement!==b)return;const _=window.getSelection();if(!_||_.rangeCount===0||!_.isCollapsed)return;const j=_.anchorNode;if(j&&(j===b||b.contains(j))){const S=UJ(b,_);S?(_.removeAllRanges(),_.addRange(S)):j.nodeType===Node.TEXT_NODE&&(g.current={node:j,offset:_.anchorOffset});return}const N=g.current,C=document.createRange();N?.node.isConnected&&b.contains(N.node)?(C.setStart(N.node,Math.min(N.offset,N.node.length)),C.collapse(!0)):(C.selectNodeContents(b),C.collapse(!0)),_.removeAllRanges(),_.addRange(C)};return document.addEventListener("selectionchange",w),()=>document.removeEventListener("selectionchange",w)},[]);const x=m.useCallback(()=>{const w=f.current;if(!w)return;const b=Kp(w),_=b.map(I=>I.type==="text"?I.text:"").join(""),j=b.some(I=>I.type!=="text");let N=null,C=null,S=null,A=null;const E=qp(w);if(E){const I=E.node.textContent?.slice(0,E.offset)??"";N=Qb(I,I.length),N===null&&(S=Nm(I,I.length)),N===null&&S===null&&(A=xS(I)),N===null&&E.node===w.firstChild&&/^\/[^\s]*$/.test(I)&&(C=I.slice(1))}o({plainText:_,hasMentions:j,segments:b,mentionQuery:N,slashQuery:C,skillQuery:S,pluginQuery:A})},[o]),v=m.useCallback(w=>{const b=f.current;if(!b)return null;const _=qp(b);if(!_)return null;const j=_.node.textContent?.slice(0,_.offset)??"";if(w==="#"){const N=xS(j);return N===null?null:{node:_.node,start:j.length-N.length-1,end:_.offset}}if(w==="@"||w==="$"){const N=w==="@"?Qb(j,j.length):Nm(j,j.length);return N===null?null:{node:_.node,start:j.length-N.length-1,end:_.offset}}return _.node!==b.firstChild||!/^\/[^\s]*$/.test(j)?null:{node:_.node,start:0,end:_.offset}},[]),y=m.useCallback((w,b)=>{const _=f.current;if(!_)return;_.focus();const j=document.createRange(),N=b?v("@"):null;if(N)j.setStart(N.node,N.start),j.setEnd(N.node,N.end),j.deleteContents();else{const A=qp(_);A?(j.setStart(A.node,A.offset),j.collapse(!0)):(j.selectNodeContents(_),j.collapse(!1))}const C=w();j.insertNode(C);const S=document.createTextNode(" ");C.parentNode?.insertBefore(S,C.nextSibling),vI(S),x()},[v,x]);return m.useImperativeHandle(p,()=>({focus:()=>f.current?.focus(),isEmpty:()=>{const w=f.current;return w?!Kp(w).some(_=>_.type!=="text"||_.text.trim().length>0):!0},getSegments:()=>f.current?Kp(f.current):[],setSegments:w=>{const b=f.current;if(b){b.textContent="";for(const _ of w)_.type==="text"?b.appendChild(document.createTextNode(_.text)):b.appendChild(Up(_));x()}},clear:()=>{const w=f.current;w&&(w.textContent="",x())},insertMention:w=>{const b=w.kind==="file"?{type:"file",path:w.relativePath}:w.kind==="chat"?{type:"chat",label:w.label,sessionFile:w.sessionFile}:{type:"ui-element",id:w.id,label:w.label,path:w.path,text:w.text,imageId:w.imageId};y(()=>Up(b),w.kind!=="ui-element")},consumeToken:w=>{const b=v(w);if(!b)return;const _=document.createRange();_.setStart(b.node,b.start),_.setEnd(b.node,b.end),_.deleteContents(),x()},insertFileChip:(w,b)=>{y(()=>Up({type:"file",path:w,...b?{label:b}:{}}),!1)},insertText:w=>{y(()=>document.createTextNode(w),!1)},getMentionAnchorRect:()=>{const w=v("@");if(!w)return null;const b=document.createRange();return b.setStart(w.node,w.start),b.setEnd(w.node,Math.min(w.start+1,w.node.length)),b.getBoundingClientRect()}}),[v,x,y]),i.jsx("div",{ref:f,contentEditable:!n,role:h?.role??"textbox","aria-placeholder":t,"data-placeholder":t,...h,onInput:x,onKeyDown:w=>{if(!w.nativeEvent.isComposing&&(w.key==="Backspace"||w.key==="Delete")){const b=f.current,_=b&&KJ(b,w.key==="Backspace"?"before":"after");if(_&&b){w.preventDefault(),qJ(_,b),x();return}}r(w)},onClick:w=>{if(!u)return;const b=w.target;if(!(b instanceof Element))return;const _=b.closest("[data-mention-kind]");if(!(_ instanceof HTMLElement)||!f.current?.contains(_))return;const j=xI(_);j&&u(j)},onKeyUp:w=>{w.key!=="Escape"&&x()},onMouseUp:x,onPaste:w=>{if(w.clipboardData.files.length>0){a(w);return}w.preventDefault();const b=w.clipboardData.getData("text/plain");b&&(l?.(b)||document.execCommand("insertText",!1,b))},onCompositionStart:d,onCompositionEnd:()=>{c(),x()},className:q("max-h-40 min-h-10 min-w-0 flex-1 overflow-y-auto pt-0.5 text-sm break-words whitespace-pre-wrap outline-none","empty:before:pointer-events-none empty:before:text-muted-foreground empty:before:content-[attr(data-placeholder)]",n&&"opacity-60",s)})}),XJ=/[\\/]/;function ZJ(e){return e.split(XJ).filter(t=>t.length>0)}function JJ(e){const t=new Map,n=e.map(ZJ),s=n.map(o=>o.join("/"));for(let o=0;o<e.length;o++){const r=e[o],a=n[o]??[];let l=Math.max(0,a.length-3);for(;l>0;){const c=a.slice(l).join("/");if(!s.some(h=>h!==s[o]&&(h===c||h.endsWith(`/${c}`))))break;l--}const d=a.slice(l).join("/");t.set(r,l>0?`…/${d}`:d)}return t}function QJ({groups:e,query:t,activeIndex:n,onActiveIndexChange:s,openFolderId:o,folderIndex:r,onOpenFolderIdChange:a,onFolderIndexChange:l,onSelect:d,id:c="composer-mention-picker",left:u=0,flyoutSide:h="right"}){const{t:p}=Q(),f=m.useMemo(()=>cD(e,t),[e,t]),g=m.useMemo(()=>JJ(e.files.map(C=>C.relativePath)),[e.files]),x=m.useRef(new Map),v=m.useRef(new Map),y=f[0]?.type==="folder";if(m.useEffect(()=>{x.current.get(n)?.scrollIntoView({block:"nearest"})},[n]),m.useEffect(()=>{o&&v.current.get(r)?.scrollIntoView({block:"nearest"})},[o,r]),f.length===0)return null;const w={agents:p("Agents"),members:p("Members"),chats:p("Chats")},b={agents:Hs,members:ra,chats:Bo},_=o?e[o]:[];let j=0;const N=(C,S)=>{const A=e[C];if(A.length===0)return null;const E=C==="files"?p("Files"):w[C];return i.jsxs("div",{role:"group","aria-label":E,children:[i.jsx("p",{className:q("px-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",S?"pt-2":"pt-1.5"),children:E}),A.map(I=>{const D=j++;return i.jsx(jS,{ref:T=>{T?x.current.set(D,T):x.current.delete(D)},id:`${c}-option-${D}`,candidate:I,active:D===n,pathLabel:I.kind==="file"?g.get(I.relativePath):void 0,onHover:()=>{s(D),y&&a(null)},onSelect:()=>d(I)},`${C}:${I.id}`)})]})};return i.jsxs("div",{"data-slot":"mention-picker",className:"absolute bottom-full z-10 mb-1.5 max-w-full",style:{left:u},children:[i.jsx("div",{id:c,role:"listbox","aria-label":p("Mention suggestions"),className:"max-h-72 w-80 max-w-full overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",children:y?i.jsxs(i.Fragment,{children:[f.filter(C=>C.type==="folder").map(C=>{const S=j++,A=b[C.id];return i.jsxs("button",{ref:E=>{E?x.current.set(S,E):x.current.delete(S)},id:`${c}-option-${S}`,type:"button",role:"option","aria-selected":n===S,onClick:()=>{s(S),a(C.id),l(0)},onMouseMove:()=>{s(S),o!==C.id&&(a(C.id),l(0))},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",n===S&&"bg-foreground/10"),children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:i.jsx(A,{className:"h-3.5 w-3.5 text-muted-foreground"})}),i.jsx("span",{className:"min-w-0 flex-1 font-medium",children:w[C.id]}),i.jsx(bn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"})]},`folder:${C.id}`)}),N("files",!0)]}):i.jsxs(i.Fragment,{children:[N("agents",!1),N("members",e.agents.length>0),N("chats",e.agents.length+e.members.length>0),N("files",e.agents.length+e.members.length+e.chats.length>0)]})}),o&&_.length>0&&i.jsx("div",{role:"listbox","aria-label":w[o],"data-slot":"mention-flyout",className:q("absolute top-0 z-20 max-h-72 w-72 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",h==="right"?"left-full ml-1":"right-full mr-1"),children:_.map((C,S)=>i.jsx(jS,{ref:A=>{A?v.current.set(S,A):v.current.delete(S)},id:`${c}-sub-${S}`,candidate:C,active:S===r,onHover:()=>l(S),onSelect:()=>d(C)},`sub:${C.id}`))})]})}function jS({ref:e,id:t,candidate:n,active:s,pathLabel:o,onHover:r,onSelect:a}){const{t:l}=Q(),d=eQ(n),c=n.kind==="agent-type"?n.source==="bot"?ra:Hs:n.kind==="chat"?Bo:d?yd:bo;return i.jsxs("button",{ref:e,id:t,type:"button",role:"option","aria-selected":s,onClick:a,onMouseMove:r,className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",s&&"bg-foreground/10"),children:[i.jsx("span",{className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background",children:i.jsx(c,{className:"h-3.5 w-3.5 text-muted-foreground"})}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx("span",{className:"shrink-0 font-medium",children:n.label}),i.jsx(oa,{variant:"outline",className:"px-1 py-0 text-[9px]",children:n.kind==="agent-type"?l(n.source==="system"?"System":n.source==="builtin"?"Built-in":n.source==="bot"?"Member":"Custom"):n.kind==="chat"?l("Chat"):l(d?"Folder":"File")}),n.kind==="agent-type"&&n.locked&&i.jsx(oa,{variant:"secondary",className:"px-1 py-0 text-[9px]",children:l("Locked")})]}),i.jsx("span",{className:q("block text-muted-foreground",n.kind==="file"?"whitespace-normal break-all":"truncate"),title:n.kind==="file"?n.relativePath:void 0,children:n.kind==="agent-type"?n.source==="bot"?n.description:l(n.description):n.kind==="chat"?n.sessionFile.split("/").at(-1):n.kind==="file"?o??n.relativePath:n.path})]})]})}function eQ(e){return e.kind==="file"&&/[\\/]$/.test(e.relativePath)}const _S=new Map,tQ=()=>!!window.electronAPI?.remote&&window.matchMedia?.("(pointer: coarse)").matches===!0;function lv({cwd:e,commands:t,running:n,busy:s,focusKey:o,pluginPresetId:r=null,autoFocus:a=!window.electronAPI?.remote,enterToSend:l=!tQ(),toolbar:d,locked:c=!1,injectedDraft:u,injectedImages:h,injectedDraftAppend:p,onDraftConsumed:f,initialRecipient:g,onInitialRecipientConsumed:x,chatCandidates:v,onActivate:y,onSend:w,onAbort:b,queuedCount:_=0,onSteerQueued:j,isolated:N=!1,placeholder:C,planMode:S=!1,voice:A,requestMicAccess:E,voiceMode:I="click",savePastedText:D}){const{t:T}=Q(),z=ba(),[$,R]=m.useState(!1),B=I==="hold"?A:void 0,H=Ce(ae=>ae.keybindings),oe=Ce(ae=>ae.privacyMasking),te=Ai(H)["send-message"],O=Ai(H)["voice-hold"],V=m.useId(),[J,pe]=m.useState([]),[fe,_e]=m.useState([]),[Ee,me]=m.useState(g),W=m.useRef(o),[G,de]=m.useState(!1),{setNodeRef:X,isOver:ie}=md({id:N?`isolated-composer:${o??"side"}`:Vc,disabled:N}),[Z,le]=m.useState(null),[be,Fe]=m.useState(null),Je=m.useRef(new Set),We=m.useRef(w);We.current=w;const et=m.useRef(oe);et.current=oe,m.useEffect(()=>{if(N)return;const ae=l7(we=>qe.current?.insertMention(we)),Te=c7(we=>qe.current?.insertText(we)),Ae=d7(()=>qe.current?.focus()),Ge=p7((we,Se)=>{Se&&pe(Me=>[...Me,{...Se,id:we.imageId}]),qe.current?.insertMention(we),qe.current?.focus()}),Ye=f7(we=>{pe(Se=>[...Se,{data:we.data,mimeType:we.mimeType}]),qe.current?.focus()}),Xe=u7(we=>{if(ne.current)return!1;const Se=et.current,Me=Se.enabled?Yh(we.text,Se).blocked:[];return Me.length>0?(Be({type:"error",title:T("Message not sent"),description:T("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:Me.join(", ")})}),!1):We.current(we)!==!1});return()=>{ae(),Te(),Ae(),Ge(),Ye(),Xe()}},[N,T]);const qe=m.useRef(null),Lt=m.useRef(null),Bt=m.useRef(null),Mt=m.useRef(!1),ne=m.useRef(c);ne.current=c,m.useEffect(()=>{if(!(N||!o))return dL({key:o,segments:()=>qe.current?.getSegments()??[],insertText:ae=>qe.current?.insertText(ae),setText:ae=>qe.current?.setSegments(ae?[{type:"text",text:ae}]:[]),busy:()=>Mt.current||ne.current||!qe.current})},[N,o]);const[se,He]=m.useState({left:0,flyoutSide:"right"}),[kt,st]=m.useState(""),[ke,ut]=m.useState(!1),[ft,ze]=m.useState(null),wt=uD(e,ft,v),Y=m.useMemo(()=>cD(wt,ft??""),[wt,ft]),[U,ue]=m.useState(null),[je,De]=m.useState(null),[Le,tt]=m.useState(null),bt=IJ(Le,o??null),[Vt,Jt]=m.useState(0),[un,nn]=m.useState(null),[Ie,it]=m.useState(0),dt=m.useRef(null),jt=m.useCallback(ae=>{(ae.plainText.trim()||ae.hasMentions)&&y?.(),st(ae.plainText),ut(ae.hasMentions);const Te=new Set(ae.segments.filter(Ge=>Ge.type==="ui-element"&&Ge.imageId).map(Ge=>Ge.type==="ui-element"?Ge.imageId:"")),Ae=[...Je.current].filter(Ge=>!Te.has(Ge));Je.current=Te,Ae.length>0&&(pe(Ge=>cL(Ge,Ae)),le(Ge=>Ge&&Ae.includes(Ge.imageId)?null:Ge)),ze(Ge=>(Ge!==ae.mentionQuery&&(Jt(0),nn(null),it(0)),ae.mentionQuery)),ue(ae.slashQuery),De(ae.skillQuery),tt(ae.pluginQuery)},[y]);m.useEffect(()=>{const ae=W.current;if(ae!==o){ae&&_S.set(ae,{segments:qe.current?.getSegments()??[],images:J,slashes:fe,recipient:Ee});const Te=o?_S.get(o):void 0,Ae=o?uL(o):void 0;qe.current?.setSegments(Ae?[{type:"text",text:Ae}]:Te?.segments??[]),Je.current=new Set((Te?.segments??[]).filter(Ge=>Ge.type==="ui-element"&&Ge.imageId).map(Ge=>Ge.type==="ui-element"?Ge.imageId:"")),pe(Te?.images??[]),_e(Te?.slashes??[]),me(Te?.recipient),W.current=o,ze(null),ue(null),De(null),Jt(0),nn(null),it(0)}a&&qe.current?.focus()},[o]),m.useEffect(()=>{g&&(me(g),x?.())},[g,x]),m.useEffect(()=>{if(!u&&!h?.length)return;const ae=BJ({segments:qe.current?.getSegments()??[],images:J,slashes:fe},{text:u,images:h},p);_e(ae.slashes),pe(ae.images),qe.current?.setSegments(ae.segments),f?.(),window.setTimeout(()=>qe.current?.focus(),0)},[u,h,p]);const Rt=fe.length===1?fe[0]:null,dn=yJ(Rt,kt.replaceAll("","")),P=Fq(t,U,je),M=U===null&&je===null&&dn!==null?SJ(Rt,dn):[];m.useEffect(()=>{Jt(0)},[U,je,dn,Le]),m.useEffect(()=>{dt.current?.children[Vt]?.scrollIntoView({block:"nearest"})},[Vt]);const L=m.useCallback(ae=>{if(ae.kind==="agent-type"){qe.current?.consumeToken("@"),me(ae),ze(null);return}qe.current?.insertMention(ae),ze(null)},[]),k=m.useCallback(ae=>{tt(null),EJ(ae,o??null).then(Te=>{const Ae=qe.current;Ae&&(Ae.consumeToken("#"),Te&&Ae.insertText(Te))})},[o]),F=ft!==null&&Y.length>0?"mention":Le!==null&&bt.length>0?"plugin":P.length>0?"slash":M.length>0?"slash-sub":null;m.useLayoutEffect(()=>{if(F!=="mention")return;const ae=Lt.current;if(!ae)return;const Te=()=>{const Ae=ae.getBoundingClientRect(),Ge=ae.querySelector('[data-slot="mention-picker"]'),Ye=Ge?.querySelector('[role="listbox"]'),Xe=Ge?.querySelector('[data-slot="mention-flyout"]'),we=qe.current?.getMentionAnchorRect(),Se=N6({anchorLeft:we?we.left-Ae.left:0,containerWidth:Ae.width,popupWidth:Ye instanceof HTMLElement?Ye.offsetWidth:280,flyoutWidth:Xe instanceof HTMLElement?Xe.offsetWidth:252,flyoutGap:4});He(Me=>Me.left===Se.left&&Me.flyoutSide===Se.flyoutSide?Me:Se)};return Te(),window.addEventListener("resize",Te),()=>window.removeEventListener("resize",Te)},[ft,kt,un,F]);const he=F==="mention"?Y.length:F==="plugin"?bt.length:F==="slash-sub"?M.length:P.length,xe=m.useCallback((ae,Te)=>{const Ae=[{type:"text",text:ae}];if(qe.current?.setSegments(Ae),!Te)return;const Ge=nw({segments:Ae,slashes:fe,images:J,recipient:Ee});w(Ge)!==!1&&(qe.current?.clear(),pe([]),_e([]),me(void 0),ze(null),ue(null),De(null))},[J,w,Ee,fe]),Pe=m.useCallback(ae=>{qe.current?.consumeToken(je!==null?"$":"/"),ue(null),De(null);const Te=oJ(ae);if(!Te){_e(Ae=>FJ(Ae,ae));return}lJ(Te,N?null:o??null).then(Ae=>{Ae&&Be({type:"error",title:T("Plugin command failed"),description:Ae})})},[je,N,o,T]),Ue=m.useCallback((ae=!1)=>{if(F==="mention"){if(un){const Ae=wt[un][Ie];Ae&&L(Ae);return}const Te=Y[Vt];Te?.type==="item"&&L(Te.candidate)}else if(F==="plugin"){const Te=bt[Vt];Te&&k(Te)}else if(F==="slash"){const Te=P[Vt];Te&&Pe(Te.name)}else if(F==="slash-sub"){const Te=M[Vt];if(!Te)return;xe(Te.name,ae)}},[Vt,Ie,un,wt,Y,L,k,bt,F,P,Pe,M,xe]),lt=kt.replaceAll("","").trim(),Qe=!!(lt||fe.length>0||J.length>0||ke),$t=Ee!==void 0,rt=s&&!$t,_t={sessionId:N?null:o??null,draft:kt.replaceAll("",""),busy:c,pluginPresetId:r},Nt=n&&_>0&&j!==void 0&&l&&!!te,Dt=Nt&&!Qe&&!$t&&!c,yt=m.useMemo(()=>oe.enabled&<?Yh(lt,oe):null,[lt,oe]),mt=()=>{if(!Qe)return;const ae=nw({segments:qe.current?.getSegments()??[],slashes:fe,images:J,recipient:Ee}),Te=oe.enabled?Yh(ae.text,oe).blocked:[];if(Te.length>0){Be({type:"error",title:T("Message not sent"),description:T("Privacy masking blocks {{kinds}}. Remove it, or change the action or allow list in Settings → Privacy.",{kinds:Te.join(", ")})});return}w(ae)!==!1&&(qe.current?.clear(),pe([]),_e([]),me(void 0),ze(null),ue(null),De(null))},St=m.useCallback(ae=>{for(const Te of ae){if(Te.type.startsWith("image/")){const Ye=new FileReader;Ye.onload=()=>{const Xe=Ye.result,we=Xe.slice(Xe.indexOf(",")+1);pe(Se=>[...Se,{data:we,mimeType:Te.type}])},Ye.readAsDataURL(Te);continue}const Ae=window.electronAPI.files.pathForFile(Te),Ge=window.electronAPI.remote;if(!Ae&&Ge){Ge.upload(Te).then(Ye=>{Ye&&qe.current?.insertFileChip(Ye)}).catch(()=>{});continue}Ae&&qe.current?.insertFileChip(Ae)}},[]),Tt=ae=>{const Te=ae.nativeEvent.isComposing||Mt.current;if(F){const Ge=F==="mention"?Y[Vt]:void 0,Ye=T6({key:ae.key,shiftKey:ae.shiftKey,isComposing:Te,activeIndex:Vt,itemCount:he,folderOpen:F==="mention"&&un!==null,activeIsFolder:F==="mention"&&Ge?.type==="folder",folderIndex:Ie,folderItemCount:un?wt[un].length:0});if(Ye.type==="move"){ae.preventDefault(),Jt(Ye.index),nn(null);return}if(Ye.type==="move-folder"){ae.preventDefault(),it(Ye.index);return}if(Ye.type==="open-folder"){ae.preventDefault(),Ge?.type==="folder"&&nn(Ge.id),it(0);return}if(Ye.type==="close-folder"){ae.preventDefault(),nn(null);return}if(Ye.type==="pick"){ae.preventDefault(),Ue(F==="slash-sub"&&ae.key==="Enter");return}if(Ye.type==="close"){ae.preventDefault(),ze(null),ue(null),De(null),tt(null),nn(null);return}}if(Te)return;const Ae=Il(ae);if(!N&&Ae&&Ae===Ai(Ce.getState().keybindings)["switch-model"]){ae.preventDefault(),hL();return}if(ae.key==="Backspace"&&fe.length>0&<.length===0&&!ke){ae.preventDefault(),_e(Ge=>Ge.slice(0,-1));return}if(ae.key==="Backspace"&&Ee&&qe.current?.isEmpty()&&fe.length===0){ae.preventDefault(),me(void 0);return}l&&!F&&Il(ae,{allowBare:!0})===te&&(ae.preventDefault(),Dt?j?.():mt())};return i.jsxs("div",{ref:Lt,className:"relative",children:[F==="mention"&&i.jsx(QJ,{id:V,groups:wt,query:ft??"",activeIndex:Vt,onActiveIndexChange:Jt,openFolderId:un,folderIndex:Ie,onOpenFolderIdChange:nn,onFolderIndexChange:it,onSelect:L,left:se.left,flyoutSide:se.flyoutSide}),F==="plugin"&&i.jsx("div",{ref:dt,role:"listbox","aria-label":T("Plugin suggestions"),className:"absolute bottom-full left-0 z-10 mb-1.5 max-h-64 w-full overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",children:bt.map((ae,Te)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Te===Vt,onMouseDown:Ae=>Ae.preventDefault(),onClick:()=>k(ae),onMouseMove:()=>Jt(Te),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===Vt&&"bg-foreground/10"),children:[i.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:"#"}),i.jsx("span",{className:"shrink-0 font-medium",children:ae.item.label}),ae.item.detail&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:ae.item.detail})]},ae.key))}),(F==="slash"||F==="slash-sub")&&i.jsx("div",{ref:dt,role:"listbox","aria-label":T("Command suggestions"),className:"absolute bottom-full left-0 z-10 mb-1.5 max-h-64 w-full overflow-y-auto rounded-lg border bg-popover p-1 shadow-md",children:(F==="slash"?P:M).map((ae,Te)=>i.jsxs("button",{type:"button",role:"option","aria-selected":Te===Vt,onClick:()=>{Jt(Te),F==="slash"?Pe(ae.name):xe(ae.name,!1)},onMouseMove:()=>Jt(Te),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs",Te===Vt&&"bg-foreground/10"),children:[i.jsx(iN,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 font-mono font-medium",children:je!==null?`$${ae.name.slice(7)}`:ae.name}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-muted-foreground",children:T(ae.description)})]},ae.name))}),i.jsxs("div",{ref:X,"data-slot":"composer","data-enso":"composer",className:q("rounded-[24px] border bg-card shadow-[0_2px_6px_rgb(0_0_0/0.03),0_12px_32px_rgb(0_0_0/0.07)] transition-[border-color,box-shadow] duration-200 focus-within:border-foreground/20 [.dark_&]:shadow-[0_2px_6px_rgb(0_0_0/0.2),0_12px_32px_rgb(0_0_0/0.3)]",(G||ie)&&"border-brand/50 bg-brand/5",($t||S)&&"border-primary/35 shadow-primary/5"),onDragOver:ae=>{ae.dataTransfer.types.includes("Files")&&(ae.preventDefault(),de(!0))},onDragLeave:ae=>{ae.currentTarget.contains(ae.relatedTarget)||de(!1)},onDrop:ae=>{const Te=Array.from(ae.dataTransfer.files);Te.length!==0&&(ae.preventDefault(),de(!1),St(Te))},children:[J.filter(ae=>!ae.id).length>0&&i.jsx("div",{className:"flex flex-wrap gap-2 px-3 pt-3",children:J.filter(ae=>!ae.id).map((ae,Te)=>i.jsxs("div",{className:"group relative",children:[i.jsx("button",{type:"button",onClick:()=>Fe(ae),className:"block rounded-md focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none","aria-label":T("Preview"),children:i.jsx("img",{src:`data:${ae.mimeType};base64,${ae.data}`,alt:"",className:"h-16 w-16 rounded-md border object-cover"})}),i.jsx("button",{type:"button",onClick:()=>pe(Ae=>Ae.filter((Ge,Ye)=>Ye!==Te)),className:"absolute -top-1.5 -right-1.5 rounded-full border bg-background p-0.5 text-muted-foreground shadow-sm transition-opacity hover:text-destructive",children:i.jsx(an,{className:"h-3 w-3"})})]},Te))}),i.jsxs("div",{className:q("flex items-start gap-1.5 px-4",J.length>0?"pt-1.5":"pt-3.5"),children:[Ee&&i.jsx(D9,{recipient:Ee,onRemove:()=>me(void 0)}),fe.map(ae=>i.jsx(_u,{name:ae,className:"mt-0.5 shrink-0",trailing:i.jsx("button",{type:"button",onClick:()=>_e(Te=>Te.filter(Ae=>Ae!==ae)),className:"rounded-sm opacity-70 hover:opacity-100","aria-label":T("Remove"),children:i.jsx(an,{className:"h-3 w-3"})})},ae)),i.jsx(YJ,{ref:qe,placeholder:fe.length>0?"":c?T("Resolve the pending approval to continue"):$t?T("Message the selected Agent…"):Nt?T("Press {{key}} to steer the next queued message into this round…",{key:fi(te)}):C||T(n?"Message will queue until this round finishes…":"Type @ to choose a file or Agent"),disabled:c,onStateChange:jt,onChipActivate:ae=>{ae.type==="ui-element"&&le({kind:"ui-element",id:ae.id,label:ae.label,path:ae.path,text:ae.text,imageId:ae.imageId})},onKeyDown:Tt,onPasteText:ae=>!D||!Bk(ae)?!1:(D(ae).catch(()=>({ok:!1,error:"unavailable"})).then(Te=>{const Ae=qe.current;Te.ok?Ae?.insertFileChip(Te.path,`${oj} · ${T("{{count}} chars",{count:Te.chars.toLocaleString()})}`):Ae?.insertText(ae)}),!0),onPaste:ae=>{const Te=Array.from(ae.clipboardData.files);Te.length!==0&&(ae.preventDefault(),St(Te))},onCompositionStart:()=>{Mt.current=!0},onCompositionEnd:()=>{Mt.current=!1},ariaProps:{role:"combobox","aria-autocomplete":"list","aria-expanded":F!==null,"aria-controls":F==="mention"?V:void 0,"aria-activedescendant":F==="mention"?un?`${V}-sub-${Ie}`:`${V}-option-${Vt}`:void 0}})]}),$t&&i.jsx("p",{className:"sr-only",children:T("Send only to the selected Agent")}),i.jsxs("div",{className:"flex items-center justify-between gap-1.5 px-3 pt-0.5 pb-2.5",children:[i.jsxs("div",{className:q("flex min-w-0 flex-1 items-center gap-1",z?"overflow-x-auto [scrollbar-width:none]":"overflow-hidden"),children:[i.jsx("input",{ref:Bt,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:ae=>{St(Array.from(ae.target.files??[])),ae.target.value=""}}),i.jsx("button",{type:"button",disabled:c,onClick:()=>Bt.current?.click(),"aria-label":T("Attach image"),title:T("Attach image"),className:"flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-40",children:i.jsx(ph,{className:"h-3.5 w-3.5"})}),i.jsx(r0,{side:"left",..._t}),B?i.jsx(OJ,{active:$,disabled:c,onChange:ae=>{R(ae),ae?document.activeElement?.blur():qe.current?.focus()}}):A?i.jsx(lD,{startSession:A,requestMicAccess:E,disabled:c,holdBinding:O||void 0,holdScope:Lt,onText:ae=>{qe.current?.insertText(ae),qe.current?.focus()}}):null,d,i.jsx(r0,{side:"right",..._t}),yt&&(yt.blocked.length>0||yt.masked>0)&&i.jsxs("span",{className:q("flex shrink-0 items-center gap-1 text-[11px]",yt.blocked.length>0?"text-red-600 dark:text-red-400":"text-sky-600 dark:text-sky-400"),"data-privacy-precheck":!0,children:[yt.blocked.length>0?i.jsx(Ck,{className:"size-3.5"}):i.jsx(Bu,{className:"size-3.5"}),yt.blocked.length>0?T("Will be blocked: {{kinds}}",{kinds:yt.blocked.join(", ")}):T("{{count}} will be masked",{count:yt.masked})]})]}),rt&&!Qe?i.jsx(ge,{variant:"outline",size:"icon",className:"size-8 shrink-0 rounded-full",onClick:b,"aria-label":T("Stop"),children:i.jsx(AV,{className:"h-4 w-4"})}):i.jsx(ge,{size:"icon",className:"size-8 shrink-0 rounded-full bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-35",onClick:mt,disabled:!Qe||c,"aria-label":T($t?"Send only to the selected Agent":"Send"),title:$t?T("Send only to the selected Agent"):l&&te?`${T("Send")} ${fi(te)}`:T("Send"),children:i.jsx(wd,{className:"h-4 w-4"})})]})]}),B&&$?i.jsx(zJ,{startSession:B,disabled:c,onText:ae=>{qe.current?.insertText(ae),document.activeElement?.blur()}}):null,i.jsx(wn,{open:Z!==null,onOpenChange:ae=>!ae&&le(null),children:i.jsxs(yn,{className:"max-w-md",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:Z?.label??T("Selected UI element")})}),i.jsx(On,{className:"space-y-2 text-xs",children:Z&&i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"text-muted-foreground break-all",children:Z.path}),Z.text&&i.jsx("p",{children:Z.text}),(()=>{const ae=J.find(Te=>Te.id===Z.imageId);return ae?i.jsx("img",{src:`data:${ae.mimeType};base64,${ae.data}`,alt:"",className:"max-h-72 w-full rounded-md border object-contain"}):null})()]})})]})}),i.jsx(wn,{open:be!==null,onOpenChange:ae=>!ae&&Fe(null),children:i.jsxs(yn,{className:"max-w-3xl",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:T("Preview")})}),i.jsx(On,{children:be&&i.jsx("img",{src:`data:${be.mimeType};base64,${be.data}`,alt:"",className:"max-h-[80vh] w-full rounded-md object-contain"})})]})})]})}function bI({title:e,className:t,onCommit:n,onCancel:s}){const[o,r]=m.useState(e),a=()=>{const l=o.trim();!l||l===e?s():n(l)};return i.jsx("input",{className:q("min-w-0 flex-1 rounded bg-transparent px-0.5 text-inherit outline-none ring-1 ring-ring",t),value:o,autoFocus:!0,onChange:l=>r(l.target.value),onBlur:a,onClick:l=>l.stopPropagation(),onPointerDown:l=>l.stopPropagation(),onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"?(l.preventDefault(),a()):l.key==="Escape"&&(l.preventDefault(),s())}})}async function wI(e,t){const n=await re.getState().reloadConversation(e);n&&Be({type:"error",title:t("Failed to reload conversation"),description:n})}async function nQ(e,t){const n=await re.getState().restartConversation(e);n&&Be({type:"error",title:t("Failed to restart conversation"),description:n})}function sQ({parentId:e,displayedId:t,trailing:n}){const{t:s}=Q(),o=re(p=>p.conversations[e]?.title??""),r=re(p=>p.conversations[e]?.started===!0),a=re(p=>p.conversations[e]?.reloading===!0),l=re(p=>!!p.conversations[e]?.spawning),d=re(p=>sJ(p.conversations,e)),[c,u]=m.useState(!1),h=p=>q("flex min-w-0 shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50");return i.jsxs(Cj,{"data-enso":"session-tabs",className:"border-b",children:[i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none]",children:[i.jsx(NS,{id:e,label:o||s("New conversation"),className:h(t===e),leading:i.jsx(vr,{className:"h-3 w-3 shrink-0"}),reloadDisabled:a||l,reloading:a,onSelect:()=>re.getState().selectTab(e,void 0)}),d.map(p=>{const f=pL({status:p.status,spawning:p.spawning,pendingApprovalCount:p.pendingApprovalCount,pendingAskCount:p.pendingAskCount,pendingCapabilityAskCount:p.pendingCapabilityAskCount});return i.jsxs("div",{className:"group/tab relative shrink-0",children:[i.jsx(NS,{id:p.id,label:p.title||p.child?.agentInstanceName||p.coworkerName||p.id,className:q(h(t===p.id),t!==p.id&&"group-hover/tab:bg-muted/50"),leading:p.mode==="task"?i.jsx(_g,{className:"h-3 w-3 shrink-0"}):i.jsx(Hs,{className:"h-3 w-3 shrink-0"}),trailing:i.jsx("span",{className:"inline-flex h-3 w-3 shrink-0 items-center justify-center group-hover/tab:invisible",children:i.jsx(Ph,{tone:f,size:"sm"})}),reloadDisabled:p.reloading||p.spawning,reloading:p.reloading,onSelect:()=>re.getState().selectTab(e,p.id)}),i.jsx("button",{type:"button",title:s("Dismiss coworker"),className:"absolute top-1/2 right-2 hidden h-3 w-3 -translate-y-1/2 items-center justify-center text-muted-foreground hover:text-destructive group-hover/tab:flex",onClick:()=>{window.confirm(s("Dismiss this coworker? Its session will be closed."))&&re.getState().dismissCoworkerFromUI(e,p.id)},children:i.jsx(an,{className:"h-3 w-3"})})]},p.id)}),i.jsx("button",{type:"button",title:s("Hire coworker"),disabled:!r,onClick:()=>u(!0),className:"shrink-0 rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",children:i.jsx(ds,{className:"h-3.5 w-3.5"})})]}),n,c&&i.jsx(iQ,{parentId:e,onClose:()=>u(!1)})]})}function NS({id:e,label:t,className:n,leading:s,trailing:o,reloadDisabled:r,reloading:a,onSelect:l}){const{t:d}=Q(),[c,u]=m.useState(!1),h=i.jsxs("button",{type:"button",className:n,onClick:()=>{c||l()},onDoubleClick:p=>{p.preventDefault(),p.stopPropagation(),u(!0)},children:[s,c?i.jsx(bI,{title:t,className:"max-w-48 text-xs",onCommit:p=>{re.getState().renameConversation(e,p),u(!1)},onCancel:()=>u(!1)}):i.jsx("span",{className:"max-w-48 truncate",children:t}),o]});return i.jsxs(uo,{children:[i.jsx(ho,{render:h}),i.jsxs(po,{className:"min-w-36",children:[i.jsxs(Ut,{onClick:()=>u(!0),children:[i.jsx(Fs,{}),d("Rename")]}),i.jsxs(Ut,{disabled:r,onClick:()=>{wI(e,d)},children:[i.jsx(Fo,{className:a?"animate-spin":void 0}),d("Reload conversation")]})]})]})}function iQ({parentId:e,onClose:t}){const{t:n}=Q(),s=Ce(x=>x.agentTypes),o=Ce(x=>x.disabledBuiltinAgentTypes),[r,a]=m.useState(""),[l,d]=m.useState(""),[c,u]=m.useState(null),h=new Set(s.map(x=>x.name.trim().toLowerCase())),p=[...fL.filter(x=>!o.includes(x.name)&&!h.has(x.name)).map(x=>x.name),...s.map(x=>x.name)],f=[{value:"",label:"general"},...p.map(x=>({value:x,label:x}))],g=async()=>{const x=await re.getState().hireCoworker(e,r.trim(),l||void 0);x?u(x):t()};return i.jsx(wn,{open:!0,onOpenChange:x=>!x&&t(),children:i.jsxs(yn,{className:"max-w-sm",children:[i.jsx(Sn,{children:i.jsx(Cn,{children:n("Hire coworker")})}),i.jsxs(On,{className:"space-y-4",children:[i.jsxs(Us,{children:[i.jsx(Ks,{children:n("Name (slug)")}),i.jsx(Xt,{value:r,onChange:x=>a(x.target.value),placeholder:"reviewer",autoFocus:!0})]}),i.jsxs(Us,{children:[i.jsx(Ks,{children:n("Agent type")}),i.jsxs(xs,{items:f,value:l,onValueChange:x=>d(x??""),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:f.map(x=>i.jsx(ns,{value:x.value,children:x.label},x.value||"general"))})]})]}),c&&i.jsx("p",{className:"text-destructive text-xs",children:c}),i.jsx("div",{className:"h-1"})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"ghost",onClick:t,children:n("Cancel")}),i.jsx(ge,{onClick:()=>{g()},disabled:!r.trim(),children:n("Hire")})]})]})})}function oQ(e,t){return e.recipient?(t.dispatchAgent(e.recipient.typeKey,{text:e.text,images:e.images,fileMentions:e.mentions.filter(n=>n.kind==="file").map(n=>({id:n.id,relativePath:n.relativePath}))}),"agent"):(t.sendCoding(e.text,e.images),"coding")}const rQ={active:"bg-green-500 animate-pulse",paused:"bg-amber-500",waiting:"bg-amber-500",blocked:"bg-destructive",completed:"bg-blue-500"};function aQ({conversationId:e,goal:t}){const{t:n}=Q(),s={active:n("working"),paused:n("paused"),waiting:n("waiting"),blocked:n("blocked"),completed:n("completed")};return i.jsxs("div",{className:"mb-1 flex items-center gap-2 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-1.5 text-xs",children:[i.jsx(Na,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",title:t.note?`${t.text} — ${t.note}`:t.text,children:[t.text,t.note&&i.jsxs("span",{className:"text-muted-foreground",children:[" — ",t.note]})]}),i.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",rQ[t.status])}),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground tabular-nums",children:[s[t.status],t.status==="active"&&t.autoTurns>0?` · ${t.autoTurns}/25`:""]}),t.status==="active"?i.jsx("button",{type:"button",title:n("Pause goal"),onClick:()=>re.getState().pauseGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(U$,{className:"h-3.5 w-3.5"})}):t.status!=="completed"?i.jsx("button",{type:"button",title:n("Resume goal"),onClick:()=>re.getState().resumeGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(pg,{className:"h-3.5 w-3.5"})}):null,i.jsx("button",{type:"button",title:n("Clear goal"),onClick:()=>re.getState().clearGoal(e),className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-destructive",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]})}function lQ(e,t){return e.trim().length>0||t>0}function TS(e,t){return e>0?`${e} ${t}`:null}function yI({conversationId:e,queued:t}){const{t:n}=Q(),[s,o]=m.useState(null),[r,a]=m.useState("");if(t.length===0)return null;const l=d=>{lQ(r,d.images?.length??0)&&re.getState().updateQueuedMessage(e,d.id,r.trim()),o(null)};return i.jsx("div",{className:"mb-1 flex flex-col gap-0.5",children:t.map(d=>i.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border/60 border-dashed bg-muted/20 px-2.5 py-1.5 text-xs",children:[i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground uppercase tracking-wide",children:n("Queued")}),s===d.id?i.jsx("input",{value:r,onChange:c=>a(c.target.value),onKeyDown:c=>{c.nativeEvent.isComposing||(c.key==="Enter"&&l(d),c.key==="Escape"&&o(null))},autoFocus:!0,className:"h-6 min-w-0 flex-1 rounded border bg-transparent px-1.5 outline-none focus:ring-1 focus:ring-ring"}):i.jsx("span",{className:"min-w-0 flex-1 truncate",children:d.text||"[image]"}),TS(d.images?.length??0,n("attachments"))&&i.jsxs("span",{title:TS(d.images?.length??0,n("attachments"))??void 0,className:"flex shrink-0 items-center gap-0.5 text-muted-foreground",children:[i.jsx(T$,{className:"h-3 w-3"}),d.images?.length]}),s===d.id?i.jsx("button",{type:"button",onClick:()=>l(d),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Un,{className:"h-3.5 w-3.5"})}):i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5",children:[i.jsx("button",{type:"button",title:n("Withdraw message"),"aria-label":n("Withdraw message"),onClick:()=>re.getState().withdrawMessage(e,{kind:"queue",id:d.id}),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(ua,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Edit"),onClick:()=>{o(d.id),a(d.text)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(Fs,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Send now"),onClick:()=>re.getState().sendQueuedNow(e,d.id),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(yx,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Interrupt and send now"),onClick:()=>{re.getState().interruptAndSendQueued(e,d.id)},className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(l6,{className:"h-3 w-3"})}),i.jsx("button",{type:"button",title:n("Remove"),onClick:()=>re.getState().removeQueuedMessage(e,d.id),className:"rounded p-0.5 text-muted-foreground hover:text-destructive",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]})]},d.id))})}const SI="mb-1 rounded-lg border border-border/60 bg-muted/20 px-2.5 py-2 text-xs";function CI({doc:e}){return i.jsx("div",{className:"mt-2 max-h-72 overflow-y-auto rounded-md border border-border/60 bg-background/60 px-3 py-2 text-sm",children:i.jsx(js,{text:e.text})})}function dQ({conversationId:e,planState:t,approvalMode:n}){const s=kj(t);return s==="awaiting_review"&&t?.pending?i.jsx(cQ,{conversationId:e,doc:t.pending,approvalMode:n},t.pending.planId):s==="executing"&&t?.executing?i.jsx(uQ,{conversationId:e,doc:t.executing},t.executing.planId):null}function cQ({conversationId:e,doc:t,approvalMode:n}){const{t:s}=Q(),o=mL(),[r,a]=m.useState(!0),[l,d]=m.useState(!1),[c,u]=m.useState(""),[h,p]=m.useState(!1),[f,g]=m.useState(!1),x=async(v,y)=>{g(!0);const w=re.getState();y&&y!==n&&w.setApprovalMode(e,y);const b=await w.respondPlan(e,t.planId,v,v==="revise"?c.trim():void 0);b&&(g(!1),Be({type:"error",title:s("Plan response failed"),description:b}))};return i.jsxs("div",{className:SI,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(ma,{className:"h-3.5 w-3.5 shrink-0 text-primary"}),i.jsx("span",{className:"shrink-0 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:s("Plan awaiting approval")}),i.jsxs("button",{type:"button",onClick:()=>a(v=>!v),className:"flex min-w-0 flex-1 items-center gap-1 text-left font-medium",title:t.title,children:[i.jsx("span",{className:"truncate",children:t.title}),i.jsx(bn,{className:q("h-3 w-3 shrink-0 transition-transform",r&&"rotate-90")})]})]}),r&&i.jsx(CI,{doc:t}),l&&i.jsx("textarea",{autoFocus:!0,value:c,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&(v.metaKey||v.ctrlKey)&&c.trim()&&(v.preventDefault(),x("revise"))},placeholder:s("What should change in this plan?"),className:"mt-2 min-h-16 w-full resize-y rounded-md border border-border/60 bg-background px-2.5 py-1.5 text-sm outline-none focus:border-brand/45"}),i.jsxs("div",{className:"mt-2 flex items-center justify-end gap-1.5",children:[i.jsx("button",{type:"button",disabled:f,onClick:()=>{x("discard")},className:"rounded-md px-2.5 py-1 text-xs text-destructive transition-colors hover:bg-destructive/10 disabled:opacity-50",children:s("Discard and exit plan mode")}),l?i.jsx("button",{type:"button",disabled:f||!c.trim(),onClick:()=>{x("revise")},className:"rounded-md px-2.5 py-1 text-xs text-foreground transition-colors hover:bg-muted disabled:opacity-50",children:s("Send feedback")}):i.jsx("button",{type:"button",disabled:f,onClick:()=>d(!0),className:"rounded-md px-2.5 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",children:s("Request changes")}),i.jsxs("div",{className:"flex",children:[i.jsx("button",{type:"button",disabled:f,onClick:()=>{x("approve")},title:s(Pl[n].labelKey),className:"rounded-l-md bg-primary px-2.5 py-1 text-xs text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:s("Approve and execute")}),i.jsxs(Ri,{open:h,onOpenChange:p,children:[i.jsx(Li,{disabled:f,"aria-label":s("Choose the approval mode for execution"),className:"flex items-center rounded-r-md border-primary-foreground/20 border-l bg-primary px-1 text-primary-foreground transition-colors hover:bg-primary/90 disabled:opacity-50",children:i.jsx(Vn,{className:"h-3.5 w-3.5"})}),i.jsxs(Oi,{side:"top",align:"end",className:"w-80 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx("p",{className:"px-2 pt-1 pb-1.5 text-muted-foreground text-xs",children:s("Approve and execute with")}),gL.map(v=>{const y=Pl[v],w=y.icon,b=v==="assistant"&&!o;return i.jsxs("button",{type:"button",disabled:b,onClick:()=>{p(!1),x("approve",v)},className:q("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",v===n?"bg-muted":"hover:bg-muted/60",b&&"cursor-not-allowed opacity-50 hover:bg-transparent"),children:[i.jsx(w,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block",children:s(y.labelKey)}),i.jsx("span",{className:"block text-xs text-muted-foreground",children:s(y.descKey)})]})]},v)})]})]})]})]})]})}function uQ({conversationId:e,doc:t}){const{t:n}=Q(),[s,o]=m.useState(!1);return i.jsxs("div",{className:q(SI,"py-1.5"),children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx(Z1,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:n("Executing plan")}),i.jsxs("button",{type:"button",onClick:()=>o(r=>!r),className:"flex min-w-0 flex-1 items-center gap-1 text-left",title:t.title,children:[i.jsx("span",{className:"truncate",children:t.title}),i.jsx(bn,{className:q("h-3 w-3 shrink-0 transition-transform",s&&"rotate-90")})]}),i.jsx("button",{type:"button",title:n("Finish plan"),onClick:()=>{re.getState().respondPlan(e,t.planId,"finish")},className:"shrink-0 rounded p-0.5 text-muted-foreground transition-colors hover:text-foreground",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}),s&&i.jsx(CI,{doc:t})]})}function hQ({active:e,onToggle:t}){const{t:n}=Q();return i.jsxs("button",{type:"button","aria-pressed":e,title:n(e?"Plan mode is on: read-only research, then a plan for your approval":"Plan first: research read-only and submit a plan for approval"),onClick:()=>t(!e),className:q("flex h-7 min-w-0 shrink-0 items-center gap-1 rounded-lg px-2 text-xs transition-colors",e?"bg-primary/10 text-primary hover:bg-primary/15":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx(ma,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"hidden @min-[28rem]:inline",children:n("Plan")})]})}function pQ({presetId:e,onSelect:t,onModel:n,disabled:s}){const{t:o}=Q(),r=Ce(h=>h.presets),a=xL(),[l,d]=m.useState(!1),c=[{id:vL,name:o("Global")},...r.map(h=>({id:h.id,name:h.name})),...a.map(h=>({id:h.id,name:h.name}))],u=c.find(h=>h.id===e)??{id:e,name:bL(e)?o("Plugin preset unavailable"):c[0]?.name??""};return s?i.jsxs("span",{className:"flex h-7 min-w-0 max-w-40 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground",title:o("Preset is locked after the conversation starts"),children:[i.jsx(Xc,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"truncate",children:u.name})]}):i.jsxs(Ri,{open:l,onOpenChange:d,children:[i.jsxs(Li,{className:"flex h-7 min-w-0 max-w-40 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",title:u.name,children:[i.jsx(Xc,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:u.name}),i.jsx(Vn,{className:"h-3 w-3 shrink-0"})]}),i.jsx(Oi,{side:"top",align:"start",className:"w-52 [&_[data-slot=popover-viewport]]:p-1",children:c.map(h=>{const p=h.id===u.id;return i.jsxs("button",{type:"button",onClick:()=>{t(h.id);const f=r.find(x=>x.id===h.id)?.pluginPresetId,g=wL(f??h.id,a);g&&n?.(g),d(!1)},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",p?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:h.name}),p&&i.jsx(Un,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},h.id)})})]})}const fQ=[];function mQ({projectId:e,conversationId:t}){const{t:n}=Q(),s=Ce(p=>p.projects.find(f=>f.id===e)?.trustedProjectCode??fQ),o=Ce(p=>p.setProjectTrustedCode),[r,a]=m.useState([]),[l,d]=m.useState(!1),[c,u]=m.useState(!1);m.useEffect(()=>{let p=!1;return d(!1),u(!1),window.electronAPI.projects.codeSources({projectId:e,conversationId:t}).then(f=>{p||a(f)}).catch(()=>{p||a([])}),()=>{p=!0}},[e,t]);const h=r.filter(p=>!s.includes(p));return l||h.length===0&&!c?null:h.length===0?i.jsxs("div",{role:"status",className:"mb-1 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-muted-foreground text-xs",children:[i.jsx(ta,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1",children:n("Project extensions trusted. They load in new sessions and after this one restarts.")}),i.jsx("button",{type:"button",onClick:()=>d(!0),title:n("Dismiss"),children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}):i.jsxs("div",{role:"alert",className:"mb-1 flex items-start gap-2 rounded-lg border border-warning/40 bg-warning/5 px-2.5 py-2 text-xs",children:[i.jsx(ta,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-warning"}),i.jsxs("div",{className:"min-w-0 flex-1 space-y-1",children:[i.jsx("p",{children:n("This project ships pi extension code that runs with your permissions. It was not loaded. Trust it only if you trust this repository.")}),i.jsx("p",{className:"truncate font-mono text-muted-foreground",title:h.join(`
|
|
89
|
-
`),children:h.join(", ")})]}),i.jsx(ge,{size:"xs",variant:"outline",onClick:()=>{o(e,r),u(!0)},children:n("Trust and load")}),i.jsx("button",{type:"button",onClick:()=>d(!0),title:n("Dismiss"),children:i.jsx(an,{className:"h-3.5 w-3.5 text-muted-foreground"})})]})}const DS={system:"System prompt",instructions:"Enabled instructions",skills:"Enabled skills",tools:"Tool definitions",conversation:"Conversation",compaction:"Compaction summary",reminders:"Reminders"};function gQ({conversationId:e}){const{t}=Q(),n=re(r=>r.conversations[e]?.compaction);if(!re(r=>r.conversations[e]?.started))return null;const o=t(n==="running"?"Compacting…":n==="queued"?"Compacts after this turn":"Compact context");return i.jsx("button",{type:"button",disabled:!!n,className:"w-full rounded-sm border border-border px-2 py-1 text-[11px] text-foreground/90 hover:bg-muted disabled:cursor-default disabled:text-muted-foreground disabled:hover:bg-transparent",onClick:()=>re.getState().compact(e),children:o})}function xQ({occupancy:e,conversationId:t}){const{t:n}=Q();if(!e)return i.jsx("p",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:n("Context occupancy unavailable until the session starts")});const s=e.contextWindow;return i.jsxs("div",{className:"flex flex-col gap-2 px-2 py-1.5",children:[i.jsxs("div",{className:"flex items-baseline justify-between gap-2 text-xs",children:[i.jsxs("span",{className:"tabular-nums",children:[gs(e.used),s?` / ${gs(s)}`:" · ?",e.percent!==void 0?` · ${e.percent}%`:""]}),i.jsx("span",{className:"text-muted-foreground",children:n("Estimate")})]}),e.compactionModelMismatch&&i.jsx("p",{className:"text-[11px] text-muted-foreground",children:n("Current summary was produced by another model family")}),e.compactedMessageCount>0&&i.jsxs("div",{className:"flex items-center justify-between gap-2 text-[11px] text-muted-foreground",children:[i.jsx("p",{children:n("{{count}} older messages are folded into the summary",{count:e.compactedMessageCount})}),t&&e.compactionEntryId&&i.jsx("button",{type:"button",className:"shrink-0 text-foreground/80 hover:underline",onClick:()=>{re.getState().forkFromEntry(t,e.compactionEntryId)},children:n("Conversation branch")})]}),i.jsx("ul",{className:"flex flex-col gap-1",children:Object.keys(DS).map(o=>{const r=e.buckets[o],a=e.used>0?Math.round(r/e.used*100):0;return i.jsxs("li",{className:"flex items-center gap-2 text-[11px]",children:[i.jsx("span",{className:"w-28 shrink-0 truncate text-muted-foreground",children:n(DS[o])}),i.jsx("span",{className:"min-w-0 flex-1",children:i.jsx("span",{className:"block h-1 overflow-hidden rounded-full bg-muted",children:i.jsx("span",{className:"block h-full bg-foreground/50",style:{width:`${a}%`}})})}),i.jsx("span",{className:"w-10 shrink-0 text-right tabular-nums",children:gs(r)})]},o)})}),t&&i.jsx(gQ,{conversationId:t})]})}const vQ=70;function bQ({percent:e,critical:t}){return i.jsx("span",{"aria-hidden":!0,className:"h-1 w-7 shrink-0 overflow-hidden rounded-full bg-muted-foreground/20",children:i.jsx("span",{className:q("block h-full rounded-full",t?"bg-destructive":e>=vQ?"bg-warning":"bg-muted-foreground/70"),style:{width:`${e}%`}})})}function wQ(e){return e?e.used:null}const dv=90;function kI(e,t){const n=wQ(e);if(n===null)return;const s=e?.contextWindow&&e.contextWindow>0?e.contextWindow:t&&t>0?t:0;return s>0?{used:n,window:s}:{used:n}}function yQ(e,t){const n={inputTokens:0,outputTokens:0,...e};return t&&(n.contextUsed=t.used,t.window!==void 0&&(n.contextWindow=t.window)),n.inputTokens===0&&n.outputTokens===0&&n.cacheHitPercent===void 0&&n.ttftAvgMs===void 0&&n.tokensPerSecond===void 0&&n.contextUsed===void 0?void 0:n}function SQ(e,t){const n={tokens:void 0,cache:void 0,context:void 0,speed:void 0};if(!t)return n;if(t.contextUsed!==void 0){const r=t.contextUsed,a=t.contextWindow??0;if(a>0){const l=Math.min(100,Math.round(r/a*100));n.context={compact:`${l}%`,full:`${gs(a)} · ${l}%`,percent:l,critical:l>=dv}}else n.context={compact:`${gs(r)}·?`,full:`${gs(r)} · ?`}}const s=[],o=[];return t.ttftAvgMs!==void 0&&(s.push(ss(t.ttftAvgMs)),o.push(e("First token avg {{duration}}",{duration:ss(t.ttftAvgMs)}))),t.tokensPerSecond!==void 0&&(s.push(`${t.tokensPerSecond} tok/s`),o.push(e("{{speed}} tok/s",{speed:t.tokensPerSecond}))),s.length>0&&(n.speed={compact:s.join(" · "),full:o.join(" · ")}),(t.inputTokens>0||t.outputTokens>0)&&(n.tokens={compact:`↑${gs(t.inputTokens)} ↓${gs(t.outputTokens)}`,full:e("Input {{input}} tok · Output {{output}} tok",{input:gs(t.inputTokens),output:gs(t.outputTokens)})}),t.cacheHitPercent!==void 0&&(n.cache={compact:`${t.cacheHitPercent}%`,full:e("Cache hit {{percent}}%",{percent:t.cacheHitPercent})}),n}function CQ(e,t){if(!t)return;const n=Math.round(t.bytes/t.limitBytes*100),s=t.blocked?e("Blocked before send"):t.stage==="wire"?e("Before send"):e("Serialized payload");return{compact:Yp(t.bytes),full:`${Yp(t.bytes)} / ${Yp(t.limitBytes)} · ${n}% · ${s}`,critical:t.blocked||n>=dv}}function Yp(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(2)} KiB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(2)} MiB`:`${(e/(1024*1024*1024)).toFixed(2)} GiB`}function kQ({className:e,orientation:t="horizontal",...n}){return i.jsx(yL,{className:q("shrink-0 bg-border data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:w-px data-[orientation=vertical]:not-[[class^='h-']]:not-[[class*='_h-']]:self-stretch",e),"data-slot":"separator",orientation:t,...n})}const jQ={minimal:"Minimal",default:"Default",full:"Full"};function _Q({icons:e,values:t}){const{t:n}=Q(),s=Ce(x=>x.statusLineSegments),o=m.useMemo(()=>jI(s),[s]),r=Ce(x=>x.toggleStatusLineSegment),a=Ce(x=>x.setStatusLineSegments),[l,d]=m.useState(null),[c,u]=m.useState(null),h=SL(o),p=jj.filter(x=>!o.includes(x)),f=()=>{d(null),u(null)},g=()=>{if(l!==null&&c!==null){const x=c>l?c-1:c,v=_L(o,l,x);v!==o&&a([...v])}f()};return i.jsxs("div",{className:"flex flex-col",children:[i.jsxs("div",{className:"flex items-center justify-between gap-2 border-b p-2",children:[i.jsx("div",{className:"flex gap-1",children:CL.map(x=>i.jsx(ge,{variant:h===x?"secondary":"ghost",size:"xs",onClick:()=>a([...kL[x]]),children:n(jQ[x])},x))}),h==="custom"&&i.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground",children:n("Custom")})]}),i.jsxs("div",{className:"max-h-80 overflow-y-auto p-2",onDragOver:x=>{l!==null&&x.preventDefault()},onDrop:x=>{l!==null&&(x.preventDefault(),g())},children:[o.map((x,v)=>{const y=e[x],w=t[x];return i.jsxs("div",{children:[l!==null&&c===v&&i.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),i.jsxs("div",{onDragOver:b=>{if(l===null)return;b.preventDefault();const _=b.currentTarget.getBoundingClientRect(),j=b.clientY<_.top+_.height/2;u(j?v:v+1)},onDrop:b=>{b.preventDefault(),g()},className:q("flex items-center justify-between gap-3 rounded-md px-2 py-1.5",l===v&&"opacity-40"),children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("span",{role:"button",tabIndex:0,draggable:!0,onDragStart:b=>{b.dataTransfer.effectAllowed="move",b.dataTransfer.setData("text/plain",x),d(v)},onDragEnd:f,"aria-label":n("Drag to reorder"),className:"shrink-0 cursor-grab text-muted-foreground/50 hover:text-foreground active:cursor-grabbing",children:i.jsx(jL,{className:"h-3.5 w-3.5"})}),i.jsx(y,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("div",{className:"flex min-w-0 flex-col",children:[i.jsx("span",{className:"text-sm",children:n(Eu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:w?.full||n("No data yet")})]})]}),i.jsx(Di,{checked:!0,onCheckedChange:b=>r(x,b)})]})]},x)}),l!==null&&c===o.length&&i.jsx("div",{className:"mx-2 my-0.5 h-0.5 rounded-full bg-primary"}),p.length>0&&i.jsxs(i.Fragment,{children:[i.jsx(kQ,{className:"my-2"}),p.map(x=>{const v=e[x],y=t[x];return i.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md px-2 py-1.5",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[i.jsx("span",{className:"w-3.5 shrink-0"}),i.jsx(v,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground/50"}),i.jsxs("div",{className:"flex min-w-0 flex-col",children:[i.jsx("span",{className:"text-sm",children:n(Eu[x])}),i.jsx("span",{className:"min-w-0 truncate text-[11px] text-muted-foreground",children:y?.full||n("No data yet")})]})]}),i.jsx(Di,{checked:!1,onCheckedChange:w=>r(x,w)})]},x)})]})]})]})}function jI(e){const t=Array.isArray(e)?e:TL,n=new Set(jj),s=new Set,o=[];for(const r of t)typeof r=="string"&&n.has(r)&&!s.has(r)&&(s.add(r),o.push(r));return o}const Eu={model:"Model",approval:"Approval mode",cwd:"Working directory",sessionName:"Session name",coworkers:"Coworkers",tokens:"Tokens",cache:"Cache hit rate",context:"Context window",requestBody:"Recent request body",turns:"Turns",speed:"Speed",duration:"Duration",sessionTime:"Session time",usage:"Subscription usage"},NQ={minimal:"Min",low:"Low",medium:"Med",high:"High",xhigh:"Extra",max:"Max"},TQ={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"},DQ={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},IQ={supervised:PL,"auto-edits":Bu,full:EL,assistant:zs},EQ={model:YV,context:ML,requestBody:AL,turns:X$,duration:J1,sessionTime:C$,speed:_g,tokens:HV,cache:ZV,cwd:ni,sessionName:c6,coworkers:ra,usage:S6};function PQ(e,t,n){if(e.status!=="running")return{llm:0,tool:0};for(let s=t.length-1;s>=0;s--){const o=t[s];if(!(o.role!=="assistant"||!o.timing))return o.timing.completedMs===void 0?{llm:Math.max(0,n-o.timing.stepStartMs),tool:0}:{llm:0,tool:Math.max(0,n-o.timing.completedMs)}}return{llm:0,tool:0}}function AQ(e){return e.split(/[\\/]+/).filter(Boolean).at(-1)??e}function nc(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function IS(e){if(e<=0)return"0m";const t=Math.round(e/6e4),n=Math.floor(t/1440),s=Math.floor(t%1440/60),o=t%60;return n>0?`${n}d${s}h`:s>0?`${s}h${o}m`:`${o}m`}function ES(e){const t=Math.max(0,Math.floor(e/1e3));if(t<60)return`${t}s`;const n=Math.floor(t/60);if(n<60)return`${n}m${t%60}s`;const s=Math.floor(n/60);return s<24?`${s}h${n%60}m`:`${Math.floor(s/24)}d${s%24}h`}function MQ(e){return{...EQ,approval:IQ[e.approvalMode??"full"]}}function RQ(e,t){const[n,s]=m.useState(()=>{if(!e)return;const o=a0.get(e);return o?{key:e,data:o.data}:void 0});return m.useEffect(()=>{if(!e)return;let o=!1;const r=a0.get(e);if(r&&Date.now()-r.fetchedAt<DL){s({key:e,data:r.data});return}return IL(e).then(a=>{o||s({key:e,data:a})}).catch(()=>{o||s(a=>a?.key===e?void 0:a)}),()=>{o=!0}},[e,t]),e&&n?.key===e?n.data:void 0}function LQ(e,t,n,s,o,r,a){const l=XW(n),d={model:void 0,requestBody:CQ(e,t.requestBody),turns:void 0,duration:void 0,sessionTime:void 0,cwd:void 0,sessionName:void 0,approval:void 0,coworkers:void 0,usage:void 0,...SQ(e,yQ(ZW(l),kI(t.occupancy,t.contextWindow)))};if(t.lastModelId){const w=s.find(_=>_.id===t.lastProviderId)?.models.find(_=>_.id===t.lastModelId)?.label??t.lastModelId,b=t.reasoningEnabled?t.thinkingLevel:void 0;d.model={compact:b?`${w} · ${e(NQ[b])}`:w,full:b?`${w} · ${e(TQ[b])}`:w}}l.steps>0&&(d.turns={compact:`${l.turns}·${l.steps}`,full:e("{{turns}} turns · {{steps}} steps",{turns:l.turns,steps:l.steps})});const c=PQ(t,n,r),u=l.llmMs+c.llm,h=l.toolMs+c.tool,p=[],f=[];u>=1e3&&(p.push(ss(u)),f.push(e("LLM {{duration}}",{duration:ss(u)}))),h>=1e3&&(p.push(ss(h)),f.push(e("Tool calls {{duration}}",{duration:ss(h)}))),p.length>0&&(d.duration={compact:p.join(" · "),full:f.join(" · ")});const g=Math.max(0,r-t.createdAt);d.sessionTime={compact:ES(g),full:ES(g)};const x=o.find(y=>y.id===t.projectId);if(x){const y=AQ(x.path);d.cwd={compact:y,full:x.path}}t.title.trim().length>0&&(d.sessionName={compact:nc(t.title,16),full:nc(t.title,60)}),d.approval={compact:"",full:e(DQ[t.approvalMode??"full"])};const v=t.coworkerIds?.length??0;if(v>0&&(d.coworkers={compact:String(v),full:e("{{count}} coworkers",{count:v})}),a&&!a.error&&a.windows.length>0){const y=a.windows,w=Math.max(...y.map(C=>C.usedPercent)),b=y[0],_=nc(b.label,24),j=b.resetsAt!==void 0?IS(b.resetsAt-r):void 0,N=y.length>1?` +${y.length-1}`:"";d.usage={compact:`${_} ${Math.round(b.usedPercent)}%${j?`·${j}`:""}${N}`,full:y.map(C=>{const S=C.resetsAt!==void 0?` · ${e("resets in {{remaining}}",{remaining:IS(C.resetsAt-r)})}`:"";return`${nc(C.label,24)} ${Math.round(C.usedPercent)}%${S}`}).join(" · "),critical:w>=dv}}return d}function _I({conversationId:e}){const{t}=Q(),n=re(S=>S.conversations[e]),s=n?.messages??[],o=wa(),r=Ce(S=>S.virtualModels),a=m.useMemo(()=>r.length===0?o:[...o,{id:_j,models:r.map(S=>({id:S.id,label:S.name}))}],[o,r]),l=Ce(S=>S.projects),d=Ce(S=>S.statusLineSegments),c=m.useMemo(()=>jI(d),[d]),[u,h]=m.useState(null),[p,f]=m.useState(!1),g=m.useMemo(()=>{if(c.includes("usage"))return Ng(o,n)?.accountKey},[c,o,n]),[x,v]=m.useState(()=>Date.now()),y=n?.status==="running"&&c.includes("duration"),w=c.includes("sessionTime"),b=c.includes("usage")&&g!==void 0;m.useEffect(()=>{if(!y&&!w&&!b)return;const S=setInterval(()=>v(Date.now()),1e3);return()=>clearInterval(S)},[y,w,b]);const _=RQ(g,x),j=m.useMemo(()=>n?MQ(n):null,[n]),N=m.useMemo(()=>n?LQ(t,n,s,a,l,x,_):null,[t,n,s,a,l,x,_]);if(!n||!j||!N)return null;const C=c.filter(S=>N[S]);return i.jsxs("div",{"data-slot":"stats-line","data-enso":"status-line",className:"group relative flex h-7 items-center justify-center px-1",children:[C.length>0&&i.jsx("div",{className:"flex min-w-0 flex-nowrap items-center gap-3 overflow-hidden",children:C.map((S,A)=>{const E=N[S];if(!E)return null;const I=j[S],D=i.jsxs("span",{title:`${t(Eu[S])} · ${E.full}`,onMouseEnter:()=>h(S),onMouseLeave:()=>h(T=>T===S?null:T),className:q("relative flex items-center gap-1 text-[11px] tabular-nums",E.critical?"text-destructive":"text-subtle-foreground"),children:[S==="context"&&E.percent!==void 0?i.jsx(bQ,{percent:E.percent,critical:!!E.critical}):i.jsx(I,{className:"h-3 w-3 shrink-0 opacity-75"}),E.compact&&i.jsx("span",{className:"truncate",children:E.compact}),u===S&&S!=="context"&&i.jsxs("div",{style:{zIndex:kn.TOOLTIP},className:"-translate-x-1/2 pointer-events-none absolute bottom-full left-1/2 mb-1.5 w-max max-w-56 overflow-hidden rounded-md border bg-popover px-2 py-1 text-popover-foreground shadow-md",children:[i.jsx("span",{className:"break-words font-medium",children:t(Eu[S])}),i.jsx("span",{className:"ml-1 break-words text-muted-foreground",children:E.full})]})]});return i.jsx("span",{className:q("shrink-0 items-center",p||NL(S,A)?"flex":"hidden group-focus-within:flex group-hover:flex"),children:S==="context"?i.jsxs(Ri,{open:p,onOpenChange:f,children:[i.jsx(Li,{className:"rounded-sm outline-none",children:D}),i.jsx(Oi,{side:"top",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(xQ,{occupancy:n.occupancy,conversationId:n.id})})]}):D},S)})}),i.jsxs(Ri,{children:[i.jsx(Li,{"aria-label":t("Status line settings"),className:"-translate-y-1/2 absolute top-1/2 right-1 flex h-5.5 w-5.5 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100",children:i.jsx(Nj,{className:"h-3.5 w-3.5"})}),i.jsx(Oi,{side:"top",align:"end",className:"w-72 [&_[data-slot=popover-viewport]]:p-0",children:i.jsx(_Q,{icons:j,values:N})})]})]})}const OQ=["pattern","query","path","file_path"],zQ=["path","file_path","query","pattern"],GQ=["command","cmd","script"],FQ=["path","file_path","pattern","query","command","url","description","summary"],PS=120;function Ha(e){const t=e.replace(/\s+/g," ").trim();return t.length>PS?`${t.slice(0,PS-1)}…`:t}function HQ(e){const t=e.toLowerCase();return t.includes("search")||t.includes("grep")||t==="find"?OQ:t==="read"||t.endsWith("_read")?zQ:t==="bash"||t.includes("shell")||t.includes("terminal")?GQ:FQ}function BQ(e,t){const n=t.trim();if(!n)return"";let s;try{s=JSON.parse(n)}catch{return Ha(n)}if(s===null)return"";if(typeof s!="object"||Array.isArray(s))return Ha(JSON.stringify(s)??String(s));const o=Tj(e,s);if(o.summary!==void 0)return Ha(o.summary);if(!o.args||typeof o.args!="object")return"";const r=o.args;for(const l of HQ(o.name)){const d=r[l];if(typeof d=="string"&&d.trim())return Ha(d)}const a=JSON.stringify(r);return a==="{}"?"":Ha(a)}function VQ(e){return e.scrollHeight-e.scrollTop-e.clientHeight<=24}const NI=new Map,$Q=e=>{const t=NI.get(e);return t?new Set(t):new Set},AS=(e,t)=>(NI.set(e,t),t),Gm=new Map,WQ=(e,t)=>{const n=Gm.get(e)??new Set;Gm.set(e,n);for(const s of t)n.add(s);return n};function cv({sessionId:e,tasks:t,subagents:n,readOnly:s}){const o=Ce(w=>w.virtualModels),{t:r}=Q(),[a,l]=m.useState(()=>$Q(e)),[d,c]=m.useState(null),u=re(w=>w.pendingAgentOpen);m.useEffect(()=>{!u||u.sessionId!==e||(c(u.agentId),re.setState({pendingAgentOpen:null}))},[u,e]);const h=WQ(e,[...t.filter(w=>w.status==="running").map(w=>w.taskId),...n.filter(w=>w.status==="running").map(w=>w.id)]),p=(w,b)=>!a.has(w)&&(b==="running"||h.has(w)),f=t.filter(w=>p(w.taskId,w.status)),g=n.filter(w=>p(w.id,w.status));if(m.useEffect(()=>{const w=Gm.get(e),b=[...t.filter(j=>j.status!=="running").map(j=>j.taskId),...n.filter(j=>j.status!=="running").map(j=>j.id)].filter(j=>w?.has(j)&&!a.has(j)&&j!==d);if(b.length===0)return;const _=setTimeout(()=>{l(j=>{const N=new Set(j);for(const C of b)N.add(C);return AS(e,N)})},5e3);return()=>clearTimeout(_)},[e,t,n,a,d]),f.length===0&&g.length===0)return null;const x=w=>{l(b=>AS(e,new Set(b).add(w))),d===w&&c(null)},v=f.find(w=>w.taskId===d)??null,y=g.find(w=>w.id===d)??null;return i.jsxs("div",{className:"relative mb-1.5",children:[(v||y)&&i.jsxs("div",{className:"absolute bottom-full left-0 right-0 z-30 mb-1.5 rounded-xl border bg-card shadow-float",children:[i.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-1.5 text-xs",children:[i.jsxs("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",children:[v?v.command:y?.description,y?.modelId?` · ${kf(o,y.modelId)}`:""]}),i.jsx("button",{type:"button",onClick:()=>c(null),className:"rounded p-0.5 text-muted-foreground hover:text-foreground",children:i.jsx(an,{className:"h-3.5 w-3.5"})})]}),v&&i.jsx(QQ,{tail:v.tail}),y&&i.jsx(UQ,{agent:y},y.id)]}),i.jsxs("div",{className:"flex flex-col gap-0.5 rounded-xl border bg-card p-1 shadow-xs",children:[f.map(w=>i.jsx(MS,{icon:Go,status:w.status,meta:i.jsx(JQ,{task:w}),open:d===w.taskId,onToggle:()=>c(d===w.taskId?null:w.taskId),stopTitle:r("Stop task"),onStop:s?void 0:()=>{window.electronAPI.agent.stopTask(e,w.taskId)},onDismiss:()=>x(w.taskId),children:i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs text-muted-foreground",title:w.command,children:w.command})},w.taskId)),g.map(w=>i.jsxs(MS,{icon:Hs,status:w.status,meta:i.jsx(ZQ,{agent:w}),open:d===w.id,onToggle:()=>c(d===w.id?null:w.id),stopTitle:r("Stop subagent"),onStop:s?void 0:()=>{window.electronAPI.agent.stopSubagent(e,w.id)},onDismiss:()=>x(w.id),children:[w.agentType&&i.jsx("span",{className:"shrink-0 font-medium",children:w.agentType}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-xs text-muted-foreground",children:[w.description,w.modelId&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" ","· ",kf(o,w.modelId)]}),w.status==="running"&&w.currentActivity&&i.jsxs("span",{className:"text-muted-foreground/60",children:[" · ",w.currentActivity]})]})]},w.id))]})]})}function MS({icon:e,status:t,meta:n,open:s,onToggle:o,stopTitle:r,onStop:a,onDismiss:l,children:d}){const{t:c}=Q();return i.jsxs("div",{className:"flex min-h-[30px] min-w-0 items-center gap-2 px-1 text-[13px]",children:[i.jsx(k7,{icon:e,state:t==="running"?"running":t==="failed"?"error":"ok"}),d,n,i.jsxs("button",{type:"button",onClick:o,"aria-expanded":s,className:"flex h-6 shrink-0 items-center gap-0.5 rounded-md px-1.5 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[c("Output"),i.jsx(Vn,{className:q("h-3 w-3 transition-transform",s&&"rotate-180")})]}),t==="running"?a&&i.jsx("button",{type:"button",onClick:a,title:r,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",children:i.jsx(ld,{className:"h-3 w-3"})}):i.jsx("button",{type:"button",onClick:l,className:"flex size-6 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:i.jsx(an,{className:"h-3 w-3"})})]})}function UQ({agent:e}){const{t}=Q(),n=e.activities??[],s=m.useRef(null),o=m.useRef(!0);return m.useEffect(()=>{const r=s.current;r&&o.current&&(r.scrollTop=r.scrollHeight)},[n,e.resultText]),i.jsxs("div",{ref:s,className:"max-h-96 space-y-2 overflow-auto px-3 py-2 text-sm",onScroll:r=>{o.current=VQ(r.currentTarget)},children:[n.map(r=>i.jsx(KQ,{activity:r},r.id)),n.length===0&&!e.resultText&&i.jsx("pre",{className:"font-mono text-xs whitespace-pre-wrap text-muted-foreground",children:(e.activityLog??[]).join(`
|
|
90
|
-
`)||t("(no output yet)")}),e.detailsPruned&&i.jsx("div",{className:"rounded-md border border-dashed px-2.5 py-2 text-xs text-muted-foreground",children:t("Earlier activity details were cleared; the final report is still available.")}),e.resultText&&e.status!=="running"&&i.jsxs("section",{className:q("rounded-lg border px-3 py-2",e.status==="failed"?"border-destructive/30 bg-destructive/5":"border-blue-500/30 bg-blue-500/5"),children:[i.jsx("div",{className:"mb-1.5 font-medium text-xs text-foreground",children:t("Final report")}),i.jsx(js,{text:e.resultText})]})]})}function KQ({activity:e}){const{t}=Q(),[n,s]=m.useState(!1);if(e.type==="assistant")return i.jsxs("section",{className:"rounded-md bg-muted/30 px-2.5 py-2",children:[i.jsx("div",{className:"mb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:t("Assistant")}),i.jsx(XQ,{text:e.text,markdown:!0})]});const o=BQ(e.toolName,e.argumentsText),r=Tj(e.toolName,e.argumentsText).name,a=Tk(r),l=`subagent-tool-${e.id.replace(/[^A-Za-z0-9_-]/g,"-")}`;return i.jsxs("section",{className:"border-b border-border/40 last:border-b-0",children:[i.jsxs("button",{type:"button","aria-controls":l,"aria-expanded":n,onClick:()=>s(d=>!d),className:"flex w-full min-w-0 items-center gap-2 rounded-md px-1.5 py-1 text-left text-xs transition-colors hover:bg-muted/50",children:[i.jsx(qQ,{toolName:r}),i.jsx("span",{className:"shrink-0 font-medium text-foreground/80",children:a?.tool??r}),o&&i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground",title:o,children:o}),!o&&i.jsx("span",{className:"min-w-0 flex-1"}),i.jsx(YQ,{status:e.status,label:t(e.status)}),i.jsx(bn,{"aria-hidden":"true",className:q("h-3 w-3 shrink-0 text-muted-foreground transition-transform",n&&"rotate-90")})]}),n&&i.jsxs("div",{id:l,className:"ml-5 border-border/50 border-l pb-2 pl-2.5",children:[a&&i.jsxs("div",{className:"mb-1 truncate font-mono text-[10px] text-muted-foreground/70",children:[a.server,".",a.tool]}),i.jsx("div",{className:"text-[10px] text-muted-foreground/70",children:t("Arguments")}),i.jsx("pre",{className:"max-h-28 overflow-auto font-mono text-[10px] leading-relaxed whitespace-pre-wrap text-muted-foreground/80",children:vi(e.argumentsText)}),e.outputText&&i.jsxs("div",{className:"mt-1.5 border-border/40 border-t pt-1.5",children:[i.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t("Result")}),i.jsx("pre",{className:"overflow-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-foreground/80",children:vi(e.outputText)})]})]})]})}function qQ({toolName:e}){const t=e.toLowerCase(),n="h-3.5 w-3.5 shrink-0 text-muted-foreground";return t.includes("search")||t.includes("grep")||t==="find"?i.jsx(ti,{"aria-hidden":"true",className:n}):t==="read"||t==="write"||t==="edit"||t==="apply_patch"||t.endsWith("_read")?i.jsx(bo,{"aria-hidden":"true",className:n}):t==="bash"||t==="exec"||t==="codemode"||t.includes("shell")||t.includes("terminal")?i.jsx(mf,{"aria-hidden":"true",className:n}):i.jsx(gg,{"aria-hidden":"true",className:n})}function YQ({status:e,label:t}){const n="h-3.5 w-3.5";return i.jsx("span",{role:"status","aria-label":t,title:t,className:q("shrink-0",e==="failed"?"text-destructive":"text-muted-foreground"),children:e==="running"?i.jsx(qt,{"aria-hidden":"true",className:q(n,"animate-spin")}):e==="done"?i.jsx(Un,{"aria-hidden":"true",className:n}):e==="failed"?i.jsx(gr,{"aria-hidden":"true",className:n}):i.jsx(bV,{"aria-hidden":"true",className:n})})}function XQ({text:e,label:t,markdown:n=!1}){const{t:s}=Q(),o=e.length>800||e.split(`
|
|
91
|
-
`).length>16,r=n?i.jsx(js,{text:e}):i.jsx("pre",{className:"overflow-x-auto font-mono text-[11px] leading-relaxed whitespace-pre-wrap text-muted-foreground",children:vi(e)});return o?i.jsxs("details",{className:"group/details",children:[i.jsxs("summary",{className:"cursor-pointer text-[10px] text-muted-foreground hover:text-foreground",children:[t?`${t} · `:"",s("{{count}} chars",{count:e.length})]}),i.jsx("div",{className:"mt-1.5",children:r})]}):i.jsxs("div",{children:[t&&i.jsx("div",{className:"mb-0.5 text-[10px] text-muted-foreground",children:t}),r]})}function ZQ({agent:e}){const[,t]=m.useState(0);return m.useEffect(()=>{if(e.status!=="running")return;const n=setInterval(()=>t(s=>s+1),1e3);return()=>clearInterval(n)},[e.status]),i.jsxs("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:[e.steps>0?`${e.steps} steps · `:"",e.outputTokens?`${e.outputTokens} tok · `:"",e.status==="running"?ss(Date.now()-e.startedAt):e.status]})}function JQ({task:e}){const[,t]=m.useState(0);return m.useEffect(()=>{if(e.status!=="running")return;const n=setInterval(()=>t(s=>s+1),1e3);return()=>clearInterval(n)},[e.status]),i.jsx("span",{className:"shrink-0 font-mono text-[10px] text-muted-foreground/70 tabular-nums",children:e.status==="running"?ss(Date.now()-e.startedAt):e.exitCode!==void 0?`exit ${e.exitCode}`:e.status})}function QQ({tail:e}){const{t}=Q(),n=m.useRef(null);return m.useEffect(()=>{const s=n.current;s&&(s.scrollTop=s.scrollHeight)},[e]),i.jsx("pre",{ref:n,className:"max-h-56 overflow-auto border-t border-border/60 px-2.5 py-2 font-mono text-xs leading-relaxed whitespace-pre-wrap text-muted-foreground",children:vi(e)||t("(no output yet)")})}function uv(e){return e==="darwin"?"Open in Finder":e==="win32"?"Open in File Explorer":"Open in File Manager"}async function hv(e,t){try{const n=await window.electronAPI.projects.reveal(e);n.ok||Be({type:"error",title:t("Could not complete the file action."),description:n.error})}catch(n){Be({type:"error",title:t("Could not complete the file action."),description:String(n)})}}const eee="group-hover:grid-cols-[1fr] group-hover:opacity-100 group-focus-visible:grid-cols-[1fr] group-focus-visible:opacity-100 group-data-popup-open:grid-cols-[1fr] group-data-popup-open:opacity-100";function tee({project:e,conversationId:t,path:n,branch:s,openDisabled:o,children:r}){const{t:a}=Q(),[l,d]=m.useState([]),c=e.kind!=="ssh"&&!window.electronAPI.remote,u=e.kind==="scratch",h=u?a("Temporary chats"):e.name,p=m.useCallback(()=>{c&&window.electronAPI.projects.openInApps().then(d).catch(()=>{})},[c]),f=v=>{hv({projectId:e.id,conversationId:t,...v?{appId:v}:{}},a)},g=l.filter(v=>v.kind==="editor"),x=l.filter(v=>v.kind==="terminal");return i.jsxs(Hi,{onOpenChange:v=>v&&p(),children:[i.jsxs(Bi,{className:"group ml-1.5 flex h-6 min-w-0 shrink-0 items-center rounded-full border border-border/60 px-2 font-mono text-[11.5px] text-muted-foreground outline-none transition-colors duration-(--duration-quick) hover:border-border focus-visible:border-border data-popup-open:border-border",title:u?h:n,"aria-label":s&&!u?`${h} / ${s}`:h,onPointerEnter:p,children:[i.jsx(yd,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:`grid grid-cols-[0fr] opacity-0 transition-[grid-template-columns,opacity] duration-(--duration-fast) ease-(--ease-smooth-out) ${eee}`,children:i.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 overflow-hidden whitespace-nowrap pl-1.5",children:[i.jsx("span",{className:"max-w-40 truncate",children:h}),s&&!u&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"opacity-40",children:"/"}),i.jsx(Ei,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-40 truncate",children:s})]})]})}),i.jsx("span",{className:"ml-1.5 flex shrink-0 items-center",children:r})]}),i.jsxs(Vi,{align:"end",className:"min-w-48",children:[c&&i.jsxs(i.Fragment,{children:[i.jsxs(pn,{disabled:o,onClick:()=>f(),children:[i.jsx(ni,{}),a(uv(window.electronAPI.env.platform))]}),i.jsx(RS,{label:a("Editors"),apps:g,fallback:i.jsx(Q1,{}),disabled:o,onOpen:f}),i.jsx(RS,{label:a("Terminals"),apps:x,fallback:i.jsx(Go,{}),disabled:o,onOpen:f}),i.jsx(va,{})]}),i.jsxs(pn,{onClick:()=>{navigator.clipboard.writeText(n)},children:[i.jsx(Vu,{}),a("Copy Path")]})]})]})}function RS({label:e,apps:t,fallback:n,disabled:s,onOpen:o}){return t.length===0?null:i.jsxs(i.Fragment,{children:[i.jsx(va,{}),i.jsxs(vg,{children:[i.jsx(bg,{children:e}),t.map(r=>i.jsxs(pn,{disabled:s,onClick:()=>o(r.id),children:[r.icon?i.jsx("img",{src:r.icon,alt:"",className:"-mx-0.5 size-4 shrink-0"}):n,r.name]},r.id))]})]})}function nee({conversationId:e}){const{t}=Q(),n=re(r=>r.conversations[e]),s=re(r=>r.rebuildWorktree),o=re(r=>r.fallbackToMainWorkspace);return!n?.worktreeMissing||!n.worktree?null:i.jsx(Dj,{open:!0,children:i.jsxs(Ij,{className:"sm:max-w-md",children:[i.jsxs(Ej,{children:[i.jsx(Pj,{className:"text-base",children:t("Isolated worktree is missing")}),i.jsx(Aj,{children:t('The worktree of this session was deleted. Rebuild it from branch "{{branch}}" (committed work is preserved), or fall back to the main working tree.',{branch:n.worktree.branch})})]}),i.jsxs(Mj,{variant:"bare",children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>{o(e)},children:t("Fall back to main working tree")}),i.jsx(ge,{size:"sm",onClick:()=>{s(e).then(r=>{r&&Be({type:"error",title:t("Failed to rebuild worktree"),description:r})})},children:t("Rebuild worktree")})]})]})})}function Pu(e,t){switch(e){case"running":return t("Stop running conversations and coworkers in this workspace before switching branches.");case"dirty":return t("Commit or stash uncommitted changes before switching branches.");case"busy":return t("This workspace is busy. Try again when its conversations are ready.");case"occupied":return t("Branch is checked out in another worktree.");case"invalid-branch":return t("Enter a valid Git branch name.");case"branch-exists":return t("A branch with this name already exists.");case"branch-not-found":return t("This branch no longer exists. Refresh the branch list.");case"same-branch":return t("This workspace is already on that branch.");case"unavailable":return t("Branches are not available for this workspace.");default:return t("Git could not switch branches.")}}function see({initialName:e,data:t,busy:n,disabled:s,error:o,returnFocus:r,onSubmit:a,onClose:l}){const{t:d}=Q(),[c,u]=m.useState(e),h=m.useRef(null),p=m.useId(),f=t?.branches.some(v=>v.name===c.trim()),g=n||s||!t?.headCommit||!!t.blockedReason||!c.trim()||f,x=f?d("A branch with this name already exists."):t?.blockedReason?Pu(t.blockedReason,d):t&&!t.headCommit?d("Create a commit before creating a branch from HEAD."):null;return i.jsx(wn,{open:!0,onOpenChange:v=>{!v&&!n&&l()},children:i.jsxs(yn,{className:"max-w-sm",initialFocus:h,finalFocus:r,showCloseButton:!n,children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:d("Create branch")}),i.jsx(Bs,{children:d("Creates a branch from the current HEAD and switches every conversation in this workspace to it.")})]}),i.jsxs(On,{children:[i.jsx(Xt,{ref:h,"aria-label":d("Branch name"),"aria-invalid":!!x,"aria-describedby":x||o?p:void 0,value:c,disabled:n,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.nativeEvent.isComposing&&(v.preventDefault(),g||a(c.trim()))}}),(x||o)&&i.jsx("p",{id:p,role:"alert",className:"mt-2 break-words text-xs text-destructive",children:x||o})]}),i.jsxs(cs,{children:[i.jsx(ge,{type:"button",variant:"outline",size:"sm",disabled:n,onClick:l,children:d("Cancel")}),i.jsxs(ge,{type:"button",size:"sm",disabled:!!g,onClick:()=>{g||a(c.trim())},children:[n&&i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin"}),d("Create and switch")]})]})]})})}function iee({data:e,loading:t,error:n,disabled:s,query:o,searchRef:r,onQueryChange:a,onSelect:l,onCreate:d,onRetry:c}){const{t:u}=Q(),h=s||t||!!n||!e||!!e.blockedReason,p=e?.branches.filter(f=>f.name.toLowerCase().includes(o.trim().toLowerCase()))??[];return i.jsxs("section",{"aria-label":u("Local branches"),className:"pb-1",onKeyDown:f=>{if(f.nativeEvent.isComposing||!["ArrowDown","ArrowUp"].includes(f.key))return;const g=Array.from(f.currentTarget.querySelectorAll("button[data-branch-row]:not(:disabled)"));if(!g.length)return;f.preventDefault();const x=g.indexOf(f.target),v=x<0?f.key==="ArrowDown"?0:g.length-1:(x+(f.key==="ArrowDown"?1:-1)+g.length)%g.length;g[v]?.focus()},children:[i.jsxs("div",{className:"relative m-1",children:[i.jsx(ti,{className:"pointer-events-none absolute left-2 top-1/2 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Xt,{ref:r,value:o,onChange:f=>a(f.target.value),"aria-label":u("Search local branches"),placeholder:u("Search local branches"),className:"h-8 text-xs [&_input]:pl-7"})]}),i.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:u("Switching branches affects all conversations in this workspace.")}),e?.blockedReason&&i.jsx("p",{role:"status",className:"px-2 py-1 text-xs text-warning",children:Pu(e.blockedReason,u)}),t?i.jsxs("div",{role:"status",className:"flex items-center gap-2 px-2 py-3 text-xs text-muted-foreground",children:[i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin"}),u("Loading...")]}):n?i.jsxs("div",{role:"alert",className:"px-2 py-2 text-xs",children:[i.jsx("p",{className:"break-words text-destructive",children:n}),i.jsx("button",{type:"button",disabled:s,onClick:c,className:"mt-1 rounded px-1 py-1 text-foreground hover:bg-muted disabled:opacity-50",children:u("Retry")})]}):i.jsxs("div",{className:"max-h-48 overflow-y-auto",children:[p.map(f=>{const g=f.name===e?.currentBranch,x=f.occupied&&!!f.worktreeConversationId,v=x?u("New conversation in this worktree"):f.occupied?u("Branch is checked out in another worktree."):null;return i.jsxs("button",{type:"button","data-branch-row":"","aria-current":g||void 0,disabled:h||g||f.occupied&&!x,title:v?`${f.name}
|
|
92
|
-
${v}`:f.name,onClick:()=>l(f),className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",g&&"bg-primary/10"),children:[x?i.jsx(Ro,{className:"h-3.5 w-3.5 shrink-0"}):i.jsx(Ei,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:f.name}),v&&i.jsx("span",{className:"block text-xs text-muted-foreground",children:v})]}),g&&i.jsx(Un,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},f.name)}),e&&p.length===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-3 text-center text-xs text-muted-foreground",children:u("No matching local branches.")})]}),i.jsxs("button",{type:"button",disabled:h||!e?.headCommit,onClick:d,title:e&&!e.headCommit?u("Create a commit before creating a branch from HEAD."):void 0,className:"mt-1 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",children:[i.jsx(ds,{className:"h-3.5 w-3.5 shrink-0"}),u("Create branch from HEAD…")]})]})}function Wc(e){return e.name?.trim()||e.branch}function oee(e,t,n){const s=new Set,o=[];for(const[r,a]of Object.entries(e)){const{worktree:l}=a;a.projectId!==t||!l||a.parentId||a.child||a.worktreeMissing||a.ended||a.historyOnly||a.workspaceMigrating||n[r]?.exists===!1||s.has(l.path)||(s.add(l.path),o.push({conversationId:r,worktree:l}))}return o}function ree(e){return!e.worktree&&!e.parentId&&!e.child&&!e.started&&!e.sessionFile&&e.messages.length===0&&!e.spawning&&e.status!=="running"&&!e.workspaceMigrating&&!e.reloading&&!e.ended&&!e.historyOnly&&!e.archived&&!e.forkedFromConversationId}function Fm(e,t,n){const s=t?.exists===!1?n("Worktree missing"):t?[t.dirty?n("Uncommitted changes"):n("Working tree clean"),...t.ahead>0?[n("{{n}} unmerged commits",{n:t.ahead})]:[]].join(" · "):n("Worktree status unknown");return[Wc(e),e.branch,e.path,s].join(`
|
|
93
|
-
`)}function aee({worktree:e,status:t}){const{t:n}=Q();return i.jsx("span",{"data-slot":"worktree-label",title:Fm(e,t,n),className:"flex shrink-0 items-center",children:i.jsx(Ei,{className:q("size-2.75",t?.exists===!1?"text-destructive":t?.dirty?"text-warning":(t?.ahead??0)>0?"text-info":"text-subtle-foreground")})})}function TI({entity:e,onClose:t}){const{t:n}=Q(),s=re(c=>c.renameWorktree),[o,r]=m.useState(e?.worktree.name??""),[a,l]=m.useState(!1);m.useEffect(()=>{r(e?.worktree.name??""),l(!1)},[e]);const d=async()=>{if(!(!e||a)){l(!0);try{const c=await s(e.conversationId,o.trim());c?Be({type:"error",title:n("Failed to rename worktree"),description:c}):t()}catch(c){Be({type:"error",title:n("Failed to rename worktree"),description:String(c)})}finally{l(!1)}}};return i.jsx(wn,{open:e!==null,onOpenChange:c=>{!c&&!a&&t()},children:i.jsxs(yn,{className:"max-w-sm",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:n("Rename worktree")}),i.jsx(Bs,{children:n("Only the display name changes, for all sessions in this worktree. Leave empty to use the branch name.")})]}),i.jsx(On,{children:i.jsx(Xt,{"aria-label":n("Worktree name"),maxLength:80,placeholder:e?.worktree.branch,value:o,disabled:a,autoFocus:!0,onChange:c=>r(c.target.value),onKeyDown:c=>{c.key==="Enter"&&!c.nativeEvent.isComposing&&(c.preventDefault(),d())}})}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",disabled:a,onClick:t,children:n("Cancel")}),i.jsxs(ge,{size:"sm",disabled:a,onClick:()=>{d()},children:[a&&i.jsx(qt,{className:"h-3.5 w-3.5 animate-spin"}),n("Save")]})]})]})})}function lee({conversationId:e,onBranchChange:t}){const{t:n}=Q(),s=re(ze=>ze.conversations[e]),o=re(ze=>ze.moveConversationToWorktree),r=re(ze=>ze.cleanupWorktree),a=re(ze=>ze.refreshWorktreeStatuses),l=re(ze=>ze.conversations),d=re(ze=>ze.worktreeStatuses),c=re(ze=>ze.attachConversationToWorktree),u=re(ze=>ze.newConversation),h=re(ze=>ze.switchWorkspaceBranch),p=re(ze=>ze.workspaceRevisionByConversation[e]??0),[f,g]=m.useState(null),x=m.useMemo(()=>oee(l,s?.projectId??"",d),[l,s?.projectId,d]),[v,y]=m.useState(!1),[w,b]=m.useState(!1),[_,j]=m.useState(!1),[N,C]=m.useState(null),[S,A]=m.useState(!1),E=Ce(ze=>s?ze.projects.find(wt=>wt.id===s.projectId):void 0),I=!!(s&&!s.parentId&&!s.child&&E?.kind!=="ssh"&&E?.kind!=="scratch"),D=`${e}\0${s?.worktree?.path??E?.path??""}`,T=m.useRef(D);T.current=D;const z=m.useRef(0),$=m.useRef(!1),R=m.useRef(null),B=m.useRef(null),H=m.useRef(null);m.useEffect(()=>{v&&(w?B:H).current?.focus()},[v,w]);const[oe,te]=m.useState(null),O=oe?.key===D?oe.data:null,V=O?.currentBranch??void 0;m.useEffect(()=>{t?.(V)},[t,V]);const[J,pe]=m.useState(!0),[fe,_e]=m.useState(null),[Ee,me]=m.useState(""),[W,G]=m.useState(null),[de,X]=m.useState(null),ie=W===D;m.useEffect(()=>{y(!1),b(!1),me(""),G(null),X(null)},[D]);const Z=m.useCallback(async(ze=!1)=>{if(!I)return;const wt=++z.current;pe(!0),_e(null);try{const Y=await window.electronAPI.worktree.branches(e);if(wt!==z.current||T.current!==D)return;if(Y.ok)te({key:D,data:Y.value});else{const U=Pu(Y.code,n);_e(U),ze&&Be({type:"error",title:n("Failed to load branches"),description:U})}}catch(Y){if(wt!==z.current||T.current!==D)return;_e(n("Failed to load branches")),ze&&Be({type:"error",title:n("Failed to load branches"),description:String(Y)})}finally{wt===z.current&&T.current===D&&pe(!1)}},[e,I,n,D]);if(m.useEffect(()=>{Z();const ze=()=>{$.current||Z()};return window.addEventListener("focus",ze),()=>{z.current+=1,window.removeEventListener("focus",ze)}},[Z,p]),!s||s.parentId||s.child||E?.kind==="ssh")return null;const le=!!s.worktree,be=_||s.spawning||s.status==="running"||!!(s.workspaceMigrating||s.reloading),Fe=s.worktreeMissing||d[e]?.exists===!1,Je=ree(s),We=O?O.currentBranch:s.worktree?.branch,et=We??(O?.headCommit?n("Detached HEAD"):""),qe=s.worktree?Wc(s.worktree):n("Local"),Lt=et&&et!==qe&&(!O?.defaultBranch||We!==O.defaultBranch)?`${qe} · ${et}`:qe,Bt=be||Fe||J||!!fe||!O||!!O.blockedReason,Mt=async(ze,wt=!1,Y)=>{if(Bt||$.current)return;$.current=!0,z.current+=1,j(!0),X(null);const U=n(Y?"Failed to create conversation":"Failed to switch branch");try{if(Y){await u(s.projectId,{worktreeFromConversationId:Y})?T.current===D&&y(!1):Be({type:"error",title:U});return}const ue=await h(e,ze,wt);if(T.current!==D)return;if(ue.ok)te({key:D,data:ue.value}),_e(null),G(null),y(!1);else{const je=Pu(ue.code,n);X(je),Be({type:"error",title:U,description:ue.code==="git-error"?`${je}
|
|
94
|
-
${ue.error}`:je}),Z()}}catch(ue){if(T.current!==D)return;X(String(ue)),Be({type:"error",title:U,description:String(ue)})}finally{$.current=!1,j(!1)}},ne=ze=>{ze.name===O?.currentBranch||ze.occupied&&!ze.worktreeConversationId||Mt(ze.name,!1,ze.occupied?ze.worktreeConversationId:void 0)},se=async ze=>{if(be)return;j(!0);const wt=n(ze?"Failed to use worktree":"Failed to create conversation");try{if(ze){const Y=await c(e,ze);Y&&Be({type:"error",title:wt,description:Y})}else await u(s.projectId,{worktreeFromConversationId:e})||Be({type:"error",title:wt})}catch(Y){Be({type:"error",title:wt,description:String(Y)})}finally{j(!1)}},He=async()=>{j(!0);try{const ze=await r(e);ze?Be({type:"error",title:n("Failed to clean up worktree"),description:ze}):a()}catch(ze){Be({type:"error",title:n("Failed to clean up worktree"),description:String(ze)})}finally{j(!1)}},kt=async(ze=!1)=>{j(!0);try{const wt=await o(e,{allowDirtyMainTree:ze});wt===Rj?A(!0):wt?Be({type:"error",title:n("Failed to move to worktree"),description:wt}):a()}catch(wt){Be({type:"error",title:n("Failed to move to worktree"),description:String(wt)})}finally{j(!1)}},st=async()=>{j(!0);try{const ze=await window.electronAPI.worktree.status(e);if(ze.ok&&jc(ze.value)){C(ze.value);return}await He()}catch(ze){Be({type:"error",title:n("Failed to clean up worktree"),description:String(ze)})}finally{j(!1)}},ke=[{id:"local",selected:!le,icon:i.jsx(Xb,{className:"h-3.5 w-3.5 shrink-0"}),name:n("Local workspace"),hint:n("Work directly in the main working tree"),onSelect:()=>{le&&st()}},{id:"worktree",selected:le,icon:i.jsx(Ei,{className:"h-3.5 w-3.5 shrink-0"}),name:s.worktree?Wc(s.worktree):n("New isolated worktree"),hint:le?s.worktree?.branch:n("Run this session on its own git worktree"),onSelect:()=>{le||kt()}}],ut=i.jsx(fs,{open:S,onOpenChange:A,title:n("Main working tree has uncommitted changes"),description:n("The new worktree branches off HEAD, so those changes stay in the main working tree and will not follow this session."),confirmLabel:n("Move anyway"),onConfirm:()=>{A(!1),kt(!0)}}),ft=()=>{const ze=[];return N?.dirty&&ze.push(n("Uncommitted changes")),N&&N.ahead>0&&ze.push(n("{{n}} unmerged commits (branch is kept)",{n:N.ahead})),ze.join("; ")};return i.jsxs(i.Fragment,{children:[i.jsxs(Ri,{open:v,onOpenChange:ze=>{_||(y(ze),ze&&(b(!1),me(""),Z()))},children:[i.jsxs(Li,{ref:R,disabled:be,className:"flex h-7 min-w-0 max-w-52 shrink items-center gap-1 rounded-lg px-2 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50",title:s.worktree?`${Lt}
|
|
95
|
-
${Fm(s.worktree,d[e],n)}`:Lt,children:[_?i.jsx(qt,{className:"h-3 w-3 shrink-0 animate-spin"}):le?i.jsx(Ei,{className:"h-3 w-3 shrink-0"}):i.jsx(Xb,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"min-w-0 truncate",children:Lt}),i.jsx(Vn,{className:"h-3 w-3 shrink-0"})]}),i.jsx(Oi,{side:"top",align:"start",className:"w-72 [&_[data-slot=popover-viewport]]:p-1",initialFocus:H,finalFocus:ie||f!==null?!1:R,children:w?i.jsxs(i.Fragment,{children:[i.jsxs("button",{type:"button",onClick:()=>b(!1),"aria-label":n("Back to workspaces"),className:"mb-1 flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground",children:[i.jsx(ad,{className:"h-3.5 w-3.5 shrink-0"}),n("Local branches")]}),i.jsx(iee,{data:O,loading:J,error:fe,disabled:be||Fe,query:Ee,searchRef:B,onQueryChange:me,onSelect:ne,onRetry:()=>{Z(!0)},onCreate:()=>{Bt||!O?.headCommit||(X(null),G(D),y(!1))}})]}):i.jsxs(i.Fragment,{children:[ke.map(ze=>i.jsxs("button",{ref:ze.id==="local"?H:void 0,type:"button",disabled:be,onClick:()=>{ze.onSelect(),y(!1)},className:q("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",ze.selected?"bg-primary/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[ze.icon,i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:ze.name}),ze.hint&&i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:ze.hint})]}),ze.selected&&i.jsx(Un,{className:"h-3.5 w-3.5 shrink-0 text-primary"})]},ze.id)),Je&&x.length>0&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsx("p",{className:"px-2 py-1 text-[11px] text-muted-foreground",children:n("Existing worktrees")}),i.jsx("div",{className:"max-h-56 overflow-y-auto",children:x.map(({conversationId:ze,worktree:wt})=>i.jsxs("button",{type:"button",disabled:be,title:Fm(wt,d[ze],n),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",onClick:()=>{y(!1),se(ze)},children:[i.jsx(Ei,{className:"h-3.5 w-3.5 shrink-0"}),i.jsxs("span",{className:"min-w-0 flex-1",children:[i.jsx("span",{className:"block truncate",children:Wc(wt)}),i.jsx("span",{className:"block truncate text-xs text-muted-foreground",children:wt.path})]})]},wt.path))})]}),s.worktree&&i.jsxs("div",{className:"mt-1 border-t pt-1",children:[i.jsxs("button",{type:"button",disabled:be||Fe,className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",onClick:()=>{y(!1),se()},children:[i.jsx(Ro,{className:"h-3.5 w-3.5"}),n("New conversation in this worktree")]}),i.jsxs("button",{type:"button",disabled:be||Fe,className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted disabled:opacity-50",onClick:()=>{y(!1),s.worktree&&g({conversationId:e,worktree:s.worktree})},children:[i.jsx(Fs,{className:"h-3.5 w-3.5"}),n("Rename worktree")]})]}),i.jsx("div",{className:"mt-1 border-t pt-1",children:i.jsxs("button",{type:"button",disabled:be,onClick:()=>b(!0),className:"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground disabled:opacity-50",children:[i.jsx(Ei,{className:"h-3.5 w-3.5 shrink-0"}),i.jsx("span",{className:"flex-1",children:n("Switch branch")}),i.jsx(bn,{className:"h-3.5 w-3.5 shrink-0"})]})})]})})]}),i.jsx(fs,{open:N!==null,onOpenChange:ze=>{ze||C(null)},title:n("Clean up worktree?"),description:n("Pending work: {{warning}}. This session returns to the main working tree. The worktree directory and uncommitted changes are removed only when no other sessions use it. The branch is kept.",{warning:ft()}),confirmLabel:n("Clean up"),onConfirm:()=>{C(null),He()}}),ie&&i.jsx(see,{initialName:Ee.trim(),data:O,busy:_,disabled:Bt,error:de,returnFocus:R,onSubmit:ze=>{Mt(ze,!0)},onClose:()=>G(null)},D),ut,i.jsx(TI,{entity:f,onClose:()=>g(null)})]})}function dee(e){if(e)for(let t=e.length-1;t>=0;t--){const n=e[t];if(!(n.role!=="assistant"||!n.model)&&!(n.stopReason==="error"||n.stopReason==="aborted"))return n.model}}const cee=e=>{wh(e)&&wo()};function uee(){const{t:e}=Q(),t=RL(),n=wa(),s=Ce(se=>se.virtualModels),o=Ce(se=>se.agentTypes),r=Ce(se=>se.defaultModel),a=Ce(se=>se.projects),l=Ce(se=>se.projectGroups),d=Ce(se=>se.voiceInputEnabled),c=Ce(se=>se.voiceModel),u=Ce(se=>se.presets),{status:h}=aj(d),p=d&&h?.state!=="unsupported"&&h?.models.find(se=>se.id===c)?.state==="ready",f=m.useSyncExternalStore(se=>re.persist?.onFinishHydration?.(se)??(()=>{}),()=>re.persist?.hasHydrated?.()??!0),g=re(jf(ZZ)),x=re(se=>se.conversations[g?.parentId??""]?.coworkerIds),v=LL(g?.presetId,se=>u.find(He=>He.id===se)).pluginPresetId??null,y=qZ(g?.displayedParentId?g.agentType:void 0),w=Fi(se=>se.snapshot),b=Tg(),_=re(se=>tJ(se.conversations)),j=g?.parentId,N=g?.parentProjectId,C=m.useMemo(()=>j!==void 0&&N!==void 0?cY(_,N,j):[],[_,j,N]),S=m.useMemo(()=>a.find(se=>se.id===g?.projectId),[g?.projectId,a]),A=m.useMemo(()=>a.find(se=>se.id===g?.parentProjectId),[g?.parentProjectId,a]),E=m.useMemo(()=>Zc(S,l),[S,l]),I=m.useMemo(()=>Zc(A,l),[A,l]),D=m.useMemo(()=>Al({defaultModel:r,...E,lastProviderId:g?.lastProviderId,lastModelId:g?.lastModelId,providers:n,credentials:aa(w),virtualModels:s}),[g?.lastModelId,g?.lastProviderId,E,r,w,n,s]),T=m.useMemo(()=>Al({defaultModel:r,...I,lastProviderId:g?.parentLastProviderId,lastModelId:g?.parentLastModelId,providers:n,credentials:aa(w),virtualModels:s}),[r,w,g?.parentLastModelId,g?.parentLastProviderId,I,n,s]),z=T.source==="none"?null:{providerId:T.providerId,modelId:T.modelId},$=D.source==="none"?void 0:b.find(se=>se.id===D.providerId),R=D.source==="none"?"":D.modelId,B=D.source==="none"?"":_f(D)?D.providerId:$?.id??"",H=re(se=>_f(D)&&g?.id?dee(se.conversations[g.id]?.messages):void 0),oe=re(jf(se=>Ng(n,g?.id?se.conversations[g.id]:void 0))),te=D.source!=="none"?null:D.reason==="oauth-credentials-error"?e("Subscription credentials could not be loaded. Choose an API-key model or retry the credential refresh."):D.reason==="oauth-credentials-loading"||D.reason==="oauth-credentials-unloaded"?e("Subscription credentials are loading. Choose an API-key model or wait, then retry."):b.length>0?e("Choose a model for this conversation or set a project, group, or global default before sending."):e("No usable model is available. Configure provider credentials and enable a model first."),O=a.find(se=>se.id===g?.projectId),V=g?.id,[J,pe]=m.useState(),fe=m.useCallback(se=>pe(V&&se?{id:V,branch:se}:void 0),[V]),_e=g?.parentWorktreeBranch??(J?.id===g?.parentId?J?.branch:void 0),Ee=Ce(se=>se.skills),me=Ce(se=>se.loadLocalSkills),W=Ce(se=>OL(se.disabledBuiltinTools,se.projects,g?.projectId,"plan")),[G,de]=m.useState([]),X=me?O?.path??"":"",ie=g?.presetId;m.useEffect(()=>{let se=!1;return window.electronAPI.assets.listProjectSkills(X,ie).then(He=>{se||de(He)}).catch(()=>{se||de([])}),()=>{se=!0}},[X,ie]);const Z=g?.commands,le=aJ(),be=m.useMemo(()=>{if(!Z)return[];const se={name:"/goal",description:e("Set a session goal (/goal <objective> · pause · resume · clear)")},He={name:"/compact",description:e("Compact the context now (/compact [summary focus])")},kt={name:"/plan",description:e("Plan mode: research read-only, then approve a plan (/plan [task] · off)")},st=Ee.filter(ut=>ut.enabled!==!1).map(ut=>({name:`/skill:${ut.name}`,description:ut.description})),ke=G.map(ut=>({name:`/skill:${ut.name}`,description:ut.description}));return QT([se,He,...W?[kt]:[],...st,...ke,...Z,...le])},[e,Ee,G,Z,le,W]),Fe=m.useRef(null),Je=!g?.displayedParentId&&["planning","awaiting_review"].includes(kj(g?.planState)),We=g?.status==="running",et=g?.busy===!0,qe=g?.parentWorktreePath??O?.path,Lt=m.useMemo(()=>(g?.pendingCapabilityAsks??[]).map(se=>({requestId:se.requestId,tool:se.capabilityId,kind:"mcp",summary:se.summary})),[g?.pendingCapabilityAsks]),Bt=m.useCallback(()=>{g&&!g.parentStarted&&g.parentSessionFile&&!g.parentWorktreeMissing&&g.parentStatus!=="failed"&&re.getState().resumeConversation(g.parentId)},[g]);m.useEffect(()=>{const se=g?.compactionError;!se||!g||(Be({type:"error",title:e("Compaction failed"),description:se}),re.getState().clearCompactionError(g.id))},[g,e]);const Mt=YZ(g,f);if(!g)return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",...Mt==="hydrating"?{"data-timeline-loading":""}:{},children:[t&&i.jsx(Cj,{"data-enso":"title-bar"}),Mt==="empty"&&i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-1 text-center",children:[i.jsx("p",{className:"text-lg font-medium",children:"EnsoCode"}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Create or select a project to start a conversation")})]})]});const ne=i.jsx(pee,{status:g.spawning?"running":g.status,pendingAskCount:(g.pendingAsks??[]).length,hasRunningChild:g.id===g.parentId&&g.parentHasRunningChild});return i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col",children:[i.jsx(nee,{conversationId:g.parentId}),i.jsx(sQ,{parentId:g.parentId,displayedId:g.id,trailing:i.jsxs("div",{className:"flex min-w-0 shrink-0 items-center gap-1",children:[i.jsx(vJ,{parentId:g.parentId,coworkerIds:x??[]}),O?i.jsx(tee,{project:O,conversationId:g.parentId,path:g.parentWorktreePath??O.path,branch:_e,openDisabled:g.parentWorktreeMissing,children:ne}):i.jsx("div",{className:"flex min-w-0 shrink-0 items-center",children:ne})]})}),i.jsx(cI,{conversationId:g.id,cwd:qe,emptyTitle:O?.name??"EnsoCode",onSuggestion:O?cee:void 0,timelineRef:Fe}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:yi,children:[O&&O.kind!=="ssh"&&O.kind!=="scratch"&&!g.displayedParentId&&i.jsx(mQ,{projectId:O.id,conversationId:g.id}),g.retry&&i.jsx(Ih,{retry:g.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(g.id)}}),(g.rewinding||g.restoringFiles)&&i.jsxs("div",{role:"status",className:"mb-1 flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-muted-foreground text-xs",children:[i.jsx(qt,{className:"h-3.5 w-3.5 shrink-0 animate-spin"}),i.jsx("span",{children:g.restoringFiles&&!g.rewinding?e("Restoring files…"):g.restoringFiles?e("Rewinding conversation and files…"):e("Rewinding…")})]}),i.jsx(jg.Provider,{value:{conversationId:g.id,projectId:g.projectId,...qe?{cwd:qe}:{}},children:i.jsx(cv,{sessionId:g.id,tasks:g.backgroundTasks??[],subagents:g.subagents??[]},g.id)}),i.jsx(Bl,{approvals:Lt,allowSession:!1,handoff:!1,onRespond:(se,He)=>{He!=="allow"&&He!=="deny"||re.getState().respondCapabilityAsk(g.id,se,He)}},Lt[0]?.requestId??"no-capability-approval"),i.jsx(Bl,{approvals:g.pendingApprovals??[],allowSession:g.childLockedProfileId===void 0,onRespond:(se,He)=>{window.electronAPI.agent.respondApproval(g.id,se,He)}}),i.jsx(mh,{asks:g.pendingAsks??[],onAnswer:(se,He)=>{window.electronAPI.agent.respondAsk(g.id,se,He)}}),g.activeOauthAsk&&i.jsx(KZ,{request:g.activeOauthAsk,conversationId:g.id},g.activeOauthAsk.requestId),!g.displayedParentId&&i.jsx(dQ,{conversationId:g.id,planState:g.planState,approvalMode:g.approvalMode??"full"}),i.jsx(yI,{conversationId:g.id,queued:g.queuedMessages??[]}),g.goal&&i.jsx(aQ,{conversationId:g.id,goal:g.goal}),i.jsx(A7,{conversationId:g.id},g.id),!g.displayedParentId&&te&&i.jsx("div",{role:"status",className:"rounded-md border border-dashed px-3 py-2 text-muted-foreground text-xs",children:te}),i.jsx(lv,{cwd:O?.path,chatCandidates:C,commands:be,running:We,busy:et,locked:(g.pendingApprovals??[]).length>0||Lt.length>0||!!(g.rewinding||g.restoringFiles),focusKey:g.id,pluginPresetId:v,planMode:Je,savePastedText:O?.kind==="ssh"?void 0:se=>window.electronAPI.files.savePastedText({conversationId:g.id,text:se}),voice:p?$T:void 0,requestMicAccess:window.electronAPI.speech.requestMicAccess,placeholder:Je?e("Describe the task — a plan comes first"):void 0,injectedDraft:g.draftText,injectedImages:g.draftImages,injectedDraftAppend:g.draftAppend,onDraftConsumed:()=>re.getState().clearDraft(g.id),queuedCount:g.queuedMessages?.length??0,onSteerQueued:()=>re.getState().steerQueued(g.id),initialRecipient:g.prefillAgentTypeKey===Jc?hee:void 0,onInitialRecipientConsumed:()=>re.getState().clearAgentPrefill(g.id),toolbar:i.jsxs(i.Fragment,{children:[!g.displayedParentId&&i.jsxs(i.Fragment,{children:[i.jsx(pQ,{presetId:g.presetId??"default",disabled:g.started,onSelect:se=>re.getState().setPreset(g.id,se),onModel:se=>re.getState().setModel(g.id,se.providerId,se.modelId)}),i.jsx(lee,{conversationId:g.id,onBranchChange:fe}),(W||g.planState?.active)&&i.jsx(hQ,{active:g.planState?.active??!1,onToggle:se=>re.getState().setPlanMode(g.id,se)}),i.jsx(zL,{mode:g.approvalMode??"full",autoReject:g.autoRejectApprovals===!0,onSelect:se=>re.getState().setApprovalMode(g.id,se),onToggleAutoReject:se=>re.getState().setAutoRejectApprovals(g.id,se)}),i.jsx(Ju,{listenHotkey:!0,providers:b,virtualModels:s,routedModelLabel:H,activeAccount:oe,providerId:B,modelId:R,reasoningEnabled:g.reasoningEnabled??!1,thinkingLevel:g.thinkingLevel??"medium",onSelect:(se,He)=>re.getState().setModel(g.id,se,He),onReasoningChange:se=>re.getState().setReasoning(g.id,se),onThinkingChange:se=>re.getState().setThinking(g.id,se)})]}),g.displayedParentId&&i.jsxs("span",{className:"text-[11px] text-muted-foreground",children:[y??(g.agentType?Sj(g.agentType,o):"coworker"),g.lastModelId?` · ${kf(s,g.lastModelId)}`:""]})]}),onActivate:Bt,onSend:se=>!se.recipient&&!O||!se.recipient&&!g.displayedParentId&&(!B||!R)?!1:(oQ(se,{dispatchAgent:(He,kt)=>{re.getState().dispatchAgent(He,kt,z)},sendCoding:(He,kt)=>{O&&(Fe.current?.scrollToBottom(),re.getState().send(He,{providerId:B,modelId:R,cwd:O.path},kt))}}),!0),onAbort:()=>{re.getState().abort()}}),i.jsx(_I,{conversationId:g.id})]})})]})}const hee={kind:"agent-type",id:Jc,typeKey:Jc,label:"Enso",displayName:"Enso",description:"EnsoCode system agent for product capabilities and team setup",source:"system",locked:!0,canDisable:!1,canEdit:!1};function pee({status:e,pendingAskCount:t=0,hasRunningChild:n=!1}){const s=Dg({status:e,pendingAskCount:t,hasRunningChild:n});return i.jsx(Ph,{tone:s,title:e})}function DI(e,t,n){const s=e.slice();return s.splice(n<0?s.length+n:n,0,s.splice(t,1)[0]),s}function fee(e,t){return e.reduce((n,s,o)=>{const r=t.get(s);return r&&(n[o]=r),n},Array(e.length))}function sc(e){return e!==null&&e>=0}function mee(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function gee(e){return typeof e=="boolean"?{draggable:e,droppable:e}:e}const ic={scaleX:1,scaleY:1},xee=e=>{var t;let{rects:n,activeNodeRect:s,activeIndex:o,overIndex:r,index:a}=e;const l=(t=n[o])!=null?t:s;if(!l)return null;const d=vee(n,a,o);if(a===o){const c=n[r];return c?{x:o<r?c.left+c.width-(l.left+l.width):c.left-l.left,y:0,...ic}:null}return a>o&&a<=r?{x:-l.width-d,y:0,...ic}:a<o&&a>=r?{x:l.width+d,y:0,...ic}:{x:0,y:0,...ic}};function vee(e,t,n){const s=e[t],o=e[t-1],r=e[t+1];return!s||!o&&!r?0:n<t?o?s.left-(o.left+o.width):r.left-(s.left+s.width):r?r.left-(s.left+s.width):s.left-(o.left+o.width)}const II=e=>{let{rects:t,activeIndex:n,overIndex:s,index:o}=e;const r=DI(t,s,n),a=t[o],l=r[o];return!l||!a?null:{x:l.left-a.left,y:l.top-a.top,scaleX:l.width/a.width,scaleY:l.height/a.height}},oc={scaleX:1,scaleY:1},LS=e=>{var t;let{activeIndex:n,activeNodeRect:s,index:o,rects:r,overIndex:a}=e;const l=(t=r[n])!=null?t:s;if(!l)return null;if(o===n){const c=r[a];return c?{x:0,y:n<a?c.top+c.height-(l.top+l.height):c.top-l.top,...oc}:null}const d=bee(r,o,n);return o>n&&o<=a?{x:0,y:-l.height-d,...oc}:o<n&&o>=a?{x:0,y:l.height+d,...oc}:{x:0,y:0,...oc}};function bee(e,t,n){const s=e[t],o=e[t-1],r=e[t+1];return s?n<t?o?s.top-(o.top+o.height):r?r.top-(s.top+s.height):0:r?r.top-(s.top+s.height):o?s.top-(o.top+o.height):0:0}const EI="Sortable",PI=Ne.createContext({activeIndex:-1,containerId:EI,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:II,disabled:{draggable:!1,droppable:!1}});function Hm(e){let{children:t,id:n,items:s,strategy:o=II,disabled:r=!1}=e;const{active:a,dragOverlay:l,droppableRects:d,over:c,measureDroppableContainers:u}=fd(),h=hd(EI,n),p=l.rect!==null,f=m.useMemo(()=>s.map(N=>typeof N=="object"&&"id"in N?N.id:N),[s]),g=a!=null,x=a?f.indexOf(a.id):-1,v=c?f.indexOf(c.id):-1,y=m.useRef(f),w=!mee(f,y.current),b=v!==-1&&x===-1||w,_=gee(r);mi(()=>{w&&g&&u(f)},[w,f,g,u]),m.useEffect(()=>{y.current=f},[f]);const j=m.useMemo(()=>({activeIndex:x,containerId:h,disabled:_,disableTransforms:b,items:f,overIndex:v,useDragOverlay:p,sortedRects:fee(f,d),strategy:o}),[x,h,_.draggable,_.droppable,b,f,v,d,p,o]);return Ne.createElement(PI.Provider,{value:j},t)}const wee=e=>{let{id:t,items:n,activeIndex:s,overIndex:o}=e;return DI(n,s,o).indexOf(t)},yee=e=>{let{containerId:t,isSorting:n,wasDragging:s,index:o,items:r,newIndex:a,previousItems:l,previousContainerId:d,transition:c}=e;return!c||!s||l!==r&&o===a?!1:n?!0:a!==o&&t===d},See={duration:200,easing:"ease"},AI="transform",Cee=zi.Transition.toString({property:AI,duration:0,easing:"linear"}),kee={roleDescription:"sortable"};function jee(e){let{disabled:t,index:n,node:s,rect:o}=e;const[r,a]=m.useState(null),l=m.useRef(n);return mi(()=>{if(!t&&n!==l.current&&s.current){const d=o.current;if(d){const c=Ca(s.current,{ignoreTransform:!0}),u={x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height};(u.x||u.y)&&a(u)}}n!==l.current&&(l.current=n)},[t,n,s,o]),m.useEffect(()=>{r&&a(null)},[r]),r}function Ah(e){let{animateLayoutChanges:t=yee,attributes:n,disabled:s,data:o,getNewIndex:r=wee,id:a,strategy:l,resizeObserverConfig:d,transition:c=See}=e;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:g,sortedRects:x,overIndex:v,useDragOverlay:y,strategy:w}=m.useContext(PI),b=_ee(s,f),_=u.indexOf(a),j=m.useMemo(()=>({sortable:{containerId:h,index:_,items:u},...o}),[h,o,_,u]),N=m.useMemo(()=>u.slice(u.indexOf(a)),[u,a]),{rect:C,node:S,isOver:A,setNodeRef:E}=md({id:a,data:j,disabled:b.droppable,resizeObserverConfig:{updateMeasurementsFor:N,...d}}),{active:I,activatorEvent:D,activeNodeRect:T,attributes:z,setNodeRef:$,listeners:R,isDragging:B,over:H,setActivatorNodeRef:oe,transform:te}=Fg({id:a,data:j,attributes:{...kee,...n},disabled:b.draggable}),O=PO(E,$),V=!!I,J=V&&!g&&sc(p)&&sc(v),pe=!y&&B,fe=pe&&J?te:null,Ee=J?fe??(l??w)({rects:x,activeNodeRect:T,activeIndex:p,overIndex:v,index:_}):null,me=sc(p)&&sc(v)?r({id:a,items:u,activeIndex:p,overIndex:v}):_,W=I?.id,G=m.useRef({activeId:W,items:u,newIndex:me,containerId:h}),de=u!==G.current.items,X=t({active:I,containerId:h,isDragging:B,isSorting:V,id:a,index:_,items:u,newIndex:G.current.newIndex,previousItems:G.current.items,previousContainerId:G.current.containerId,transition:c,wasDragging:G.current.activeId!=null}),ie=jee({disabled:!X,index:_,node:S,rect:C});return m.useEffect(()=>{V&&G.current.newIndex!==me&&(G.current.newIndex=me),h!==G.current.containerId&&(G.current.containerId=h),u!==G.current.items&&(G.current.items=u)},[V,me,h,u]),m.useEffect(()=>{if(W===G.current.activeId)return;if(W!=null&&G.current.activeId==null){G.current.activeId=W;return}const le=setTimeout(()=>{G.current.activeId=W},50);return()=>clearTimeout(le)},[W]),{active:I,activeIndex:p,attributes:z,data:j,rect:C,index:_,newIndex:me,items:u,isOver:A,isSorting:V,isDragging:B,listeners:R,node:S,overIndex:v,over:H,setNodeRef:O,setActivatorNodeRef:oe,setDroppableNodeRef:E,setDraggableNodeRef:$,transform:ie??Ee,transition:Z()};function Z(){if(ie||de&&G.current.newIndex===_)return Cee;if(!(pe&&!nh(D)||!c)&&(V||X))return zi.Transition.toString({...c,property:AI})}}function _ee(e,t){var n,s;return typeof e=="boolean"?{draggable:e,droppable:!1}:{draggable:(n=e?.draggable)!=null?n:t.draggable,droppable:(s=e?.droppable)!=null?s:t.droppable}}hn.Down,hn.Right,hn.Up,hn.Left;const Nee=e=>e==="/"?null:e.replace(/\/[^/]+$/,"")||"/";function Tee(e,t){const n=e.includes("\\")&&!e.includes("/")?"\\":"/";return e.endsWith(n)?`${e}${t}`:`${e}${n}${t}`}function OS({list:e,create:t,initialPath:n,reloadKey:s=0,onSelect:o,onClose:r}){const{t:a}=Q(),[l,d]=m.useState(null),[c,u]=m.useState(!1),[h,p]=m.useState(""),[f,g]=m.useState(null),[x,v]=m.useState(""),y=m.useRef(0),w=m.useRef(null),b=m.useRef(e);b.current=e;const _=m.useCallback((E,I=!1)=>{const D=++y.current;u(!0),p(""),b.current(E,I).then(T=>{if(!(D!==y.current||!T)){if("error"in T){p(T.error);return}d(T),w.current=T.path}}).catch(()=>{D===y.current&&p(a("Failed to list remote directory."))}).finally(()=>{D===y.current&&u(!1)})},[a]),j=m.useRef(n);m.useEffect(()=>{_(j.current)},[_]),m.useEffect(()=>{s&&_(w.current??j.current,!0)},[s,_]);const N=l?.path??null,C=l?.dirs??[],S=l?.parent??null,A=()=>{if(!t||!N||f===null||!f.trim())return;const E=++y.current;u(!0),v(""),t(N,f).then(I=>{if(E===y.current){if("error"in I){v(a(I.error));return}g(null),p(""),d(I),w.current=I.path}}).catch(()=>{E===y.current&&v(a("Failed to list remote directory."))}).finally(()=>{E===y.current&&u(!1)})};return i.jsxs("div",{className:"w-full space-y-1.5 rounded-md border bg-muted/30 p-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground text-xs",children:N??"…"}),i.jsx(ge,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!S||c,onClick:()=>S&&_(S),children:a("Up")}),t&&i.jsx(ge,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",disabled:!N||c||f!==null,onClick:()=>{g(""),v("")},children:a("New Folder")}),i.jsx(ge,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:r,children:a("Close")})]}),f!==null&&i.jsxs("div",{className:"space-y-1",children:[i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx(Xt,{autoFocus:!0,size:"sm",className:"min-w-0 flex-1 font-mono text-xs",placeholder:a("Folder name"),value:f,disabled:c,onChange:E=>g(E.target.value),onKeyDown:E=>{E.key==="Enter"?(E.preventDefault(),A()):E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),g(null))}}),i.jsx(ge,{type:"button",size:"sm",className:"h-7 px-2 text-xs",disabled:c||!f.trim(),onClick:A,children:a("Create")}),i.jsx(ge,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",disabled:c,onClick:()=>g(null),children:a("Cancel")})]}),x&&i.jsx("p",{className:"px-1 text-destructive text-xs",children:x})]}),i.jsxs("div",{className:"relative min-h-16 max-h-56 overflow-y-auto",children:[h?i.jsx("p",{className:"px-1 py-2 text-destructive text-xs",children:h}):C.length===0&&!c?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:a("No subdirectories")}):i.jsx("div",{className:c?"pointer-events-none space-y-0.5 opacity-40":"space-y-0.5",children:C.map(E=>i.jsxs("button",{type:"button",className:"block w-full truncate rounded px-1.5 py-1 text-left font-mono text-xs hover:bg-muted",disabled:c,onClick:()=>N&&_(Tee(N,E)),children:[E,"/"]},E))}),c&&i.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60",children:[i.jsx(qt,{className:"h-4 w-4 animate-spin text-muted-foreground"}),i.jsx("span",{className:"sr-only",children:a("Loading...")})]})]}),i.jsx(ge,{type:"button",variant:"outline",size:"sm",className:"h-7 w-full text-xs",disabled:!N||c,onClick:()=>N&&o(N),children:a("Use this directory")})]})}function Dee({open:e,onOpenChange:t,onAdd:n,groups:s=[],defaultGroupId:o}){const{t:r}=Q(),a=Ce(G=>G.projects),[l,d]=m.useState("local"),[c,u]=m.useState(""),[h,p]=m.useState(""),[f,g]=m.useState(""),[x,v]=m.useState([]),[y,w]=m.useState(o),[b,_]=m.useState(!1),[j,N]=m.useState([]),[C,S]=m.useState(""),[A,E]=m.useState(null),[I,D]=m.useState(null),[T,z]=m.useState(0),[$,R]=m.useState(!1),B=m.useMemo(()=>[{value:"",label:r("Ungrouped")},...s.map(G=>({value:G.id,label:G.name}))],[s,r]);m.useEffect(()=>{e&&(d("local"),u(""),p(""),g(""),w(o),_(!1),S(""),E(null),D(null),z(0),window.electronAPI.sshConnections.list().then(v).catch(()=>v([])),window.electronAPI.projects.getRecent().then(N).catch(()=>N([])))},[e,o]);const H=m.useMemo(()=>new Set(a.map(G=>G.path)),[a]),oe=m.useMemo(()=>j.filter(G=>!H.has(G.path)),[j,H]),te=m.useCallback((G,de)=>{if(!de)return!0;const X=de.toLowerCase();return G.path.toLowerCase().includes(X)||G.displayPath.toLowerCase().includes(X)||G.sourceName.toLowerCase().includes(X)},[]),O=!!window.electronAPI.remote,V=async()=>{if(O){_(de=>!de);return}const G=await window.electronAPI.dialog.selectDirectory();G&&u(G)},J=m.useCallback(G=>window.electronAPI.projects.listHostDirs(G).then(de=>de.ok?de:{error:de.error}),[]),pe=m.useCallback((G,de)=>window.electronAPI.projects.createHostDir(G,de).then(X=>X.ok?X:{error:X.error}),[]),fe=m.useCallback(async(G,de)=>{const X=await window.electronAPI.sshConnections.listDirs(h,G);if(X.ok)return{path:X.path,parent:Nee(X.path),dirs:X.dirs};const ie=l0(X,x.find(Z=>Z.id===h));return!ie||de?{error:X.error}:(D("browse"),E(ie),null)},[h,x]),_e=l==="local"?c.trim().length>0:h.length>0&&f.trim().startsWith("/"),Ee=()=>{const G=x.find(de=>de.id===h);n({path:f.trim(),sshConnectionId:h,sshHost:G?.name,...y?{groupId:y}:{}}),t(!1)},me=G=>{if(G.preventDefault(),!_e)return;if(l!=="ssh"){n({path:c.trim(),...y?{groupId:y}:{}}),t(!1);return}S("");const de=x.find(X=>X.id===h);window.electronAPI.sshConnections.test(h).then(X=>{if(!X.ok){const ie=l0(X,de);if(ie){D("submit"),E(ie);return}S(X.error);return}Ee()})},W=async()=>{if(!A)return;R(!0);const G=await window.electronAPI.sshConnections.trustHost(h);if(R(!1),!G.ok){S(G.error||r("Could not save host key.")),E(null),D(null);return}const de=I;if(E(null),D(null),de==="browse"){z(X=>X+1);return}de==="submit"&&Ee()};return i.jsxs(wn,{open:e,onOpenChange:t,children:[i.jsx(yn,{className:"max-w-lg",children:i.jsxs("form",{onSubmit:me,className:"flex flex-col",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:r("Add project")}),i.jsx(Bs,{children:r("Add a local directory as the conversation working folder.")})]}),i.jsxs(On,{className:"space-y-4",children:[i.jsx(Wu,{value:l,onValueChange:G=>{d(G),_(!1)},children:i.jsxs(Uu,{children:[i.jsx(Ds,{value:"local",children:r("Local directory")}),i.jsx(Ds,{value:"ssh",children:r("Remote (SSH)")})]})}),l==="ssh"?i.jsxs(i.Fragment,{children:[i.jsxs(Us,{className:"w-full",children:[i.jsx(Ks,{children:r("SSH connection")}),x.length===0?i.jsx("p",{className:"text-sm text-muted-foreground",children:r("Add an SSH connection in Settings first.")}):i.jsxs(xs,{items:[{value:"",label:r("Select an SSH connection")},...x.map(G=>({value:G.id,label:`${G.name} (${G.user?`${G.user}@`:""}${G.host})`}))],value:h,onValueChange:G=>p(G??""),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsxs(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(ns,{value:"",children:r("Select an SSH connection")}),x.map(G=>i.jsxs(ns,{value:G.id,children:[G.name," (",G.user?`${G.user}@`:"",G.host,")"]},G.id))]})]})]}),i.jsxs(Us,{className:"w-full",children:[i.jsx(Ks,{children:r("Remote directory")}),i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx(Xt,{value:f,onChange:G=>g(G.target.value),placeholder:"/home/user/project",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,className:"min-w-0 flex-1"}),i.jsx(ge,{type:"button",variant:"outline",disabled:!h,onClick:()=>_(G=>!G),children:r("Browse")})]})]}),b&&h&&i.jsx(OS,{list:fe,initialPath:f.trim().startsWith("/")?f.trim():void 0,reloadKey:T,onSelect:G=>{g(G),_(!1)},onClose:()=>_(!1)},h),i.jsx("p",{className:"text-xs text-muted-foreground",children:r("Tools run on the remote host; chat history stays local.")}),C&&i.jsx("p",{className:"text-destructive text-xs",children:C})]}):i.jsxs(Us,{className:"w-full",children:[i.jsx(Ks,{children:r("Working directory")}),i.jsxs(ev,{value:c,onValueChange:G=>u(G??""),items:oe,filter:te,itemToStringValue:G=>G.path,children:[i.jsxs("div",{className:"flex w-full gap-2",children:[i.jsx("div",{className:"min-w-0 flex-1",children:i.jsx(tv,{placeholder:r("Type a path or select from recent projects..."),showClear:!!c,showTrigger:!0})}),i.jsx(ge,{type:"button",variant:"outline",onClick:()=>{V()},children:r("Browse")})]}),i.jsxs(qD,{zIndex:kn.DROPDOWN_IN_MODAL,children:[i.jsx(sv,{children:r("No matching projects found")}),i.jsx(iv,{children:G=>i.jsxs(nv,{value:G,className:"gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",title:G.path,children:G.displayPath}),i.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:G.sourceName})]},G.path)})]})]}),b&&O&&i.jsx(OS,{list:J,create:pe,initialPath:c.trim()||void 0,onSelect:G=>{u(G),_(!1)},onClose:()=>_(!1)})]}),s.length>0&&i.jsxs(Us,{children:[i.jsx(Ks,{children:r("Project group")}),i.jsxs(xs,{items:B,value:y??"",onValueChange:G=>w(G||void 0),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:B.map(G=>i.jsx(ns,{value:G.value,children:G.label},G.value||"ungrouped"))})]})]})]}),i.jsxs(cs,{children:[i.jsx(ge,{type:"button",variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(ge,{type:"submit",size:"sm",disabled:!_e,children:r("Add")})]})]})}),i.jsx(GL,{challenge:A,nested:!0,busy:$,onTrust:()=>{W()},onDismiss:()=>{$||(E(null),D(null))}})]})}function Iee(e,t){return{x:e.left-t,width:Math.max(0,e.width)}}const MI="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm transition-colors",RI="flex size-4.5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",Eee=24,Ba=20;function Pee({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,query:a,onQueryChange:l,searchOpen:d,onSearchOpenChange:c,onSelect:u,onAddGroup:h,onEditGroup:p}){const{t:f}=Q(),g=e.slice().sort((H,oe)=>H.order-oe.order),x=g.length>0,v=d||a.length>0,y=m.useRef(null),w=m.useRef(null),b=m.useRef(null),_=m.useRef(null),j=m.useRef(null),[N,C]=m.useState({left:!1,right:!1,overflow:!1}),{active:S}=fd(),A=g.find(H=>H.id===t),E=t===us?f("Ungrouped"):A?.name??null,I=E?f("Search in {{group}}...",{group:E}):f("Search conversations..."),D=m.useCallback(()=>{const H=b.current,oe=w.current,te=_.current,O=j.current,V=oe?.querySelector("[data-selected]");if(!H||!oe||!te||!O||!V||H.offsetParent===null){O&&(O.style.width="0px");return}const J=oe.getBoundingClientRect(),pe=H.getBoundingClientRect(),fe=V.getBoundingClientRect(),_e=Iee(fe,J.left);te.style.left=`${J.left-pe.left}px`,te.style.width=`${J.width}px`,O.style.transform=`translateX(${_e.x}px)`,O.style.width=`${_e.width}px`},[]),T=m.useCallback(()=>{const H=w.current;D(),!(!H||H.clientWidth===0)&&C(oe=>{const te=oe.overflow?Eee:0,O={left:H.scrollLeft>1,right:H.scrollLeft+H.clientWidth<H.scrollWidth-1,overflow:H.scrollWidth>H.clientWidth+te+1};return oe.left===O.left&&oe.right===O.right&&oe.overflow===O.overflow?oe:O})},[D]);m.useLayoutEffect(()=>{const H=w.current;if(!H)return;T();const oe=new ResizeObserver(T);return oe.observe(H),H.firstElementChild&&oe.observe(H.firstElementChild),()=>oe.disconnect()},[T]),m.useLayoutEffect(()=>{D()},[D,S,t,v,g.length]),m.useEffect(()=>{const H=w.current;if(!H)return;const oe=te=>{Math.abs(te.deltaY)<=Math.abs(te.deltaX)||H.scrollWidth<=H.clientWidth||(H.scrollLeft+=te.deltaY,te.preventDefault())};return H.addEventListener("wheel",oe,{passive:!1}),()=>H.removeEventListener("wheel",oe)},[]);const z=m.useRef(!1);m.useLayoutEffect(()=>{const H=w.current,oe=H?.querySelector("[data-selected]");if(!H||!oe||H.clientWidth===0)return;const te=z.current?"smooth":"auto";z.current=!0;const O=oe.offsetLeft,V=O+oe.offsetWidth;O<H.scrollLeft+Ba?H.scrollTo({left:O-Ba,behavior:te}):V>H.scrollLeft+H.clientWidth-Ba&&H.scrollTo({left:V-H.clientWidth+Ba,behavior:te})},[t,x,d]),m.useEffect(()=>{d&&y.current?.focus()},[d]);const $=()=>{l(""),c(!1)},R=H=>H?`${Ba}px`:"0px",B=N.left||N.right?`linear-gradient(to right, transparent, #000 ${R(N.left)}, #000 calc(100% - ${R(N.right)}), transparent)`:void 0;return i.jsxs("div",{className:"group/bar shrink-0",children:[i.jsxs("div",{className:"relative z-[1] flex h-[35px] items-end gap-1.5 px-3.5",children:[v&&i.jsxs("label",{className:"mb-1 flex h-7 min-w-0 flex-1 cursor-text items-center gap-2 rounded-lg border border-transparent bg-foreground/5 pr-0.5 pl-2.5 text-xs text-muted-foreground transition-colors focus-within:border-brand/45",children:[i.jsx(oN,{className:"size-3.5 shrink-0"}),i.jsx("input",{ref:y,value:a,onChange:H=>l(H.target.value),onKeyDown:H=>{H.key==="Escape"&&(H.stopPropagation(),$())},onBlur:()=>{!a&&document.hasFocus()&&c(!1)},placeholder:I,className:"h-full min-w-0 flex-1 bg-transparent text-foreground outline-none placeholder:text-muted-foreground"}),i.jsx("button",{type:"button",onClick:$,className:"flex size-5 shrink-0 items-center justify-center rounded-md transition-colors hover:bg-foreground/5 hover:text-foreground",title:f("Close"),"aria-label":f("Close"),children:i.jsx(an,{className:"size-3"})})]}),i.jsxs("div",{ref:b,className:q("relative flex min-w-0 flex-1 items-center gap-1.5",v&&"hidden"),children:[i.jsx("div",{ref:w,onScroll:T,style:{maskImage:B},className:"min-w-0 overflow-x-auto [scrollbar-width:none]",children:i.jsxs("div",{className:"flex w-max gap-3.5",children:[i.jsx("button",{type:"button","data-selected":t===Mn||void 0,onClick:()=>u(Mn),className:Au(t===Mn,!1),children:i.jsx(Mu,{label:f("All"),count:s})}),i.jsx("button",{type:"button","data-selected":t===pr||void 0,onClick:()=>u(pr),className:Au(t===pr,!1),children:i.jsx(Mu,{label:f("Recent"),count:o})}),i.jsx(Hm,{items:g.map(H=>av(H.id)),strategy:xee,children:g.map(H=>i.jsx(Aee,{group:H,count:n[H.id]??0,selected:t===H.id,onSelect:()=>u(H.id)},H.id))}),x&&i.jsx(Mee,{label:f("Ungrouped"),count:r,selected:t===us,onSelect:()=>u(us)})]})}),i.jsx("span",{ref:_,"aria-hidden":!0,className:"pointer-events-none absolute -bottom-px z-10 h-[1.5px] overflow-hidden",children:i.jsx("span",{ref:j,className:"absolute top-0 left-0 h-full rounded-full bg-foreground"})}),i.jsx("button",{type:"button",onClick:h,className:q(RI,"opacity-0 focus-visible:opacity-100 group-hover/bar:opacity-100 [@media(hover:none)]:opacity-100"),title:f("New group"),"aria-label":f("New group"),children:i.jsx(ds,{className:"size-3"})}),N.overflow&&i.jsx(Ree,{groups:g,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:u,onAddGroup:h,onEditGroup:p})]})]}),i.jsx("div",{className:"mx-3.5 h-px bg-border"})]})}function Au(e,t){return q("flex shrink-0 items-center whitespace-nowrap pt-1 pb-[7px] text-[0.8929rem] transition-colors",e?"font-medium text-foreground":"text-subtle-foreground hover:text-foreground",t&&"rounded-t-md bg-foreground/[0.075] text-foreground")}function Mu({label:e,count:t,emoji:n,color:s}){return i.jsxs(i.Fragment,{children:[n&&i.jsx("span",{className:"mr-1 text-[13px] leading-none",children:n}),s&&i.jsx("span",{className:"mr-1.5 size-1.5 shrink-0 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}),i.jsx("span",{className:"max-w-32 truncate",children:e}),i.jsx("span",{className:"ml-1 font-normal text-[0.75rem] text-subtle-foreground/75 tabular-nums",children:t})]})}const LI=e=>e?.type==="project";function Aee({group:e,count:t,selected:n,onSelect:s}){const{attributes:o,listeners:r,setNodeRef:a,transform:l,transition:d,isDragging:c,isOver:u,active:h}=Ah({id:av(e.id),data:{type:"project-group",groupId:e.id}});return i.jsx("button",{ref:a,type:"button","data-selected":n||void 0,onClick:s,style:{transform:l?`translate3d(${Math.round(l.x)}px, 0, 0)`:void 0,transition:d},className:q(Au(n,u&&LI(h?.data.current)),c&&"z-10 cursor-grabbing text-foreground"),...o,...r,children:i.jsx(Mu,{label:e.name,count:t,emoji:e.emoji,color:e.color})})}function Mee({label:e,count:t,selected:n,onSelect:s}){const{active:o}=fd(),{setNodeRef:r,isOver:a}=md({id:av(us),disabled:o?.data.current?.type==="project-group"});return i.jsx("button",{ref:r,type:"button","data-selected":n||void 0,onClick:s,className:Au(n,a&&LI(o?.data.current)),children:i.jsx(Mu,{label:e,count:t})})}function Ree({groups:e,selectedId:t,counts:n,totalCount:s,recentCount:o,ungroupedCount:r,onSelect:a,onAddGroup:l,onEditGroup:d}){const{t:c}=Q(),[u,h]=m.useState(!1),p=f=>()=>{h(!1),f()};return i.jsxs(Ri,{open:u,onOpenChange:h,children:[i.jsx(Li,{className:q(RI,"ml-auto data-popup-open:bg-foreground/5 data-popup-open:text-foreground"),title:c("All groups"),"aria-label":c("All groups"),children:i.jsx(Vn,{className:"size-3"})}),i.jsxs(Oi,{side:"bottom",align:"end",className:"w-56 [&_[data-slot=popover-viewport]]:p-1",children:[i.jsx(rc,{label:c("All"),count:s,selected:t===Mn,onSelect:p(()=>a(Mn))}),i.jsx(rc,{label:c("Recent"),count:o,selected:t===pr,onSelect:p(()=>a(pr))}),e.map(f=>i.jsx(rc,{label:f.name,emoji:f.emoji,color:f.color,count:n[f.id]??0,selected:t===f.id,onSelect:p(()=>a(f.id)),onEdit:p(()=>d(f.id))},f.id)),e.length>0&&i.jsx(rc,{label:c("Ungrouped"),count:r,selected:t===us,onSelect:p(()=>a(us))}),i.jsx("div",{className:"my-1 border-t"}),i.jsxs("button",{type:"button",onClick:p(l),className:q(MI,"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx(ds,{className:"size-3.5 shrink-0"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:c("New group")})]})]})]})}function rc({label:e,count:t,emoji:n,color:s,selected:o,onSelect:r,onEdit:a}){const{t:l}=Q();return i.jsxs("div",{className:"group/row relative",children:[i.jsxs("button",{type:"button",onClick:r,className:q(MI,o?"bg-brand/10 text-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[i.jsx("span",{className:"flex w-4 shrink-0 items-center justify-center gap-1",children:n?i.jsx("span",{className:"text-[13px] leading-none",children:n}):s?i.jsx("span",{className:"size-2 rounded-full",style:{backgroundColor:s},"aria-hidden":!0}):null}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs tabular-nums",children:t}),i.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center",children:o&&i.jsx(Un,{className:q("size-3.5 text-brand",a&&"group-hover/row:opacity-0")})})]}),a&&i.jsx("button",{type:"button",onClick:a,className:"absolute inset-y-0 right-2 my-auto flex size-5 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:bg-background hover:text-foreground focus-visible:opacity-100 group-hover/row:opacity-100",title:l("Edit group"),"aria-label":l("Edit group"),children:i.jsx(Fs,{className:"size-3.5"})})]})}function OI({value:e,reasoningEnabled:t,thinkingLevel:n,onChange:s,onReasoningChange:o,onThinkingChange:r,description:a,inheritLabel:l}){const{t:d}=Q(),c=Ce(g=>g.virtualModels),u=Tg(),h=e?u.find(g=>g.id===e.providerId):void 0,p=h?.models.find(g=>g.id===e?.modelId),f=hj(c,e);return i.jsxs(Us,{className:"w-full items-stretch",children:[i.jsx(Ks,{children:d("Default model")}),i.jsx(Lj,{children:a}),u.length>0&&i.jsx("div",{className:"w-full min-w-0",children:i.jsx(Ju,{providers:u,virtualModels:c,providerId:f?e?.providerId??"":h?.id??"",modelId:f?f.id:p?.id??"",reasoningEnabled:t,thinkingLevel:n,emptyLabel:l,side:"bottom",triggerClassName:FL,zIndex:kn.DROPDOWN_IN_MODAL,onSelect:(g,x)=>s({providerId:g,modelId:x}),onReasoningChange:o,onThinkingChange:r})}),e&&!f&&(!h||!p)&&i.jsx("p",{className:"text-muted-foreground text-xs",children:d("Selected model is unavailable — falls back to the default model.")}),e&&i.jsx(ge,{type:"button",variant:"ghost",size:"sm",className:"self-start",onClick:()=>s(null),children:d("Follow default model")})]})}const Lee=["#3b82f6","#22c55e","#eab308","#f97316","#ef4444","#a855f7","#06b6d4","#64748b"];function Oee({open:e,group:t,projects:n,onOpenChange:s,onSave:o,onDelete:r}){const{t:a}=Q(),l=Ce(D=>D.defaultReasoningEnabled),d=Ce(D=>D.defaultThinkingLevel),[c,u]=m.useState(""),[h,p]=m.useState(),[f,g]=m.useState(null),[x,v]=m.useState(!0),[y,w]=m.useState("medium"),[b,_]=m.useState(new Set),[j,N]=m.useState(""),C=t===null,S=C?n??[]:[],A=j.trim().toLowerCase(),E=A?S.filter(D=>D.name.toLowerCase().includes(A)):S;m.useEffect(()=>{if(!e)return;u(t?.name??""),p(t?.color),g(t?.defaultModel??null);const D=Qc({defaultReasoningEnabled:l,defaultThinkingLevel:d});v(t?.defaultReasoningEnabled??D.reasoningEnabled),w(t?.defaultThinkingLevel??D.thinkingLevel),_(new Set),N("")},[e,t,l,d]);const I=D=>{_(T=>{const z=new Set(T);return z.has(D)?z.delete(D):z.add(D),z})};return i.jsx(wn,{open:e,onOpenChange:s,children:i.jsx(yn,{className:"max-w-md",children:i.jsxs("form",{className:"flex flex-col",onSubmit:D=>{D.preventDefault();const T=c.trim();T&&(o({name:T,color:h,defaultModel:f,defaultReasoningEnabled:f?x:null,defaultThinkingLevel:f?y:null,...C&&b.size>0?{projectIds:[...b]}:{}}),s(!1))},children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:a(t?"Edit group":"New group")}),i.jsx(Bs,{children:a("Groups organize projects in the sidebar.")})]}),i.jsxs(On,{className:"space-y-3",children:[i.jsxs(Us,{children:[i.jsx(Ks,{children:a("Name")}),i.jsx(Xt,{value:c,onChange:D=>u(D.target.value),autoFocus:!0})]}),i.jsxs("div",{className:"flex flex-wrap gap-2",children:[i.jsx("button",{type:"button",className:"flex h-6 w-6 items-center justify-center rounded-full border border-border bg-background text-muted-foreground",style:{outline:h==null?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(void 0),"aria-label":a("No color"),children:i.jsx(an,{className:"h-3 w-3"})}),Lee.map(D=>i.jsx("button",{type:"button",className:"h-6 w-6 rounded-full border border-border",style:{backgroundColor:D,outline:h===D?"2px solid var(--color-ring)":void 0,outlineOffset:2},onClick:()=>p(h===D?void 0:D),"aria-label":D},D))]}),i.jsx(OI,{value:f,reasoningEnabled:x,thinkingLevel:y,onChange:D=>{if(g(D),D)return;const T=Qc({defaultReasoningEnabled:l,defaultThinkingLevel:d});v(T.reasoningEnabled),w(T.thinkingLevel)},onReasoningChange:v,onThinkingChange:w,description:a("Used for new conversations in this group."),inheritLabel:a("Follows the global default")}),S.length>0&&i.jsxs(Us,{className:"w-full items-stretch",children:[i.jsx(Ks,{children:a("Move projects into this group")}),i.jsx(Xt,{value:j,onChange:D=>N(D.target.value),placeholder:a("Filter projects...")}),i.jsxs("div",{className:"max-h-48 w-full space-y-0.5 overflow-y-auto rounded-md border p-1.5",children:[E.map(D=>i.jsxs("label",{className:"flex w-full cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-accent/50",children:[i.jsx(dd,{checked:b.has(D.id),onCheckedChange:()=>I(D.id)}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-sm",children:D.name})]},D.id)),E.length===0&&i.jsx("p",{className:"px-2 py-3 text-center text-xs text-muted-foreground",children:a("No matching projects found")})]})]})]}),i.jsxs(cs,{className:t?"sm:justify-between":void 0,children:[t&&r?i.jsx(ge,{type:"button",variant:"outline",size:"sm",className:"text-destructive",onClick:()=>{r(),s(!1)},children:a("Delete group")}):i.jsx("span",{}),i.jsxs("div",{className:"flex gap-2",children:[i.jsx(ge,{type:"button",variant:"outline",size:"sm",onClick:()=>s(!1),children:a("Cancel")}),i.jsx(ge,{type:"submit",size:"sm",disabled:!c.trim(),children:a("Save")})]})]})]})})})}function zee({project:e,onClose:t}){const{t:n}=Q(),[s,o]=m.useState(null),[r,a]=m.useState(null),[l,d]=m.useState(null),[c,u]=m.useState(!1);m.useEffect(()=>{e&&(o(null),a(null),d(null),window.electronAPI.sessionImport.scan(e.path).then(o).catch(()=>o([])))},[e]),m.useEffect(()=>{if(!r){d(null);return}d(null),window.electronAPI.sessionImport.read(r.sourceId,r.path).then(d).catch(()=>d([]))},[r]);const h=async()=>{if(!(!e||!r)){u(!0);try{const p=await window.electronAPI.sessionImport.import(r.sourceId,r.path,e.path);p&&(re.getState().addImportedConversation(e.id,p),t())}finally{u(!1)}}};return i.jsx(wn,{open:e!==null,onOpenChange:p=>!p&&t(),children:i.jsxs(yn,{className:"max-w-3xl",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:n("Import session")}),i.jsx(Bs,{children:n("Pick a conversation from a local AI app under {{name}}.",{name:e?.name??""})})]}),i.jsx(On,{children:s===null?i.jsx("div",{className:"flex flex-col items-center gap-3 py-12",children:i.jsx(hr,{className:"size-5"})}):s.length===0?i.jsx("p",{className:"py-12 text-center text-sm text-muted-foreground",children:n("No sessions found for this project")}):i.jsxs("div",{className:"flex h-96 gap-3",children:[i.jsx("div",{className:"flex w-64 shrink-0 flex-col overflow-y-auto rounded-lg border",children:s.map(p=>i.jsxs("div",{children:[i.jsx("p",{className:"sticky top-0 bg-background px-2.5 pt-2 pb-1 text-[10px] font-semibold tracking-[0.18em] text-muted-foreground uppercase",children:p.sourceName}),p.sessions.map(f=>i.jsxs("button",{type:"button",onClick:()=>a({sourceId:p.sourceId,path:f.path}),className:q("w-full px-2.5 py-1.5 text-left",r?.path===f.path?"bg-muted":"hover:bg-muted/50"),children:[i.jsx("p",{className:"truncate text-xs",children:f.title||n("Untitled")}),i.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[new Date(f.updatedAt).toLocaleString()," ·"," ",n("{{count}} messages",{count:f.messageCount})]})]},f.path))]},p.sourceId))}),i.jsx("div",{className:"min-w-0 flex-1 overflow-y-auto rounded-lg border bg-muted/20 p-3",children:r?l===null?i.jsx("div",{className:"flex justify-center py-12",children:i.jsx(hr,{className:"size-4"})}):i.jsx("div",{className:"flex flex-col gap-2.5",children:l.map((p,f)=>i.jsx("div",{className:q("max-w-[90%] rounded-lg px-2.5 py-1.5 text-xs whitespace-pre-wrap",p.role==="user"?"self-end bg-primary/10":"self-start bg-background border"),children:p.text.length>600?`${p.text.slice(0,600)}…`:p.text},f))}):i.jsx("p",{className:"py-12 text-center text-xs text-muted-foreground",children:n("Select a session to preview")})})]})}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",onClick:t,children:n("Cancel")}),i.jsxs(ge,{onClick:()=>{h()},disabled:!r||c,children:[c?i.jsx(hr,{className:"mr-1.5 size-3.5"}):i.jsx(sd,{className:"mr-1.5 h-3.5 w-3.5"}),n("Import")]})]})]})})}function Gee({open:e,project:t,onOpenChange:n}){const{t:s}=Q(),o=Ce(O=>O.projectGroups),r=Ce(O=>O.defaultReasoningEnabled),a=Ce(O=>O.defaultThinkingLevel),l=Ce(O=>O.setProjectDefaultModel),d=Ce(O=>O.setProjectGroupId),c=Ce(O=>O.setProjectAlias),u=Ce(O=>O.setProjectDisabledBuiltinTools),h=Ce(O=>O.setProjectSubagentAllowedModes),p=Ce(O=>O.setProjectTrustedCode),f=Ce(O=>O.disabledBuiltinTools),g=Ce(O=>O.subagentAllowedModes),[x,v]=m.useState(""),[y,w]=m.useState(null),[b,_]=m.useState(!0),[j,N]=m.useState("medium"),[C,S]=m.useState(""),[A,E]=m.useState(!0),[I,D]=m.useState([]),[T,z]=m.useState(!0),[$,R]=m.useState([]),[B,H]=m.useState(!1);m.useEffect(()=>{if(!e)return;H(!1),w(t?.defaultModel??null),S(t?.groupId??""),v(t?.alias??"");const O=t?.groupId?o.find(fe=>fe.id===t.groupId):void 0,V=Qc({groupReasoningEnabled:O?.defaultReasoningEnabled,groupThinkingLevel:O?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(t?.defaultReasoningEnabled??V.reasoningEnabled),N(t?.defaultThinkingLevel??V.thinkingLevel);const J=t?.disabledBuiltinTools===void 0;E(J),D(J?[...f]:[...t?.disabledBuiltinTools??[]]);const pe=t?.subagentAllowedModes===void 0;z(pe),R(pe?[...g]:[...t?.subagentAllowedModes??[]])},[e,t,o,r,a,f,g]);const oe=m.useMemo(()=>[{value:"",label:s("Ungrouped")},...o.slice().sort((O,V)=>O.order-V.order).map(O=>({value:O.id,label:O.name}))],[o,s]),te=t?.kind==="ssh"?`${t.sshConnectionName??t.sshHost}:${t.path}`:t?.path??"";return i.jsx(wn,{open:e,onOpenChange:n,children:i.jsx(yn,{className:"max-w-lg",children:i.jsxs("form",{className:"contents",onSubmit:O=>{O.preventDefault(),t&&(l(t.id,y,y?{reasoningEnabled:b,thinkingLevel:j}:null),d(t.id,C||null),c(t.id,x),u(t.id,A?null:I),h(t.id,T?null:$),B&&p(t.id,null),n(!1))},children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:s("Project settings")}),i.jsx(Bs,{children:t?Po(t):s("Project")})]}),i.jsxs(On,{className:"max-h-[60vh] space-y-4",children:[i.jsxs(Us,{className:"w-full items-stretch",children:[i.jsx(Ks,{children:s("Alias")}),i.jsx(Xt,{value:x,onChange:O=>v(O.target.value),placeholder:t?Po({...t,alias:void 0}):""}),i.jsx(Lj,{children:s("Shown in the sidebar instead of the folder name. Leave blank to reset.")})]}),i.jsxs(Us,{className:"w-full items-stretch",children:[i.jsx(Ks,{children:s("Path")}),i.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[i.jsx("p",{className:"min-w-0 flex-1 truncate font-mono text-xs",title:te,children:te}),i.jsx(dk,{text:te,className:"shrink-0"}),t&&t.kind!=="ssh"&&i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.projects.reveal({projectId:t.id})},className:"shrink-0 transition-colors hover:text-foreground",title:s("Open folder"),children:i.jsx(ni,{className:"h-3 w-3"})})]})]}),o.length>0&&i.jsxs(Us,{className:"w-full items-stretch",children:[i.jsx(Ks,{children:s("Project group")}),i.jsxs(xs,{items:oe,value:C,onValueChange:O=>S(O??""),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:oe.map(O=>i.jsx(ns,{value:O.value,children:O.label},O.value||"ungrouped"))})]})]}),i.jsx(OI,{value:y,reasoningEnabled:b,thinkingLevel:j,onChange:O=>{if(w(O),O)return;const V=C?o.find(pe=>pe.id===C):void 0,J=Qc({groupReasoningEnabled:V?.defaultReasoningEnabled,groupThinkingLevel:V?.defaultThinkingLevel,defaultReasoningEnabled:r,defaultThinkingLevel:a});_(J.reasoningEnabled),N(J.thinkingLevel)},onReasoningChange:_,onThinkingChange:N,description:s("Used for new conversations in this project."),inheritLabel:s("Follows group, then global default")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("Session choice overrides the project default.")}),i.jsxs("div",{className:"space-y-3",children:[i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global built-in tools")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, configure built-in tools for this project. They override the global setting on the next session.")})]}),i.jsx(Di,{checked:A,onCheckedChange:E})]}),!A&&i.jsx("div",{className:"space-y-2",children:HL.map(O=>i.jsxs("div",{className:"flex items-center gap-3 rounded-md border px-3 py-2.5",children:[i.jsx(gg,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"text-sm font-medium",children:s(O.name)}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s(O.description)})]}),i.jsx(Di,{checked:!I.includes(O.id),onCheckedChange:V=>D(J=>V?J.filter(pe=>pe!==O.id):[...new Set([...J,O.id])])})]},O.id))}),i.jsxs("div",{className:"flex items-center justify-between gap-4 rounded-lg border px-3 py-2.5",children:[i.jsxs("div",{className:"min-w-0",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Follow global unified agent modes")}),i.jsx("p",{className:"text-muted-foreground text-xs",children:s("When off, this project uses its own explicit Agent mode permission mask.")})]}),i.jsx(Di,{checked:T,onCheckedChange:O=>{z(O),O||R([...g])}})]}),!T&&i.jsxs("div",{className:"space-y-2 rounded-lg border px-3 py-2.5",children:[[["task","One-shot task agents"],["coworker","Persistent coworkers"]].map(([O,V])=>i.jsxs("div",{className:"flex items-center justify-between gap-4",children:[i.jsx("span",{className:"text-sm",children:s(V)}),i.jsx(Di,{checked:$.includes(O),disabled:(A?f:I).includes("subagent"),onCheckedChange:J=>R(pe=>J?[...new Set([...pe,O])]:pe.filter(fe=>fe!==O))})]},O)),(A?f:I).includes("subagent")&&i.jsx("p",{className:"text-muted-foreground text-xs",children:s("The unified subagent tool is off. Re-enabling it keeps this mode selection.")})]})]}),t?.trustedProjectCode?.length?i.jsxs("div",{className:"flex items-start gap-3 rounded-lg border px-3 py-2.5",children:[i.jsx(ta,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsx("p",{className:"font-medium text-sm",children:s("Trusted project extensions")}),i.jsx("p",{className:"truncate font-mono text-muted-foreground text-xs",title:t.trustedProjectCode.join(`
|
|
96
|
-
`),children:t.trustedProjectCode.join(", ")}),B&&i.jsx("p",{className:"text-muted-foreground text-xs",children:s("No longer loaded after saving, starting with the next session.")})]}),i.jsx(ge,{type:"button",size:"xs",variant:"outline",disabled:B,onClick:()=>H(!0),children:s("Revoke trust")})]}):null]}),i.jsxs(cs,{children:[i.jsx(ge,{type:"button",variant:"outline",size:"sm",onClick:()=>n(!1),children:s("Cancel")}),i.jsx(ge,{type:"submit",size:"sm",disabled:!t,children:s("Save")})]})]})})})}const Mh=5,zI=15,zS=9;function Rh(e,t){return e<=0?0:Math.min(e,Mh+Math.max(0,t))}function Fee(e,t){return Rh(e,t)>=e?0:Math.min(Math.max(0,e-Mh),t+zI)}function Hee(e){return Math.max(0,e-zI)}function Bee(e){const{order:t,conversations:n,pinnedOrderIds:s=[],projectIds:o,archivedProjectIds:r=[],collapsedProjects:a={},revealedExtras:l={},searching:d=!1,matches:c=()=>!0,projectMatches:u=()=>!1,leadingIds:h=[]}=e,p=[],f=new Set,g=v=>{f.has(v)||p.length>=zS||(f.add(v),p.push(v))};for(const v of h)g(v);const x=Oj(t,n,s,r);for(const v of d?x.filter(c):x)g(v);for(const v of o){if(p.length>=zS)break;if(d?!1:a[v]===!0)continue;const w=ol(t,n,v),b=!d||u(v)?w:w.filter(c),_=d?b:b.slice(0,Rh(b.length,l[v]??0));for(const j of _)g(j)}return p}function pv(e,t){const n=new Map(e.map(o=>[o.id,o])),s=[];for(const o of t){const r=n.get(o);r&&(s.push(r),n.delete(o))}for(const o of e)n.has(o.id)&&s.push(o);return s}function ac(e,t,n,s){const o=pv(e,t).map(l=>l.id),r=o.indexOf(n),a=o.indexOf(s);return r===-1||a===-1||r===a||(o.splice(r,1),o.splice(a,0,n)),o}function Vee(e,t){const n=new Map(e.map(r=>[r.id,r])),s=[],o=new Set;for(const r of t){const a=n.get(r);a&&(s.push(a),o.add(r))}return{pinned:s,rest:e.filter(r=>!o.has(r.id))}}function $ee(e,t){return e.includes(t)?e.filter(n=>n!==t):[t,...e]}function Wee(e,t,n){const s=n.includes(e),o=n.includes(t);return s&&o?"pinned":!s&&!o?"order":null}const Uc="enso-project-order",Bm="enso-pinned-order",el="enso-archived-projects",GS="enso-pinned-projects",Vm=new Set;function ur(e){try{const t=JSON.parse(localStorage.getItem(e)??"[]");return Array.isArray(t)?t:[]}catch{return[]}}function Jo(e,t){localStorage.setItem(e,JSON.stringify(t));for(const n of Vm)n()}function Uee(e){return Vm.add(e),()=>Vm.delete(e)}function Xp(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function FS(e){return e==="browser"||typeof e=="string"&&e.startsWith("browser:")}function Kee(e){if(typeof e.contentComponent=="string")return e.contentComponent;if(typeof e.component=="string")return e.component}function HS(e){if(!Xp(e)||!Xp(e.panels))return{browsers:0,terminals:0};let t=0,n=0;for(const[s,o]of Object.entries(e.panels)){if(!Xp(o))continue;const r=Kee(o);r==="browser"||FS(o.id)||FS(s)?t+=1:r==="terminal"&&(n+=1)}return{browsers:t,terminals:n}}function qee({conversationId:e}){const{t}=Q(),n=gn(o=>HS(o.layouts[e]).browsers),s=gn(o=>HS(o.layouts[e]).terminals);return n===0&&s===0?null:i.jsxs("span",{"data-slot":"session-tab-counts",className:"flex shrink-0 items-center gap-1.5 text-[10px] tabular-nums text-muted-foreground/70",children:[n>0&&i.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} browsers",{n}),children:[i.jsx(fo,{className:"h-3 w-3","aria-hidden":!0}),n]}),s>0&&i.jsxs("span",{className:"inline-flex items-center gap-0.5",title:t("{{n}} terminals",{n:s}),children:[i.jsx(Go,{className:"h-3 w-3","aria-hidden":!0}),s]})]})}const Yee=[7,15,30],BS="h-6.5 rounded-lg px-2 text-xs text-subtle-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",VS="enso-collapsed-scratch",Zi="flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",Zp="-my-0.5 flex size-5 shrink-0 items-center justify-center rounded-[5px] text-subtle-foreground opacity-0 transition-opacity hover:bg-foreground/5 hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100";function $S({width:e,collapsed:t,onToggleCollapse:n,onOpenSearch:s,onNavigate:o}){const{t:r,locale:a}=Q(),l=Ce(K=>K.projects),c=Zu()==="mobile",u=Ce(K=>K.scratchSessionsEnabled),h=Ce(K=>K.projectGroups),p=Ce(K=>K.createProjectGroup),f=Ce(K=>K.updateProjectGroup),g=Ce(K=>K.removeProjectGroup),x=Ce(K=>K.reorderProjectGroups),v=Ce(K=>K.setProjectGroupId),y=Ce(K=>K.keybindings),w=Ce(K=>K.activeRetentionMinutes),b=Ai(y)["search-workspace"],_=b?fi(b):"",j=Ce(K=>K.addProject),N=Ce(K=>K.removeProject),C=re(K=>ov(K.conversations)),S=re(K=>K.order),A=re(K=>K.activeId),E=re(K=>K.newConversation),I=re(K=>K.selectConversation),D=m.useRef(o);D.current=o;const T=m.useCallback(K=>{D.current?.(),I(K)},[I]),z=re(K=>K.removeConversation),$=re(K=>K.togglePinConversation),R=re(K=>K.toggleArchiveConversation),B=re(K=>K.moveConversationToWorktree),H=re(K=>K.cleanupWorktree),oe=re(K=>K.refreshWorktreeStatuses),te=re(K=>K.worktreeStatuses),[O,V]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-projects")??"{}")}catch{return{}}}),J=K=>{V(ye=>{const at={...ye,[K]:!ye[K]};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(at)),at})},[pe,fe]=m.useState(()=>{try{return localStorage.getItem(VS)==="1"}catch{return!1}}),_e=K=>{try{localStorage.setItem(VS,K?"1":"0")}catch{}},Ee=()=>{fe(K=>{const ye=!K;return _e(ye),ye})},me=()=>{fe(K=>K&&(_e(!1),!1))},[W,G]=m.useState(()=>ur(Uc)),de=pv(l.filter(K=>K.kind!=="scratch"),W),X=l.find(K=>K.kind==="scratch"),[ie,Z]=m.useState(()=>ur(el)),[le,be]=m.useState(()=>ur(GS)),Fe=K=>{be(K),Jo(GS,K)},Je=K=>{if(Fe($ee(le,K)),!le.includes(K)&&ie.includes(K)){const ye=ie.filter(at=>at!==K);Z(ye),Jo(el,ye)}},We=K=>{const ye=ie.includes(K)?ie.filter(at=>at!==K):[...ie,K];Z(ye),Jo(el,ye),!ie.includes(K)&&le.includes(K)&&Fe(le.filter(at=>at!==K))},[et,qe]=m.useState(()=>{try{return localStorage.getItem("enso-selected-project-group")??Mn}catch{return Mn}}),[Lt,Bt]=m.useState(()=>{try{return JSON.parse(localStorage.getItem("enso-collapsed-project-groups")??"{}")}catch{return{}}}),Mt=K=>{qe(K),localStorage.setItem("enso-selected-project-group",K)},ne=K=>{Bt(ye=>{const at={...ye,[K]:!ye[K]};return localStorage.setItem("enso-collapsed-project-groups",JSON.stringify(at)),at})},se=et===Mn||et===pr||et===us||h.some(K=>K.id===et)?et:Mn,He=se===pr,kt=h.find(K=>K.id===se)?.id,st=Or(de,h,ie,se),ke=BL(Or(de,h,ie,Mn),S,C,Date.now()),{pinned:ut,rest:ft}=He?{pinned:[],rest:ke}:Vee(st,le),ze=zj(ft,h,[]),wt=[...ut,...ft],Y=wt.map(K=>K.id),U=new Set(Y),[ue,je]=m.useState(()=>ur(Bm)),{active:De}=fd(),Le=De?.data.current;Yj({onDragEnd:K=>{const ye=K.active.data.current;if(!ye)return;const at=K.over?String(K.over.id):null,xt=RJ(ye,at,A??void 0,{projectGroupId:It=>l.find(is=>is.id===It)?.groupId});if(xt)switch(xt.kind){case"move-project-to-group":{if(He&&xt.beforeProjectId)break;if(v(xt.projectId,xt.groupId),xt.beforeProjectId){const It=ac(l,W,xt.projectId,xt.beforeProjectId);G(It),Jo(Uc,It)}break}case"reorder-groups":x(xt.activeId,xt.overId);break;case"reorder-projects":{if(He)break;const It=Wee(xt.activeId,xt.overId,le);if(It==="pinned"){const Uo=ac(le.map(So=>({id:So})),le,xt.activeId,xt.overId);Fe(Uo);break}if(It!=="order")break;const is=ac(l,W,xt.activeId,xt.overId);G(is),Jo(Uc,is);break}case"insert-file-mention":Xl({kind:"file",id:xt.path,label:xt.label,relativePath:xt.path});break;case"insert-chat-mention":Xl({kind:"chat",id:xt.conversationId,label:xt.label,sessionFile:xt.sessionFile});break;case"pin-conversation":$(xt.conversationId);break;case"reorder-pinned":{const It=ac(Dt.map(is=>({id:is})),ue,xt.activeId,xt.overId);je(It),Jo(Bm,It);break}}}});const[tt,bt]=m.useState(null),[Vt,Jt]=m.useState(null),[un,nn]=m.useState(!1),[Ie,it]=m.useState(!1),[dt,jt]=m.useState(null),Rt=K=>{const ye=new Set(l.map(at=>at.id));K.sshConnectionId&&jt({name:bj(K.path),path:K.path,sshHost:K.sshHost}),j(K.path,K.sshConnectionId?{sshConnectionId:K.sshConnectionId}:void 0,K.groupId??kt).then(at=>{if(at){if(ie.includes(at.id)){const xt=ie.filter(It=>It!==at.id);Z(xt),Jo(el,xt)}if(ye.has(at.id)){V(It=>{if(It[at.id]!==!0)return It;const is={...It,[at.id]:!1};return localStorage.setItem("enso-collapsed-projects",JSON.stringify(is)),is});const xt=ol(S,C,at.id)[0];if(xt){T(xt);return}}E(at.id)}}).catch(at=>{Be({type:"error",title:r("Failed to add project"),description:at instanceof Error?at.message:String(at)})}).finally(()=>jt(null))},[dn,P]=m.useState(null),[M,L]=m.useState(null),k=async K=>{const ye=C[K];let at;if(ye?.worktree){const xt=await ln(K);jc(xt)&&(at=Kn(xt))}L({kind:"conversation",id:K,worktreeWarning:at})},[F,he]=m.useState({}),[xe,Pe]=m.useState(""),[Ue,lt]=m.useState(!1),[Qe,$t]=m.useState(()=>Date.now());m.useEffect(()=>{const K=setInterval(()=>$t(Date.now()),VL);return()=>clearInterval(K)},[]);const rt={now:Qe,ms:w*6e4},_t=$L(S,C,ie,rt),Nt=K=>{const ye=qS(l,C[K].projectId),at=KL(K,C,rt);if(at===void 0)return ye;const xt=r("Stays in Active for about {{count}} more min",{count:Math.ceil(at/6e4)});return ye?`${ye}
|
|
97
|
-
${xt}`:xt},Dt=Oj(S,C,ue,ie),yt=WL(S,C,de.map(K=>K.id),ie).filter(K=>u||K.projectId!==X?.id),mt=xe.trim().length>0,St=K=>Fa(xe,[C[K]?.title||r("New conversation")]),Tt=X?ol(S,C,X.id).filter(K=>!mt||St(K)):[],ae=mt?!1:pe,Te=K=>{const ye=C[K]?.projectId;return!ye||U.has(ye)},Ae=(mt?_t.filter(St):_t).filter(Te),Ge=Bee({order:S,conversations:C,pinnedOrderIds:ue,projectIds:Y,archivedProjectIds:ie,collapsedProjects:O,revealedExtras:F,searching:mt,matches:St,projectMatches:K=>{const ye=de.find(at=>at.id===K);return!!(ye&&Fa(xe,[ye.alias??"",ye.name,ye.path]))},leadingIds:Ae}),Ye=m.useRef(Ge);Ye.current=Ge;const Xe=(mt?Dt.filter(St):Dt).filter(Te),we=new Set(Xe),Se=new Set(Ae),Me=(K,ye)=>{if(t||!Ue)return;const at=Ge.indexOf(K);if(!(at<0||(Se.has(K)?"active":we.has(K)?"pinned":"project")!==ye))return fi(`mod+${at+1}`)},[Oe,Re]=m.useState(!1),[Ve,Ct]=m.useState(""),[zt,Gt]=m.useState(null),Ft=Ve.trim()?yt.map(K=>{const ye=l.find(xt=>xt.id===K.projectId);return K.projectArchived===!0&&!!(ye&&Fa(Ve,[ye.alias??"",ye.name,ye.path]))?K:{...K,ids:K.ids.filter(xt=>Fa(Ve,[C[xt]?.title||r("New conversation")]))}}).filter(K=>K.ids.length>0):yt,ee=K=>{if(se===Mn)return!0;const ye=l.find(at=>at.id===K.projectId);return ye?se===us?!ye.groupId||!h.some(at=>at.id===ye.groupId):ye.groupId===se:se===us},Wt=Ft.filter(ee),Zt=yt.filter(ee).reduce((K,ye)=>K+ye.ids.length,0),sn=()=>{Ct(""),Re(!0)};m.useEffect(()=>{se!==et&&(qe(Mn),localStorage.setItem("enso-selected-project-group",Mn))},[se,et]),m.useEffect(()=>{const K=It=>{const Uo=(u0?It.metaKey:It.ctrlKey)&&!It.shiftKey&&!It.altKey;if(lt(Uo),!Uo||It.repeat||ts.getState().activeNodeId!=="local")return;const So=Number(It.key);if(So<1||So>9)return;const Ko=Ye.current[So-1];Ko&&(It.preventDefault(),T(Ko))},ye=It=>{const is=u0?It.metaKey:It.ctrlKey;lt(is&&!It.shiftKey&&!It.altKey)},at=()=>lt(!1),xt=()=>{document.hidden&&at()};return window.addEventListener("keydown",K),window.addEventListener("keyup",ye),window.addEventListener("blur",at),document.addEventListener("visibilitychange",xt),()=>{window.removeEventListener("keydown",K),window.removeEventListener("keyup",ye),window.removeEventListener("blur",at),document.removeEventListener("visibilitychange",xt)}},[T]),m.useEffect(()=>{oe();const K=setInterval(()=>{oe()},3e4),ye=()=>{oe()};return window.addEventListener("focus",ye),()=>{clearInterval(K),window.removeEventListener("focus",ye)}},[oe]);const[At,Qt]=m.useState(null),[en,Dn]=m.useState(null),ln=async K=>{const ye=await window.electronAPI.worktree.status(K);return ye.ok?ye.value:void 0},Nn=async(K,ye)=>{const at=await H(K);if(at){Be({type:"error",title:r("Failed to clean up worktree"),description:at});return}ye&&R(K),oe()},xn=async K=>{const ye=await ln(K);if(jc(ye)){Qt({kind:"cleanup",id:K,status:ye});return}await Nn(K,!1)},mn=async K=>{const ye=C[K];if(!ye)return;if(ye.archived||!ye.worktree){R(K);return}const at=await ln(K);if(jc(at)){Qt({kind:"archive",id:K,status:at});return}await Nn(K,!0)},Hn=async K=>{for(const ye of K)!C[ye]||C[ye].archived||await mn(ye)},zn=async(K,ye=!1)=>{const at=await B(K,{allowDirtyMainTree:ye});if(at===Rj){Dn(K);return}if(at){Be({type:"error",title:r("Failed to move to worktree"),description:at});return}oe()},Kn=K=>{const ye=[];return K?.dirty&&ye.push(r("Uncommitted changes")),K&&K.ahead>0&&ye.push(r("{{n}} unmerged commits (branch is kept)",{n:K.ahead})),ye.join("; ")};return i.jsxs(Ms.aside,{initial:!1,animate:{width:t?48:e},transition:Jr,"data-enso":"sidebar",className:"flex shrink-0 flex-col overflow-hidden",children:[t&&i.jsxs("div",{className:"flex w-full flex-1 flex-col items-center gap-1 py-2",children:[i.jsx("button",{type:"button",onClick:()=>nn(!0),className:Zi,title:r("Add project"),children:i.jsx(qb,{className:"h-4 w-4"})}),i.jsx("div",{className:"flex-1"}),Zt>0&&i.jsx("button",{type:"button",onClick:sn,className:Zi,title:`${r("Archived")} (${Zt})`,children:i.jsx(Ii,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:Zi,title:r("Compact view"),children:i.jsx(d0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:()=>window.electronAPI.window.openSettings(),className:Zi,title:r("Settings"),children:i.jsx(ui,{className:"h-4 w-4"})})]}),i.jsxs("div",{className:q("flex h-full min-h-0 flex-col",c&&"pt-3",t&&"hidden"),style:{width:e},children:[i.jsx(Pee,{groups:h,selectedId:se,counts:Object.fromEntries(h.map(K=>[K.id,Or(de,h,ie,K.id).length])),totalCount:Or(de,h,ie,Mn).length,recentCount:ke.length,ungroupedCount:Or(de,h,ie,us).length,query:xe,onQueryChange:Pe,searchOpen:Ie,onSearchOpenChange:it,onSelect:Mt,onAddGroup:()=>bt({mode:"create"}),onEditGroup:K=>bt({mode:"edit",id:K})}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pt-0.5 pb-2 pl-1.5 [scrollbar-gutter:stable]",children:[de.length===0&&i.jsx("button",{type:"button",onClick:()=>nn(!0),className:"mt-2 w-full rounded-lg border border-dashed px-3 py-6 text-center text-sm text-muted-foreground transition-colors hover:border-brand/50 hover:text-foreground",children:r("Add a project to start")}),de.length===0&&u&&X&&i.jsx("button",{type:"button",onClick:()=>{me(),E(X.id)},className:"mt-1 w-full rounded-lg px-3 py-2 text-center text-sm text-muted-foreground transition-colors hover:bg-foreground/5 hover:text-foreground",children:r("Start a temporary chat")}),Ae.length>0&&i.jsxs("div",{"data-slot":"active-section",children:[i.jsx($a,{children:r("Active")}),i.jsx("div",{className:"flex flex-col",children:Ae.map(K=>i.jsx(US,{id:K,dragId:AJ(K),conversation:C[K],children:i.jsx(Va,{id:K,conversation:C[K],active:A===K,switchHint:Me(K,"active"),locale:a,nowTick:Qe,hoverTitle:Nt(K),worktreeStatus:C[K].worktree?te[K]:void 0,isolated:!!C[K].worktree,onSelect:T,onTogglePin:$,onToggleArchive:ye=>{mn(ye)},onCleanupWorktree:ye=>{xn(ye)},onMoveToWorktree:ye=>{zn(ye)},onRemove:ye=>{k(ye)}})},K))})]}),Dt.length===0&&Le?.type==="chat"&&!Le.pinned&&i.jsx(KS,{children:i.jsxs("div",{className:"flex items-center justify-center gap-1.5 rounded-lg border border-dashed px-2 py-2 text-xs text-muted-foreground",children:[i.jsx(di,{className:"h-3.5 w-3.5"}),r("Drop here to pin")]})}),Xe.length>0&&i.jsxs(KS,{"data-slot":"pinned-section",children:[i.jsx($a,{children:r("Pinned")}),i.jsx("div",{className:"flex flex-col",children:i.jsx(Hm,{items:Xe.map(K=>gI(K)),strategy:LS,children:Xe.map(K=>i.jsx(ete,{id:K,conversation:C[K],children:i.jsx(Va,{id:K,conversation:C[K],active:A===K,switchHint:Me(K,"pinned"),locale:a,nowTick:Qe,hoverTitle:qS(l,C[K].projectId),worktreeStatus:C[K].worktree?te[K]:void 0,isolated:!!C[K].worktree,onSelect:T,onTogglePin:$,onToggleArchive:ye=>{mn(ye)},onCleanupWorktree:ye=>{xn(ye)},onMoveToWorktree:ye=>{zn(ye)},onRemove:ye=>{k(ye)}})},K))})})]}),u&&X&&i.jsxs("div",{"data-slot":"scratch-section",children:[i.jsxs("div",{className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[i.jsxs("button",{type:"button",onClick:Ee,"aria-expanded":!ae,className:"flex min-w-0 flex-1 items-center gap-1 text-left transition-colors hover:text-foreground",children:[i.jsx("span",{className:"min-w-0 truncate",children:r("Temporary chats")}),i.jsx(bn,{className:q("size-3 shrink-0 transition-[opacity,transform] duration-150",!ae&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:"ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",children:Tt.length})]}),i.jsx("button",{type:"button",className:Zp,title:r("Start a temporary chat"),"aria-label":r("Start a temporary chat"),onClick:()=>{me(),E(X.id)},children:i.jsx(ds,{className:"size-3.25"})})]}),i.jsx(hl,{initial:!1,children:!ae&&i.jsx(Ms.div,{initial:"initial",animate:"animate",exit:"exit",variants:Ep,className:"overflow-hidden",children:i.jsx("div",{className:"flex flex-col",children:Tt.map(K=>i.jsx(Va,{id:K,conversation:C[K],active:A===K,switchHint:Me(K,"project"),locale:a,nowTick:Qe,onSelect:T,onTogglePin:$,onToggleArchive:ye=>{mn(ye)},onCleanupWorktree:ye=>{xn(ye)},onMoveToWorktree:ye=>{zn(ye)},onRemove:ye=>{k(ye)}},K))})},"scratch-conversations")})]}),de.length>0&&i.jsx($a,{actions:i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:()=>it(!0),className:q(Zp,(Ie||mt)&&"bg-foreground/5 text-foreground opacity-100"),title:r("Search conversations..."),"aria-label":r("Search conversations..."),children:i.jsx(oN,{className:"size-3.25"})}),i.jsx("button",{type:"button",onClick:()=>nn(!0),className:Zp,title:r("Add project"),"aria-label":r("Add project"),children:i.jsx(ds,{className:"size-3.25"})})]}),children:r("Projects")}),dt&&i.jsxs("div",{className:"flex h-8 w-full items-center gap-2 rounded-lg px-2 text-muted-foreground",children:[i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:i.jsx(qt,{className:"size-4 animate-spin"})}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium",title:dt.path,children:[dt.name,dt.sshHost&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal",children:dt.sshHost})]}),i.jsx("span",{className:"shrink-0 text-xs",children:r("Adding...")})]}),i.jsx(Hm,{items:[...se===Mn?ze.map(K=>K.groupId===us?rv:mI(K.groupId)):[],...Y.map(K=>fI(K))],strategy:LS,children:(()=>{const K=ye=>{const at=ol(S,C,ye.id),xt=Fa(xe,[ye.alias??"",ye.name,ye.path]),It=!mt||xt?at:at.filter(St);if(mt&&It.length===0)return null;const is=mt?!1:O[ye.id]===!0,Uo=F[ye.id]??0,So=mt?It.length:Rh(It.length,Uo),Ko=It.slice(So),jr=le.includes(ye.id),Pv=[{kind:"item",key:"pin",label:r(jr?"Unpin project":"Pin project"),icon:jr?i.jsx(vu,{}):i.jsx(di,{}),onSelect:()=>Je(ye.id)},{kind:"item",key:"settings",label:r("Project settings"),icon:i.jsx(ui,{}),onSelect:()=>Jt(ye.id)},...ye.kind!=="ssh"?[{kind:"item",key:"reveal",label:r(uv(window.electronAPI.env.platform)),icon:i.jsx(ni,{}),onSelect:()=>hv({projectId:ye.id},r)}]:[],{kind:"item",key:"import",label:r("Import session"),icon:i.jsx(qL,{}),onSelect:()=>P(ye)},{kind:"separator",key:"sep-group"},{kind:"submenu",key:"move-to-group",label:r("Move to group"),icon:i.jsx(Jp,{}),items:[{kind:"item",key:"ungrouped",label:r("Ungrouped"),icon:i.jsx(Jp,{}),onSelect:()=>v(ye.id,null)},...h.map(Ki=>({kind:"item",key:`group-${Ki.id}`,label:Ki.name,icon:i.jsx(Jp,{emoji:Ki.emoji,color:Ki.color}),onSelect:()=>v(ye.id,Ki.id)}))]},{kind:"item",key:"new-group",label:r("New group"),icon:i.jsx(qb,{}),onSelect:()=>bt({mode:"create"})},{kind:"separator",key:"sep-danger"},{kind:"item",key:"archive",label:r("Archive project"),icon:i.jsx(Ii,{}),onSelect:()=>We(ye.id)},{kind:"item",key:"remove",label:r("Remove project"),icon:i.jsx(Gs,{}),destructive:!0,onSelect:()=>L({kind:"project",project:ye,conversationIds:at})}];return i.jsx(Qee,{project:ye,activitySorted:He,children:Ki=>i.jsxs(uo,{children:[i.jsx(ho,{render:i.jsxs("div",{ref:Ki.setNodeRef,style:Ki.style,children:[i.jsxs("div",{className:"group flex h-8 w-full items-center gap-1 rounded-lg px-2 transition-colors hover:bg-foreground/5",...Ki.handleProps,children:[i.jsxs("button",{type:"button",onClick:()=>J(ye.id),className:"flex min-w-0 flex-1 items-center gap-2 text-left",title:ye.path,children:[i.jsx(GI,{folded:is}),i.jsxs("span",{className:"min-w-0 flex-1 truncate text-[0.9286rem] font-medium text-foreground",title:ye.kind==="ssh"?`${ye.sshHost}:${ye.path}`:ye.path,children:[Po(ye),ye.kind==="ssh"&&i.jsx("span",{className:"ml-1.5 rounded bg-muted px-1 py-0.5 text-[10px] font-normal text-muted-foreground",children:ye.sshConnectionName??ye.sshHost}),He&&i.jsx("span",{className:"ml-1.5 font-normal text-[0.7857rem] text-subtle-foreground",children:h.find(Qn=>Qn.id===ye.groupId)?.name??r("Ungrouped")})]})]}),i.jsx("button",{type:"button",onClick:()=>Je(ye.id),className:"hidden shrink-0 rounded-md p-1 text-muted-foreground group-hover:block hover:bg-muted hover:text-foreground",title:r(jr?"Unpin project":"Pin project"),children:jr?i.jsx(vu,{className:"h-3.5 w-3.5"}):i.jsx(di,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:()=>{E(ye.id)},className:"shrink-0 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground focus-visible:opacity-100",title:r("New conversation"),children:i.jsx(Ro,{className:"h-3.5 w-3.5"})}),i.jsx(nte,{actions:Pv}),(jr||is)&&i.jsxs("span",{className:"flex shrink-0 items-center justify-center gap-1 py-1 text-[0.7857rem] text-subtle-foreground tabular-nums group-hover:opacity-0","aria-hidden":!0,children:[jr&&i.jsx(di,{className:"h-3.5 w-3.5"}),is&&at.length]})]}),i.jsx(hl,{initial:!1,children:!is&&i.jsx(Ms.div,{initial:"initial",animate:"animate",exit:"exit",variants:Ep,className:"overflow-hidden",children:i.jsxs("div",{className:"flex flex-col",children:[It.slice(0,So).map(Qn=>i.jsx(Ms.div,{layout:Le?.type==="project"?!1:"position",transition:Jr,children:i.jsx(US,{id:Qn,conversation:C[Qn],children:i.jsx(Va,{id:Qn,conversation:C[Qn],active:A===Qn,switchHint:Me(Qn,"project"),locale:a,nowTick:Qe,worktreeStatus:C[Qn].worktree?te[Qn]:void 0,isolated:!!C[Qn].worktree,onSelect:T,onTogglePin:$,onToggleArchive:qo=>{mn(qo)},onCleanupWorktree:qo=>{xn(qo)},onMoveToWorktree:qo=>{zn(qo)},onRemove:qo=>{k(qo)}})})},Qn)),!mt&&at.length>Mh&&i.jsxs("div",{className:"flex items-center gap-1 pl-6",children:[Ko.length>0&&i.jsxs(uo,{children:[i.jsx(ho,{render:i.jsx("button",{type:"button",onClick:()=>he(Qn=>({...Qn,[ye.id]:Fee(It.length,Qn[ye.id]??0)})),className:BS,children:r("Show {{n}} more",{n:Ko.length})})}),i.jsx(po,{className:"min-w-36",children:i.jsxs(Ut,{onClick:()=>{Hn(Ko)},children:[i.jsx(Ii,{}),r("Archive {{n}} conversations",{n:Ko.length})]})})]}),Uo>0&&i.jsx("button",{type:"button",onClick:()=>he(Qn=>({...Qn,[ye.id]:Hee(Qn[ye.id]??0)})),className:BS,children:r("Collapse")})]}),It.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-subtle-foreground",children:r("No conversations yet")})]})})})]})}),i.jsx(po,{className:"min-w-40",children:Ru(Pv)})]})},ye.id)};return He&&!mt&&wt.length===0?i.jsx("p",{className:"px-2 py-6 text-center text-xs text-muted-foreground",children:r("No projects active in the last {{n}} days",{n:UL})}):!mt&&de.length>0&&wt.length===0?i.jsx("p",{className:"px-2 py-1.5 text-xs text-subtle-foreground",children:r("No projects in this group yet")}):se===Mn&&h.length>0?i.jsxs("div",{children:[ut.length>0&&i.jsxs("div",{children:[i.jsx($a,{children:r("Pinned projects")}),i.jsx("div",{children:ut.map(K)})]}),ze.map(ye=>{const at=mt?!1:Lt[ye.groupId]===!0;return i.jsxs("div",{children:[i.jsx(Xee,{groupId:ye.groupId,name:ye.group?.name??r("Ungrouped"),emoji:ye.group?.emoji,color:ye.group?.color,count:ye.projects.length,folded:at,sortable:ye.groupId!==us,onToggle:()=>ne(ye.groupId),onEdit:ye.group?()=>bt({mode:"edit",id:ye.groupId}):void 0}),i.jsx(hl,{initial:!1,children:!at&&i.jsx(Ms.div,{initial:"initial",animate:"animate",exit:"exit",variants:Ep,className:"overflow-hidden",children:i.jsx("div",{children:ye.projects.map(K)})},`content-${ye.groupId}`)})]},ye.groupId)})]}):ut.length>0&&ft.length>0?i.jsxs("div",{className:"space-y-2",children:[i.jsxs("div",{children:[i.jsx($a,{children:r("Pinned projects")}),i.jsx("div",{children:ut.map(K)})]}),i.jsx("div",{children:ft.map(K)})]}):wt.map(K)})()})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[i.jsx(Gj,{}),Zt>0&&i.jsx("button",{type:"button","data-slot":"archived-button",onClick:sn,className:Zi,title:`${r("Archived")} (${Zt})`,children:i.jsx(Ii,{className:"h-4 w-4"})}),window.electronAPI.remote&&i.jsx("button",{type:"button",onClick:()=>window.electronAPI.remote?.exitDesk(),className:Zi,title:r("Compact view"),children:i.jsx(d0,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:()=>window.electronAPI.window.openSettings(),className:Zi,title:r("Settings"),"aria-label":r("Settings"),children:i.jsx(ui,{className:"h-4 w-4"})}),c&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",onClick:s,className:Zi,title:_?`${r("Search anything")} (${_})`:r("Search anything"),children:i.jsx(ti,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:n,className:Zi,title:r("Collapse sidebar"),children:i.jsx(wx,{className:"h-4 w-4"})})]})]})]}),i.jsx(wn,{open:Oe,onOpenChange:Re,children:i.jsxs(yn,{className:"h-[min(40rem,85vh)] max-w-xl",children:[i.jsxs(Sn,{children:[i.jsxs(Cn,{className:"flex items-baseline gap-2",children:[r("Archived"),i.jsx("span",{className:"font-sans text-sm text-muted-foreground tabular-nums",children:Zt})]}),i.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[i.jsxs(qu,{"data-size":"sm",children:[i.jsx(Yu,{children:i.jsx(ti,{})}),i.jsx(Xu,{value:Ve,placeholder:r("Search conversations..."),onChange:K=>Ct(K.target.value)})]}),i.jsx(WS,{open:zt==="*",onOpenChange:K=>Gt(K?"*":null),idsForDays:K=>c0(S,C,K,Date.now()),onPick:(K,ye)=>L({kind:"archived",days:K,conversationIds:ye}),className:"h-8 w-8 rounded-md opacity-100 hover:bg-muted"})]})]}),i.jsxs(On,{className:"flex flex-col gap-y-3 border-t pt-3!",children:[Wt.length===0&&i.jsx("p",{className:"py-10 text-center text-sm text-muted-foreground",children:Ve.trim()?r("No matching conversations"):r("No conversations")}),Wt.map(K=>{const ye=l.find(xt=>xt.id===K.projectId),at=ye?Po(ye):r("Other");return i.jsxs("div",{children:[i.jsxs("div",{className:"group flex items-center gap-2 rounded-md pr-0.5 pl-2",children:[K.projectArchived&&i.jsx(c$,{className:"size-4 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate py-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:at}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground tabular-nums",children:K.ids.length}),K.projectArchived?i.jsx("button",{type:"button",onClick:()=>We(K.projectId),className:"shrink-0 rounded p-0.5 text-muted-foreground hover:bg-muted hover:text-foreground",title:r("Unarchive project"),children:i.jsx(Fl,{className:"h-3.5 w-3.5"})}):i.jsx(WS,{open:zt===K.projectId,onOpenChange:xt=>Gt(xt?K.projectId:null),idsForDays:xt=>c0(S,C,xt,Date.now(),K.projectId),onPick:(xt,It)=>L({kind:"archived",days:xt,conversationIds:It,projectName:at})})]}),i.jsx("div",{className:"flex flex-col",children:K.ids.map(xt=>i.jsx(Ms.div,{layout:"position",transition:Jr,children:i.jsx(Va,{id:xt,conversation:C[xt],active:A===xt,locale:a,nowTick:Qe,worktreeStatus:C[xt].worktree?te[xt]:void 0,isolated:!!C[xt].worktree,menuZIndex:kn.DROPDOWN_IN_MODAL,onSelect:It=>{T(It),Re(!1)},onTogglePin:$,onToggleArchive:It=>{mn(It)},onCleanupWorktree:It=>{xn(It)},onMoveToWorktree:It=>{zn(It)},onRemove:It=>{k(It)}})},xt))})]},K.projectId)})]})]})}),i.jsx(Dee,{open:un,onOpenChange:nn,onAdd:Rt,groups:h,defaultGroupId:kt}),i.jsx(Oee,{open:tt!==null,group:tt?.mode==="edit"?h.find(K=>K.id===tt.id)??null:null,projects:de.filter(K=>!ie.includes(K.id)),onOpenChange:K=>{K||bt(null)},onSave:K=>{if(tt?.mode==="edit"){f(tt.id,K);return}const ye=p(K);for(const at of K.projectIds??[])v(at,ye.id)},onDelete:tt?.mode==="edit"?()=>{const K=tt.id;g(K),et===K&&Mt(Mn)}:void 0}),i.jsx(Gee,{open:Vt!==null,project:l.find(K=>K.id===Vt)??null,onOpenChange:K=>{K||Jt(null)}}),i.jsx(zee,{project:dn,onClose:()=>P(null)}),i.jsx(fs,{open:At!==null,onOpenChange:K=>{K||Qt(null)},title:At?.kind==="archive"?r("Archive session and clean up worktree?"):r("Clean up worktree?"),description:r("Pending work: {{warning}}. This session returns to the main working tree. The worktree directory and uncommitted changes are removed only when no other sessions use it. The branch is kept.",{warning:Kn(At?.status)}),confirmLabel:At?.kind==="archive"?r("Archive"):r("Clean up"),onConfirm:()=>{At&&Nn(At.id,At.kind==="archive")}}),i.jsx(fs,{open:en!==null,onOpenChange:K=>{K||Dn(null)},title:r("Main working tree has uncommitted changes"),description:r("The new worktree branches off HEAD, so those changes stay in the main working tree and will not follow this session."),confirmLabel:r("Move anyway"),onConfirm:()=>{if(!en)return;const K=en;Dn(null),zn(K,!0)}}),i.jsx(fs,{open:M!==null,onOpenChange:K=>{K||L(null)},title:M?.kind==="project"?r("Remove project?"):M?.kind==="archived"?r("Delete archived conversations?"):r("Delete conversation?"),description:M?.kind==="project"?r('"{{name}}" and its {{count}} conversations will be removed from the list.',{name:M.project.name,count:M.conversationIds.length}):M?.kind==="archived"?M.days===0?M.projectName?r('All {{count}} archived conversations in "{{name}}" will be removed from the list.',{count:M.conversationIds.length,name:M.projectName}):r("All {{count}} archived conversations will be removed from the list.",{count:M.conversationIds.length}):M.projectName?r('{{count}} conversations in "{{name}}" archived more than {{days}} days ago will be removed from the list.',{count:M.conversationIds.length,days:M.days,name:M.projectName}):r("{{count}} conversations archived more than {{days}} days ago will be removed from the list.",{count:M.conversationIds.length,days:M.days}):M?.kind==="conversation"&&M.worktreeWarning?r("Pending work: {{warning}}. This conversation will be removed. Its worktree directory and uncommitted changes are removed only when no other sessions use it. The branch is kept.",{warning:M.worktreeWarning}):r("This conversation will be removed from the list."),confirmLabel:r("Remove"),onConfirm:()=>{if(M)if(M.kind==="project"){for(const K of M.conversationIds)z(K);N(M.project.id)}else if(M.kind==="archived")for(const K of M.conversationIds)z(K);else z(M.id)}}),Ws.createPortal(i.jsx(cG,{dropAnimation:null,children:Le?.type==="project"?i.jsx(Jee,{projectId:Le.projectId,name:Zee(l,Le.projectId,Le.name),folded:O[Le.projectId]===!0,revealedExtra:F[Le.projectId]??0,width:e}):(Le?.type==="chat"||Le?.type==="workspace-file")&&i.jsxs("div",{className:"flex w-56 items-center gap-2 rounded-lg border bg-background/95 px-3 py-1.5 text-sm shadow-float",children:[Le.type==="workspace-file"?i.jsx(bo,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):i.jsx(di,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:Le.type==="workspace-file"?Le.name:Le.title.split(`
|
|
98
|
-
`)[0].trim()||r("New conversation")})]})}),document.body)]})}function Xee({groupId:e,name:t,emoji:n,color:s,count:o,folded:r,sortable:a,onToggle:l,onEdit:d}){const c=e===us?rv:mI(e),u=md({id:c}),h=Ah({id:c,data:{type:"project-group",groupId:e},disabled:!a}),p=f=>{u.setNodeRef(f),h.setNodeRef(f)};return i.jsxs("div",{ref:p,style:{transform:zi.Transform.toString(h.transform),transition:h.transition,opacity:h.isDragging?.4:void 0},className:q("group relative flex w-full select-none items-center rounded-md pt-3.5 pr-2.5 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground transition-colors hover:text-foreground",u.isOver&&"bg-foreground/5 text-foreground",a&&"cursor-grab"),...a?h.listeners:{},...a?h.attributes:{},children:[i.jsxs("button",{type:"button",onClick:l,onPointerDown:f=>f.stopPropagation(),className:"flex min-w-0 flex-1 items-center gap-1.5",children:[i.jsx("span",{className:"min-w-0 truncate text-left",children:t}),n&&i.jsx("span",{className:"shrink-0 text-sm leading-none",children:n}),s&&i.jsx("span",{className:"size-2 shrink-0 rounded-full",style:{backgroundColor:s}}),i.jsx(bn,{className:q("size-3 shrink-0 transition-[opacity,transform] duration-150",!r&&"rotate-90 opacity-0 group-hover:opacity-100")}),i.jsx("span",{className:q("ml-auto shrink-0 font-normal text-[0.7857rem] tabular-nums",d&&"transition-opacity group-hover:opacity-0"),children:o})]}),d&&i.jsx("button",{type:"button",onClick:f=>{f.stopPropagation(),d()},onPointerDown:f=>f.stopPropagation(),className:"absolute right-1.5 bottom-0.5 flex size-5 items-center justify-center rounded-[5px] opacity-0 transition-opacity hover:bg-foreground/5 hover:text-foreground group-hover:opacity-100 [@media(hover:none)]:opacity-100",children:i.jsx(Fs,{className:"size-3.25"})})]})}function Zee(e,t,n){const s=e.find(o=>o.id===t);return s?Po(s):n}function Jee({projectId:e,name:t,folded:n,revealedExtra:s,width:o}){const{t:r}=Q(),a=re(h=>ov(h.conversations)),l=re(h=>h.order),d=ol(l,a,e),c=n?[]:d.slice(0,Rh(d.length,s)),u=Math.max(0,d.length-c.length);return i.jsxs("div",{className:"pointer-events-none rounded-lg border bg-background/95 py-0.5 shadow-float",style:{width:o??224},children:[i.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] font-medium",children:[i.jsx(GI,{folded:n}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t})]}),!n&&i.jsxs("div",{className:"flex flex-col",children:[c.map(h=>{const p=a[h];return p?i.jsxs("div",{className:"flex h-8 items-center gap-2 px-2 text-[0.9286rem] text-foreground/88",children:[i.jsx(FI,{conversation:p}),i.jsx("span",{className:"min-w-0 truncate",children:p.title||r("New conversation")})]},h):null}),d.length>Mh&&i.jsxs("div",{className:"flex items-center gap-1",children:[u>0&&i.jsx("div",{className:"flex-1 rounded-lg py-1 text-center text-xs text-muted-foreground",children:r("Show {{n}} more",{n:u})}),s>0&&i.jsx("div",{className:"flex-1 rounded-lg py-1 text-center text-xs text-muted-foreground",children:r("Collapse")})]}),d.length===0&&i.jsx("p",{className:"py-1.5 pl-8 text-xs text-muted-foreground",children:r("No conversations yet")})]})]})}function Qee({project:e,activitySorted:t=!1,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Ah({id:fI(e.id),disabled:{droppable:t},data:{type:"project",projectId:e.id,path:e.path,name:e.name}});return n({setNodeRef:s,style:{transform:t?void 0:zi.Transform.toString(o),transition:r,opacity:l?.4:void 0},handleProps:a??{}})}function WS({open:e,onOpenChange:t,idsForDays:n,onPick:s,className:o}){const{t:r}=Q();return i.jsxs(Hi,{open:e,onOpenChange:t,children:[i.jsx(Bi,{className:q("flex h-6 w-6 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:text-destructive",e&&"opacity-100",o),title:r("Clean up archived"),"aria-label":r("Clean up archived"),children:i.jsx(Ig,{className:"h-3.5 w-3.5"})}),i.jsxs(Vi,{align:"end",className:"min-w-40",zIndex:kn.DROPDOWN_IN_MODAL,children:[Yee.map(a=>{const l=n(a);return i.jsx(pn,{variant:"destructive",disabled:l.length===0,onClick:()=>s(a,l),children:r("Older than {{days}} days",{days:a})},a)}),(()=>{const a=n(0);return i.jsx(pn,{variant:"destructive",disabled:a.length===0,onClick:()=>s(0,a),children:r("Delete all archived")})})()]})]})}function ete({id:e,conversation:t,children:n}){const{setNodeRef:s,transform:o,transition:r,listeners:a,isDragging:l}=Ah({id:gI(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return i.jsx("div",{ref:s,...a,style:{transform:zi.Transform.toString(o),transition:r,opacity:l?.4:void 0},children:n})}function US({id:e,conversation:t,children:n,dragId:s}){const{setNodeRef:o,listeners:r,isDragging:a}=Fg({id:s??PJ(e),data:{type:"chat",conversationId:e,title:t.title,sessionFile:t.sessionFile,pinned:t.pinned===!0}});return i.jsx("div",{ref:o,...r,style:{opacity:a?.4:void 0},children:n})}function KS({children:e,...t}){const{setNodeRef:n,isOver:s,active:o}=md({id:pI}),r=o?.data.current?.type==="chat";return i.jsx("div",{ref:n,className:q("rounded-lg",s&&r&&"bg-brand/8 ring-1 ring-brand/40"),...t,children:e})}function Va({id:e,conversation:t,active:n,locale:s,nowTick:o,hoverTitle:r,subtitle:a,isolated:l,worktreeStatus:d,switchHint:c,menuZIndex:u,onSelect:h,onTogglePin:p,onToggleArchive:f,onCleanupWorktree:g,onMoveToWorktree:x,onRemove:v}){const{t:y}=Q(),w=Ce(O=>O.projects.some(V=>V.id===t.projectId&&V.kind!=="ssh")),b=Ce(O=>O.projects.some(V=>V.id===t.projectId&&V.kind==="scratch")),[_,j]=m.useState(!1),N=re(O=>O.conversations[e]?.worktree),C=re(O=>!!O.conversations[e]?.workspaceMigrating),S=re(O=>O.conversations[e]?.worktreeMissing),[A,E]=m.useState(!1),[I,D]=m.useState(null),T=A||C||t.spawning||t.status==="running"||t.reloading===!0,z=async()=>{if(!T){E(!0);try{await re.getState().newConversation(t.projectId,{worktreeFromConversationId:e})||Be({type:"error",title:y("Failed to create conversation")})}catch(O){Be({type:"error",title:y("Failed to create conversation"),description:String(O)})}finally{E(!1)}}},$=t.pinned===!0,R=t.archived===!0,B=$?vu:di,H=t.title||y("New conversation"),oe=t.forkedFromConversationId?re.getState().conversations[t.forkedFromConversationId]?.title:void 0,te=i.jsxs("div",{"data-slot":"conversation-row","data-pinned":$?"true":"false",className:q("group flex h-8 cursor-pointer items-center gap-2 rounded-lg px-2 text-[0.9286rem] transition-colors",n?"bg-foreground/[0.075] text-foreground dark:bg-foreground/10":"text-foreground/88 hover:bg-foreground/5 hover:text-foreground"),onClick:()=>{_||h(e)},onDoubleClick:O=>{O.preventDefault(),O.stopPropagation(),j(!0)},onKeyDown:O=>{O.key==="Enter"&&!_&&h(e)},role:"button",tabIndex:0,title:r,children:[i.jsx(FI,{conversation:t}),i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[i.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[oe&&i.jsx("span",{className:"max-w-1/3 truncate text-[0.7857rem] text-subtle-foreground",children:y("Branched from {{title}}",{title:oe})}),_?i.jsx(bI,{title:H,onCommit:O=>{re.getState().renameConversation(e,O),j(!1)},onCancel:()=>j(!1)}):i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[H,a&&i.jsx("span",{className:"ml-1.5 text-[0.7857rem] text-subtle-foreground",children:a})]})]}),l&&N&&i.jsx(aee,{worktree:N,status:d}),i.jsx(qee,{conversationId:e}),!_&&i.jsx(tte,{pending:t.titleSummaryPending,error:t.titleSummaryError,onRetry:()=>re.getState().retryTitleSummary(e)}),!_&&(c?i.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums",children:c}):i.jsxs(i.Fragment,{children:[$&&!R&&i.jsx(di,{className:"h-3 w-3 shrink-0 text-subtle-foreground group-hover:hidden","aria-hidden":!0}),i.jsx("span",{className:"shrink-0 text-[0.7857rem] text-subtle-foreground tabular-nums group-hover:hidden",children:Oo(t.lastActiveAt??t.createdAt,s,o)}),!R&&i.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),p(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y($?"Unpin":"Pin"),children:i.jsx(B,{className:"h-3.5 w-3.5"})}),i.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),f(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-foreground",title:y(R?"Unarchive":"Archive"),children:R?i.jsx(Fl,{className:"h-3.5 w-3.5"}):i.jsx(Ii,{className:"h-3.5 w-3.5"})}),R&&i.jsx("button",{type:"button",onClick:O=>{O.stopPropagation(),v(e)},className:"hidden shrink-0 rounded p-0.5 text-muted-foreground group-hover:block hover:text-destructive",title:y("Delete"),children:i.jsx(Gs,{className:"h-3.5 w-3.5"})})]}))]})]});return i.jsxs(i.Fragment,{children:[i.jsxs(uo,{children:[i.jsx(ho,{render:te}),i.jsxs(po,{className:"min-w-36",zIndex:u,children:[i.jsxs(Ut,{onClick:()=>j(!0),children:[i.jsx(Fs,{}),y("Rename")]}),i.jsxs(Ut,{disabled:t.reloading===!0||t.spawning,onClick:()=>{wI(e,y)},children:[i.jsx(Fo,{className:t.reloading?"animate-spin":void 0}),y("Reload conversation")]}),i.jsxs(Ut,{disabled:T,onClick:()=>{nQ(e,y)},children:[i.jsx(na,{}),y("Restart conversation (reload settings)")]}),w&&i.jsxs(Ut,{disabled:C||S||d?.exists===!1,onClick:()=>{hv({projectId:t.projectId,conversationId:e},y)},children:[i.jsx(ni,{}),y(uv(window.electronAPI.env.platform))]}),!R&&i.jsxs(Ut,{onClick:()=>p(e),children:[i.jsx(B,{}),y($?"Unpin":"Pin")]}),i.jsxs(Ut,{onClick:()=>f(e),children:[R?i.jsx(Fl,{}):i.jsx(Ii,{}),y(R?"Unarchive":"Archive")]}),N&&i.jsxs(i.Fragment,{children:[i.jsxs(Ut,{disabled:T||S||d?.exists===!1,onClick:()=>{z()},children:[A?i.jsx(qt,{className:"animate-spin"}):i.jsx(Ro,{}),y("New conversation in this worktree")]}),i.jsxs(Ut,{disabled:T||S||d?.exists===!1,onClick:()=>D({conversationId:e,worktree:N}),children:[i.jsx(Fs,{}),y("Rename worktree")]})]}),!R&&(l?g&&i.jsxs(Ut,{disabled:T,onClick:()=>g(e),children:[i.jsx(Ig,{}),y("Clean up worktree")]}):x&&w&&!b&&i.jsxs(Ut,{disabled:T,onClick:()=>x(e),children:[i.jsx(g$,{}),y("Move to worktree")]})),i.jsx(Cg,{}),i.jsxs(Ut,{variant:"destructive",onClick:()=>v(e),children:[i.jsx(Gs,{}),y("Delete")]})]})]}),i.jsx(TI,{entity:I,onClose:()=>D(null)})]})}function tte({pending:e,error:t,onRetry:n}){const{t:s}=Q();return e?i.jsxs(wf,{children:[i.jsx(yf,{render:i.jsx("span",{role:"status",className:"shrink-0 text-muted-foreground/60","aria-label":s("Summarizing title")}),children:i.jsx(qt,{className:"h-3 w-3 animate-spin"})}),i.jsx(Sf,{side:"right",children:s("Summarizing title")})]}):t?i.jsxs(wf,{children:[i.jsx(yf,{render:i.jsx("button",{type:"button","aria-label":s("Title summary failed"),className:"shrink-0 rounded p-0.5 text-destructive hover:text-destructive/80",onClick:o=>{o.stopPropagation(),n()}}),children:i.jsx(gr,{className:"h-3 w-3"})}),i.jsxs(Sf,{side:"right",className:"max-w-72",children:[i.jsx("p",{className:"font-medium",children:s("Title summary failed")}),i.jsx("p",{className:"mt-0.5 break-all text-muted-foreground",children:t}),i.jsx("p",{className:"mt-1 text-muted-foreground/70",children:s("Click to retry")})]})]}):null}function qS(e,t){const n=e.find(s=>s.id===t);return n?Po(n):void 0}function Jp({emoji:e,color:t}){return e?i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-sm leading-none",children:e}):i.jsx(f$,{style:t?{color:t}:void 0})}function Ru(e,t="context"){return e.map(n=>n.kind==="separator"?t==="menu"?i.jsx(va,{},n.key):i.jsx(Cg,{},n.key):n.kind==="submenu"?t==="menu"?i.jsxs(ej,{children:[i.jsxs(tj,{children:[n.icon,n.label]}),i.jsx(nj,{className:"min-w-40",children:Ru(n.items,"menu")})]},n.key):i.jsxs(mj,{children:[i.jsxs(gj,{children:[n.icon,n.label]}),i.jsx(xj,{className:"min-w-40",children:Ru(n.items)})]},n.key):t==="menu"?i.jsxs(pn,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key):i.jsxs(Ut,{onClick:n.onSelect,variant:n.destructive?"destructive":"default",children:[n.icon,n.label]},n.key))}function nte({actions:e}){const{t}=Q();return i.jsxs(Hi,{children:[i.jsx(Bi,{"aria-label":t("More actions"),className:"shrink-0 rounded-md p-1 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 hover:bg-muted hover:text-foreground focus-visible:opacity-100 data-popup-open:bg-muted data-popup-open:text-foreground data-popup-open:opacity-100",title:t("More actions"),onPointerDown:n=>n.stopPropagation(),children:i.jsx(hh,{className:"h-3.5 w-3.5"})}),i.jsx(Vi,{align:"end",className:"min-w-40",children:Ru(e,"menu")})]})}function $a({children:e,actions:t}){return i.jsxs("div",{className:"group flex items-center gap-1 pt-3.5 pr-1 pb-1 pl-2 text-[0.8214rem] font-medium text-subtle-foreground",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate",children:e}),t]})}function GI({folded:e}){return i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-subtle-foreground",children:i.jsx(bn,{className:q("size-3.5 transition-transform duration-150",!e&&"rotate-90")})})}function FI({conversation:e}){const t=(e.pendingApprovals?.length??0)>0||(e.pendingCapabilityAsks?.length??0)>0?"attention":Dg({status:e.status,spawning:e.spawning,unread:e.unread,pendingAskCount:e.pendingAsks?.length??0,hasRunningChild:e.hasRunningChild});return i.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center",children:t!=="idle"&&i.jsx(Ph,{tone:t,size:"sm"})})}function ste(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Qp={exports:{}};const ite={},ote=Object.freeze(Object.defineProperty({__proto__:null,default:ite},Symbol.toStringTag,{value:"Module"})),rte=YL(ote);var YS;function ate(){return YS||(YS=1,(function(e){(function(t){var n=function(P){var M,L=new Float64Array(16);if(P)for(M=0;M<P.length;M++)L[M]=P[M];return L},s=function(){throw new Error("no PRNG")},o=new Uint8Array(16),r=new Uint8Array(32);r[0]=9;var a=n(),l=n([1]),d=n([56129,1]),c=n([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),u=n([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),h=n([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),p=n([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),f=n([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function g(P,M,L,k){P[M]=L>>24&255,P[M+1]=L>>16&255,P[M+2]=L>>8&255,P[M+3]=L&255,P[M+4]=k>>24&255,P[M+5]=k>>16&255,P[M+6]=k>>8&255,P[M+7]=k&255}function x(P,M,L,k,F){var he,xe=0;for(he=0;he<F;he++)xe|=P[M+he]^L[k+he];return(1&xe-1>>>8)-1}function v(P,M,L,k){return x(P,M,L,k,16)}function y(P,M,L,k){return x(P,M,L,k,32)}function w(P,M,L,k){for(var F=k[0]&255|(k[1]&255)<<8|(k[2]&255)<<16|(k[3]&255)<<24,he=L[0]&255|(L[1]&255)<<8|(L[2]&255)<<16|(L[3]&255)<<24,xe=L[4]&255|(L[5]&255)<<8|(L[6]&255)<<16|(L[7]&255)<<24,Pe=L[8]&255|(L[9]&255)<<8|(L[10]&255)<<16|(L[11]&255)<<24,Ue=L[12]&255|(L[13]&255)<<8|(L[14]&255)<<16|(L[15]&255)<<24,lt=k[4]&255|(k[5]&255)<<8|(k[6]&255)<<16|(k[7]&255)<<24,Qe=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,$t=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,rt=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,_t=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,Nt=k[8]&255|(k[9]&255)<<8|(k[10]&255)<<16|(k[11]&255)<<24,Dt=L[16]&255|(L[17]&255)<<8|(L[18]&255)<<16|(L[19]&255)<<24,yt=L[20]&255|(L[21]&255)<<8|(L[22]&255)<<16|(L[23]&255)<<24,mt=L[24]&255|(L[25]&255)<<8|(L[26]&255)<<16|(L[27]&255)<<24,St=L[28]&255|(L[29]&255)<<8|(L[30]&255)<<16|(L[31]&255)<<24,Tt=k[12]&255|(k[13]&255)<<8|(k[14]&255)<<16|(k[15]&255)<<24,ae=F,Te=he,Ae=xe,Ge=Pe,Ye=Ue,Xe=lt,we=Qe,Se=$t,Me=rt,Oe=_t,Re=Nt,Ve=Dt,Ct=yt,zt=mt,Gt=St,Ft=Tt,ee,Wt=0;Wt<20;Wt+=2)ee=ae+Ct|0,Ye^=ee<<7|ee>>>25,ee=Ye+ae|0,Me^=ee<<9|ee>>>23,ee=Me+Ye|0,Ct^=ee<<13|ee>>>19,ee=Ct+Me|0,ae^=ee<<18|ee>>>14,ee=Xe+Te|0,Oe^=ee<<7|ee>>>25,ee=Oe+Xe|0,zt^=ee<<9|ee>>>23,ee=zt+Oe|0,Te^=ee<<13|ee>>>19,ee=Te+zt|0,Xe^=ee<<18|ee>>>14,ee=Re+we|0,Gt^=ee<<7|ee>>>25,ee=Gt+Re|0,Ae^=ee<<9|ee>>>23,ee=Ae+Gt|0,we^=ee<<13|ee>>>19,ee=we+Ae|0,Re^=ee<<18|ee>>>14,ee=Ft+Ve|0,Ge^=ee<<7|ee>>>25,ee=Ge+Ft|0,Se^=ee<<9|ee>>>23,ee=Se+Ge|0,Ve^=ee<<13|ee>>>19,ee=Ve+Se|0,Ft^=ee<<18|ee>>>14,ee=ae+Ge|0,Te^=ee<<7|ee>>>25,ee=Te+ae|0,Ae^=ee<<9|ee>>>23,ee=Ae+Te|0,Ge^=ee<<13|ee>>>19,ee=Ge+Ae|0,ae^=ee<<18|ee>>>14,ee=Xe+Ye|0,we^=ee<<7|ee>>>25,ee=we+Xe|0,Se^=ee<<9|ee>>>23,ee=Se+we|0,Ye^=ee<<13|ee>>>19,ee=Ye+Se|0,Xe^=ee<<18|ee>>>14,ee=Re+Oe|0,Ve^=ee<<7|ee>>>25,ee=Ve+Re|0,Me^=ee<<9|ee>>>23,ee=Me+Ve|0,Oe^=ee<<13|ee>>>19,ee=Oe+Me|0,Re^=ee<<18|ee>>>14,ee=Ft+Gt|0,Ct^=ee<<7|ee>>>25,ee=Ct+Ft|0,zt^=ee<<9|ee>>>23,ee=zt+Ct|0,Gt^=ee<<13|ee>>>19,ee=Gt+zt|0,Ft^=ee<<18|ee>>>14;ae=ae+F|0,Te=Te+he|0,Ae=Ae+xe|0,Ge=Ge+Pe|0,Ye=Ye+Ue|0,Xe=Xe+lt|0,we=we+Qe|0,Se=Se+$t|0,Me=Me+rt|0,Oe=Oe+_t|0,Re=Re+Nt|0,Ve=Ve+Dt|0,Ct=Ct+yt|0,zt=zt+mt|0,Gt=Gt+St|0,Ft=Ft+Tt|0,P[0]=ae>>>0&255,P[1]=ae>>>8&255,P[2]=ae>>>16&255,P[3]=ae>>>24&255,P[4]=Te>>>0&255,P[5]=Te>>>8&255,P[6]=Te>>>16&255,P[7]=Te>>>24&255,P[8]=Ae>>>0&255,P[9]=Ae>>>8&255,P[10]=Ae>>>16&255,P[11]=Ae>>>24&255,P[12]=Ge>>>0&255,P[13]=Ge>>>8&255,P[14]=Ge>>>16&255,P[15]=Ge>>>24&255,P[16]=Ye>>>0&255,P[17]=Ye>>>8&255,P[18]=Ye>>>16&255,P[19]=Ye>>>24&255,P[20]=Xe>>>0&255,P[21]=Xe>>>8&255,P[22]=Xe>>>16&255,P[23]=Xe>>>24&255,P[24]=we>>>0&255,P[25]=we>>>8&255,P[26]=we>>>16&255,P[27]=we>>>24&255,P[28]=Se>>>0&255,P[29]=Se>>>8&255,P[30]=Se>>>16&255,P[31]=Se>>>24&255,P[32]=Me>>>0&255,P[33]=Me>>>8&255,P[34]=Me>>>16&255,P[35]=Me>>>24&255,P[36]=Oe>>>0&255,P[37]=Oe>>>8&255,P[38]=Oe>>>16&255,P[39]=Oe>>>24&255,P[40]=Re>>>0&255,P[41]=Re>>>8&255,P[42]=Re>>>16&255,P[43]=Re>>>24&255,P[44]=Ve>>>0&255,P[45]=Ve>>>8&255,P[46]=Ve>>>16&255,P[47]=Ve>>>24&255,P[48]=Ct>>>0&255,P[49]=Ct>>>8&255,P[50]=Ct>>>16&255,P[51]=Ct>>>24&255,P[52]=zt>>>0&255,P[53]=zt>>>8&255,P[54]=zt>>>16&255,P[55]=zt>>>24&255,P[56]=Gt>>>0&255,P[57]=Gt>>>8&255,P[58]=Gt>>>16&255,P[59]=Gt>>>24&255,P[60]=Ft>>>0&255,P[61]=Ft>>>8&255,P[62]=Ft>>>16&255,P[63]=Ft>>>24&255}function b(P,M,L,k){for(var F=k[0]&255|(k[1]&255)<<8|(k[2]&255)<<16|(k[3]&255)<<24,he=L[0]&255|(L[1]&255)<<8|(L[2]&255)<<16|(L[3]&255)<<24,xe=L[4]&255|(L[5]&255)<<8|(L[6]&255)<<16|(L[7]&255)<<24,Pe=L[8]&255|(L[9]&255)<<8|(L[10]&255)<<16|(L[11]&255)<<24,Ue=L[12]&255|(L[13]&255)<<8|(L[14]&255)<<16|(L[15]&255)<<24,lt=k[4]&255|(k[5]&255)<<8|(k[6]&255)<<16|(k[7]&255)<<24,Qe=M[0]&255|(M[1]&255)<<8|(M[2]&255)<<16|(M[3]&255)<<24,$t=M[4]&255|(M[5]&255)<<8|(M[6]&255)<<16|(M[7]&255)<<24,rt=M[8]&255|(M[9]&255)<<8|(M[10]&255)<<16|(M[11]&255)<<24,_t=M[12]&255|(M[13]&255)<<8|(M[14]&255)<<16|(M[15]&255)<<24,Nt=k[8]&255|(k[9]&255)<<8|(k[10]&255)<<16|(k[11]&255)<<24,Dt=L[16]&255|(L[17]&255)<<8|(L[18]&255)<<16|(L[19]&255)<<24,yt=L[20]&255|(L[21]&255)<<8|(L[22]&255)<<16|(L[23]&255)<<24,mt=L[24]&255|(L[25]&255)<<8|(L[26]&255)<<16|(L[27]&255)<<24,St=L[28]&255|(L[29]&255)<<8|(L[30]&255)<<16|(L[31]&255)<<24,Tt=k[12]&255|(k[13]&255)<<8|(k[14]&255)<<16|(k[15]&255)<<24,ae=F,Te=he,Ae=xe,Ge=Pe,Ye=Ue,Xe=lt,we=Qe,Se=$t,Me=rt,Oe=_t,Re=Nt,Ve=Dt,Ct=yt,zt=mt,Gt=St,Ft=Tt,ee,Wt=0;Wt<20;Wt+=2)ee=ae+Ct|0,Ye^=ee<<7|ee>>>25,ee=Ye+ae|0,Me^=ee<<9|ee>>>23,ee=Me+Ye|0,Ct^=ee<<13|ee>>>19,ee=Ct+Me|0,ae^=ee<<18|ee>>>14,ee=Xe+Te|0,Oe^=ee<<7|ee>>>25,ee=Oe+Xe|0,zt^=ee<<9|ee>>>23,ee=zt+Oe|0,Te^=ee<<13|ee>>>19,ee=Te+zt|0,Xe^=ee<<18|ee>>>14,ee=Re+we|0,Gt^=ee<<7|ee>>>25,ee=Gt+Re|0,Ae^=ee<<9|ee>>>23,ee=Ae+Gt|0,we^=ee<<13|ee>>>19,ee=we+Ae|0,Re^=ee<<18|ee>>>14,ee=Ft+Ve|0,Ge^=ee<<7|ee>>>25,ee=Ge+Ft|0,Se^=ee<<9|ee>>>23,ee=Se+Ge|0,Ve^=ee<<13|ee>>>19,ee=Ve+Se|0,Ft^=ee<<18|ee>>>14,ee=ae+Ge|0,Te^=ee<<7|ee>>>25,ee=Te+ae|0,Ae^=ee<<9|ee>>>23,ee=Ae+Te|0,Ge^=ee<<13|ee>>>19,ee=Ge+Ae|0,ae^=ee<<18|ee>>>14,ee=Xe+Ye|0,we^=ee<<7|ee>>>25,ee=we+Xe|0,Se^=ee<<9|ee>>>23,ee=Se+we|0,Ye^=ee<<13|ee>>>19,ee=Ye+Se|0,Xe^=ee<<18|ee>>>14,ee=Re+Oe|0,Ve^=ee<<7|ee>>>25,ee=Ve+Re|0,Me^=ee<<9|ee>>>23,ee=Me+Ve|0,Oe^=ee<<13|ee>>>19,ee=Oe+Me|0,Re^=ee<<18|ee>>>14,ee=Ft+Gt|0,Ct^=ee<<7|ee>>>25,ee=Ct+Ft|0,zt^=ee<<9|ee>>>23,ee=zt+Ct|0,Gt^=ee<<13|ee>>>19,ee=Gt+zt|0,Ft^=ee<<18|ee>>>14;P[0]=ae>>>0&255,P[1]=ae>>>8&255,P[2]=ae>>>16&255,P[3]=ae>>>24&255,P[4]=Xe>>>0&255,P[5]=Xe>>>8&255,P[6]=Xe>>>16&255,P[7]=Xe>>>24&255,P[8]=Re>>>0&255,P[9]=Re>>>8&255,P[10]=Re>>>16&255,P[11]=Re>>>24&255,P[12]=Ft>>>0&255,P[13]=Ft>>>8&255,P[14]=Ft>>>16&255,P[15]=Ft>>>24&255,P[16]=we>>>0&255,P[17]=we>>>8&255,P[18]=we>>>16&255,P[19]=we>>>24&255,P[20]=Se>>>0&255,P[21]=Se>>>8&255,P[22]=Se>>>16&255,P[23]=Se>>>24&255,P[24]=Me>>>0&255,P[25]=Me>>>8&255,P[26]=Me>>>16&255,P[27]=Me>>>24&255,P[28]=Oe>>>0&255,P[29]=Oe>>>8&255,P[30]=Oe>>>16&255,P[31]=Oe>>>24&255}function _(P,M,L,k){w(P,M,L,k)}function j(P,M,L,k){b(P,M,L,k)}var N=new Uint8Array([101,120,112,97,110,100,32,51,50,45,98,121,116,101,32,107]);function C(P,M,L,k,F,he,xe){var Pe=new Uint8Array(16),Ue=new Uint8Array(64),lt,Qe;for(Qe=0;Qe<16;Qe++)Pe[Qe]=0;for(Qe=0;Qe<8;Qe++)Pe[Qe]=he[Qe];for(;F>=64;){for(_(Ue,Pe,xe,N),Qe=0;Qe<64;Qe++)P[M+Qe]=L[k+Qe]^Ue[Qe];for(lt=1,Qe=8;Qe<16;Qe++)lt=lt+(Pe[Qe]&255)|0,Pe[Qe]=lt&255,lt>>>=8;F-=64,M+=64,k+=64}if(F>0)for(_(Ue,Pe,xe,N),Qe=0;Qe<F;Qe++)P[M+Qe]=L[k+Qe]^Ue[Qe];return 0}function S(P,M,L,k,F){var he=new Uint8Array(16),xe=new Uint8Array(64),Pe,Ue;for(Ue=0;Ue<16;Ue++)he[Ue]=0;for(Ue=0;Ue<8;Ue++)he[Ue]=k[Ue];for(;L>=64;){for(_(xe,he,F,N),Ue=0;Ue<64;Ue++)P[M+Ue]=xe[Ue];for(Pe=1,Ue=8;Ue<16;Ue++)Pe=Pe+(he[Ue]&255)|0,he[Ue]=Pe&255,Pe>>>=8;L-=64,M+=64}if(L>0)for(_(xe,he,F,N),Ue=0;Ue<L;Ue++)P[M+Ue]=xe[Ue];return 0}function A(P,M,L,k,F){var he=new Uint8Array(32);j(he,k,F,N);for(var xe=new Uint8Array(8),Pe=0;Pe<8;Pe++)xe[Pe]=k[Pe+16];return S(P,M,L,xe,he)}function E(P,M,L,k,F,he,xe){var Pe=new Uint8Array(32);j(Pe,he,xe,N);for(var Ue=new Uint8Array(8),lt=0;lt<8;lt++)Ue[lt]=he[lt+16];return C(P,M,L,k,F,Ue,Pe)}var I=function(P){this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.leftover=0,this.fin=0;var M,L,k,F,he,xe,Pe,Ue;M=P[0]&255|(P[1]&255)<<8,this.r[0]=M&8191,L=P[2]&255|(P[3]&255)<<8,this.r[1]=(M>>>13|L<<3)&8191,k=P[4]&255|(P[5]&255)<<8,this.r[2]=(L>>>10|k<<6)&7939,F=P[6]&255|(P[7]&255)<<8,this.r[3]=(k>>>7|F<<9)&8191,he=P[8]&255|(P[9]&255)<<8,this.r[4]=(F>>>4|he<<12)&255,this.r[5]=he>>>1&8190,xe=P[10]&255|(P[11]&255)<<8,this.r[6]=(he>>>14|xe<<2)&8191,Pe=P[12]&255|(P[13]&255)<<8,this.r[7]=(xe>>>11|Pe<<5)&8065,Ue=P[14]&255|(P[15]&255)<<8,this.r[8]=(Pe>>>8|Ue<<8)&8191,this.r[9]=Ue>>>5&127,this.pad[0]=P[16]&255|(P[17]&255)<<8,this.pad[1]=P[18]&255|(P[19]&255)<<8,this.pad[2]=P[20]&255|(P[21]&255)<<8,this.pad[3]=P[22]&255|(P[23]&255)<<8,this.pad[4]=P[24]&255|(P[25]&255)<<8,this.pad[5]=P[26]&255|(P[27]&255)<<8,this.pad[6]=P[28]&255|(P[29]&255)<<8,this.pad[7]=P[30]&255|(P[31]&255)<<8};I.prototype.blocks=function(P,M,L){for(var k=this.fin?0:2048,F,he,xe,Pe,Ue,lt,Qe,$t,rt,_t,Nt,Dt,yt,mt,St,Tt,ae,Te,Ae,Ge=this.h[0],Ye=this.h[1],Xe=this.h[2],we=this.h[3],Se=this.h[4],Me=this.h[5],Oe=this.h[6],Re=this.h[7],Ve=this.h[8],Ct=this.h[9],zt=this.r[0],Gt=this.r[1],Ft=this.r[2],ee=this.r[3],Wt=this.r[4],Zt=this.r[5],sn=this.r[6],At=this.r[7],Qt=this.r[8],en=this.r[9];L>=16;)F=P[M+0]&255|(P[M+1]&255)<<8,Ge+=F&8191,he=P[M+2]&255|(P[M+3]&255)<<8,Ye+=(F>>>13|he<<3)&8191,xe=P[M+4]&255|(P[M+5]&255)<<8,Xe+=(he>>>10|xe<<6)&8191,Pe=P[M+6]&255|(P[M+7]&255)<<8,we+=(xe>>>7|Pe<<9)&8191,Ue=P[M+8]&255|(P[M+9]&255)<<8,Se+=(Pe>>>4|Ue<<12)&8191,Me+=Ue>>>1&8191,lt=P[M+10]&255|(P[M+11]&255)<<8,Oe+=(Ue>>>14|lt<<2)&8191,Qe=P[M+12]&255|(P[M+13]&255)<<8,Re+=(lt>>>11|Qe<<5)&8191,$t=P[M+14]&255|(P[M+15]&255)<<8,Ve+=(Qe>>>8|$t<<8)&8191,Ct+=$t>>>5|k,rt=0,_t=rt,_t+=Ge*zt,_t+=Ye*(5*en),_t+=Xe*(5*Qt),_t+=we*(5*At),_t+=Se*(5*sn),rt=_t>>>13,_t&=8191,_t+=Me*(5*Zt),_t+=Oe*(5*Wt),_t+=Re*(5*ee),_t+=Ve*(5*Ft),_t+=Ct*(5*Gt),rt+=_t>>>13,_t&=8191,Nt=rt,Nt+=Ge*Gt,Nt+=Ye*zt,Nt+=Xe*(5*en),Nt+=we*(5*Qt),Nt+=Se*(5*At),rt=Nt>>>13,Nt&=8191,Nt+=Me*(5*sn),Nt+=Oe*(5*Zt),Nt+=Re*(5*Wt),Nt+=Ve*(5*ee),Nt+=Ct*(5*Ft),rt+=Nt>>>13,Nt&=8191,Dt=rt,Dt+=Ge*Ft,Dt+=Ye*Gt,Dt+=Xe*zt,Dt+=we*(5*en),Dt+=Se*(5*Qt),rt=Dt>>>13,Dt&=8191,Dt+=Me*(5*At),Dt+=Oe*(5*sn),Dt+=Re*(5*Zt),Dt+=Ve*(5*Wt),Dt+=Ct*(5*ee),rt+=Dt>>>13,Dt&=8191,yt=rt,yt+=Ge*ee,yt+=Ye*Ft,yt+=Xe*Gt,yt+=we*zt,yt+=Se*(5*en),rt=yt>>>13,yt&=8191,yt+=Me*(5*Qt),yt+=Oe*(5*At),yt+=Re*(5*sn),yt+=Ve*(5*Zt),yt+=Ct*(5*Wt),rt+=yt>>>13,yt&=8191,mt=rt,mt+=Ge*Wt,mt+=Ye*ee,mt+=Xe*Ft,mt+=we*Gt,mt+=Se*zt,rt=mt>>>13,mt&=8191,mt+=Me*(5*en),mt+=Oe*(5*Qt),mt+=Re*(5*At),mt+=Ve*(5*sn),mt+=Ct*(5*Zt),rt+=mt>>>13,mt&=8191,St=rt,St+=Ge*Zt,St+=Ye*Wt,St+=Xe*ee,St+=we*Ft,St+=Se*Gt,rt=St>>>13,St&=8191,St+=Me*zt,St+=Oe*(5*en),St+=Re*(5*Qt),St+=Ve*(5*At),St+=Ct*(5*sn),rt+=St>>>13,St&=8191,Tt=rt,Tt+=Ge*sn,Tt+=Ye*Zt,Tt+=Xe*Wt,Tt+=we*ee,Tt+=Se*Ft,rt=Tt>>>13,Tt&=8191,Tt+=Me*Gt,Tt+=Oe*zt,Tt+=Re*(5*en),Tt+=Ve*(5*Qt),Tt+=Ct*(5*At),rt+=Tt>>>13,Tt&=8191,ae=rt,ae+=Ge*At,ae+=Ye*sn,ae+=Xe*Zt,ae+=we*Wt,ae+=Se*ee,rt=ae>>>13,ae&=8191,ae+=Me*Ft,ae+=Oe*Gt,ae+=Re*zt,ae+=Ve*(5*en),ae+=Ct*(5*Qt),rt+=ae>>>13,ae&=8191,Te=rt,Te+=Ge*Qt,Te+=Ye*At,Te+=Xe*sn,Te+=we*Zt,Te+=Se*Wt,rt=Te>>>13,Te&=8191,Te+=Me*ee,Te+=Oe*Ft,Te+=Re*Gt,Te+=Ve*zt,Te+=Ct*(5*en),rt+=Te>>>13,Te&=8191,Ae=rt,Ae+=Ge*en,Ae+=Ye*Qt,Ae+=Xe*At,Ae+=we*sn,Ae+=Se*Zt,rt=Ae>>>13,Ae&=8191,Ae+=Me*Wt,Ae+=Oe*ee,Ae+=Re*Ft,Ae+=Ve*Gt,Ae+=Ct*zt,rt+=Ae>>>13,Ae&=8191,rt=(rt<<2)+rt|0,rt=rt+_t|0,_t=rt&8191,rt=rt>>>13,Nt+=rt,Ge=_t,Ye=Nt,Xe=Dt,we=yt,Se=mt,Me=St,Oe=Tt,Re=ae,Ve=Te,Ct=Ae,M+=16,L-=16;this.h[0]=Ge,this.h[1]=Ye,this.h[2]=Xe,this.h[3]=we,this.h[4]=Se,this.h[5]=Me,this.h[6]=Oe,this.h[7]=Re,this.h[8]=Ve,this.h[9]=Ct},I.prototype.finish=function(P,M){var L=new Uint16Array(10),k,F,he,xe;if(this.leftover){for(xe=this.leftover,this.buffer[xe++]=1;xe<16;xe++)this.buffer[xe]=0;this.fin=1,this.blocks(this.buffer,0,16)}for(k=this.h[1]>>>13,this.h[1]&=8191,xe=2;xe<10;xe++)this.h[xe]+=k,k=this.h[xe]>>>13,this.h[xe]&=8191;for(this.h[0]+=k*5,k=this.h[0]>>>13,this.h[0]&=8191,this.h[1]+=k,k=this.h[1]>>>13,this.h[1]&=8191,this.h[2]+=k,L[0]=this.h[0]+5,k=L[0]>>>13,L[0]&=8191,xe=1;xe<10;xe++)L[xe]=this.h[xe]+k,k=L[xe]>>>13,L[xe]&=8191;for(L[9]-=8192,F=(k^1)-1,xe=0;xe<10;xe++)L[xe]&=F;for(F=~F,xe=0;xe<10;xe++)this.h[xe]=this.h[xe]&F|L[xe];for(this.h[0]=(this.h[0]|this.h[1]<<13)&65535,this.h[1]=(this.h[1]>>>3|this.h[2]<<10)&65535,this.h[2]=(this.h[2]>>>6|this.h[3]<<7)&65535,this.h[3]=(this.h[3]>>>9|this.h[4]<<4)&65535,this.h[4]=(this.h[4]>>>12|this.h[5]<<1|this.h[6]<<14)&65535,this.h[5]=(this.h[6]>>>2|this.h[7]<<11)&65535,this.h[6]=(this.h[7]>>>5|this.h[8]<<8)&65535,this.h[7]=(this.h[8]>>>8|this.h[9]<<5)&65535,he=this.h[0]+this.pad[0],this.h[0]=he&65535,xe=1;xe<8;xe++)he=(this.h[xe]+this.pad[xe]|0)+(he>>>16)|0,this.h[xe]=he&65535;P[M+0]=this.h[0]>>>0&255,P[M+1]=this.h[0]>>>8&255,P[M+2]=this.h[1]>>>0&255,P[M+3]=this.h[1]>>>8&255,P[M+4]=this.h[2]>>>0&255,P[M+5]=this.h[2]>>>8&255,P[M+6]=this.h[3]>>>0&255,P[M+7]=this.h[3]>>>8&255,P[M+8]=this.h[4]>>>0&255,P[M+9]=this.h[4]>>>8&255,P[M+10]=this.h[5]>>>0&255,P[M+11]=this.h[5]>>>8&255,P[M+12]=this.h[6]>>>0&255,P[M+13]=this.h[6]>>>8&255,P[M+14]=this.h[7]>>>0&255,P[M+15]=this.h[7]>>>8&255},I.prototype.update=function(P,M,L){var k,F;if(this.leftover){for(F=16-this.leftover,F>L&&(F=L),k=0;k<F;k++)this.buffer[this.leftover+k]=P[M+k];if(L-=F,M+=F,this.leftover+=F,this.leftover<16)return;this.blocks(this.buffer,0,16),this.leftover=0}if(L>=16&&(F=L-L%16,this.blocks(P,M,F),M+=F,L-=F),L){for(k=0;k<L;k++)this.buffer[this.leftover+k]=P[M+k];this.leftover+=L}};function D(P,M,L,k,F,he){var xe=new I(he);return xe.update(L,k,F),xe.finish(P,M),0}function T(P,M,L,k,F,he){var xe=new Uint8Array(16);return D(xe,0,L,k,F,he),v(P,M,xe,0)}function z(P,M,L,k,F){var he;if(L<32)return-1;for(E(P,0,M,0,L,k,F),D(P,16,P,32,L-32,P),he=0;he<16;he++)P[he]=0;return 0}function $(P,M,L,k,F){var he,xe=new Uint8Array(32);if(L<32||(A(xe,0,32,k,F),T(M,16,M,32,L-32,xe)!==0))return-1;for(E(P,0,M,0,L,k,F),he=0;he<32;he++)P[he]=0;return 0}function R(P,M){var L;for(L=0;L<16;L++)P[L]=M[L]|0}function B(P){var M,L,k=1;for(M=0;M<16;M++)L=P[M]+k+65535,k=Math.floor(L/65536),P[M]=L-k*65536;P[0]+=k-1+37*(k-1)}function H(P,M,L){for(var k,F=~(L-1),he=0;he<16;he++)k=F&(P[he]^M[he]),P[he]^=k,M[he]^=k}function oe(P,M){var L,k,F,he=n(),xe=n();for(L=0;L<16;L++)xe[L]=M[L];for(B(xe),B(xe),B(xe),k=0;k<2;k++){for(he[0]=xe[0]-65517,L=1;L<15;L++)he[L]=xe[L]-65535-(he[L-1]>>16&1),he[L-1]&=65535;he[15]=xe[15]-32767-(he[14]>>16&1),F=he[15]>>16&1,he[14]&=65535,H(xe,he,1-F)}for(L=0;L<16;L++)P[2*L]=xe[L]&255,P[2*L+1]=xe[L]>>8}function te(P,M){var L=new Uint8Array(32),k=new Uint8Array(32);return oe(L,P),oe(k,M),y(L,0,k,0)}function O(P){var M=new Uint8Array(32);return oe(M,P),M[0]&1}function V(P,M){var L;for(L=0;L<16;L++)P[L]=M[2*L]+(M[2*L+1]<<8);P[15]&=32767}function J(P,M,L){for(var k=0;k<16;k++)P[k]=M[k]+L[k]}function pe(P,M,L){for(var k=0;k<16;k++)P[k]=M[k]-L[k]}function fe(P,M,L){var k,F,he=0,xe=0,Pe=0,Ue=0,lt=0,Qe=0,$t=0,rt=0,_t=0,Nt=0,Dt=0,yt=0,mt=0,St=0,Tt=0,ae=0,Te=0,Ae=0,Ge=0,Ye=0,Xe=0,we=0,Se=0,Me=0,Oe=0,Re=0,Ve=0,Ct=0,zt=0,Gt=0,Ft=0,ee=L[0],Wt=L[1],Zt=L[2],sn=L[3],At=L[4],Qt=L[5],en=L[6],Dn=L[7],ln=L[8],Nn=L[9],xn=L[10],mn=L[11],Hn=L[12],zn=L[13],Kn=L[14],K=L[15];k=M[0],he+=k*ee,xe+=k*Wt,Pe+=k*Zt,Ue+=k*sn,lt+=k*At,Qe+=k*Qt,$t+=k*en,rt+=k*Dn,_t+=k*ln,Nt+=k*Nn,Dt+=k*xn,yt+=k*mn,mt+=k*Hn,St+=k*zn,Tt+=k*Kn,ae+=k*K,k=M[1],xe+=k*ee,Pe+=k*Wt,Ue+=k*Zt,lt+=k*sn,Qe+=k*At,$t+=k*Qt,rt+=k*en,_t+=k*Dn,Nt+=k*ln,Dt+=k*Nn,yt+=k*xn,mt+=k*mn,St+=k*Hn,Tt+=k*zn,ae+=k*Kn,Te+=k*K,k=M[2],Pe+=k*ee,Ue+=k*Wt,lt+=k*Zt,Qe+=k*sn,$t+=k*At,rt+=k*Qt,_t+=k*en,Nt+=k*Dn,Dt+=k*ln,yt+=k*Nn,mt+=k*xn,St+=k*mn,Tt+=k*Hn,ae+=k*zn,Te+=k*Kn,Ae+=k*K,k=M[3],Ue+=k*ee,lt+=k*Wt,Qe+=k*Zt,$t+=k*sn,rt+=k*At,_t+=k*Qt,Nt+=k*en,Dt+=k*Dn,yt+=k*ln,mt+=k*Nn,St+=k*xn,Tt+=k*mn,ae+=k*Hn,Te+=k*zn,Ae+=k*Kn,Ge+=k*K,k=M[4],lt+=k*ee,Qe+=k*Wt,$t+=k*Zt,rt+=k*sn,_t+=k*At,Nt+=k*Qt,Dt+=k*en,yt+=k*Dn,mt+=k*ln,St+=k*Nn,Tt+=k*xn,ae+=k*mn,Te+=k*Hn,Ae+=k*zn,Ge+=k*Kn,Ye+=k*K,k=M[5],Qe+=k*ee,$t+=k*Wt,rt+=k*Zt,_t+=k*sn,Nt+=k*At,Dt+=k*Qt,yt+=k*en,mt+=k*Dn,St+=k*ln,Tt+=k*Nn,ae+=k*xn,Te+=k*mn,Ae+=k*Hn,Ge+=k*zn,Ye+=k*Kn,Xe+=k*K,k=M[6],$t+=k*ee,rt+=k*Wt,_t+=k*Zt,Nt+=k*sn,Dt+=k*At,yt+=k*Qt,mt+=k*en,St+=k*Dn,Tt+=k*ln,ae+=k*Nn,Te+=k*xn,Ae+=k*mn,Ge+=k*Hn,Ye+=k*zn,Xe+=k*Kn,we+=k*K,k=M[7],rt+=k*ee,_t+=k*Wt,Nt+=k*Zt,Dt+=k*sn,yt+=k*At,mt+=k*Qt,St+=k*en,Tt+=k*Dn,ae+=k*ln,Te+=k*Nn,Ae+=k*xn,Ge+=k*mn,Ye+=k*Hn,Xe+=k*zn,we+=k*Kn,Se+=k*K,k=M[8],_t+=k*ee,Nt+=k*Wt,Dt+=k*Zt,yt+=k*sn,mt+=k*At,St+=k*Qt,Tt+=k*en,ae+=k*Dn,Te+=k*ln,Ae+=k*Nn,Ge+=k*xn,Ye+=k*mn,Xe+=k*Hn,we+=k*zn,Se+=k*Kn,Me+=k*K,k=M[9],Nt+=k*ee,Dt+=k*Wt,yt+=k*Zt,mt+=k*sn,St+=k*At,Tt+=k*Qt,ae+=k*en,Te+=k*Dn,Ae+=k*ln,Ge+=k*Nn,Ye+=k*xn,Xe+=k*mn,we+=k*Hn,Se+=k*zn,Me+=k*Kn,Oe+=k*K,k=M[10],Dt+=k*ee,yt+=k*Wt,mt+=k*Zt,St+=k*sn,Tt+=k*At,ae+=k*Qt,Te+=k*en,Ae+=k*Dn,Ge+=k*ln,Ye+=k*Nn,Xe+=k*xn,we+=k*mn,Se+=k*Hn,Me+=k*zn,Oe+=k*Kn,Re+=k*K,k=M[11],yt+=k*ee,mt+=k*Wt,St+=k*Zt,Tt+=k*sn,ae+=k*At,Te+=k*Qt,Ae+=k*en,Ge+=k*Dn,Ye+=k*ln,Xe+=k*Nn,we+=k*xn,Se+=k*mn,Me+=k*Hn,Oe+=k*zn,Re+=k*Kn,Ve+=k*K,k=M[12],mt+=k*ee,St+=k*Wt,Tt+=k*Zt,ae+=k*sn,Te+=k*At,Ae+=k*Qt,Ge+=k*en,Ye+=k*Dn,Xe+=k*ln,we+=k*Nn,Se+=k*xn,Me+=k*mn,Oe+=k*Hn,Re+=k*zn,Ve+=k*Kn,Ct+=k*K,k=M[13],St+=k*ee,Tt+=k*Wt,ae+=k*Zt,Te+=k*sn,Ae+=k*At,Ge+=k*Qt,Ye+=k*en,Xe+=k*Dn,we+=k*ln,Se+=k*Nn,Me+=k*xn,Oe+=k*mn,Re+=k*Hn,Ve+=k*zn,Ct+=k*Kn,zt+=k*K,k=M[14],Tt+=k*ee,ae+=k*Wt,Te+=k*Zt,Ae+=k*sn,Ge+=k*At,Ye+=k*Qt,Xe+=k*en,we+=k*Dn,Se+=k*ln,Me+=k*Nn,Oe+=k*xn,Re+=k*mn,Ve+=k*Hn,Ct+=k*zn,zt+=k*Kn,Gt+=k*K,k=M[15],ae+=k*ee,Te+=k*Wt,Ae+=k*Zt,Ge+=k*sn,Ye+=k*At,Xe+=k*Qt,we+=k*en,Se+=k*Dn,Me+=k*ln,Oe+=k*Nn,Re+=k*xn,Ve+=k*mn,Ct+=k*Hn,zt+=k*zn,Gt+=k*Kn,Ft+=k*K,he+=38*Te,xe+=38*Ae,Pe+=38*Ge,Ue+=38*Ye,lt+=38*Xe,Qe+=38*we,$t+=38*Se,rt+=38*Me,_t+=38*Oe,Nt+=38*Re,Dt+=38*Ve,yt+=38*Ct,mt+=38*zt,St+=38*Gt,Tt+=38*Ft,F=1,k=he+F+65535,F=Math.floor(k/65536),he=k-F*65536,k=xe+F+65535,F=Math.floor(k/65536),xe=k-F*65536,k=Pe+F+65535,F=Math.floor(k/65536),Pe=k-F*65536,k=Ue+F+65535,F=Math.floor(k/65536),Ue=k-F*65536,k=lt+F+65535,F=Math.floor(k/65536),lt=k-F*65536,k=Qe+F+65535,F=Math.floor(k/65536),Qe=k-F*65536,k=$t+F+65535,F=Math.floor(k/65536),$t=k-F*65536,k=rt+F+65535,F=Math.floor(k/65536),rt=k-F*65536,k=_t+F+65535,F=Math.floor(k/65536),_t=k-F*65536,k=Nt+F+65535,F=Math.floor(k/65536),Nt=k-F*65536,k=Dt+F+65535,F=Math.floor(k/65536),Dt=k-F*65536,k=yt+F+65535,F=Math.floor(k/65536),yt=k-F*65536,k=mt+F+65535,F=Math.floor(k/65536),mt=k-F*65536,k=St+F+65535,F=Math.floor(k/65536),St=k-F*65536,k=Tt+F+65535,F=Math.floor(k/65536),Tt=k-F*65536,k=ae+F+65535,F=Math.floor(k/65536),ae=k-F*65536,he+=F-1+37*(F-1),F=1,k=he+F+65535,F=Math.floor(k/65536),he=k-F*65536,k=xe+F+65535,F=Math.floor(k/65536),xe=k-F*65536,k=Pe+F+65535,F=Math.floor(k/65536),Pe=k-F*65536,k=Ue+F+65535,F=Math.floor(k/65536),Ue=k-F*65536,k=lt+F+65535,F=Math.floor(k/65536),lt=k-F*65536,k=Qe+F+65535,F=Math.floor(k/65536),Qe=k-F*65536,k=$t+F+65535,F=Math.floor(k/65536),$t=k-F*65536,k=rt+F+65535,F=Math.floor(k/65536),rt=k-F*65536,k=_t+F+65535,F=Math.floor(k/65536),_t=k-F*65536,k=Nt+F+65535,F=Math.floor(k/65536),Nt=k-F*65536,k=Dt+F+65535,F=Math.floor(k/65536),Dt=k-F*65536,k=yt+F+65535,F=Math.floor(k/65536),yt=k-F*65536,k=mt+F+65535,F=Math.floor(k/65536),mt=k-F*65536,k=St+F+65535,F=Math.floor(k/65536),St=k-F*65536,k=Tt+F+65535,F=Math.floor(k/65536),Tt=k-F*65536,k=ae+F+65535,F=Math.floor(k/65536),ae=k-F*65536,he+=F-1+37*(F-1),P[0]=he,P[1]=xe,P[2]=Pe,P[3]=Ue,P[4]=lt,P[5]=Qe,P[6]=$t,P[7]=rt,P[8]=_t,P[9]=Nt,P[10]=Dt,P[11]=yt,P[12]=mt,P[13]=St,P[14]=Tt,P[15]=ae}function _e(P,M){fe(P,M,M)}function Ee(P,M){var L=n(),k;for(k=0;k<16;k++)L[k]=M[k];for(k=253;k>=0;k--)_e(L,L),k!==2&&k!==4&&fe(L,L,M);for(k=0;k<16;k++)P[k]=L[k]}function me(P,M){var L=n(),k;for(k=0;k<16;k++)L[k]=M[k];for(k=250;k>=0;k--)_e(L,L),k!==1&&fe(L,L,M);for(k=0;k<16;k++)P[k]=L[k]}function W(P,M,L){var k=new Uint8Array(32),F=new Float64Array(80),he,xe,Pe=n(),Ue=n(),lt=n(),Qe=n(),$t=n(),rt=n();for(xe=0;xe<31;xe++)k[xe]=M[xe];for(k[31]=M[31]&127|64,k[0]&=248,V(F,L),xe=0;xe<16;xe++)Ue[xe]=F[xe],Qe[xe]=Pe[xe]=lt[xe]=0;for(Pe[0]=Qe[0]=1,xe=254;xe>=0;--xe)he=k[xe>>>3]>>>(xe&7)&1,H(Pe,Ue,he),H(lt,Qe,he),J($t,Pe,lt),pe(Pe,Pe,lt),J(lt,Ue,Qe),pe(Ue,Ue,Qe),_e(Qe,$t),_e(rt,Pe),fe(Pe,lt,Pe),fe(lt,Ue,$t),J($t,Pe,lt),pe(Pe,Pe,lt),_e(Ue,Pe),pe(lt,Qe,rt),fe(Pe,lt,d),J(Pe,Pe,Qe),fe(lt,lt,Pe),fe(Pe,Qe,rt),fe(Qe,Ue,F),_e(Ue,$t),H(Pe,Ue,he),H(lt,Qe,he);for(xe=0;xe<16;xe++)F[xe+16]=Pe[xe],F[xe+32]=lt[xe],F[xe+48]=Ue[xe],F[xe+64]=Qe[xe];var _t=F.subarray(32),Nt=F.subarray(16);return Ee(_t,_t),fe(Nt,Nt,_t),oe(P,Nt),0}function G(P,M){return W(P,M,r)}function de(P,M){return s(M,32),G(P,M)}function X(P,M,L){var k=new Uint8Array(32);return W(k,L,M),j(P,o,k,N)}var ie=z,Z=$;function le(P,M,L,k,F,he){var xe=new Uint8Array(32);return X(xe,F,he),ie(P,M,L,k,xe)}function be(P,M,L,k,F,he){var xe=new Uint8Array(32);return X(xe,F,he),Z(P,M,L,k,xe)}var Fe=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591];function Je(P,M,L,k){for(var F=new Int32Array(16),he=new Int32Array(16),xe,Pe,Ue,lt,Qe,$t,rt,_t,Nt,Dt,yt,mt,St,Tt,ae,Te,Ae,Ge,Ye,Xe,we,Se,Me,Oe,Re,Ve,Ct=P[0],zt=P[1],Gt=P[2],Ft=P[3],ee=P[4],Wt=P[5],Zt=P[6],sn=P[7],At=M[0],Qt=M[1],en=M[2],Dn=M[3],ln=M[4],Nn=M[5],xn=M[6],mn=M[7],Hn=0;k>=128;){for(Ye=0;Ye<16;Ye++)Xe=8*Ye+Hn,F[Ye]=L[Xe+0]<<24|L[Xe+1]<<16|L[Xe+2]<<8|L[Xe+3],he[Ye]=L[Xe+4]<<24|L[Xe+5]<<16|L[Xe+6]<<8|L[Xe+7];for(Ye=0;Ye<80;Ye++)if(xe=Ct,Pe=zt,Ue=Gt,lt=Ft,Qe=ee,$t=Wt,rt=Zt,_t=sn,Nt=At,Dt=Qt,yt=en,mt=Dn,St=ln,Tt=Nn,ae=xn,Te=mn,we=sn,Se=mn,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=(ee>>>14|ln<<18)^(ee>>>18|ln<<14)^(ln>>>9|ee<<23),Se=(ln>>>14|ee<<18)^(ln>>>18|ee<<14)^(ee>>>9|ln<<23),Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,we=ee&Wt^~ee&Zt,Se=ln&Nn^~ln&xn,Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,we=Fe[Ye*2],Se=Fe[Ye*2+1],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,we=F[Ye%16],Se=he[Ye%16],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,Ae=Re&65535|Ve<<16,Ge=Me&65535|Oe<<16,we=Ae,Se=Ge,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=(Ct>>>28|At<<4)^(At>>>2|Ct<<30)^(At>>>7|Ct<<25),Se=(At>>>28|Ct<<4)^(Ct>>>2|At<<30)^(Ct>>>7|At<<25),Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,we=Ct&zt^Ct&Gt^zt&Gt,Se=At&Qt^At&en^Qt&en,Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,_t=Re&65535|Ve<<16,Te=Me&65535|Oe<<16,we=lt,Se=mt,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=Ae,Se=Ge,Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,lt=Re&65535|Ve<<16,mt=Me&65535|Oe<<16,zt=xe,Gt=Pe,Ft=Ue,ee=lt,Wt=Qe,Zt=$t,sn=rt,Ct=_t,Qt=Nt,en=Dt,Dn=yt,ln=mt,Nn=St,xn=Tt,mn=ae,At=Te,Ye%16===15)for(Xe=0;Xe<16;Xe++)we=F[Xe],Se=he[Xe],Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=F[(Xe+9)%16],Se=he[(Xe+9)%16],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Ae=F[(Xe+1)%16],Ge=he[(Xe+1)%16],we=(Ae>>>1|Ge<<31)^(Ae>>>8|Ge<<24)^Ae>>>7,Se=(Ge>>>1|Ae<<31)^(Ge>>>8|Ae<<24)^(Ge>>>7|Ae<<25),Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Ae=F[(Xe+14)%16],Ge=he[(Xe+14)%16],we=(Ae>>>19|Ge<<13)^(Ge>>>29|Ae<<3)^Ae>>>6,Se=(Ge>>>19|Ae<<13)^(Ae>>>29|Ge<<3)^(Ge>>>6|Ae<<26),Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,F[Xe]=Re&65535|Ve<<16,he[Xe]=Me&65535|Oe<<16;we=Ct,Se=At,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[0],Se=M[0],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[0]=Ct=Re&65535|Ve<<16,M[0]=At=Me&65535|Oe<<16,we=zt,Se=Qt,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[1],Se=M[1],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[1]=zt=Re&65535|Ve<<16,M[1]=Qt=Me&65535|Oe<<16,we=Gt,Se=en,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[2],Se=M[2],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[2]=Gt=Re&65535|Ve<<16,M[2]=en=Me&65535|Oe<<16,we=Ft,Se=Dn,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[3],Se=M[3],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[3]=Ft=Re&65535|Ve<<16,M[3]=Dn=Me&65535|Oe<<16,we=ee,Se=ln,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[4],Se=M[4],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[4]=ee=Re&65535|Ve<<16,M[4]=ln=Me&65535|Oe<<16,we=Wt,Se=Nn,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[5],Se=M[5],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[5]=Wt=Re&65535|Ve<<16,M[5]=Nn=Me&65535|Oe<<16,we=Zt,Se=xn,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[6],Se=M[6],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[6]=Zt=Re&65535|Ve<<16,M[6]=xn=Me&65535|Oe<<16,we=sn,Se=mn,Me=Se&65535,Oe=Se>>>16,Re=we&65535,Ve=we>>>16,we=P[7],Se=M[7],Me+=Se&65535,Oe+=Se>>>16,Re+=we&65535,Ve+=we>>>16,Oe+=Me>>>16,Re+=Oe>>>16,Ve+=Re>>>16,P[7]=sn=Re&65535|Ve<<16,M[7]=mn=Me&65535|Oe<<16,Hn+=128,k-=128}return k}function We(P,M,L){var k=new Int32Array(8),F=new Int32Array(8),he=new Uint8Array(256),xe,Pe=L;for(k[0]=1779033703,k[1]=3144134277,k[2]=1013904242,k[3]=2773480762,k[4]=1359893119,k[5]=2600822924,k[6]=528734635,k[7]=1541459225,F[0]=4089235720,F[1]=2227873595,F[2]=4271175723,F[3]=1595750129,F[4]=2917565137,F[5]=725511199,F[6]=4215389547,F[7]=327033209,Je(k,F,M,L),L%=128,xe=0;xe<L;xe++)he[xe]=M[Pe-L+xe];for(he[L]=128,L=256-128*(L<112?1:0),he[L-9]=0,g(he,L-8,Pe/536870912|0,Pe<<3),Je(k,F,he,L),xe=0;xe<8;xe++)g(P,8*xe,k[xe],F[xe]);return 0}function et(P,M){var L=n(),k=n(),F=n(),he=n(),xe=n(),Pe=n(),Ue=n(),lt=n(),Qe=n();pe(L,P[1],P[0]),pe(Qe,M[1],M[0]),fe(L,L,Qe),J(k,P[0],P[1]),J(Qe,M[0],M[1]),fe(k,k,Qe),fe(F,P[3],M[3]),fe(F,F,u),fe(he,P[2],M[2]),J(he,he,he),pe(xe,k,L),pe(Pe,he,F),J(Ue,he,F),J(lt,k,L),fe(P[0],xe,Pe),fe(P[1],lt,Ue),fe(P[2],Ue,Pe),fe(P[3],xe,lt)}function qe(P,M,L){var k;for(k=0;k<4;k++)H(P[k],M[k],L)}function Lt(P,M){var L=n(),k=n(),F=n();Ee(F,M[2]),fe(L,M[0],F),fe(k,M[1],F),oe(P,k),P[31]^=O(L)<<7}function Bt(P,M,L){var k,F;for(R(P[0],a),R(P[1],l),R(P[2],l),R(P[3],a),F=255;F>=0;--F)k=L[F/8|0]>>(F&7)&1,qe(P,M,k),et(M,P),et(P,P),qe(P,M,k)}function Mt(P,M){var L=[n(),n(),n(),n()];R(L[0],h),R(L[1],p),R(L[2],l),fe(L[3],h,p),Bt(P,L,M)}function ne(P,M,L){var k=new Uint8Array(64),F=[n(),n(),n(),n()],he;for(L||s(M,32),We(k,M,32),k[0]&=248,k[31]&=127,k[31]|=64,Mt(F,k),Lt(P,F),he=0;he<32;he++)M[he+32]=P[he];return 0}var se=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]);function He(P,M){var L,k,F,he;for(k=63;k>=32;--k){for(L=0,F=k-32,he=k-12;F<he;++F)M[F]+=L-16*M[k]*se[F-(k-32)],L=Math.floor((M[F]+128)/256),M[F]-=L*256;M[F]+=L,M[k]=0}for(L=0,F=0;F<32;F++)M[F]+=L-(M[31]>>4)*se[F],L=M[F]>>8,M[F]&=255;for(F=0;F<32;F++)M[F]-=L*se[F];for(k=0;k<32;k++)M[k+1]+=M[k]>>8,P[k]=M[k]&255}function kt(P){var M=new Float64Array(64),L;for(L=0;L<64;L++)M[L]=P[L];for(L=0;L<64;L++)P[L]=0;He(P,M)}function st(P,M,L,k){var F=new Uint8Array(64),he=new Uint8Array(64),xe=new Uint8Array(64),Pe,Ue,lt=new Float64Array(64),Qe=[n(),n(),n(),n()];We(F,k,32),F[0]&=248,F[31]&=127,F[31]|=64;var $t=L+64;for(Pe=0;Pe<L;Pe++)P[64+Pe]=M[Pe];for(Pe=0;Pe<32;Pe++)P[32+Pe]=F[32+Pe];for(We(xe,P.subarray(32),L+32),kt(xe),Mt(Qe,xe),Lt(P,Qe),Pe=32;Pe<64;Pe++)P[Pe]=k[Pe];for(We(he,P,L+64),kt(he),Pe=0;Pe<64;Pe++)lt[Pe]=0;for(Pe=0;Pe<32;Pe++)lt[Pe]=xe[Pe];for(Pe=0;Pe<32;Pe++)for(Ue=0;Ue<32;Ue++)lt[Pe+Ue]+=he[Pe]*F[Ue];return He(P.subarray(32),lt),$t}function ke(P,M){var L=n(),k=n(),F=n(),he=n(),xe=n(),Pe=n(),Ue=n();return R(P[2],l),V(P[1],M),_e(F,P[1]),fe(he,F,c),pe(F,F,P[2]),J(he,P[2],he),_e(xe,he),_e(Pe,xe),fe(Ue,Pe,xe),fe(L,Ue,F),fe(L,L,he),me(L,L),fe(L,L,F),fe(L,L,he),fe(L,L,he),fe(P[0],L,he),_e(k,P[0]),fe(k,k,he),te(k,F)&&fe(P[0],P[0],f),_e(k,P[0]),fe(k,k,he),te(k,F)?-1:(O(P[0])===M[31]>>7&&pe(P[0],a,P[0]),fe(P[3],P[0],P[1]),0)}function ut(P,M,L,k){var F,he=new Uint8Array(32),xe=new Uint8Array(64),Pe=[n(),n(),n(),n()],Ue=[n(),n(),n(),n()];if(L<64||ke(Ue,k))return-1;for(F=0;F<L;F++)P[F]=M[F];for(F=0;F<32;F++)P[F+32]=k[F];if(We(xe,P,L),kt(xe),Bt(Pe,Ue,xe),Mt(Ue,M.subarray(32)),et(Pe,Ue),Lt(he,Pe),L-=64,y(M,0,he,0)){for(F=0;F<L;F++)P[F]=0;return-1}for(F=0;F<L;F++)P[F]=M[F+64];return L}var ft=32,ze=24,wt=32,Y=16,U=32,ue=32,je=32,De=32,Le=32,tt=ze,bt=wt,Vt=Y,Jt=64,un=32,nn=64,Ie=32,it=64;t.lowlevel={crypto_core_hsalsa20:j,crypto_stream_xor:E,crypto_stream:A,crypto_stream_salsa20_xor:C,crypto_stream_salsa20:S,crypto_onetimeauth:D,crypto_onetimeauth_verify:T,crypto_verify_16:v,crypto_verify_32:y,crypto_secretbox:z,crypto_secretbox_open:$,crypto_scalarmult:W,crypto_scalarmult_base:G,crypto_box_beforenm:X,crypto_box_afternm:ie,crypto_box:le,crypto_box_open:be,crypto_box_keypair:de,crypto_hash:We,crypto_sign:st,crypto_sign_keypair:ne,crypto_sign_open:ut,crypto_secretbox_KEYBYTES:ft,crypto_secretbox_NONCEBYTES:ze,crypto_secretbox_ZEROBYTES:wt,crypto_secretbox_BOXZEROBYTES:Y,crypto_scalarmult_BYTES:U,crypto_scalarmult_SCALARBYTES:ue,crypto_box_PUBLICKEYBYTES:je,crypto_box_SECRETKEYBYTES:De,crypto_box_BEFORENMBYTES:Le,crypto_box_NONCEBYTES:tt,crypto_box_ZEROBYTES:bt,crypto_box_BOXZEROBYTES:Vt,crypto_sign_BYTES:Jt,crypto_sign_PUBLICKEYBYTES:un,crypto_sign_SECRETKEYBYTES:nn,crypto_sign_SEEDBYTES:Ie,crypto_hash_BYTES:it,gf:n,D:c,L:se,pack25519:oe,unpack25519:V,M:fe,A:J,S:_e,Z:pe,pow2523:me,add:et,set25519:R,modL:He,scalarmult:Bt,scalarbase:Mt};function dt(P,M){if(P.length!==ft)throw new Error("bad key size");if(M.length!==ze)throw new Error("bad nonce size")}function jt(P,M){if(P.length!==je)throw new Error("bad public key size");if(M.length!==De)throw new Error("bad secret key size")}function Rt(){for(var P=0;P<arguments.length;P++)if(!(arguments[P]instanceof Uint8Array))throw new TypeError("unexpected type, use Uint8Array")}function dn(P){for(var M=0;M<P.length;M++)P[M]=0}t.randomBytes=function(P){var M=new Uint8Array(P);return s(M,P),M},t.secretbox=function(P,M,L){Rt(P,M,L),dt(L,M);for(var k=new Uint8Array(wt+P.length),F=new Uint8Array(k.length),he=0;he<P.length;he++)k[he+wt]=P[he];return z(F,k,k.length,M,L),F.subarray(Y)},t.secretbox.open=function(P,M,L){Rt(P,M,L),dt(L,M);for(var k=new Uint8Array(Y+P.length),F=new Uint8Array(k.length),he=0;he<P.length;he++)k[he+Y]=P[he];return k.length<32||$(F,k,k.length,M,L)!==0?null:F.subarray(wt)},t.secretbox.keyLength=ft,t.secretbox.nonceLength=ze,t.secretbox.overheadLength=Y,t.scalarMult=function(P,M){if(Rt(P,M),P.length!==ue)throw new Error("bad n size");if(M.length!==U)throw new Error("bad p size");var L=new Uint8Array(U);return W(L,P,M),L},t.scalarMult.base=function(P){if(Rt(P),P.length!==ue)throw new Error("bad n size");var M=new Uint8Array(U);return G(M,P),M},t.scalarMult.scalarLength=ue,t.scalarMult.groupElementLength=U,t.box=function(P,M,L,k){var F=t.box.before(L,k);return t.secretbox(P,M,F)},t.box.before=function(P,M){Rt(P,M),jt(P,M);var L=new Uint8Array(Le);return X(L,P,M),L},t.box.after=t.secretbox,t.box.open=function(P,M,L,k){var F=t.box.before(L,k);return t.secretbox.open(P,M,F)},t.box.open.after=t.secretbox.open,t.box.keyPair=function(){var P=new Uint8Array(je),M=new Uint8Array(De);return de(P,M),{publicKey:P,secretKey:M}},t.box.keyPair.fromSecretKey=function(P){if(Rt(P),P.length!==De)throw new Error("bad secret key size");var M=new Uint8Array(je);return G(M,P),{publicKey:M,secretKey:new Uint8Array(P)}},t.box.publicKeyLength=je,t.box.secretKeyLength=De,t.box.sharedKeyLength=Le,t.box.nonceLength=tt,t.box.overheadLength=t.secretbox.overheadLength,t.sign=function(P,M){if(Rt(P,M),M.length!==nn)throw new Error("bad secret key size");var L=new Uint8Array(Jt+P.length);return st(L,P,P.length,M),L},t.sign.open=function(P,M){if(Rt(P,M),M.length!==un)throw new Error("bad public key size");var L=new Uint8Array(P.length),k=ut(L,P,P.length,M);if(k<0)return null;for(var F=new Uint8Array(k),he=0;he<F.length;he++)F[he]=L[he];return F},t.sign.detached=function(P,M){for(var L=t.sign(P,M),k=new Uint8Array(Jt),F=0;F<k.length;F++)k[F]=L[F];return k},t.sign.detached.verify=function(P,M,L){if(Rt(P,M,L),M.length!==Jt)throw new Error("bad signature size");if(L.length!==un)throw new Error("bad public key size");var k=new Uint8Array(Jt+P.length),F=new Uint8Array(Jt+P.length),he;for(he=0;he<Jt;he++)k[he]=M[he];for(he=0;he<P.length;he++)k[he+Jt]=P[he];return ut(F,k,k.length,L)>=0},t.sign.keyPair=function(){var P=new Uint8Array(un),M=new Uint8Array(nn);return ne(P,M),{publicKey:P,secretKey:M}},t.sign.keyPair.fromSecretKey=function(P){if(Rt(P),P.length!==nn)throw new Error("bad secret key size");for(var M=new Uint8Array(un),L=0;L<M.length;L++)M[L]=P[32+L];return{publicKey:M,secretKey:new Uint8Array(P)}},t.sign.keyPair.fromSeed=function(P){if(Rt(P),P.length!==Ie)throw new Error("bad seed size");for(var M=new Uint8Array(un),L=new Uint8Array(nn),k=0;k<32;k++)L[k]=P[k];return ne(M,L,!0),{publicKey:M,secretKey:L}},t.sign.publicKeyLength=un,t.sign.secretKeyLength=nn,t.sign.seedLength=Ie,t.sign.signatureLength=Jt,t.hash=function(P){Rt(P);var M=new Uint8Array(it);return We(M,P,P.length),M},t.hash.hashLength=it,t.verify=function(P,M){return Rt(P,M),P.length===0||M.length===0||P.length!==M.length?!1:x(P,0,M,0,P.length)===0},t.setPRNG=function(P){s=P},(function(){var P=typeof self<"u"?self.crypto||self.msCrypto:null;if(P&&P.getRandomValues){var M=65536;t.setPRNG(function(L,k){var F,he=new Uint8Array(k);for(F=0;F<k;F+=M)P.getRandomValues(he.subarray(F,F+Math.min(k-F,M)));for(F=0;F<k;F++)L[F]=he[F];dn(he)})}else typeof ste<"u"&&(P=rte,P&&P.randomBytes&&t.setPRNG(function(L,k){var F,he=P.randomBytes(k);for(F=0;F<k;F++)L[F]=he[F];dn(he)}))})()})(e.exports?e.exports:self.nacl=self.nacl||{})})(Qp)),Qp.exports}ate();new TextEncoder;new TextDecoder;function lte(e){return{id:e.id,name:e.name,path:e.path,...e.alias?.trim()?{alias:e.alias.trim()}:{},...e.groupId?{groupId:e.groupId}:{},...e.kind==="ssh"?{kind:"ssh",...e.sshConnectionName?{sshConnectionName:e.sshConnectionName}:{},...e.sshHost?{sshHost:e.sshHost}:{}}:{}}}function dte(e){return e.kind!=="ssh"?void 0:e.sshConnectionName?.trim()||e.sshHost}function HI(e){return e.alias?.trim()||e.name}function XS(e){const t=HI(e),n=dte(e);return n?`${t} (${n})`:t}const lc={supervised:"Supervised","auto-edits":"Auto-accept edits",full:"Full access",assistant:"Assistant approval"},ZS={minimal:"Min",low:"Low",medium:"Medium",high:"High",xhigh:"Extra High",max:"Max"};function cte({open:e,onOpenChange:t,projects:n,providers:s,onCreate:o}){const{t:r}=Q(),a=Ce(D=>D.approvalReviewer),l=Ce(D=>D.lastApprovalMode),d=wa(),c=Fi(D=>D.snapshot),u=m.useMemo(()=>XL(a,d,aa(c),l),[a,l,d,c]),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(null),[y,w]=m.useState(u),[b,_]=m.useState(!1),[j,N]=m.useState("medium");m.useEffect(()=>{e&&(p(null),g(null),v(null),w(u))},[e,u]);const C=n.find(D=>D.id===h)?.id??n[0]?.id??"",S=s.find(D=>D.id===f)??s[0]??{id:"",models:[]},A=S.models.find(D=>D.id===x)?.id??S.models[0]?.id??"",E=!!(C&&S.id&&A),I=()=>{E&&(Ce.getState().setLastApprovalMode(y),o({projectId:C,providerId:S.id,modelId:A,approvalMode:y,...b?{reasoningEnabled:!0,thinkingLevel:j}:{}}),t(!1))};return i.jsx(wn,{open:e,onOpenChange:t,children:i.jsxs(yn,{className:"max-w-md",children:[i.jsxs(Sn,{children:[i.jsx(Cn,{children:r("New remote conversation")}),i.jsx(Bs,{children:r("The conversation runs on the remote computer with its projects, models and keys.")})]}),i.jsxs(On,{className:"space-y-4",children:[i.jsx(Wa,{label:r("Project"),children:i.jsxs(xs,{items:n.map(D=>({value:D.id,label:XS(D)})),value:C,onValueChange:D=>p(D),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:n.map(D=>i.jsx(ns,{value:D.id,children:XS(D)},D.id))})]})}),i.jsx(Wa,{label:r("Provider"),children:i.jsxs(xs,{items:s.map(D=>({value:D.id,label:D.name})),value:S.id,onValueChange:D=>{g(D),v(null)},children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:s.map(D=>i.jsx(ns,{value:D.id,children:D.name},D.id))})]})}),i.jsx(Wa,{label:r("Model"),children:i.jsxs(xs,{items:S.models.map(D=>({value:D.id,label:D.label??D.id})),value:A,onValueChange:D=>v(D),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:S.models.map(D=>i.jsx(ns,{value:D.id,children:D.label??D.id},D.id))})]})}),i.jsx(Wa,{label:r("Approval mode"),children:i.jsxs(xs,{items:Object.keys(lc).map(D=>({value:D,label:r(lc[D])})),value:y,onValueChange:D=>w(D),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:Object.keys(lc).map(D=>i.jsx(ns,{value:D,children:r(lc[D])},D))})]})}),i.jsxs("div",{className:"flex items-center justify-between",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:r("Reasoning")}),i.jsx(Di,{checked:b,onCheckedChange:_})]}),b&&i.jsx(Wa,{label:r("Thinking level"),children:i.jsxs(xs,{items:Nf.map(D=>({value:D,label:r(ZS[D])})),value:j,onValueChange:D=>N(D),children:[i.jsx(vs,{className:"w-full",children:i.jsx(bs,{})}),i.jsx(ws,{zIndex:kn.DROPDOWN_IN_MODAL,children:Nf.map(D=>i.jsx(ns,{value:D,children:r(ZS[D])},D))})]})})]}),i.jsxs(cs,{children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:()=>t(!1),children:r("Cancel")}),i.jsx(ge,{size:"sm",disabled:!E,onClick:I,children:r("Create")})]})]})})}function Wa({label:e,children:t}){return i.jsxs("div",{className:"space-y-1.5",children:[i.jsx("span",{className:"text-muted-foreground text-xs",children:e}),t]})}function ute(e){return e.map(t=>({id:t.id,name:t.name,api:"openai-completions",apiKey:"",baseUrl:"",enabled:!0,models:t.models.map(n=>({id:n.id,...n.label?{label:n.label}:{}}))}))}function hte(e){return Nf.includes(e??"")?e:"medium"}function pte(e){const{t}=Q(),{node:n,sessionId:s,entry:o,view:r,syncing:a}=e,l=m.useRef(null),d=r?.status==="running",c=m.useMemo(()=>r?[...r.messages.entries()].sort((v,y)=>v[0]-y[0]):[],[r]),u=m.useMemo(()=>c.map(([,v])=>v),[c]),h=m.useMemo(()=>xr(u,d,[],o?.cwd,{pendingApprovals:r?.approvals,compaction:r?.compaction,compactionNoticeAt:ZL(c.map(([v])=>v),r?.compactionNoticeAt)}),[u,c,d,o?.cwd,r?.approvals,r?.compaction,r?.compactionNoticeAt]);m.useEffect(()=>{l.current?.isAtBottom()&&l.current.pinToBottom()},[h]);const p=m.useMemo(()=>({sessionId:s,canRewind:!1,canRetry:!1}),[s]),f=m.useMemo(()=>ute(e.providers),[e.providers]),g=o&&!o.parentId,x=n.hostOnline?a&&s?t("Syncing…"):null:n.connected?t("Remote desktop is offline"):t("Connecting…");return i.jsx(bh.Provider,{value:p,children:i.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col bg-background",children:[i.jsxs("header",{className:"flex h-9 shrink-0 items-center gap-2 border-b px-3",children:[i.jsx(JL,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"shrink-0 text-muted-foreground text-xs",children:n.label}),i.jsx(QL,{node:n}),o&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"text-muted-foreground/50",children:"/"}),i.jsx("span",{className:"min-w-0 truncate text-sm",children:o.title||t("New conversation")}),o.projectName&&i.jsx("span",{className:"truncate font-mono text-muted-foreground text-xs",children:o.projectName})]}),i.jsx("div",{className:"flex-1"}),x&&i.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground",children:x})]}),e.tabGroup&&i.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-x-auto border-b px-2 py-1",children:[i.jsx(JS,{active:s===e.tabGroup.parent.id,label:e.tabGroup.parent.title||t("New conversation"),status:e.tabGroup.parent.status,onClick:()=>e.onSelectTab(e.tabGroup.parent.id),icon:i.jsx(vr,{className:"h-3 w-3 shrink-0"})}),e.tabGroup.children.map(v=>i.jsx(JS,{active:s===v.id,icon:i.jsx(Hs,{className:"h-3 w-3 shrink-0"}),label:v.title||"coworker",status:v.status,onClick:()=>e.onSelectTab(v.id)},v.id))]}),s===null?i.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-1 px-6 text-center",children:[i.jsx("p",{className:"font-medium text-lg",children:n.label}),i.jsx("p",{className:"text-muted-foreground text-sm",children:n.hostOnline?t("Select a conversation on the left, or create one"):x??""})]}):i.jsx(Ch,{ref:l,items:h,busy:d||r===null,loading:!d&&r===null,running:d,error:void 0,emptyTitle:o?.projectName||n.label,historyLoading:e.historyLoading,hasOlder:e.hasOlder,onStartReached:e.hasOlder?e.onLoadOlder:void 0},s),s!==null&&i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:yi,children:[r?.retry&&i.jsx(Ih,{retry:r.retry}),i.jsx(cv,{sessionId:s,tasks:r?.tasks??[],subagents:r?.subagents??[]},s),i.jsx(Bl,{approvals:r?.approvals??[],onRespond:e.onApproval}),i.jsx(mh,{asks:r?.asks??[],onAnswer:e.onAsk}),i.jsx(lv,{commands:[],running:d,busy:d,locked:(r?.approvals??[]).length>0,focusKey:`${n.nodeId}:${s}`,toolbar:g&&o?i.jsx(Ju,{providers:f,providerId:o.providerId??"",modelId:o.modelId??"",reasoningEnabled:o.reasoningEnabled??!1,thinkingLevel:hte(o.thinkingLevel),onSelect:e.onSetModel,onReasoningChange:e.onSetReasoning,onThinkingChange:e.onSetThinking}):i.jsx("span",{className:"text-[11px] text-muted-foreground",children:o?.modelId??""}),onSend:v=>!v.text.trim()&&v.images.length===0?!1:(e.onSend(v.text,v.images),l.current?.scrollToBottom(),!0),onAbort:e.onAbort})]})})]})})}function JS({active:e,icon:t,label:n,status:s,onClick:o}){return i.jsxs("button",{type:"button",onClick:o,className:q("flex shrink-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",e?"bg-muted text-foreground":"text-muted-foreground hover:bg-muted/50"),children:[t,i.jsx("span",{className:"max-w-32 truncate",children:n}),i.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",s==="running"?"animate-pulse bg-brand":s==="failed"?"bg-destructive":"bg-muted-foreground/30")})]})}function Lu(e){return[...e].sort((t,n)=>(n.updatedAt??0)-(t.updatedAt??0))}function BI(e){const t=n=>(n.pendingAskCount??0)>0||(n.pendingApprovalCount??0)>0;return[...e.filter(t),...e.filter(n=>!t(n))]}function fte(e,t){const n=Lu(e),s=new Map(n.map(r=>[r.id,r])),o=[];for(const r of t){const a=s.get(r);a&&(o.push(a),s.delete(r))}return[...o,...BI([...s.values()])]}function QS(e){return BI([...Lu(e.filter(t=>t.pinned)),...Lu(e.filter(t=>!t.pinned))])}const eC="flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground";function mte({width:e,node:t,catalog:n,pinnedOrder:s,projects:o,groups:r=[],activeId:a,canCreate:l,onSelect:d,onNewConversation:c}){const{t:u,locale:h}=Q(),[p,f]=m.useState(Mn),[g,x]=m.useState(""),[v,y]=m.useState({}),[w,b]=m.useState(!1),[_,j]=m.useState(()=>Date.now());m.useEffect(()=>{const H=setInterval(()=>j(Date.now()),6e4);return()=>clearInterval(H)},[]);const N=p===Mn||p===us||r.some(H=>H.id===p)?p:Mn,C=o.filter(H=>H.archived).map(H=>H.id),S=Or(o,r,C,N),A=new Set(S.map(H=>H.id)),E=g.trim().toLowerCase(),I=m.useMemo(()=>n.filter(H=>!H.parentId&&(!E||H.title.toLowerCase().includes(E))),[n,E]),D=fte(I.filter(H=>H.pinned&&!H.archived&&(!H.projectId||A.has(H.projectId))),s),T=Lu(I.filter(H=>H.archived?N===Mn?!0:!!(H.projectId&&A.has(H.projectId)):!1)),z=I.filter(H=>!H.archived),$=new Set(o.map(H=>H.id)),R=QS(z.filter(H=>!$.has(H.projectId))),B=(H,oe)=>i.jsxs("button",{type:"button",onClick:()=>d(H.id),className:q("group flex w-full items-center gap-2 rounded-lg py-1.5 pr-2 pl-4 text-left text-sm transition-colors",a===H.id?"bg-brand/10 dark:bg-brand/15":"hover:bg-muted/60"),children:[i.jsx("span",{className:q("h-2 w-2 shrink-0 rounded-full",H.status==="running"&&"animate-pulse bg-brand",H.status==="failed"&&"bg-destructive",H.status==="idle"&&(H.unread?"bg-emerald-500":"bg-muted-foreground/30"))}),i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[H.title||u("New conversation"),oe&&i.jsx("span",{className:"ml-1.5 text-[10px] text-muted-foreground",children:oe})]}),H.updatedAt!==void 0&&i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/80 tabular-nums",children:Oo(H.updatedAt,h,_)})]},H.id);return i.jsxs("aside",{className:"flex shrink-0 flex-col overflow-hidden border-r bg-background",style:{width:e},children:[i.jsx("div",{className:q("shrink-0 px-2 py-2",r.length===0&&"border-b"),children:i.jsxs("div",{className:"relative",children:[i.jsx(ti,{className:"pointer-events-none absolute top-1/2 left-2.5 z-10 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground"}),i.jsx(Xt,{value:g,onChange:H=>x(H.target.value),placeholder:u("Search conversations..."),className:"h-8 border-transparent bg-muted/60 text-xs shadow-none ring-brand/15 before:hidden has-focus-visible:border-brand/45 [&_input]:pl-8"})]})}),r.length>0&&i.jsx("div",{className:"shrink-0 border-b px-2 pb-2",children:i.jsxs(xs,{items:[{value:Mn,label:u("All")},...r.slice().sort((H,oe)=>H.order-oe.order).map(H=>({value:H.id,label:H.name})),{value:us,label:u("Ungrouped")}],value:N,onValueChange:H=>{H&&f(H)},children:[i.jsx(vs,{className:"w-full",size:"sm",children:i.jsx(bs,{})}),i.jsxs(ws,{children:[i.jsx(ns,{value:Mn,children:u("All")}),r.slice().sort((H,oe)=>H.order-oe.order).map(H=>i.jsx(ns,{value:H.id,children:H.name},H.id)),i.jsx(ns,{value:us,children:u("Ungrouped")})]})]})}),i.jsxs("div",{className:"min-h-0 flex-1 space-y-2 overflow-y-auto p-2",children:[!t.hostOnline&&n.length===0&&i.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:t.connected?u("Remote desktop is offline"):u("Connecting…")}),t.hostOnline&&o.length===0&&i.jsx("p",{className:"rounded-lg border border-dashed px-3 py-6 text-center text-muted-foreground text-sm",children:u("The remote desktop has no projects yet")}),D.length>0&&i.jsxs("div",{children:[i.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-2",children:[i.jsx(di,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"font-medium text-sm",children:u("Pinned")})]}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:D.map(H=>B(H,H.projectName))})]}),(N===Mn&&r.length>0?zj(o,r,C).flatMap(H=>{const oe=v[`g:${H.groupId}`]===!0;return[{kind:"header",section:H,foldedSection:oe},...oe?[]:H.projects.map(te=>({kind:"project",project:te}))]}):S.map(H=>({kind:"project",project:H}))).map(H=>{if(H.kind==="header")return i.jsxs("button",{type:"button",onClick:()=>y(V=>({...V,[`g:${H.section.groupId}`]:!V[`g:${H.section.groupId}`]})),className:"flex h-7 w-full items-center gap-1 rounded-md px-2 text-left text-xs font-medium text-muted-foreground",children:[i.jsx(bn,{className:q("h-3.5 w-3.5 shrink-0 transition-transform duration-150",!H.foldedSection&&"rotate-90")}),H.section.group?.emoji&&i.jsx("span",{className:"shrink-0 text-sm",children:H.section.group.emoji}),H.section.group?.color&&i.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:H.section.group.color}}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:H.section.group?.name??u("Ungrouped")}),i.jsx("span",{className:"shrink-0 text-[10px] text-muted-foreground/70",children:H.section.projects.length})]},`hdr-${H.section.groupId}`);const{project:oe}=H,te=QS(z.filter(V=>V.projectId===oe.id&&!V.pinned));if(E&&te.length===0)return null;const O=v[oe.id]===!0;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>y(V=>({...V,[oe.id]:!O})),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[O?i.jsx(bn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):i.jsx(Vn,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:HI(oe)}),oe.sshHost&&i.jsx("span",{className:"shrink-0 rounded bg-muted px-1 font-mono text-[10px] text-muted-foreground",children:"ssh"})]}),!O&&i.jsxs("div",{className:"flex flex-col gap-y-0.5",children:[te.length===0&&i.jsx("p",{className:"px-4 py-1.5 text-muted-foreground text-xs",children:u("No conversations")}),te.map(V=>B(V))]})]},oe.id)}),R.length>0&&i.jsxs("div",{children:[i.jsx("div",{className:"px-2 py-2 font-medium text-sm",children:u("Other")}),i.jsx("div",{className:"flex flex-col gap-y-0.5",children:R.map(H=>B(H))})]}),T.length>0&&i.jsxs("div",{children:[i.jsxs("button",{type:"button",onClick:()=>b(H=>!H),className:"flex w-full items-center gap-1.5 rounded-lg px-2 py-2 text-left transition-colors hover:bg-muted/60",children:[i.jsx(Ii,{className:"h-3.5 w-3.5 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium text-sm",children:u("Archived")}),i.jsx("span",{className:"text-[10px] text-muted-foreground",children:T.length})]}),w&&i.jsx("div",{className:"flex flex-col gap-y-0.5",children:T.map(H=>B(H,H.projectName))})]})]}),i.jsxs("div",{className:"flex shrink-0 items-center gap-0.5 p-1.5",children:[i.jsx(Gj,{}),i.jsx("button",{type:"button",onClick:()=>{window.electronAPI.nodes.openSettings(t.nodeId)},disabled:!t.hostOnline,className:q(eC,!t.hostOnline&&"opacity-40"),title:u("Node settings"),children:i.jsx(ui,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:c,disabled:!l,className:q(eC,!l&&"opacity-40"),title:u("New remote conversation"),children:i.jsx(sN,{className:"h-4 w-4"})})]})]})}function gte({nodeId:e,sidebarWidth:t}){const n=ts(v=>v.nodes.find(y=>y.nodeId===e)),s=ts(v=>v.byNode[e])??xte,o=ts(v=>v.selectSession),r=ts(v=>v.send),a=ts(v=>v.requestHistory),l=ts(v=>v.spawn),[d,c]=m.useState(!1),u=s.activeSessionId,h=m.useMemo(()=>s.catalog.find(v=>v.id===u),[s.catalog,u]),p=m.useMemo(()=>{if(!h)return;const v=h.parentId?s.catalog.find(w=>w.id===h.parentId):h;if(!v)return;const y=s.catalog.filter(w=>w.parentId===v.id);return y.length>0?{parent:v,children:y}:void 0},[s.catalog,h]),f=u?s.sessions[u]??null:null,g=!!(f&&f.messages.size>0&&Math.min(...f.messages.keys())>0);if(!n)return null;const x=v=>r(e,v);return i.jsxs(i.Fragment,{children:[i.jsx(mte,{width:t,node:n,catalog:s.catalog,pinnedOrder:s.pinnedOrder,projects:s.projects,groups:s.groups,activeId:u,canCreate:n.hostOnline&&s.projects.length>0,onSelect:v=>o(e,v),onNewConversation:()=>c(!0)}),i.jsx(pte,{node:n,sessionId:u,entry:h,tabGroup:p,view:f,syncing:s.sync.state==="syncing",providers:s.providers,hasOlder:g,historyLoading:!!(u&&s.historyPending.has(u)),onLoadOlder:()=>u&&a(e,u),onSelectTab:v=>o(e,v),onSend:(v,y)=>{u&&x({type:f?.status==="running"?"steer":"prompt",sessionId:u,text:v,...y.length?{images:y}:{}})},onAbort:()=>u&&x({type:"abort",sessionId:u}),onApproval:(v,y)=>u&&x({type:"approval-respond",sessionId:u,requestId:v,decision:y}),onAsk:(v,y)=>u&&x({type:"ask-respond",sessionId:u,requestId:v,answer:y}),onSetModel:(v,y)=>u&&x({type:"set-model",sessionId:u,providerId:v,modelId:y}),onSetReasoning:v=>u&&x({type:"set-reasoning",sessionId:u,enabled:v}),onSetThinking:v=>u&&x({type:"set-thinking",sessionId:u,level:v})}),i.jsx(cte,{open:d,onOpenChange:c,projects:s.projects,providers:s.providers,onCreate:v=>l(e,v)})]})}const xte=e5(),ef=["welcome","provider","skill","mcp","instruction","preset","agentType","done"];function vte(){const{t:e}=Q();_k();const t=Ce(I=>I.setOnboarded),n=wa(),s=Ce(I=>I.virtualModels),o=Ce(I=>I.skills),r=Ce(I=>I.mcpServers),a=Ce(I=>I.instructions),l=Ce(I=>I.presets),d=Ce(I=>I.defaultModel),c=Fi(I=>I.snapshot),u=Al({defaultModel:d,providers:n,credentials:aa(c),virtualModels:s}).source!=="none",[h,p]=m.useState(0),[f,g]=m.useState(null),[x,v]=m.useState(!1),[y,w]=m.useState(!1),[b,_]=m.useState(!1),j=ef[h],N=()=>t(!0),C=()=>{N(),window.electronAPI.window.summonAgent({typeKey:Jc})},S=()=>p(I=>Math.min(ef.length-1,I+1)),A=()=>p(I=>Math.max(0,I-1)),E={provider:{icon:n5,title:e("Model Providers"),desc:e("Add a provider subscription or API Key, or import providers from local AI apps"),count:n.length,onImport:()=>w(!0),importLabel:e("Add model or provider"),secondary:{label:e("Import from local apps"),onClick:()=>v(!0)}},skill:{icon:zs,title:e("Skills"),desc:e("Import skills from Claude Code, Codex or Cursor"),count:o.length,onImport:()=>g("skill"),importLabel:e("Scan and import")},mcp:{icon:lk,title:e("MCP Servers"),desc:e("Import MCP servers configured in local AI apps"),count:r.length,onImport:()=>g("mcp"),importLabel:e("Scan and import")},instruction:{icon:Xc,title:e("Instruction Files"),desc:e("Import global instruction files configured in local AI tools"),count:a.length,onImport:()=>g("instruction"),importLabel:e("Scan and import")}};return i.jsxs("div",{className:"fixed inset-0 z-[45] flex items-center justify-center bg-black/40 backdrop-blur-sm","data-enso-float":"",children:[i.jsxs("div",{className:"relative flex w-[32rem] max-w-[90vw] flex-col rounded-2xl border bg-popover p-6 shadow-xl",children:[i.jsx("button",{type:"button",onClick:N,className:"absolute right-3 top-3 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground","aria-label":e("Close"),children:i.jsx(an,{className:"h-4 w-4"})}),i.jsx("div",{className:"mb-5 flex items-center gap-1.5",children:ef.map((I,D)=>i.jsx("span",{className:q("h-1 flex-1 rounded-full transition-colors",D<=h?"bg-primary":"bg-muted")},I))}),j==="welcome"&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:i.jsx(t5,{className:"h-6 w-6 text-primary"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("Welcome to EnsoCode")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Import your providers and assets from local AI apps to get started. You can skip any step.")})]}),j!=="welcome"&&j!=="done"&&j!=="preset"&&j!=="agentType"&&i.jsx(tC,{...E[j],importedLabel:e("{{count}} imported",{count:E[j].count})}),j==="preset"&&i.jsx(tC,{icon:Xc,title:e("Presets"),desc:e("Bundle skills, MCP servers and an instruction file into a preset (optional)"),count:l.length,onImport:()=>_(!0),importedLabel:e("{{count}} presets",{count:l.length}),importLabel:e("New preset")}),j==="agentType"&&i.jsxs("div",{className:"flex flex-col gap-3 py-2",children:[i.jsxs("div",{className:"flex flex-col items-center gap-2 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:i.jsx(Hs,{className:"h-6 w-6 text-muted-foreground"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("Agent types")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("Give subagents their own model, skills and MCP servers (optional)")})]}),i.jsx("div",{className:"max-h-64 overflow-y-auto pr-1",children:i.jsx(s5,{})})]}),j==="done"&&i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-primary/10",children:i.jsx(Un,{className:"h-6 w-6 text-primary"})}),i.jsx("h2",{className:"text-lg font-semibold",children:e("All set")}),i.jsx("p",{className:"text-sm text-muted-foreground",children:e("You can always import more from Settings later.")})]}),u&&i.jsxs("div",{className:"mt-4 flex items-center justify-between rounded-lg border border-dashed px-3 py-2",children:[i.jsx("p",{className:"text-xs text-muted-foreground",children:e("Need help choosing a setup? Ask Enso.")}),i.jsxs(ge,{variant:"ghost",size:"sm",onClick:C,children:[i.jsx(zs,{className:"h-3.5 w-3.5"}),e("Ask Enso")]})]}),i.jsxs("div",{className:"mt-6 flex items-center justify-between",children:[i.jsx(ge,{variant:"ghost",size:"sm",onClick:A,disabled:h===0,children:e("Back")}),i.jsxs("div",{className:"flex items-center gap-2",children:[j!=="done"&&j!=="welcome"&&i.jsx(ge,{variant:"ghost",size:"sm",onClick:S,children:e("Skip")}),j==="done"?i.jsx(ge,{size:"sm",onClick:N,children:e("Done")}):i.jsx(ge,{size:"sm",onClick:S,children:e(j==="welcome"?"Get started":"Next")})]})]})]}),i.jsx(i5,{open:x,onOpenChange:v}),i.jsx(o5,{open:y,onOpenChange:w}),f&&i.jsx(r5,{kind:f,open:!0,onOpenChange:I=>!I&&g(null)}),b&&i.jsx(a5,{preset:null,onClose:()=>_(!1)})]})}function tC({icon:e,title:t,desc:n,count:s,onImport:o,importedLabel:r,importLabel:a,secondary:l}){return i.jsxs("div",{className:"flex flex-col items-center gap-3 py-6 text-center",children:[i.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-full bg-muted",children:i.jsx(e,{className:"h-6 w-6 text-muted-foreground"})}),i.jsx("h2",{className:"text-lg font-semibold",children:t}),i.jsx("p",{className:"text-sm text-muted-foreground",children:n}),i.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[i.jsx(ge,{variant:"outline",size:"sm",onClick:o,children:a}),l&&i.jsx(ge,{variant:"ghost",size:"sm",onClick:l.onClick,children:l.label})]}),s>0&&i.jsx("p",{className:"text-xs text-primary",children:r})]})}const tf=["project","all","all-including-archived"];function nC(e,t=!1){const n=tf.length,s=tf.indexOf(e);return tf[(s+(t?n-1:1))%n]??"all"}const bte=50,nf=160,wte=["title","project","id","body","tool"],fv=/[\p{Letter}\p{Number}]+/gu,yte=/[\u3400-\u9fff]/u,Ste=/[^.!?。?!]+[.!?。?!]?/g;function VI(e){return e.toLowerCase().match(fv)??[]}function mv(e){return yte.test(e)}function $I(e){return VI(e)}function WI(e,t){if(t.length===0)return!1;const n=e.toLowerCase(),s=VI(e);return t.every(o=>mv(o)?n.includes(o):s.some(r=>r.startsWith(o)))}function UI(e,t){return e.isDraftEmpty?!1:t.scope==="project"?e.projectId===t.currentProjectId&&!e.archived:t.scope==="all"?!e.archived:!0}function Cte(e,t){const n=e.toLowerCase(),s=$I(t);if(s.length===0||n.length!==e.length)return[{text:e,match:!1}];const o=[];for(const l of s){if(mv(l)){for(let d=n.indexOf(l);d>=0;d=n.indexOf(l,d+1))o.push([d,d+l.length]);continue}for(const d of n.matchAll(fv))d.index!==void 0&&d[0].startsWith(l)&&o.push([d.index,d.index+l.length])}if(o.length===0)return[{text:e,match:!1}];o.sort((l,d)=>l[0]-d[0]);const r=[];let a=0;for(const[l,d]of o){if(d<=a)continue;const c=Math.max(l,a);c>a&&r.push({text:e.slice(a,c),match:!1});const u=r.at(-1);u?.match&&c===a?u.text+=e.slice(c,d):r.push({text:e.slice(c,d),match:!0}),a=d}return a<e.length&&r.push({text:e.slice(a),match:!1}),r}function kte(e,t){const n=e.toLowerCase();let s=-1;for(const o of t){if(mv(o)){const r=n.indexOf(o);r>=0&&(s<0||r<s)&&(s=r);continue}for(const r of e.matchAll(fv))if(r[0].toLowerCase().startsWith(o)&&r.index!==void 0){(s<0||r.index<s)&&(s=r.index);break}}return s}function jte(e,t){if(e.length<=nf)return e;const n=Math.max(0,kte(e,t)),s=Math.min(n,Math.max(0,e.length-nf));return e.slice(s,s+nf)}function _te(e){return(e.match(Ste)??[]).map(t=>t.trim()).filter(Boolean)}function Nte(e,t){const n=_te(e);if(n.length<=1)return;const s=n.findIndex(r=>WI(r,t));if(s<0)return;const o=[...[n[s-1],n[s-2]].filter(r=>!!r),...[n[s+1],n[s+2]].filter(r=>!!r)];return o.length>0?o:void 0}function Tte(e,t,n,s){return e.title.trim().toLowerCase()===n.trim().toLowerCase()?0:t==="title"?1:e.projectId===s?2:3}function Dte(e,t,n){const s=n.trim().toLowerCase(),o=e.fields.filter(r=>r.field==="id"?r.text.toLowerCase().startsWith(s):WI(r.text,t));if(o.length!==0)return wte.map(r=>o.find(a=>a.field===r)).find(r=>!!r)}function KI(e,t,n,s){return{conversationId:e.conversationId,projectId:e.projectId,title:e.title,field:t.field,snippet:t.snippet,...t.nearby?{nearby:t.nearby}:{},...e.isCurrent?{isCurrent:!0}:{},...e.archived?{archived:!0}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.coworkerId?{coworkerId:e.coworkerId}:{},rank:Tte(e,t.field,n,s),lastActiveAt:e.lastActiveAt}}function qI(e,t=bte){return e.sort((n,s)=>n.rank-s.rank||s.lastActiveAt-n.lastActiveAt),e.slice(0,t).map(({rank:n,lastActiveAt:s,...o})=>o)}function Ite(e,t,n){const s=$I(t);if(s.length===0)return[];const o=[];for(const r of e){if(!UI(r,n))continue;const a=Dte(r,s,t);if(!a)continue;const l=Nte(a.text,s);o.push(KI(r,{field:a.field,snippet:jte(a.text,s),nearby:l},t,n.currentProjectId))}return qI(o,n.limit)}function Ete(e,t,n,s,o){const r=new Map(e.map(l=>[l.conversationId,l])),a=new Map;for(const l of[...t,...n]){const d=r.get(l.conversationId);!d||a.has(l.conversationId)||!UI(d,o)||a.set(l.conversationId,KI(d,l,s,o.currentProjectId))}return qI([...a.values()],o.limit)}const Pte=120,Ate=8;function YI(e){return!e.started&&!e.sessionFile&&e.messages.length===0}function jl(e){return e.messages.at(-1)?.timestamp??e.lastActiveAt??e.createdAt}function Mte(e,t){return e.filter(n=>n.parentId||YI(n)||n.archived&&t.scope!=="all-including-archived"?!1:t.scope!=="project"||n.projectId===t.currentProjectId).sort((n,s)=>jl(s)-jl(n)).slice(0,t.limit??Ate)}function Rte(e){return e.content.map(t=>t.type==="text"?t.text:"").join(`
|
|
99
|
-
`).trim()}function Lte(e){if(e.role!=="toolResult"&&!e.content.some(s=>s.type==="toolCall"))return;const t=[e.toolName,...e.content.flatMap(s=>s.type==="toolCall"?[s.name]:[])].filter(s=>!!s);if(t.length===0)return;const n=e.content.flatMap(s=>s.type==="toolCall"&&s.arguments!=null?[JSON.stringify(s.arguments)]:[]).join(" ").slice(0,Pte);return`${t.join(" ")} ${n}`.trim()}function Ote(e){const t=[{field:"title",text:e.title},{field:"project",text:e.projectName},{field:"id",text:e.conversationId},{field:"body",text:e.messages.map(Rte).filter(Boolean).join(`
|
|
100
|
-
`)}],n=e.messages.map(Lte).filter(s=>!!s);return n.length>0&&t.push({field:"tool",text:n.join(`
|
|
101
|
-
`)}),{conversationId:e.conversationId,projectId:e.projectId,projectName:e.projectName,title:e.title,lastActiveAt:e.lastActiveAt,fields:t,...e.archived?{archived:!0}:{},...e.isDraftEmpty?{isDraftEmpty:!0}:{},...e.isCurrent?{isCurrent:!0}:{},...e.parentConversationId?{parentConversationId:e.parentConversationId}:{},...e.coworkerId?{coworkerId:e.coworkerId}:{}}}const sC=[],zte={project:"This project",all:"All projects","all-including-archived":"Include archived"},Gte={general:"General",shortcuts:"Shortcuts",appearance:"Appearance",providers:"Model Providers",skills:"Skills",plugins:"Enso plugins",claudePlugins:"Claude Code plugins",mcp:"MCP Servers",instructions:"Instruction Files",presets:"Presets",agents:"Agent types",workflows:"Workflows",tools:"Built-in tools",memory:"Memory",privacy:"Privacy",phone:"Devices",ssh:"SSH",usage:"Usage",resources:"Resources",voice:"Voice input",experimental:"Experimental",bots:"Bot mode",botTemplates:"Bot templates"};function Ua({text:e,query:t}){let n=0;return Cte(e,t).map(s=>{const o=n;return n+=s.text.length,s.match?i.jsx("mark",{className:"rounded-[3px] bg-brand/14 text-foreground",children:s.text},o):i.jsx("span",{children:s.text},o)})}function Ar({icon:e,title:t,badges:n,detail:s,meta:o}){return i.jsxs(i.Fragment,{children:[i.jsx(e,{className:"size-4 shrink-0 text-muted-foreground"}),i.jsxs("div",{className:"min-w-0 flex-1",children:[i.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[i.jsx("span",{className:"truncate",children:t}),n]}),s&&i.jsx("p",{className:"truncate text-muted-foreground text-xs",children:s})]}),o&&i.jsx("span",{className:"max-w-48 shrink-0 truncate text-muted-foreground text-xs",children:o})]})}function Fte(e){try{return new URL(e).host||e}catch{return e}}function Hte({open:e,onOpenChange:t}){const{t:n,locale:s}=Q(),[o,r]=m.useState(""),[a,l]=m.useState("all"),[d,c]=m.useState(),[u,h]=m.useState([]),[p,f]=m.useState([]),g=re(W=>W.conversations),x=re(W=>W.activeId),v=Ce(W=>W.projects),y=Ce(W=>W.scratchSessionsEnabled),w=Ce(W=>W.keybindings),b=(x?g[x]?.projectId:void 0)??v[0]?.id??"",_=o.trim(),j=`${a}
|
|
102
|
-
${b}
|
|
103
|
-
${_}`,N=d?.key===j?d.hits:sC,C=m.useMemo(()=>{if(!e)return[];const G=(x?g[x]:void 0)?.activeTabId,de=G&&g[G]?G:x;return Object.values(g).map(X=>{const ie=v.find(Z=>Z.id===X.projectId);return!y&&ie?.kind==="scratch"?null:Ote({conversationId:X.id,projectId:X.projectId,projectName:ie?.name??X.projectId,title:X.title,lastActiveAt:jl(X),archived:X.archived,isDraftEmpty:YI(X),isCurrent:X.id===de,parentConversationId:X.parentId,coworkerId:X.parentId?X.id:void 0,messages:X.messages})}).filter(X=>X!==null)},[x,g,e,v,y]),S=m.useMemo(()=>_?Ite(C,o,{currentProjectId:b,scope:a}):sC,[b,C,o,a,_]),A=m.useMemo(()=>e?Mte(Object.values(g),{scope:a,currentProjectId:b}):[],[g,b,e,a]),E=l5(p),I=m.useMemo(()=>_?d5(E,o,{translate:W=>n(W)}):[],[o,E,n,_]),D=m.useMemo(()=>o.trim()?c5(u,o):[],[u,o]),T=m.useMemo(()=>u5(u),[u]);m.useEffect(()=>{if(!e)return;const W=G=>{G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),t(!1))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[t,e]),m.useEffect(()=>{if(!e){r(""),l("all"),c(void 0);return}window.electronAPI.browser.listSearchableTabs().then(W=>h(W.filter(G=>!Fj(G.conversationId)))).catch(()=>{h([])}),window.electronAPI.sshConnections.list().then(W=>{f(W.map(G=>({id:G.id,name:G.name})))}).catch(()=>{f([])})},[e]),m.useEffect(()=>{if(!e||!_||!b)return;let W=!1;const G=window.setTimeout(()=>{window.electronAPI.workspaceSearch.query({query:_,currentProjectId:b,scope:a}).then(de=>{W||c({key:j,hits:de.hits})}).catch(()=>{W||c({key:j,hits:[]})})},80);return()=>{W=!0,window.clearTimeout(G)}},[j,b,e,a,_]);const z=m.useMemo(()=>Ete(C,S,N,o,{currentProjectId:b,scope:a}),[N,b,C,S,o,a]),$=W=>{const G=re.getState(),de=G.conversations[W.conversationId],X=W.parentConversationId??de?.parentId;if(X&&G.conversations[X]?(G.selectConversation(X),G.selectTab(X,W.coworkerId??W.conversationId)):G.selectConversation(W.conversationId),t(!1),W.field==="body"||W.field==="tool"){const ie=o.trim().split(/\s+/).find(Boolean);ie&&window.setTimeout(()=>rI(ie),0)}},R=W=>{const G=re.getState(),X=G.conversations[W.conversationId]?.parentId;X&&G.conversations[X]?(G.selectConversation(X),G.selectTab(X,W.conversationId)):G.selectConversation(W.conversationId),Eg({conversationId:W.conversationId,tabId:W.tabId,title:W.title||n("Browser")}),t(!1)},B=W=>{window.electronAPI.window.openSettings({category:W.category,rowId:W.id}),t(!1)},H=_.length>0&&z.length===0&&D.length===0&&I.length===0,oe=W=>{W.key==="Escape"&&(W.preventDefault(),W.stopPropagation(),t(!1))},te=W=>{if(W.key!=="Tab"||W.nativeEvent.isComposing){oe(W);return}W.altKey||W.ctrlKey||W.metaKey||(W.preventDefault(),l(G=>nC(G,W.shiftKey)))},O=Ai(w),V=Date.now(),J=W=>{const G=v.find(de=>de.id===W);return G?Po(G):""},pe=(W,G)=>[J(W),G?Oo(G,s,V):""].filter(Boolean).join(" · "),fe=(W,G)=>i.jsxs(i.Fragment,{children:[W&&i.jsx(oa,{size:"sm",className:"bg-brand/10 text-brand",children:n("Current")}),G&&i.jsx(oa,{variant:"outline",size:"sm",children:n("Archived")})]}),_e=W=>{const G=g[W.conversationId],de=W.parentConversationId??G?.parentId;let X=vr;de&&(X=G?.child?.mode==="task"?_g:Hs);const ie=W.title||G?.child?.agentInstanceName||G?.coworkerName||n("New conversation"),Z=de?g[de]?.title||n("New conversation"):void 0,le=W.field==="body"||W.field==="tool"||W.field==="id"?W.snippet.replace(/\s+/g," ").trim():"";return i.jsx(Ar,{icon:X,title:i.jsxs(i.Fragment,{children:[Z&&i.jsxs("span",{className:"text-muted-foreground",children:[Z," › "]}),i.jsx(Ua,{text:ie,query:o})]}),badges:fe(W.isCurrent,W.archived),detail:le&&i.jsx(Ua,{text:le,query:o}),meta:pe(W.projectId,G?jl(G):void 0)})},Ee=(W,G)=>i.jsx(sr,{value:G,className:"gap-2.5",onClick:()=>R(W),children:i.jsx(Ar,{icon:fo,title:i.jsx(Ua,{text:W.title||W.url,query:o}),meta:Fte(W.url)})},G),me=i.jsxs("button",{type:"button",tabIndex:-1,"data-search-scope":a,title:n("Switch scope"),className:"flex h-7 shrink-0 items-center gap-1.5 rounded-md border px-2 text-muted-foreground text-xs transition-colors hover:bg-accent hover:text-foreground",onPointerDown:W=>{W.preventDefault(),W.stopPropagation(),l(G=>nC(G,W.shiftKey))},children:[n(zte[a]),i.jsx(ai,{className:"h-4 min-w-4 text-[10px]",children:"⇥"})]});return i.jsx(XD,{open:e,onOpenChange:t,children:i.jsx(ZD,{className:"max-h-[min(36rem,calc(100vh-6rem))] max-w-2xl",onKeyDown:oe,children:i.jsxs(JD,{children:[i.jsx(QD,{placeholder:n("Search conversations, browser tabs, settings…"),value:o,onChange:W=>r(W.currentTarget.value),onKeyDown:te,endAddon:me}),i.jsxs(nI,{children:[H&&i.jsxs(tI,{children:[n("No matching results"),a!=="all-including-archived"&&i.jsxs("span",{className:"mt-2 flex items-center justify-center gap-1.5 text-xs",children:[i.jsx(ai,{children:"⇥"}),n(a==="project"?"Search all projects":"Include archived")]})]}),i.jsxs(eI,{children:[!_&&i.jsxs(i.Fragment,{children:[A.length>0&&i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Recent")}),A.map(W=>i.jsx(sr,{value:`recent-${W.id}`,className:"gap-2.5",onClick:()=>$({conversationId:W.id,field:"title",snippet:W.title}),children:i.jsx(Ar,{icon:vr,title:W.title||n("New conversation"),badges:fe(W.id===x,W.archived),meta:pe(W.projectId,jl(W))})},W.id))]}),T.length>0&&i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Browser")}),T.map(W=>Ee(W,`recent-browser-${W.tabId}`))]}),i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Actions")}),i.jsxs(sr,{value:"new-conversation",className:"gap-2.5",onClick:()=>{b&&re.getState().newConversation(b),t(!1)},children:[i.jsx(Ar,{icon:ds,title:i.jsxs(i.Fragment,{children:[n("New conversation"),J(b)&&i.jsxs("span",{className:"text-muted-foreground",children:[" · ",J(b)]})]})}),i.jsx(oS,{children:fi(O["new-conversation"])})]}),i.jsxs(sr,{value:"open-settings",className:"gap-2.5",onClick:()=>{window.electronAPI.window.openSettings(),t(!1)},children:[i.jsx(Ar,{icon:ui,title:n("Open settings")}),i.jsx(oS,{children:fi(O["open-settings"])})]})]})]}),_.length>0&&z.length>0&&i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Conversations")}),z.map(W=>i.jsx(sr,{value:`conv-${W.conversationId}-${W.field}`,className:"gap-2.5",onClick:()=>$(W),children:_e(W)},`${W.conversationId}-${W.field}`))]}),_.length>0&&D.length>0&&i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Browser")}),D.map(W=>Ee(W,`browser-${W.tabId}`))]}),_.length>0&&I.length>0&&i.jsxs(Er,{children:[i.jsx(Pr,{children:n("Settings")}),I.map(W=>i.jsx(sr,{value:`settings-${W.id}`,className:"gap-2.5",onClick:()=>B(W),children:i.jsx(Ar,{icon:ui,title:i.jsx(Ua,{text:n(W.title),query:o}),detail:W.description&&i.jsx(Ua,{text:n(W.description),query:o}),meta:n(Gte[W.category]??W.category)})},W.id))]})]})]}),i.jsxs(sI,{children:[i.jsxs("div",{className:"flex items-center gap-4",children:[i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsxs(fj,{children:[i.jsx(ai,{children:"↑"}),i.jsx(ai,{children:"↓"})]}),n("Navigate")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(ai,{children:"↵"}),n("Open")]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(ai,{children:"⇥"}),n("Switch scope")]})]}),i.jsxs("span",{className:"flex items-center gap-1.5",children:[i.jsx(ai,{children:"esc"}),n("Close")]})]})]})})})}var XI,ZI=class{constructor(){}},Zs=class extends ZI{constructor(e,t,n,s){super(),this.viewId=e,this.groupId=t,this.panelId=n,this.tabGroupId=s}},_l=class extends ZI{constructor(e,t){super(),this.viewId=e,this.paneId=t}},xo=class JI{constructor(){}static getInstance(){return JI.INSTANCE}hasData(t){return t&&t===this.proto}clearData(t){this.hasData(t)&&(this.proto=void 0,this.data=void 0)}getData(t){if(this.hasData(t))return this.data}setData(t,n){n&&(this.data=t,this.proto=n)}};XI=xo;xo.INSTANCE=new XI;function Ln(){const e=xo.getInstance();if(e.hasData(Zs.prototype))return e.getData(Zs.prototype)[0]}function Ka(){const e=xo.getInstance();if(e.hasData(_l.prototype))return e.getData(_l.prototype)[0]}let rn;(function(e){e.NONE={dispose:()=>{}};function t(n){return{dispose:()=>{n()}}}e.from=t})(rn||(rn={}));var ct=class{get isDisposed(){return this._isDisposed}constructor(...e){this._isDisposed=!1,this._disposables=new Set(e)}addDisposables(...e){e.forEach(t=>this._disposables.add(t))}removeDisposable(e){this._disposables.delete(e)}dispose(){this._isDisposed||(this._isDisposed=!0,this._disposables.forEach(e=>e.dispose()),this._disposables.clear())}},Fn=class{constructor(){this._disposable=rn.NONE}get value(){return this._disposable===rn.NONE?void 0:this._disposable}set value(e){this._disposable&&this._disposable.dispose(),this._disposable=e}dispose(){this._disposable&&(this._disposable.dispose(),this._disposable=rn.NONE)}};let Qs;(function(e){e.any=(...t)=>n=>{const s=t.map(o=>o(n));return{dispose:()=>{s.forEach(o=>{o.dispose()})}}}})(Qs||(Qs={}));var gv=class{constructor(){this._defaultPrevented=!1}get defaultPrevented(){return this._defaultPrevented}preventDefault(){this._defaultPrevented=!0}},QI=class{constructor(){this._isAccepted=!1}get isAccepted(){return this._isAccepted}accept(){this._isAccepted=!0}},Bte=class{constructor(){this.events=new Map}get size(){return this.events.size}add(e,t){this.events.set(e,t)}delete(e){this.events.delete(e)}clear(){this.events.clear()}},iC=class eE{static create(){var t;return new eE((t=new Error("listener stacktrace").stack)!==null&&t!==void 0?t:"")}constructor(t){this.value=t}print(){console.warn("dockview: stacktrace",this.value)}},Vte=class{constructor(e,t){this.callback=e,this.stacktrace=t}},ve=class Ci{static setLeakageMonitorEnabled(t){t!==Ci.ENABLE_TRACKING&&Ci.MEMORY_LEAK_WATCHER.clear(),Ci.ENABLE_TRACKING=t}get value(){return this._last}constructor(t){this.options=t,this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=t=>{var n;!((n=this.options)===null||n===void 0)&&n.replay&&this._last!==void 0&&t(this._last);const s=new Vte(t,Ci.ENABLE_TRACKING?iC.create():void 0);return this._listeners.push(s),{dispose:()=>{const o=this._listeners.indexOf(s);o>-1&&this._listeners.splice(o,1)}}},Ci.ENABLE_TRACKING&&Ci.MEMORY_LEAK_WATCHER.add(this._event,iC.create())),this._event}fire(t){var n;if(this._pauseTokens!==void 0&&this._pauseTokens.size>0)return;!((n=this.options)===null||n===void 0)&&n.replay&&(this._last=t);const s=this._listeners,o=s.length;if(o!==0){if(o===1){s[0].callback(t);return}for(const r of s.slice())r.callback(t)}}pause(){var t;const n={};return(t=this._pauseTokens)!==null&&t!==void 0||(this._pauseTokens=new Set),this._pauseTokens.add(n),rn.from(()=>{var s;return(s=this._pauseTokens)===null||s===void 0?void 0:s.delete(n)})}dispose(){this._disposed||(this._disposed=!0,this._listeners.length>0&&(Ci.ENABLE_TRACKING?queueMicrotask(()=>{for(const n of this._listeners){var t;console.warn("dockview: stacktrace",(t=n.stacktrace)===null||t===void 0?void 0:t.print())}this._listeners=[]}):this._listeners=[]),Ci.ENABLE_TRACKING&&this._event&&Ci.MEMORY_LEAK_WATCHER.delete(this._event))}};ve.ENABLE_TRACKING=!1;ve.MEMORY_LEAK_WATCHER=new Bte;function ot(e,t,n,s){return e.addEventListener(t,n,s),{dispose:()=>{e.removeEventListener(t,n,s)}}}var oC=class{constructor(){this._onFired=new ve,this._currentFireCount=0,this._queued=!1,this.onEvent=e=>{const t=this._currentFireCount;return this._onFired.event(()=>{this._currentFireCount>t&&e()})}}fire(){this._currentFireCount++,!this._queued&&(this._queued=!0,queueMicrotask(()=>{this._queued=!1,this._onFired.fire()}))}dispose(){this._onFired.dispose()}},$te=class extends ct{constructor(e){super(),this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._value=null,this.addDisposables(this._onDidChange,kr(e,t=>{const n=t.target.scrollWidth>t.target.clientWidth,s=t.target.scrollHeight>t.target.clientHeight;this._value={hasScrollX:n,hasScrollY:s},this._onDidChange.fire(this._value)}))}};function kr(e,t){const n=new ResizeObserver(s=>{requestAnimationFrame(()=>{const o=s[0];t(o)})});return n.observe(e),{dispose:()=>{n.unobserve(e),n.disconnect()}}}const bi=(e,...t)=>{for(const n of t)e.classList.contains(n)&&e.classList.remove(n)},wi=(e,...t)=>{for(const n of t)e.classList.contains(n)||e.classList.add(n)},Ze=(e,t,n)=>{const s=e.classList.contains(t);n&&!s&&e.classList.add(t),!n&&s&&e.classList.remove(t)};function $m(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}function tE(e){return new Wte(e)}var Wte=class extends ct{constructor(e){super(),this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this.addDisposables(this._onDidFocus,this._onDidBlur);let t=$m(document.activeElement,e),n=!1;const s=()=>{n=!1,t||(t=!0,this._onDidFocus.fire())},o=()=>{t&&(n=!0,globalThis.setTimeout(()=>{n&&(n=!1,t=!1,this._onDidBlur.fire())},0))};this._refreshStateHandler=()=>{$m(document.activeElement,e)!==t&&(t?o():s())},this.addDisposables(ot(e,"focus",s,!0)),this.addDisposables(ot(e,"blur",o,!0))}refreshState(){this._refreshStateHandler()}};const nE="dv-quasiPreventDefault";function sE(e){e[nE]=!0}function rC(e){return e[nE]}function Ute(e,t,n={}){const s=Array.from(t),{nonce:o}=n,r=typeof o=="function"?o(e):o;for(const a of s){if(a.href){const c=e.createElement("link");c.href=a.href,c.type=a.type,c.rel="stylesheet",e.head.appendChild(c);continue}let l=[];try{a.cssRules&&(l=Array.from(a.cssRules).map(c=>c.cssText))}catch(c){console.warn("dockview: failed to access stylesheet rules due to security restrictions",c)}const d=e.createDocumentFragment();for(const c of l){const u=e.createElement("style");r&&u.setAttribute("nonce",r),u.appendChild(e.createTextNode(c)),d.appendChild(u)}e.head.appendChild(d)}}function Wm(e){const{left:t,top:n,width:s,height:o}=e.getBoundingClientRect();return{left:t+window.scrollX,top:n+window.scrollY,width:s,height:o}}function iE(e){let t=e;for(;t?.parentNode;){if(t.parentNode===document)return!0;t.parentNode instanceof DocumentFragment?t=t.parentNode.host:t=t.parentNode}return!1}function Kte(e,t){e.dataset.testid=t}function qte(e,t){const n=[];function s(o){if(o.nodeType===Node.ELEMENT_NODE){e.includes(o.tagName)&&n.push(o),o.shadowRoot&&s(o.shadowRoot);for(const r of o.children)s(r)}}return s(t instanceof Document?t.documentElement:t),n}function Jl(e=document){const t=qte(["IFRAME","WEBVIEW"],e),n=new WeakMap;for(const s of t)n.set(s,s.style.pointerEvents),s.style.pointerEvents="none";return{release:()=>{for(const o of t){var s;o.style.pointerEvents=(s=n.get(o))!==null&&s!==void 0?s:"auto"}t.splice(0,t.length)}}}function Yte(e){function t(o){const r=[];for(let a=0;a<o.classList.length;a++)r.push(o.classList.item(a));return r}let n,s=e;for(;s!==null&&(n=t(s).find(o=>o.startsWith("dockview-theme-")),typeof n!="string");)s=s.parentElement;return n}var Lh=class{constructor(e){this.element=e,this._classNames=[]}setClassNames(e){for(const t of this._classNames)Ze(this.element,t,!1);this._classNames=e.split(" ").filter(t=>t.trim().length>0);for(const t of this._classNames)Ze(this.element,t,!0)}};const oE=100;function sf(e,t){const n=Wm(e),s=Wm(t);return!(n.left<s.left||n.left+n.width>s.left+s.width||n.top<s.top||n.top+n.height>s.top+s.height)}function Xte(e){const t=new ve;let n=e.screenX,s=e.screenY,o,r=0,a=!1;const l=()=>{if(a||e.closed)return;const c=e.screenX,u=e.screenY;(c!==n||u!==s)&&(clearTimeout(o),o=setTimeout(()=>{t.fire()},oE),n=c,s=u),r=requestAnimationFrame(l)};l();const d=t.dispose.bind(t);return t.dispose=()=>{a||(a=!0,cancelAnimationFrame(r),clearTimeout(o)),d()},t}function Zte(e,t){let n;return new ct(ot(e,"resize",()=>{clearTimeout(n),n=setTimeout(()=>{t()},oE)}))}function Jte(e,t,n){var s;const o=(s=void 0)!==null&&s!==void 0?s:10,r=e.getBoundingClientRect(),a=t.getBoundingClientRect();let l=0,d=0;const c=r.left-a.left,u=r.top-a.top,h=r.bottom-a.bottom,p=r.right-a.right;c<o?l=o-c:p>o&&(l=-o-p),u<o?d=o-u:h>o&&(d=-h-o),(l!==0||d!==0)&&(e.style.transform=`translate(${l}px, ${d}px)`)}function Qte(e){let t=e;for(;t&&(t.style.zIndex==="auto"||t.style.zIndex==="");)t=t.parentElement;return t}function ao(e){if(e.length===0)throw new Error("Invalid tail call");return[e.slice(0,e.length-1),e[e.length-1]]}function rE(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function of(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))}function dc(e,t){const n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))}function ene(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(t(s))return n}return-1}function aE(e,t){const n=e.indexOf(t);return n>-1?(e.splice(n,1),!0):!1}const En=(e,t,n)=>t>n?t:Math.min(n,Math.max(e,t)),xv=()=>{let e=1;return{next:()=>(e++).toString()}},ii=(e,t)=>{const n=[];if(typeof t!="number"&&(t=e,e=0),e<=t)for(let s=e;s<t;s++)n.push(s);else for(let s=e;s>t;s--)n.push(s);return n};var tne=class{set size(e){this._size=e}setContainerGeometry(e,t){this._appliedStyles[e]!==t&&(this._appliedStyles[e]=t,this.container.style[e]=t)}get size(){return this._size}get cachedVisibleSize(){return this._cachedVisibleSize}get visible(){return this._cachedVisibleSize===void 0}get minimumSize(){return this.visible?this.view.minimumSize:0}get viewMinimumSize(){return this.view.minimumSize}get maximumSize(){return this.visible?this.view.maximumSize:0}get viewMaximumSize(){return this.view.maximumSize}get priority(){return this.view.priority}get snap(){return!!this.view.snap}set enabled(e){this.container.style.pointerEvents=e?"":"none"}constructor(e,t,n,s){this.container=e,this.view=t,this.disposable=s,this._cachedVisibleSize=void 0,this._appliedStyles={},typeof n=="number"?(this._size=n,this._cachedVisibleSize=void 0,e.classList.add("visible")):(this._size=0,this._cachedVisibleSize=n.cachedVisibleSize)}setVisible(e,t){if(e!==this.visible){if(e){var n;this.size=En((n=this._cachedVisibleSize)!==null&&n!==void 0?n:0,this.viewMinimumSize,this.viewMaximumSize),this._cachedVisibleSize=void 0}else this._cachedVisibleSize=typeof t=="number"?t:this.size,this.size=0;this.container.classList.toggle("visible",e),this.view.setVisible&&this.view.setVisible(e)}}dispose(){return this.disposable.dispose(),this.view}};function aC(e,t,n){e.appliedLeft!==t&&(e.appliedLeft=t,e.container.style.left=t),e.appliedTop!==n&&(e.appliedTop=n,e.container.style.top=n)}let ks;(function(e){e.Distribute={type:"distribute"};function t(s){return{type:"split",index:s}}e.Split=t;function n(s){return{type:"invisible",cachedVisibleSize:s}}e.Invisible=n})(ks||(ks={}));var yr=class{get contentSize(){return this._contentSize}get size(){return this._size}set size(e){this._size=e}get orthogonalSize(){return this._orthogonalSize}set orthogonalSize(e){this._orthogonalSize=e}get length(){return this.viewItems.length}get proportions(){return this._proportions?[...this._proportions]:void 0}get orientation(){return this._orientation}set orientation(e){this._orientation=e;const t=this.size;this.size=this.orthogonalSize,this.orthogonalSize=t,bi(this.element,"dv-horizontal","dv-vertical"),this.element.classList.add(this.orientation=="HORIZONTAL"?"dv-horizontal":"dv-vertical")}get minimumSize(){return this.viewItems.reduce((e,t)=>e+t.minimumSize,0)}get maximumSize(){return this.length===0?Number.POSITIVE_INFINITY:this.viewItems.reduce((e,t)=>e+t.maximumSize,0)}get startSnappingEnabled(){return this._startSnappingEnabled}set startSnappingEnabled(e){this._startSnappingEnabled!==e&&(this._startSnappingEnabled=e,this.updateSashEnablement())}get endSnappingEnabled(){return this._endSnappingEnabled}set endSnappingEnabled(e){this._endSnappingEnabled!==e&&(this._endSnappingEnabled=e,this.updateSashEnablement())}get disabled(){return this._disabled}set disabled(e){this._disabled=e,Ze(this.element,"dv-splitview-disabled",e)}get margin(){return this._margin}set margin(e){this._margin=e,Ze(this.element,"dv-splitview-has-margin",e!==0)}constructor(e,t){var n,s;this.container=e,this.viewItems=[],this.sashes=[],this._size=0,this._orthogonalSize=0,this._contentSize=0,this._proportions=void 0,this._startSnappingEnabled=!0,this._endSnappingEnabled=!0,this._disabled=!1,this._margin=0,this._onDidSashEnd=new ve,this.onDidSashEnd=this._onDidSashEnd.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this.resize=(o,r,a=this.viewItems.map(f=>f.size),l,d,c=Number.NEGATIVE_INFINITY,u=Number.POSITIVE_INFINITY,h,p)=>{if(o<0||o>this.viewItems.length)return 0;const f=ii(o,-1),g=ii(o+1,this.viewItems.length);if(d)for(const E of d)of(f,E),of(g,E);if(l)for(const E of l)dc(f,E),dc(g,E);const x=f.reduce((E,I)=>E+this.viewItems[I].minimumSize-a[I],0),v=f.reduce((E,I)=>E+this.viewItems[I].maximumSize-a[I],0),y=g.length===0?Number.POSITIVE_INFINITY:g.reduce((E,I)=>E+a[I]-this.viewItems[I].minimumSize,0),w=g.length===0?Number.NEGATIVE_INFINITY:g.reduce((E,I)=>E+a[I]-this.viewItems[I].maximumSize,0),b=Math.max(x,w),_=Math.min(y,v);let j=!1;if(h){const E=this.viewItems[h.index],I=r>=h.limitDelta;j=I!==E.visible,E.setVisible(I,h.size)}if(!j&&p){const E=this.viewItems[p.index],I=r<p.limitDelta;j=I!==E.visible,E.setVisible(I,p.size)}if(j)return this.resize(o,r,a,l,d,c,u);const N=En(r,b,_);let C=0,S=N;for(const E of f){const I=this.viewItems[E],D=a[E],T=En(D+S,I.minimumSize,I.maximumSize),z=T-D;C+=z,S-=z,I.size=T}let A=C;for(const E of g){const I=this.viewItems[E],D=a[E],T=En(D-A,I.minimumSize,I.maximumSize),z=T-D;A+=z,I.size=T}return r},this._orientation=(n=t.orientation)!==null&&n!==void 0?n:"VERTICAL",this.element=this.createContainer(),this.margin=(s=t.margin)!==null&&s!==void 0?s:0,this.proportionalLayout=t.proportionalLayout===void 0?!0:!!t.proportionalLayout,this.viewContainer=this.createViewContainer(),this.sashContainer=this.createSashContainer(),this.element.appendChild(this.sashContainer),this.element.appendChild(this.viewContainer),this.container.appendChild(this.element),this.style(t.styles),t.descriptor&&(this._size=t.descriptor.size,t.descriptor.views.forEach((o,r)=>{const a=o.visible===void 0||o.visible?o.size:{type:"invisible",cachedVisibleSize:o.size},l=o.view;this.addView(l,a,r,!0)}),this._contentSize=this.viewItems.reduce((o,r)=>o+r.size,0),this.saveProportions())}style(e){e?.separatorBorder==="transparent"?(bi(this.element,"dv-separator-border"),this.element.style.removeProperty("--dv-separator-border")):(wi(this.element,"dv-separator-border"),e?.separatorBorder&&this.element.style.setProperty("--dv-separator-border",e.separatorBorder))}isViewVisible(e){if(e<0||e>=this.viewItems.length)throw new Error("Index out of bounds");return this.viewItems[e].visible}setViewVisible(e,t){if(e<0||e>=this.viewItems.length)throw new Error("Index out of bounds");const n=this.viewItems[e];n.setVisible(t,n.size),this.distributeEmptySpace(e),this.layoutViews(),this.saveProportions()}getViewSize(e){return e<0||e>=this.viewItems.length?-1:this.viewItems[e].size}resizeView(e,t){if(e<0||e>=this.viewItems.length)return;const n=ii(this.viewItems.length).filter(a=>a!==e),s=[...n.filter(a=>this.viewItems[a].priority==="low"),e],o=n.filter(a=>this.viewItems[a].priority==="high"),r=this.viewItems[e];t=Math.round(t),t=En(t,r.minimumSize,Math.min(r.maximumSize,this._size)),r.size=t,this.relayout(s,o)}getViews(){return this.viewItems.map(e=>e.view)}onDidChange(e,t){const n=this.viewItems.indexOf(e);if(n<0||n>=this.viewItems.length)return;t=typeof t=="number"?t:e.size,t=En(t,e.minimumSize,e.maximumSize),e.size=t;const s=ii(this.viewItems.length).filter(a=>a!==n),o=[...s.filter(a=>this.viewItems[a].priority==="low"),n],r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout([...o,n],r)}addView(e,t=ks.Distribute,n=this.viewItems.length,s){const o=document.createElement("div");o.className="dv-view",o.appendChild(e.element);let r;typeof t=="number"?r=t:t.type==="split"?r=this.getViewSize(t.index)/2:t.type==="invisible"?r={cachedVisibleSize:t.cachedVisibleSize}:r=e.minimumSize;const a=e.onDidChange(d=>this.onDidChange(l,d.size)),l=new tne(o,e,r,{dispose:()=>{a.dispose(),o.remove()}});if(n===this.viewItems.length?this.viewContainer.appendChild(o):this.viewContainer.insertBefore(o,this.viewContainer.children.item(n)),this.viewItems.splice(n,0,l),this.viewItems.length>1){const d=document.createElement("div");d.className="dv-sash";const c=h=>{var p;for(const R of this.viewItems)R.enabled=!1;const f=(p=d.ownerDocument)!==null&&p!==void 0?p:document,g=Jl(f),x=this._orientation==="HORIZONTAL"?h.clientX:h.clientY,v=ene(this.sashes,R=>R.container===d),y=this.viewItems.map(R=>R.size);let w,b;const _=ii(v,-1),j=ii(v+1,this.viewItems.length),N=_.reduce((R,B)=>R+(this.viewItems[B].minimumSize-y[B]),0),C=_.reduce((R,B)=>R+(this.viewItems[B].viewMaximumSize-y[B]),0),S=j.length===0?Number.POSITIVE_INFINITY:j.reduce((R,B)=>R+(y[B]-this.viewItems[B].minimumSize),0),A=j.length===0?Number.NEGATIVE_INFINITY:j.reduce((R,B)=>R+(y[B]-this.viewItems[B].viewMaximumSize),0),E=Math.max(N,A),I=Math.min(S,C),D=this.findFirstSnapIndex(_),T=this.findFirstSnapIndex(j);if(typeof D=="number"){const R=this.viewItems[D],B=Math.floor(R.viewMinimumSize/2);w={index:D,limitDelta:R.visible?E-B:E+B,size:R.size}}if(typeof T=="number"){const R=this.viewItems[T],B=Math.floor(R.viewMinimumSize/2);b={index:T,limitDelta:R.visible?I+B:I-B,size:R.size}}const z=R=>{const B=(this._orientation==="HORIZONTAL"?R.clientX:R.clientY)-x;this.resize(v,B,y,void 0,void 0,E,I,w,b),this.distributeEmptySpace(),this.layoutViews()},$=()=>{for(const R of this.viewItems)R.enabled=!0;g.release(),this.saveProportions(),f.removeEventListener("pointermove",z),f.removeEventListener("pointerup",$),f.removeEventListener("pointercancel",$),f.removeEventListener("contextmenu",$),this._onDidSashEnd.fire(void 0)};f.addEventListener("pointermove",z),f.addEventListener("pointerup",$),f.addEventListener("pointercancel",$),f.addEventListener("contextmenu",$)};d.addEventListener("pointerdown",c);const u={container:d,disposable:()=>{d.removeEventListener("pointerdown",c),d.remove()}};this.sashContainer.appendChild(d),this.sashes.push(u)}s||this.relayout([n]),!s&&typeof t!="number"&&t.type==="distribute"&&this.distributeViewSizes(),this._onDidAddView.fire(e)}distributeViewSizes(){const e=[];let t=0;for(const a of this.viewItems)a.maximumSize-a.minimumSize>0&&(e.push(a),t+=a.size);const n=Math.floor(t/e.length);for(const a of e)a.size=En(n,a.minimumSize,a.maximumSize);const s=ii(this.viewItems.length),o=s.filter(a=>this.viewItems[a].priority==="low"),r=s.filter(a=>this.viewItems[a].priority==="high");this.relayout(o,r)}removeView(e,t,n=!1){const s=this.viewItems.splice(e,1)[0];if(s.dispose(),this.viewItems.length>=1){const o=Math.max(e-1,0);this.sashes.splice(o,1)[0].disposable()}return n||this.relayout(),t?.type==="distribute"&&this.distributeViewSizes(),this._onDidRemoveView.fire(s.view),s.view}getViewCachedVisibleSize(e){if(e<0||e>=this.viewItems.length)throw new Error("Index out of bounds");return this.viewItems[e].cachedVisibleSize}moveView(e,t){const n=this.getViewCachedVisibleSize(e),s=n===void 0?this.getViewSize(e):ks.Invisible(n),o=this.removeView(e,void 0,!0);this.addView(o,s,t)}layout(e,t){const n=Math.max(this.size,this._contentSize);if(this.size=e,this.orthogonalSize=t,this.proportions){let s=0;for(let o=0;o<this.viewItems.length;o++){const r=this.viewItems[o],a=this.proportions[o];typeof a=="number"?s+=a:e-=r.size}for(let o=0;o<this.viewItems.length;o++){const r=this.viewItems[o],a=this.proportions[o];typeof a=="number"&&s>0&&(r.size=En(Math.round(a*e/s),r.minimumSize,r.maximumSize))}}else{const s=ii(this.viewItems.length),o=s.filter(a=>this.viewItems[a].priority==="low"),r=s.filter(a=>this.viewItems[a].priority==="high");this.resize(this.viewItems.length-1,e-n,void 0,o,r)}this.distributeEmptySpace(),this.layoutViews()}relayout(e,t){const n=this.viewItems.reduce((s,o)=>s+o.size,0);this.resize(this.viewItems.length-1,this._size-n,void 0,e,t),this.distributeEmptySpace(),this.layoutViews(),this.saveProportions()}distributeEmptySpace(e){let t=0;for(const r of this.viewItems)t+=r.size;let n=this.size-t;if(n===0)return;const s=ii(this.viewItems.length-1,-1);let o=!1;for(const r of this.viewItems)if(r.priority==="low"||r.priority==="high"){o=!0;break}if(o){const r=s.filter(l=>this.viewItems[l].priority==="low"),a=s.filter(l=>this.viewItems[l].priority==="high");for(const l of a)of(s,l);for(const l of r)dc(s,l)}typeof e=="number"&&dc(s,e);for(let r=0;n!==0&&r<s.length;r++){const a=this.viewItems[s[r]],l=En(a.size+n,a.minimumSize,a.maximumSize),d=l-a.size;n-=d,a.size=l}}saveProportions(){this.proportionalLayout&&this._contentSize>0&&(this._proportions=this.viewItems.map(e=>e.visible?e.size/this._contentSize:void 0))}layoutViews(){let e=0,t=0;for(const d of this.viewItems)e+=d.size,d.visible&&t++;if(this._contentSize=e,this.updateSashEnablement(),this.viewItems.length===0)return;const n=Math.max(0,t-1),s=this.margin*n/Math.max(1,t);let o=0;const r=[],a=4;let l=0;this.viewItems.forEach((d,c)=>{o+=this.viewItems[c].size,r.push(o),l+=d.visible?1:0;const u=d.visible?d.size-s:0,h=Math.max(0,l-1),p=c===0||h===0?0:r[c-1]+h/n*s;if(c<this.viewItems.length-1){const f=d.visible?p+u-a/2+this.margin/2:p,g=this.sashes[c];this._orientation==="HORIZONTAL"&&aC(g,`${f}px`,"0px"),this._orientation==="VERTICAL"&&aC(g,"0px",`${f}px`)}this._orientation==="HORIZONTAL"&&(d.setContainerGeometry("width",`${u}px`),d.setContainerGeometry("left",`${p}px`),d.setContainerGeometry("top",""),d.setContainerGeometry("height","")),this._orientation==="VERTICAL"&&(d.setContainerGeometry("height",`${u}px`),d.setContainerGeometry("top",`${p}px`),d.setContainerGeometry("width",""),d.setContainerGeometry("left","")),d.view.layout(d.size-s,this._orthogonalSize)})}findFirstSnapIndex(e){for(const t of e){const n=this.viewItems[t];if(n.visible&&n.snap)return t}for(const t of e){const n=this.viewItems[t];if(n.visible&&n.maximumSize-n.minimumSize>0)return;if(!n.visible&&n.snap)return t}}updateSashEnablement(){if(this.sashes.length===0)return;let e=!1;const t=this.viewItems.map(l=>e=l.size-l.minimumSize>0||e);e=!1;const n=this.viewItems.map(l=>e=l.maximumSize-l.size>0||e),s=[...this.viewItems].reverse();e=!1;const o=s.map(l=>e=l.size-l.minimumSize>0||e).reverse();e=!1;const r=s.map(l=>e=l.maximumSize-l.size>0||e).reverse();let a=0;for(let l=0;l<this.sashes.length;l++){const d=this.sashes[l],c=this.viewItems[l];a+=c.size;const u=!(t[l]&&r[l+1]),h=!(n[l]&&o[l+1]);if(u&&h){const p=ii(l,-1),f=ii(l+1,this.viewItems.length),g=this.findFirstSnapIndex(p),x=this.findFirstSnapIndex(f),v=typeof g=="number"&&!this.viewItems[g].visible,y=typeof x=="number"&&!this.viewItems[x].visible;v&&o[l]&&(a>0||this.startSnappingEnabled)?this.updateSash(d,1):y&&t[l]&&(a<this._contentSize||this.endSnappingEnabled)?this.updateSash(d,0):this.updateSash(d,2)}else u&&!h?this.updateSash(d,1):!u&&h?this.updateSash(d,0):this.updateSash(d,3)}}updateSash(e,t){Ze(e.container,"dv-disabled",t===2),Ze(e.container,"dv-enabled",t===3),Ze(e.container,"dv-maximum",t===0),Ze(e.container,"dv-minimum",t===1)}createViewContainer(){const e=document.createElement("div");return e.className="dv-view-container",e}createSashContainer(){const e=document.createElement("div");return e.className="dv-sash-container",e}createContainer(){const e=document.createElement("div");return e.className=`dv-split-view-container ${this._orientation==="HORIZONTAL"?"dv-horizontal":"dv-vertical"}`,e}dispose(){this._onDidSashEnd.dispose(),this._onDidAddView.dispose(),this._onDidRemoveView.dispose();for(let e=0;e<this.element.children.length;e++)if(this.element.children.item(e)===this.element){this.element.remove();break}for(const e of this.viewItems)e.dispose();this.element.remove()}};const Um=Object.keys({orientation:void 0,descriptor:void 0,proportionalLayout:void 0,styles:void 0,margin:void 0,disableAutoResizing:void 0,className:void 0});var lC=class extends ct{get onDidAddView(){return this.splitview.onDidAddView}get onDidRemoveView(){return this.splitview.onDidRemoveView}get minimumSize(){return this.splitview.minimumSize}get maximumSize(){return this.splitview.maximumSize}get orientation(){return this.splitview.orientation}get size(){return this.splitview.size}get orthogonalSize(){return this.splitview.orthogonalSize}constructor(e,t){var n;super(),this.paneItems=[],this.skipAnimation=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orientation=(n=t.orientation)!==null&&n!==void 0?n:"VERTICAL",this.element=document.createElement("div"),this.element.className="dv-pane-container",e.appendChild(this.element),this.splitview=new yr(this.element,{orientation:this._orientation,proportionalLayout:!1,descriptor:t.descriptor}),this.getPanes().forEach(s=>{const o=new ct(s.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)})),r={pane:s,disposable:{dispose:()=>{o.dispose()}}};this.paneItems.push(r),s.orthogonalSize=this.splitview.orthogonalSize}),this.addDisposables(this._onDidChange,this.splitview.onDidSashEnd(()=>{this._onDidChange.fire(void 0)}),this.splitview.onDidAddView(()=>{this._onDidChange.fire()}),this.splitview.onDidRemoveView(()=>{this._onDidChange.fire()}))}setViewVisible(e,t){this.splitview.setViewVisible(e,t)}addPane(e,t,n=this.splitview.length,s=!1){const o=e.onDidChangeExpansionState(()=>{this.setupAnimation(),this._onDidChange.fire(void 0)}),r={pane:e,disposable:{dispose:()=>{o.dispose()}}};this.paneItems.splice(n,0,r),e.orthogonalSize=this.splitview.orthogonalSize,this.splitview.addView(e,t,n,s)}getViewSize(e){return this.splitview.getViewSize(e)}getViewCachedVisibleSize(e){return this.splitview.getViewCachedVisibleSize(e)}getPanes(){return this.splitview.getViews()}removePane(e,t){const n=this.paneItems.splice(e,1)[0];return this.splitview.removeView(e),t?.skipDispose||(n.disposable.dispose(),n.pane.dispose()),n}moveView(e,t){if(e===t)return;const n=this.removePane(e,{skipDispose:!0});n.disposable.dispose(),this.skipAnimation=!0;try{this.addPane(n.pane,n.pane.size,t,!1)}finally{this.skipAnimation=!1}}layout(e,t){this.splitview.layout(e,t)}setupAnimation(){this.skipAnimation||(this.animationTimer&&(clearTimeout(this.animationTimer),this.animationTimer=void 0),wi(this.element,"dv-animated"),this.animationTimer=setTimeout(()=>{this.animationTimer=void 0,bi(this.element,"dv-animated")},200))}dispose(){super.dispose(),this.animationTimer&&(clearTimeout(this.animationTimer),this.animationTimer=void 0),this.paneItems.forEach(e=>{e.disposable.dispose(),e.pane.dispose()}),this.paneItems=[],this.splitview.dispose(),this.element.remove()}},rs=class{get minimumWidth(){return this.view.minimumWidth}get maximumWidth(){return this.view.maximumWidth}get minimumHeight(){return this.view.minimumHeight}get maximumHeight(){return this.view.maximumHeight}get priority(){return this.view.priority}get snap(){return this.view.snap}get minimumSize(){return this.orientation==="HORIZONTAL"?this.minimumHeight:this.minimumWidth}get maximumSize(){return this.orientation==="HORIZONTAL"?this.maximumHeight:this.maximumWidth}get minimumOrthogonalSize(){return this.orientation==="HORIZONTAL"?this.minimumWidth:this.minimumHeight}get maximumOrthogonalSize(){return this.orientation==="HORIZONTAL"?this.maximumWidth:this.maximumHeight}get orthogonalSize(){return this._orthogonalSize}get size(){return this._size}get element(){return this.view.element}get width(){return this.orientation==="HORIZONTAL"?this.orthogonalSize:this.size}get height(){return this.orientation==="HORIZONTAL"?this.size:this.orthogonalSize}constructor(e,t,n,s=0){this.view=e,this.orientation=t,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orthogonalSize=n,this._size=s,this._disposable=this.view.onDidChange(o=>{o?this._onDidChange.fire({size:this.orientation==="VERTICAL"?o.width:o.height,orthogonalSize:this.orientation==="VERTICAL"?o.height:o.width}):this._onDidChange.fire({})})}setVisible(e){this.view.setVisible&&this.view.setVisible(e)}layout(e,t){this._size=e,this._orthogonalSize=t,this.view.layout(this.width,this.height)}dispose(){this._onDidChange.dispose(),this._disposable.dispose()}},Yn=class Km extends ct{get width(){return this.orientation==="HORIZONTAL"?this.size:this.orthogonalSize}get height(){return this.orientation==="HORIZONTAL"?this.orthogonalSize:this.size}get minimumSize(){if(this._cachedMinimumSize===void 0){let t=0;for(let n=0;n<this.children.length;n++)this.splitview.isViewVisible(n)&&(t=Math.max(t,this.children[n].minimumOrthogonalSize));this._cachedMinimumSize=t}return this._cachedMinimumSize}get maximumSize(){if(this._cachedMaximumSize===void 0){let t=Number.POSITIVE_INFINITY;for(let n=0;n<this.children.length;n++)this.splitview.isViewVisible(n)&&(t=Math.min(t,this.children[n].maximumOrthogonalSize));this._cachedMaximumSize=t}return this._cachedMaximumSize}get minimumOrthogonalSize(){return this.splitview.minimumSize}get maximumOrthogonalSize(){return this.splitview.maximumSize}get orthogonalSize(){return this._orthogonalSize}get size(){return this._size}get minimumWidth(){return this.orientation==="HORIZONTAL"?this.minimumOrthogonalSize:this.minimumSize}get minimumHeight(){return this.orientation==="HORIZONTAL"?this.minimumSize:this.minimumOrthogonalSize}get maximumWidth(){return this.orientation==="HORIZONTAL"?this.maximumOrthogonalSize:this.maximumSize}get maximumHeight(){return this.orientation==="HORIZONTAL"?this.maximumSize:this.maximumOrthogonalSize}get priority(){var t;return(t=this._cachedPriority)!==null&&t!==void 0||(this._cachedPriority=this.computePriority()),this._cachedPriority}computePriority(){if(this.children.length===0)return"normal";let t=!1,n=!1;for(const o of this.children){var s;const r=(s=o.priority)!==null&&s!==void 0?s:"normal";r==="high"?t=!0:r==="low"&&(n=!0)}return t?"high":n?"low":"normal"}invalidateCachedSizes(){this._cachedMinimumSize=void 0,this._cachedMaximumSize=void 0,this._cachedPriority=void 0}get disabled(){return this.splitview.disabled}set disabled(t){this.splitview.disabled=t}get margin(){return this.splitview.margin}set margin(t){this.splitview.margin=t,this.children.forEach(n=>{n instanceof Km&&(n.margin=t)})}constructor(t,n,s,o,r,a,l,d){if(super(),this.orientation=t,this.proportionalLayout=n,this.styles=s,this._childrenDisposable=rn.NONE,this.children=[],this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidVisibilityChange=new ve,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._orthogonalSize=r,this._size=o,this.element=document.createElement("div"),this.element.className="dv-branch-node",d){const c={views:d.map(u=>{var h;return{view:u.node,size:u.node.size,visible:(h=u.visible)!==null&&h!==void 0?h:!0}}),size:this.orthogonalSize};this.children=d.map(u=>u.node),this.splitview=new yr(this.element,{orientation:this.orientation,descriptor:c,proportionalLayout:n,styles:s,margin:l})}else this.splitview=new yr(this.element,{orientation:this.orientation,proportionalLayout:n,styles:s,margin:l}),this.splitview.layout(this.size,this.orthogonalSize);this.disabled=a,this.addDisposables(this._onDidChange,this._onDidVisibilityChange,this.splitview.onDidSashEnd(()=>{this._onDidChange.fire({})})),this.setupChildrenEvents()}setVisible(t){}isChildVisible(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.isViewVisible(t)}setChildVisible(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");if(this.splitview.isViewVisible(t)===n)return;const s=this.splitview.contentSize===0;this.splitview.setViewVisible(t,n),this.invalidateCachedSizes();const o=this.splitview.contentSize===0;(n&&s||!n&&o)&&this._onDidVisibilityChange.fire({visible:n})}moveChild(t,n){if(t===n)return;if(t<0||t>=this.children.length)throw new Error("Invalid from index");t<n&&n--,this.splitview.moveView(t,n);const s=this._removeChild(t);this._addChild(s,n)}getChildSize(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.getViewSize(t)}resizeChild(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");this.splitview.resizeView(t,n)}layout(t,n){this._size=n,this._orthogonalSize=t,this.splitview.layout(n,t)}addChild(t,n,s,o){if(s<0||s>this.children.length)throw new Error("Invalid index");this.splitview.addView(t,n,s,o),this._addChild(t,s)}getChildCachedVisibleSize(t){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.getViewCachedVisibleSize(t)}removeChild(t,n){if(t<0||t>=this.children.length)throw new Error("Invalid index");return this.splitview.removeView(t,n),this._removeChild(t)}_addChild(t,n){this.children.splice(n,0,t),this.setupChildrenEvents()}_removeChild(t){const[n]=this.children.splice(t,1);return this.setupChildrenEvents(),n}setupChildrenEvents(){this.invalidateCachedSizes(),this._childrenDisposable.dispose(),this._childrenDisposable=new ct(Qs.any(...this.children.map(t=>t.onDidChange))(t=>{this.invalidateCachedSizes(),this._onDidChange.fire({size:t.orthogonalSize})}),...this.children.map((t,n)=>t instanceof Km?t.onDidVisibilityChange(({visible:s})=>{this.setChildVisible(n,s)}):rn.NONE))}dispose(){this._childrenDisposable.dispose(),this.splitview.dispose(),this.children.forEach(t=>t.dispose()),super.dispose()}};function qm(e,t){if(e instanceof rs)return e;if(e instanceof Yn)return qm(e.children[t?e.children.length-1:0],t);throw new Error("invalid node")}function lE(e,t,n){if(e instanceof Yn){const s=new Yn(e.orientation,e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);for(let o=e.children.length-1;o>=0;o--){const r=e.children[o];s.addChild(lE(r,r.size,r.orthogonalSize),r.size,0,!0)}return s}else return new rs(e.view,e.orientation,n)}function Ym(e,t,n){if(e instanceof Yn){const s=new Yn(Ni(e.orientation),e.proportionalLayout,e.styles,t,n,e.disabled,e.margin);let o=0;for(let r=e.children.length-1;r>=0;r--){const a=e.children[r],l=a instanceof Yn?a.orthogonalSize:a.size;let d=e.size===0?0:Math.round(t*l/e.size);o+=d,r===0&&(d+=t-o),s.addChild(Ym(a,n,d),d,0,!0)}return s}else return new rs(e.view,Ni(e.orientation),n)}function nne(e){const t=e.parentElement;if(!t)throw new Error("Invalid grid element");let n=t.firstElementChild,s=0;for(;n!==e&&n!==t.lastElementChild&&n;)n=n.nextElementSibling,s++;return s}function Tn(e){const t=e.parentElement;if(!t)throw new Error("Invalid grid element");if(/\bdv-grid-view\b/.test(t.className))return[];const n=nne(t),s=t.parentElement.parentElement.parentElement;return[...Tn(s),n]}function Vs(e,t,n){if(ine(e,t)===sne(n)){const[s,o]=ao(t);let r=o;return(n==="right"||n==="bottom")&&(r+=1),[...s,r]}else{const s=n==="right"||n==="bottom"?1:0;return[...t,s]}}function sne(e){return e==="top"||e==="bottom"?"VERTICAL":"HORIZONTAL"}function ine(e,t){return t.length%2===0?Ni(e):e}const Ni=e=>e==="HORIZONTAL"?"VERTICAL":"HORIZONTAL";function one(e){return!!e.children}const Xm=(e,t)=>{const n=t==="VERTICAL"?e.box.width:e.box.height;if(!one(e))return typeof e.cachedVisibleSize=="number"?{type:"leaf",data:e.view.toJSON(),size:e.cachedVisibleSize,visible:!1}:{type:"leaf",data:e.view.toJSON(),size:n};const s=e.children.map(o=>Xm(o,Ni(t)));return typeof e.cachedVisibleSize=="number"?{type:"branch",data:s,size:e.cachedVisibleSize,visible:!1}:{type:"branch",data:s,size:n}};var dE=class{get length(){return this._root?this._root.children.length:0}get orientation(){return this.root.orientation}set orientation(e){if(this.root.orientation===e)return;const{size:t,orthogonalSize:n}=this.root;this.root=Ym(this.root,n,t),this.root.layout(t,n)}get width(){return this.root.width}get height(){return this.root.height}get minimumWidth(){return this.root.minimumWidth}get minimumHeight(){return this.root.minimumHeight}get maximumWidth(){return this.root.maximumWidth}get maximumHeight(){return this.root.maximumHeight}get locked(){return this._locked}set locked(e){this._locked=e;const t=[this.root];for(;t.length>0;){const n=t.pop();n instanceof Yn&&(n.disabled=e,t.push(...n.children))}}get margin(){return this._margin}set margin(e){this._margin=e,this.root.margin=e}maximizedView(){var e;return(e=this._maximizedNode)===null||e===void 0?void 0:e.leaf.view}hasMaximizedView(){return this._maximizedNode!==void 0}maximizeView(e){var t;const n=Tn(e.element),[s,o]=this.getNode(n);if(!(o instanceof rs)||((t=this._maximizedNode)===null||t===void 0?void 0:t.leaf)===o)return;this.hasMaximizedView()&&this.exitMaximizedView(),Xm(this.getView(),this.orientation);const r=[];function a(l,d){for(let c=0;c<l.children.length;c++){const u=l.children[c];u instanceof rs?u!==d&&(l.isChildVisible(c)?l.setChildVisible(c,!1):r.push(u)):a(u,d)}}a(this.root,o),this._maximizedNode={leaf:o,hiddenOnMaximize:r},this._onDidMaximizedNodeChange.fire({view:o.view,isMaximized:!0})}exitMaximizedView(){if(!this._maximizedNode)return;const e=this._maximizedNode.hiddenOnMaximize;function t(s){for(let o=s.children.length-1;o>=0;o--){const r=s.children[o];r instanceof rs?e.includes(r)||s.setChildVisible(o,!0):t(r)}}t(this.root);const n=this._maximizedNode.leaf;this._maximizedNode=void 0,this._onDidMaximizedNodeChange.fire({view:n.view,isMaximized:!1})}serialize(){const e=this.maximizedView();let t;e&&(t=Tn(e.element));const n=this._onDidMaximizedNodeChange.pause();try{this.hasMaximizedView()&&this.exitMaximizedView();const s={root:Xm(this.getView(),this.orientation),width:this.width,height:this.height,orientation:this.orientation};return t&&(s.maximizedNode={location:t}),e&&this.maximizeView(e),s}finally{n.dispose()}}dispose(){this.disposable.dispose(),this._onDidChange.dispose(),this._onDidMaximizedNodeChange.dispose(),this._onDidViewVisibilityChange.dispose(),this.root.dispose(),this._maximizedNode=void 0,this.element.remove()}clear(){const e=this.root.orientation;this.root=new Yn(e,this.proportionalLayout,this.styles,this.root.size,this.root.orthogonalSize,this.locked,this.margin)}deserialize(e,t){const n=e.orientation,s=n==="VERTICAL"?e.height:e.width;if(this._deserialize(e.root,n,t,s),this.layout(e.width,e.height),e.maximizedNode){const o=e.maximizedNode.location,[r,a]=this.getNode(o);if(!(a instanceof rs))return;this.maximizeView(a.view)}}_deserialize(e,t,n,s){this.root=this._deserializeNode(e,t,n,s)}_deserializeNode(e,t,n,s){let o;if(e.type==="branch"){const a=e.data.map(l=>({node:this._deserializeNode(l,Ni(t),n,e.size),visible:l.visible}));o=new Yn(t,this.proportionalLayout,this.styles,e.size,s,this.locked,this.margin,a)}else{const a=n.fromJSON(e);if(typeof e.visible=="boolean"){var r;(r=a.setVisible)===null||r===void 0||r.call(a,e.visible)}o=new rs(a,t,s,e.size)}return o}get root(){return this._root}set root(e){const t=this._root;t&&(t.dispose(),this._maximizedNode=void 0,t.element.remove()),this._root=e,this.element.appendChild(this._root.element),this.disposable.value=this._root.onDidChange(n=>{this._onDidChange.fire(n)})}normalize(){if(!this._root||this._root.children.length!==1)return;const e=this.root,t=e.children[0];if(t instanceof rs)return;e.element.remove();const n=e.removeChild(0);e.dispose(),n.dispose(),this._root=lE(t,t.size,t.orthogonalSize),this.element.appendChild(this._root.element),this.disposable.value=this._root.onDidChange(s=>{this._onDidChange.fire(s)})}insertOrthogonalSplitviewAtRoot(){if(!this._root)return;const e=this.root;if(e.element.remove(),this._root=new Yn(Ni(e.orientation),this.proportionalLayout,this.styles,this.root.orthogonalSize,this.root.size,this.locked,this.margin),e.children.length!==0)if(e.children.length===1){const t=e.children[0];e.removeChild(0).dispose(),e.dispose(),this._root.addChild(Ym(t,t.orthogonalSize,t.size),ks.Distribute,0)}else this._root.addChild(e,ks.Distribute,0);this.element.appendChild(this._root.element),this.disposable.value=this._root.onDidChange(t=>{this._onDidChange.fire(t)})}next(e){return this.progmaticSelect(e)}previous(e){return this.progmaticSelect(e,!0)}getView(e){const t=e?this.getNode(e)[1]:this.root;return this._getViews(t,this.orientation)}_getViews(e,t,n){const s={height:e.height,width:e.width};if(e instanceof rs)return{box:s,view:e.view,cachedVisibleSize:n};const o=[];for(let r=0;r<e.children.length;r++){const a=e.children[r],l=e.getChildCachedVisibleSize(r);o.push(this._getViews(a,Ni(t),l))}return{box:s,children:o,cachedVisibleSize:n}}progmaticSelect(e,t=!1){const[n,s]=this.getNode(e);if(!(s instanceof rs))throw new TypeError("invalid location");for(let o=n.length-1;o>-1;o--){const r=n[o],a=e[o]||0;if(t?a-1>-1:a+1<r.children.length)return qm(r.children[t?a-1:a+1],t)}return qm(this.root,t)}constructor(e,t,n,s,o){this.proportionalLayout=e,this.styles=t,this._locked=!1,this._margin=0,this._maximizedNode=void 0,this.disposable=new Fn,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidViewVisibilityChange=new ve,this.onDidViewVisibilityChange=this._onDidViewVisibilityChange.event,this._onDidMaximizedNodeChange=new ve,this.onDidMaximizedNodeChange=this._onDidMaximizedNodeChange.event,this.element=document.createElement("div"),this.element.className="dv-grid-view",this._locked=s??!1,this._margin=o??0,this.root=new Yn(n,e,t,0,0,this.locked,this.margin)}isViewVisible(e){const[t,n]=ao(e),[,s]=this.getNode(t);if(!(s instanceof Yn))throw new TypeError("Invalid from location");return s.isChildVisible(n)}setViewVisible(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=ao(e),[,o]=this.getNode(n);if(!(o instanceof Yn))throw new TypeError("Invalid from location");this._onDidViewVisibilityChange.fire(),o.setChildVisible(s,t)}moveView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[,s]=this.getNode(e);if(!(s instanceof Yn))throw new TypeError("Invalid location");s.moveChild(t,n)}addView(e,t,n){this.hasMaximizedView()&&this.exitMaximizedView();const[s,o]=ao(n),[r,a]=this.getNode(s);if(a instanceof Yn){const l=new rs(e,Ni(a.orientation),a.orthogonalSize);a.addChild(l,t,o)}else{const[l,...d]=[...r].reverse(),[c,...u]=[...s].reverse();let h=0;const p=l.getChildCachedVisibleSize(c);typeof p=="number"&&(h=ks.Invisible(p)),l.removeChild(c).dispose();const f=new Yn(a.orientation,this.proportionalLayout,this.styles,a.size,a.orthogonalSize,this.locked,this.margin);l.addChild(f,a.size,c);const g=new rs(a.view,l.orientation,a.size);f.addChild(g,h,0),typeof t!="number"&&t.type==="split"&&(t={type:"split",index:0});const x=new rs(e,l.orientation,a.size);f.addChild(x,t,o)}}remove(e,t){const n=Tn(e.element);return this.removeView(n,t)}removeView(e,t){this.hasMaximizedView()&&this.exitMaximizedView();const[n,s]=ao(e),[o,r]=this.getNode(n);if(!(r instanceof Yn))throw new TypeError("Invalid location");const a=r.children[s];if(!(a instanceof rs))throw new TypeError("Invalid location");if(r.removeChild(s,t),a.dispose(),r.children.length!==1)return a.view;const l=r.children[0];if(o.length===0)return l instanceof rs||(r.removeChild(0,t),this.root=l),a.view;const[d,...c]=[...o].reverse(),[u,...h]=[...n].reverse(),p=r.isChildVisible(0);r.removeChild(0,t);const f=d.children.map((g,x)=>d.getChildSize(x));if(d.removeChild(u,t).dispose(),l instanceof Yn){f.splice(u,1,...l.children.map(g=>g.size));for(let g=0;g<l.children.length;g++){const x=l.children[g];d.addChild(x,x.size,u+g)}for(;l.children.length>0;)l.removeChild(0)}else{const g=new rs(l.view,Ni(l.orientation),l.size),x=p?l.orthogonalSize:ks.Invisible(l.orthogonalSize);d.addChild(g,x,u)}l.dispose();for(let g=0;g<f.length;g++)d.resizeChild(g,f[g]);return a.view}layout(e,t){const[n,s]=this.root.orientation==="HORIZONTAL"?[t,e]:[e,t];this.root.layout(n,s)}getNode(e,t=this.root,n=[]){if(e.length===0)return[n,t];if(!(t instanceof Yn))throw new TypeError("Invalid location");const[s,...o]=e;if(s<0||s>=t.children.length)throw new Error("Invalid location");const r=t.children[s];return n.push(t),this.getNode(o,r,n)}};const Zm=Object.keys({disableAutoResizing:void 0,proportionalLayout:void 0,orientation:void 0,hideBorders:void 0,className:void 0});var vv=class extends ct{get element(){return this._element}get disableResizing(){return this._disableResizing}set disableResizing(e){this._disableResizing=e}constructor(e,t=!1){super(),this._lastWidth=-1,this._lastHeight=-1,this._disableResizing=t,this._element=e,this.addDisposables(kr(this._element,n=>{if(this.isDisposed||this.disableResizing||!this._element.offsetParent||!iE(this._element))return;const s=Math.round(n.contentRect.width),o=Math.round(n.contentRect.height);s===this._lastWidth&&o===this._lastHeight||(this._lastWidth=s,this._lastHeight=o,this.layout(s,o))}))}};const rne=xv();function Ou(e){switch(e){case"left":return"left";case"right":return"right";case"above":return"top";case"below":return"bottom";default:return"center"}}var cE=class extends vv{get id(){return this._id}get size(){return this._groups.size}get groups(){return Array.from(this._groups.values()).map(e=>e.value)}get width(){return this.gridview.width}get height(){return this.gridview.height}get minimumHeight(){return this.gridview.minimumHeight}get maximumHeight(){return this.gridview.maximumHeight}get minimumWidth(){return this.gridview.minimumWidth}get maximumWidth(){return this.gridview.maximumWidth}get activeGroup(){return this._activeGroup}get locked(){return this.gridview.locked}set locked(e){this.gridview.locked=e}constructor(e,t){var n;super(document.createElement("div"),t.disableAutoResizing),this._id=rne.next(),this._groups=new Map,this._onDidRemove=new ve,this.onDidRemove=this._onDidRemove.event,this._onDidAdd=new ve,this.onDidAdd=this._onDidAdd.event,this._onDidMaximizedChange=new ve,this.onDidMaximizedChange=this._onDidMaximizedChange.event,this._onDidActiveChange=new ve,this.onDidActiveChange=this._onDidActiveChange.event,this._bufferOnDidLayoutChange=new oC,this.onDidLayoutChange=this._bufferOnDidLayoutChange.onEvent,this._onDidViewVisibilityChangeMicroTaskQueue=new oC,this.onDidViewVisibilityChangeMicroTaskQueue=this._onDidViewVisibilityChangeMicroTaskQueue.onEvent,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Lh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this.gridview=new dE(!!t.proportionalLayout,t.styles,t.orientation,t.locked,t.margin),this.gridview.locked=!!t.locked,this.element.appendChild(this.gridview.element),this.layout(0,0,!0),this.addDisposables(this.gridview.onDidMaximizedNodeChange(s=>{this._onDidMaximizedChange.fire({panel:s.view,isMaximized:s.isMaximized})}),this.gridview.onDidViewVisibilityChange(()=>this._onDidViewVisibilityChangeMicroTaskQueue.fire()),this.onDidViewVisibilityChangeMicroTaskQueue(()=>{this.forceRelayout()}),rn.from(()=>{this.element.remove()}),this.gridview.onDidChange(()=>{this._bufferOnDidLayoutChange.fire()}),Qs.any(this.onDidAdd,this.onDidRemove,this.onDidActiveChange)(()=>{this._bufferOnDidLayoutChange.fire()}),this._onDidMaximizedChange,this._onDidViewVisibilityChangeMicroTaskQueue,this._bufferOnDidLayoutChange)}setVisible(e,t){this.gridview.setViewVisible(Tn(e.element),t),this._bufferOnDidLayoutChange.fire()}isVisible(e){return this.gridview.isViewVisible(Tn(e.element))}updateOptions(e){if(e.proportionalLayout,e.orientation&&(this.gridview.orientation=e.orientation),"disableAutoResizing"in e){var t;this.disableResizing=(t=e.disableAutoResizing)!==null&&t!==void 0?t:!1}if("locked"in e){var n;this.locked=(n=e.locked)!==null&&n!==void 0?n:!1}if("margin"in e){var s;this.gridview.margin=(s=e.margin)!==null&&s!==void 0?s:0}if("className"in e){var o;this._classNames.setClassNames((o=e.className)!==null&&o!==void 0?o:"")}}maximizeGroup(e){this.gridview.maximizeView(e),this.doSetGroupActive(e)}isMaximizedGroup(e){return this.gridview.maximizedView()===e}exitMaximizedGroup(){this.gridview.exitMaximizedView()}hasMaximizedGroup(){return this.gridview.hasMaximizedView()}doAddGroup(e,t=[0],n,s=this.gridview){s.addView(e,n??ks.Distribute,t),this._onDidAdd.fire(e)}doRemoveGroup(e,t){if(!this._groups.has(e.id))throw new Error("invalid operation");const n=this._groups.get(e.id),s=this.gridview.remove(e,ks.Distribute);if(n&&!t?.skipDispose&&(n.disposable.dispose(),n.value.dispose(),this._groups.delete(e.id),this._onDidRemove.fire(e)),!t?.skipActive&&this._activeGroup===e){const o=Array.from(this._groups.values());this.doSetGroupActive(o.length>0?o[0].value:void 0)}return s}getPanel(e){var t;return(t=this._groups.get(e))===null||t===void 0?void 0:t.value}doSetGroupActive(e){this._activeGroup!==e&&(this._activeGroup&&this._activeGroup.setActive(!1),e&&e.setActive(!0),this._activeGroup=e,this._onDidActiveChange.fire(e))}removeGroup(e){this.doRemoveGroup(e)}activateNext(e){var t,n;if((t=e)!==null&&t!==void 0||(e={}),!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}const s=Tn(e.group.element),o=(n=this.gridview.next(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(o)}activatePrevious(e){var t,n;if((t=e)!==null&&t!==void 0||(e={}),!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}const s=Tn(e.group.element),o=(n=this.gridview.previous(s))===null||n===void 0?void 0:n.view;this.doSetGroupActive(o)}forceRelayout(){this.layout(this.width,this.height,!0)}layout(e,t,n){(n||e!==this.width||t!==this.height)&&(this.gridview.element.style.height=`${t}px`,this.gridview.element.style.width=`${e}px`,this.gridview.layout(e,t))}dispose(){this._onDidActiveChange.dispose(),this._onDidAdd.dispose(),this._onDidRemove.dispose();for(const e of this.groups)e.dispose();this.gridview.dispose(),super.dispose()}};function Ql(e){"@babel/helpers - typeof";return Ql=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ql(e)}function ane(e,t){if(Ql(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(Ql(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function lne(e){var t=ane(e,"string");return Ql(t)=="symbol"?t:t+""}function dne(e,t,n){return(t=lne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dC(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,s)}return n}function pt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?dC(Object(n),!0).forEach(function(s){dne(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dC(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}function cne(e,t){return e==="center"?`Tab into ${t}`:`Split ${e} of ${t}`}function une(e,t){return e==="center"?`docked into ${t}`:`split ${e} of ${t}`}const zu={panelOpened:e=>`${e} opened`,panelClosed:e=>`${e} closed`,groupMaximized:e=>`${e} maximized`,groupRestored:e=>`${e} restored`,groupFloated:e=>`${e} floated`,groupDocked:e=>`${e} docked`,groupPoppedOut:e=>`${e} opened in a new window`,closeTab:e=>`Close ${e}`,closeTabPlain:()=>"Close",movePickTarget:(e,t,n,s)=>`Moving ${e}. Target ${t}, ${n} of ${s}. Enter to choose where, Escape to cancel.`,movePickEdge:(e,t)=>`${cne(e,t)}. Arrows to change, Enter to confirm, Escape to go back.`,moveCommitted:(e,t,n)=>`${e} ${une(n,t)}.`,moveCancelled:()=>"Move cancelled.",moveNotAllowed:()=>"That move is not allowed.",moveFloated:e=>`${e} floated.`};function uE(e){return e?pt(pt({},zu),e):zu}var hE=class{get minimumSize(){return this.component.minimumSize}get maximumSize(){return this.component.maximumSize}get width(){return this.component.width}get height(){return this.component.height}get length(){return this.component.length}get orientation(){return this.component.orientation}get panels(){return this.component.panels}get onDidLayoutFromJSON(){return this.component.onDidLayoutFromJSON}get onDidLayoutChange(){return this.component.onDidLayoutChange}get onDidAddView(){return this.component.onDidAddView}get onDidRemoveView(){return this.component.onDidRemoveView}constructor(e){this.component=e}removePanel(e,t){this.component.removePanel(e,t)}focus(){this.component.focus()}getPanel(e){return this.component.getPanel(e)}layout(e,t){return this.component.layout(e,t)}addPanel(e){return this.component.addPanel(e)}movePanel(e,t){this.component.movePanel(e,t)}fromJSON(e){this.component.fromJSON(e)}toJSON(){return this.component.toJSON()}clear(){this.component.clear()}updateOptions(e){this.component.updateOptions(e)}dispose(){this.component.dispose()}},ed=class{get minimumSize(){return this.component.minimumSize}get maximumSize(){return this.component.maximumSize}get width(){return this.component.width}get height(){return this.component.height}get panels(){return this.component.panels}get onDidLayoutChange(){return this.component.onDidLayoutChange}get onDidLayoutFromJSON(){return this.component.onDidLayoutFromJSON}get onDidAddView(){return this.component.onDidAddView}get onDidRemoveView(){return this.component.onDidRemoveView}get onDidDrop(){return this.component.onDidDrop}get onUnhandledDragOver(){return this.component.onUnhandledDragOver}constructor(e){this.component=e}removePanel(e){this.component.removePanel(e)}getPanel(e){return this.component.getPanel(e)}movePanel(e,t){this.component.movePanel(e,t)}focus(){this.component.focus()}layout(e,t){this.component.layout(e,t)}addPanel(e){return this.component.addPanel(e)}fromJSON(e){this.component.fromJSON(e)}toJSON(){return this.component.toJSON()}clear(){this.component.clear()}updateOptions(e){this.component.updateOptions(e)}dispose(){this.component.dispose()}},pE=class{get width(){return this.component.width}get height(){return this.component.height}get minimumHeight(){return this.component.minimumHeight}get maximumHeight(){return this.component.maximumHeight}get minimumWidth(){return this.component.minimumWidth}get maximumWidth(){return this.component.maximumWidth}get onDidLayoutChange(){return this.component.onDidLayoutChange}get onDidAddPanel(){return this.component.onDidAddGroup}get onDidRemovePanel(){return this.component.onDidRemoveGroup}get onDidActivePanelChange(){return this.component.onDidActiveGroupChange}get onDidLayoutFromJSON(){return this.component.onDidLayoutFromJSON}get panels(){return this.component.groups}get orientation(){return this.component.orientation}set orientation(e){this.component.updateOptions({orientation:e})}constructor(e){this.component=e}focus(){this.component.focus()}layout(e,t,n=!1){this.component.layout(e,t,n)}addPanel(e){return this.component.addPanel(e)}removePanel(e,t){this.component.removePanel(e,t)}movePanel(e,t){this.component.movePanel(e,t)}getPanel(e){return this.component.getPanel(e)}fromJSON(e){return this.component.fromJSON(e)}toJSON(){return this.component.toJSON()}clear(){this.component.clear()}updateOptions(e){this.component.updateOptions(e)}dispose(){this.component.dispose()}},bv=class{get id(){return this.component.id}get width(){return this.component.width}get height(){return this.component.height}get minimumHeight(){return this.component.minimumHeight}get maximumHeight(){return this.component.maximumHeight}get minimumWidth(){return this.component.minimumWidth}get maximumWidth(){return this.component.maximumWidth}get size(){return this.component.size}get tabGroupColors(){return this.component.tabGroupColorPalette.entries()}get totalPanels(){return this.component.totalPanels}get onDidActiveGroupChange(){return this.component.onDidActiveGroupChange}get onDidAddGroup(){return this.component.onDidAddGroup}get onDidRemoveGroup(){return this.component.onDidRemoveGroup}get onDidActivePanelChange(){return this.component.onDidActivePanelChange}get onDidPanelPinnedChange(){return this.component.onDidPanelPinnedChange}get onDidAddPanel(){return this.component.onDidAddPanel}get onDidRemovePanel(){return this.component.onDidRemovePanel}get onDidMovePanel(){return this.component.onDidMovePanel}get onDidLayoutFromJSON(){return this.component.onDidLayoutFromJSON}get onDidLayoutChange(){return this.component.onDidLayoutChange}get onDidDrop(){return this.component.onDidDrop}get onWillDrop(){return this.component.onWillDrop}get onWillMutateLayout(){return this.component.onWillMutateLayout}get onDidMutateLayout(){return this.component.onDidMutateLayout}get onWillShowOverlay(){return this.component.onWillShowOverlay}get onWillDragGroup(){return this.component.onWillDragGroup}get onWillDragPanel(){return this.component.onWillDragPanel}get onUnhandledDragOver(){return this.component.onUnhandledDragOver}get onDidPopoutGroupSizeChange(){return this.component.onDidPopoutGroupSizeChange}get onDidPopoutGroupPositionChange(){return this.component.onDidPopoutGroupPositionChange}get onDidAddPopoutGroup(){return this.component.onDidAddPopoutGroup}get onDidRemovePopoutGroup(){return this.component.onDidRemovePopoutGroup}get onDidOpenPopoutWindowFail(){return this.component.onDidOpenPopoutWindowFail}getPopouts(){return this.component.getPopouts()}get onDidCreateTabGroup(){return this.component.onDidCreateTabGroup}get onDidDestroyTabGroup(){return this.component.onDidDestroyTabGroup}get onDidAddPanelToTabGroup(){return this.component.onDidAddPanelToTabGroup}get onDidRemovePanelFromTabGroup(){return this.component.onDidRemovePanelFromTabGroup}get onDidTabGroupChange(){return this.component.onDidTabGroupChange}get onDidTabGroupCollapsedChange(){return this.component.onDidTabGroupCollapsedChange}get panels(){return this.component.panels}get groups(){return this.component.groups}adjacentGroupInDirection(e,t){return this.component.adjacentGroupInDirection(e,t)}get activePanel(){return this.component.activePanel}get activeGroup(){return this.component.activeGroup}get messages(){return uE(this.component.options.messages)}constructor(e){this.component=e}focus(){this.component.focus()}getPanel(e){return this.component.getGroupPanel(e)}layout(e,t,n=!1){this.component.layout(e,t,n)}addPanel(e){return this.component.withOrigin("api",()=>this.component.addPanel(e))}removePanel(e){this.component.withOrigin("api",()=>this.component.removePanel(e))}addGroup(e){return this.component.withOrigin("api",()=>this.component.addGroup(e))}closeAllGroups(){return this.component.withOrigin("api",()=>this.component.closeAllGroups())}removeGroup(e){this.component.withOrigin("api",()=>this.component.removeGroup(e))}getGroup(e){return this.component.getPanel(e)}addFloatingGroup(e,t){return this.component.withOrigin("api",()=>this.component.addFloatingGroup(e,t))}fromJSON(e,t){this.component.withOrigin("api",()=>this.component.fromJSON(e,t))}toJSON(){return this.component.toJSON()}clear(){this.component.withOrigin("api",()=>this.component.clear())}undo(){this.component.undo()}redo(){this.component.redo()}get canUndo(){return this.component.canUndo}get canRedo(){return this.component.canRedo}clearHistory(){this.component.clearHistory()}get onDidChangeHistory(){return this.component.onDidChangeHistory}get smartGuidesEnabled(){return this.component.smartGuidesEnabled}setSmartGuidesEnabled(e){this.component.setSmartGuidesEnabled(e)}updateSmartGuidesOptions(e){this.component.updateSmartGuidesOptions(e)}get onDidSnapFloat(){return this.component.onDidSnapFloat}get onDidSnapTogether(){return this.component.onDidSnapTogether}get popoutRestorationPromise(){return this.component.popoutRestorationPromise}activateNext(e){this.component.activateNext(e)}activatePrevious(e){this.component.activatePrevious(e)}moveToNext(e){this.activateNext(e)}moveToPrevious(e){this.activatePrevious(e)}maximizeGroup(e){this.component.withOrigin("api",()=>this.component.maximizeGroup(e.group))}hasMaximizedGroup(){return this.component.hasMaximizedGroup()}exitMaximizedGroup(){this.component.withOrigin("api",()=>this.component.exitMaximizedGroup())}get onDidMaximizedGroupChange(){return this.component.onDidMaximizedGroupChange}addPopoutGroup(e,t){return this.component.withOrigin("api",()=>this.component.addPopoutGroup(e,t))}addEdgeGroup(e,t){return this.component.addEdgeGroup(e,t)}revealEdgeGroupWithData(e,t,n){this.component.revealEdgeGroupWithData(e,t,n)}getEdgeGroup(e){return this.component.getEdgeGroup(e)}setEdgeGroupVisible(e,t){this.component.setEdgeGroupVisible(e,t)}isEdgeGroupVisible(e){return this.component.isEdgeGroupVisible(e)}removeEdgeGroup(e){this.component.removeEdgeGroup(e)}pinEdgeGroup(e){this.component.pinEdgeGroup(e)}autoHideEdgeGroup(e){this.component.autoHideEdgeGroup(e)}peekEdgeGroup(e,t){this.component.peekEdgeGroup(e,t)}updateOptions(e){this.component.updateOptions(e)}_getGroupModel(e){const t=this.component.getPanel(e);if(!t)throw new Error(`dockview: group '${e}' not found`);return t.model}createTabGroup(e){const t=this._getGroupModel(e.groupId);return this.component.withOrigin("api",()=>t.createTabGroup({label:e.label,color:e.color,componentParams:e.componentParams}))}dissolveTabGroup(e){const t=this._getGroupModel(e.groupId);this.component.withOrigin("api",()=>t.dissolveTabGroup(e.tabGroupId))}addPanelToTabGroup(e){const t=this._getGroupModel(e.groupId);this.component.withOrigin("api",()=>t.addPanelToTabGroup(e.tabGroupId,e.panelId,e.index))}removePanelFromTabGroup(e){const t=this._getGroupModel(e.groupId);this.component.withOrigin("api",()=>t.removePanelFromTabGroup(e.panelId))}getTabGroups(e){return this._getGroupModel(e.groupId).getTabGroups()}getTabGroupForPanel(e){return this._getGroupModel(e.groupId).getTabGroupForPanel(e.panelId)}moveTabGroup(e){this._getGroupModel(e.groupId).moveTabGroup(e.tabGroupId,e.index)}dispose(){this.component.dispose()}},fE=class extends ct{constructor(e,t){super(),this.element=e,this.callbacks=t,this.target=null,this.registerListeners()}onDragEnter(e){this.target=e.target,this.callbacks.onDragEnter(e)}onDragOver(e){e.preventDefault(),this.callbacks.onDragOver&&this.callbacks.onDragOver(e)}onDragLeave(e){this.target===e.target&&(this.target=null,this.callbacks.onDragLeave(e))}onDragEnd(e){this.target=null,this.callbacks.onDragEnd(e)}onDrop(e){this.callbacks.onDrop(e)}registerListeners(){this.addDisposables(ot(this.element,"dragenter",e=>{this.onDragEnter(e)},!0)),this.addDisposables(ot(this.element,"dragover",e=>{this.onDragOver(e)},!0)),this.addDisposables(ot(this.element,"dragleave",e=>{this.onDragLeave(e)})),this.addDisposables(ot(this.element,"dragend",e=>{this.onDragEnd(e)})),this.addDisposables(ot(this.element,"drop",e=>{this.onDrop(e)}))}};const hne={value:50,type:"percentage"},pne=100,fne=100;function Jm(){const e=document.createElement("div");e.className="dv-drop-target-dropzone";const t=document.createElement("div");return t.className="dv-drop-target-selection",e.appendChild(t),{dropzone:e,selection:t}}function mE(e,t,n,s){var o,r,a;const l=(o=s?.smallWidthBoundary)!==null&&o!==void 0?o:pne,d=(r=s?.smallHeightBoundary)!==null&&r!==void 0?r:fne,c=t<l,u=n<d,h=e==="left",p=e==="right",f=e==="top",g=e==="bottom",x=!c&&p,v=!c&&h,y=!u&&f,w=!u&&g;let b=1;const _=(a=s?.size)!==null&&a!==void 0?a:hne;return _.type==="percentage"?b=En(_.value,0,100)/100:((x||v)&&(b=En(0,_.value,t)/t),(y||w)&&(b=En(0,_.value,n)/n)),{isSmallX:c,isSmallY:u,isLeft:h,isRight:p,isTop:f,isBottom:g,rightClass:x,leftClass:v,topClass:y,bottomClass:w,size:b}}function gE(e,t,n,s,o){const r=mE(t,n,s,o),{rightClass:a,leftClass:l,topClass:d,bottomClass:c,size:u}=r,h={top:"0px",left:"0px",width:"100%",height:"100%"};a?(h.left=`${100*(1-u)}%`,h.width=`${100*u}%`):l?h.width=`${100*u}%`:d?h.height=`${100*u}%`:c&&(h.top=`${100*(1-u)}%`,h.height=`${100*u}%`),r.isSmallX&&r.isLeft&&(h.width="4px"),r.isSmallX&&r.isRight&&(h.left=`${n-4}px`,h.width="4px"),r.isSmallY&&r.isTop&&(h.height="4px"),r.isSmallY&&r.isBottom&&(h.top=`${s-4}px`,h.height="4px"),e.style.top=h.top,e.style.left=h.left,e.style.width=h.width,e.style.height=h.height,e.style.visibility="visible",(!e.style.transform||e.style.transform==="")&&(e.style.transform="translate3d(0, 0, 0)");const p=r.isSmallX&&(r.isLeft||r.isRight)||r.isSmallY&&(r.isTop||r.isBottom);Ze(e,"dv-drop-target-small-vertical",r.isSmallY),Ze(e,"dv-drop-target-small-horizontal",r.isSmallX),Ze(e,"dv-drop-target-selection-line",p),Ze(e,"dv-drop-target-left",r.isLeft),Ze(e,"dv-drop-target-right",r.isRight),Ze(e,"dv-drop-target-top",r.isTop),Ze(e,"dv-drop-target-bottom",r.isBottom),Ze(e,"dv-drop-target-center",t==="center")}function mne(e,t){const n=`${Math.round(t.top)}px`,s=`${Math.round(t.left)}px`,o=`${Math.round(t.width)}px`,r=`${Math.round(t.height)}px`;return e.style.top!==n||e.style.left!==s||e.style.width!==o||e.style.height!==r}function gne(e,t){e.style.top=`${Math.round(t.top)}px`,e.style.left=`${Math.round(t.left)}px`,e.style.width=`${Math.round(t.width)}px`,e.style.height=`${Math.round(t.height)}px`,e.style.visibility="visible",(!e.style.transform||e.style.transform==="")&&(e.style.transform="translate3d(0, 0, 0)")}function xE(e){const t=mE(e.quadrant,e.width,e.height,e.overlayModel),{rightClass:n,leftClass:s,topClass:o,bottomClass:r,size:a}=t,l=e.outlineElement.getBoundingClientRect(),d=e.targetModel.getElements(void 0,e.outlineElement),c=d.root,u=d.overlay,h=c.getBoundingClientRect(),p=l.top-h.top,f=l.left-h.left,g={top:p,left:f,width:e.width,height:e.height};return n?(g.left=f+e.width*(1-a),g.width=e.width*a):s?g.width=e.width*a:o?g.height=e.height*a:r&&(g.top=p+e.height*(1-a),g.height=e.height*a),t.isSmallX&&t.isLeft&&(g.width=4),t.isSmallX&&t.isRight&&(g.left=f+e.width-4,g.width=4),t.isSmallY&&t.isTop&&(g.height=4),t.isSmallY&&t.isBottom&&(g.top=p+e.height-4,g.height=4),mne(u,g)?(gne(u,g),u.className=`dv-drop-target-anchor${e.className?` ${e.className}`:""}`,Ze(u,"dv-drop-target-left",t.isLeft),Ze(u,"dv-drop-target-right",t.isRight),Ze(u,"dv-drop-target-top",t.isTop),Ze(u,"dv-drop-target-bottom",t.isBottom),Ze(u,"dv-drop-target-anchor-line",t.isSmallX&&(t.isLeft||t.isRight)||t.isSmallY&&(t.isTop||t.isBottom)),Ze(u,"dv-drop-target-center",e.quadrant==="center"),d.changed&&(Ze(u,"dv-drop-target-anchor-container-changed",!0),setTimeout(()=>{Ze(u,"dv-drop-target-anchor-container-changed",!1)},10)),{boundsChanged:!0,targetChanged:d.changed}):{boundsChanged:!1,targetChanged:d.changed}}var vE=class extends gv{get nativeEvent(){return this.options.nativeEvent}get position(){return this.options.position}get edge(){return!!this.options.edge}get edgeGroup(){return!!this.options.edgeGroup}constructor(e){super(),this.options=e}};function cC(e){switch(e){case"above":return"top";case"below":return"bottom";case"left":return"left";case"right":return"right";case"within":return"center";default:throw new Error(`invalid direction '${e}'`)}}function xne(e){switch(e){case"top":return"above";case"bottom":return"below";case"left":return"left";case"right":return"right";case"center":return"within";default:throw new Error(`invalid position '${e}'`)}}const vne={value:20,type:"percentage"};var Oh=class tl extends ct{get disabled(){return this._disabled}set disabled(t){this._disabled=t}get state(){return this._state}constructor(t,n){super(),this.element=t,this.options=n,this._edge=!1,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(this.options.acceptedTargetZones),this.dnd=new fE(this.element,{onDragEnter:()=>{var s,o;(s=(o=this.options).getOverrideTarget)===null||s===void 0||(s=s.call(o))===null||s===void 0||s.getElements()},onDragOver:s=>{var o,r,a,l,d,c,u;if(this._disabled){this.clearOwnOverlay();return}tl.ACTUAL_TARGET=this;const h=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);if(this._acceptedTargetZonesSet.size===0){this.clearOwnOverlay();return}const p=(a=(l=(d=this.options).getOverlayOutline)===null||l===void 0?void 0:l.call(d))!==null&&a!==void 0?a:this.element,f=p.offsetWidth,g=p.offsetHeight;if(f===0||g===0)return;const x=p.getBoundingClientRect(),v=((c=s.clientX)!==null&&c!==void 0?c:0)-x.left,y=((u=s.clientY)!==null&&u!==void 0?u:0)-x.top,w=this.resolvePosition(v,y,f,g,s);if(this.isAlreadyUsed(s)){this.removeDropTarget();return}if(w===null){this.clearOwnOverlay();return}const b=w.position;if(!this.options.canDisplayOverlay(s,b)){this.clearOwnOverlay();return}const _=new vE({nativeEvent:s,position:b,edge:w.edge,edgeGroup:w.edgeGroup});if(this._onWillShowOverlay.fire(_),_.defaultPrevented){this.clearOwnOverlay();return}if(this.markAsUsed(s),w.edge){this.clearOwnOverlay(),this._state=b,this._edge=!0;return}if(this._edge=!1,!h){if(!this.targetElement){const j=Jm();this.targetElement=j.dropzone,this.overlayElement=j.selection,this._state="center",p.classList.add("dv-drop-target"),p.append(this.targetElement)}}this.toggleClasses(b,f,g),this._state=b},onDragLeave:()=>{var s,o;const r=(s=(o=this.options).getOverrideTarget)===null||s===void 0?void 0:s.call(o);if(r){var a;this._state=void 0,this._edge=!1,(a=r.scheduleClear)===null||a===void 0||a.call(r);return}this.removeDropTarget()},onDragEnd:s=>{var o,r;const a=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);a&&tl.ACTUAL_TARGET===this&&this._state&&(s.stopPropagation(),this._onDrop.fire({position:this._state,nativeEvent:s,edge:this._edge})),this.removeDropTarget(),a?.clear()},onDrop:s=>{var o,r;s.preventDefault();const a=this._state,l=this._edge;this.removeDropTarget(),(o=(r=this.options).getOverrideTarget)===null||o===void 0||(o=o.call(r))===null||o===void 0||o.clear(),a&&(s.stopPropagation(),this._onDrop.fire({position:a,nativeEvent:s,edge:l}))}}),this.addDisposables(this._onDrop,this._onWillShowOverlay,this.dnd)}setTargetZones(t){this._acceptedTargetZonesSet=new Set(t)}setOverlayModel(t){this.options.overlayModel=t}dispose(){this.removeDropTarget(),super.dispose()}markAsUsed(t){t[tl.USED_EVENT_ID]=!0}isAlreadyUsed(t){const n=t[tl.USED_EVENT_ID];return typeof n=="boolean"&&n}toggleClasses(t,n,s){var o,r;const a=(o=(r=this.options).getOverrideTarget)===null||o===void 0?void 0:o.call(r);if(a){var l,d,c;xE({outlineElement:(l=(d=(c=this.options).getOverlayOutline)===null||d===void 0?void 0:d.call(c))!==null&&l!==void 0?l:this.element,targetModel:a,quadrant:t,width:n,height:s,overlayModel:this.options.overlayModel,className:this.options.className});return}this.overlayElement&&gE(this.overlayElement,t,n,s,this.options.overlayModel)}resolvePosition(t,n,s,o,r){var a,l;const d=(a=(l=this.options).getPositionResolver)===null||a===void 0?void 0:a.call(l);if(d){const u=d.resolve({x:t,y:n,width:s,height:o,zones:this._acceptedTargetZonesSet,event:r});return u?{position:u.position,edge:!!u.edge,edgeGroup:!!u.edgeGroup}:null}const c=this.calculateQuadrant(this._acceptedTargetZonesSet,t,n,s,o);return c?{position:c,edge:!1,edgeGroup:!1}:null}calculateQuadrant(t,n,s,o,r){var a,l;const d=(a=(l=this.options.overlayModel)===null||l===void 0?void 0:l.activationSize)!==null&&a!==void 0?a:vne;return d.type==="percentage"?bE(t,n,s,o,r,d.value):wE(t,n,s,o,r,d.value)}clearOwnOverlay(){const t=this._state!==void 0;if(this.removeDropTarget(),t){var n,s;(n=(s=this.options).getOverrideTarget)===null||n===void 0||(n=n.call(s))===null||n===void 0||n.clear()}}removeDropTarget(){if(this._state=void 0,this._edge=!1,this.targetElement){var t;(t=this.targetElement.parentElement)===null||t===void 0||t.classList.remove("dv-drop-target"),this.targetElement.remove(),this.targetElement=void 0,this.overlayElement=void 0}}showOverlay(t){var n,s,o,r,a;const l=(n=(s=this.options).getOverrideTarget)===null||n===void 0?void 0:n.call(s),d=(o=(r=(a=this.options).getOverlayOutline)===null||r===void 0?void 0:r.call(a))!==null&&o!==void 0?o:this.element,c=d.offsetWidth,u=d.offsetHeight;if(!l&&!this.targetElement){const h=Jm();this.targetElement=h.dropzone,this.overlayElement=h.selection,d.classList.add("dv-drop-target"),d.append(this.targetElement)}this.toggleClasses(t,c,u),this._state=t}clearOverlay(){var t,n;this.removeDropTarget(),(t=(n=this.options).getOverrideTarget)===null||t===void 0||(t=t.call(n))===null||t===void 0||t.clear(),this._state=void 0}};Oh.USED_EVENT_ID="__dockview_droptarget_event_is_used__";function bE(e,t,n,s,o,r){const a=100*t/s,l=100*n/o;return e.has("left")&&a<r?"left":e.has("right")&&a>100-r?"right":e.has("top")&&l<r?"top":e.has("bottom")&&l>100-r?"bottom":e.has("center")?"center":null}function wE(e,t,n,s,o,r){return e.has("left")&&t<r?"left":e.has("right")&&t>s-r?"right":e.has("top")&&n<r?"top":e.has("bottom")&&n>o-r?"bottom":e.has("center")?"center":null}function bne(e,t,n){var s,o,r;wi(t,"dv-dragged"),t.style.top="-9999px",((s=n?.ownerDocument)!==null&&s!==void 0?s:document).body.appendChild(t),e.setDragImage(t,(o=n?.x)!==null&&o!==void 0?o:0,(r=n?.y)!==null&&r!==void 0?r:0),setTimeout(()=>{bi(t,"dv-dragged"),t.remove()},0)}var Gu=class nl extends ct{static getInstance(){var t;return(t=nl._instance)!==null&&t!==void 0||(nl._instance=new nl),nl._instance}constructor(){super(),this._targets=new Set,this._targetByElement=new Map,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._onDragMove=new ve,this.onDragMove=this._onDragMove.event,this._onDragEnd=new ve,this.onDragEnd=this._onDragEnd.event,this.addDisposables(this._onDragStart,this._onDragMove,this._onDragEnd)}get active(){return this._active}registerTarget(t){return this._targets.add(t),this._targetByElement.set(t.element,t),{dispose:()=>{this._targets.delete(t),this._targetByElement.get(t.element)===t&&this._targetByElement.delete(t.element),this._currentTarget===t&&(this._currentTarget=void 0)}}}beginDrag(t){var n,s,o;this._active&&this.cancel();const{pointerEvent:r,source:a}=t,l=t.getData();this._active={pointerId:r.pointerId,startX:r.clientX,startY:r.clientY,source:a},this._lastPointerEvent=r,this._onDragMoveCallback=t.onDragMove,this._onDragEndCallback=t.onDragEnd,this._dataDisposable=l,this._ghost=t.ghost,this._iframeShield=Jl((n=a.ownerDocument)!==null&&n!==void 0?n:document);const d={clientX:r.clientX,clientY:r.clientY,pointerEvent:r};this._onDragStart.fire(d);const c=(s=(o=a.ownerDocument)===null||o===void 0?void 0:o.defaultView)!==null&&s!==void 0?s:globalThis.window;this._moveListener=ot(c,"pointermove",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleMove(u)}),this._upListener=ot(c,"pointerup",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!0)}),this._cancelListener=ot(c,"pointercancel",u=>{var h;u.pointerId===((h=this._active)===null||h===void 0?void 0:h.pointerId)&&this._handleEnd(u,!1)})}cancel(){var t,n;if(!this._active)return;const s=this._onDragEndCallback,o=this._lastPointerEvent;if((t=this._currentTarget)===null||t===void 0||t.handleDragLeave(),this._teardown(),(n=this._dataDisposable)===null||n===void 0||n.dispose(),this._dataDisposable=void 0,o){const r={clientX:o.clientX,clientY:o.clientY,pointerEvent:o};s?.(r,!1),this._onDragEnd.fire(r)}}_findTargetUnder(t,n){var s,o;const r=((s=(o=this._active)===null||o===void 0?void 0:o.source.ownerDocument)!==null&&s!==void 0?s:document).elementsFromPoint(t,n);for(const a of r){let l=a;for(;l;){const d=this._targetByElement.get(l);if(d)return d;l=l.parentElement}}}_handleMove(t){var n,s;this._lastPointerEvent=t,(n=this._ghost)===null||n===void 0||n.update(t.clientX,t.clientY);const o={clientX:t.clientX,clientY:t.clientY,pointerEvent:t},r=this._findTargetUnder(t.clientX,t.clientY);if(r!==this._currentTarget){var a;(a=this._currentTarget)===null||a===void 0||a.handleDragLeave(),this._currentTarget=r}r&&r.handleDragOver(o),(s=this._onDragMoveCallback)===null||s===void 0||s.call(this,o),this._onDragMove.fire(o)}_handleEnd(t,n){const s={clientX:t.clientX,clientY:t.clientY,pointerEvent:t};if(n&&this._currentTarget)this._currentTarget.handleDrop(s);else{var o;(o=this._currentTarget)===null||o===void 0||o.handleDragLeave()}const r=this._onDragEndCallback,a=this._dataDisposable;this._teardown(),this._dataDisposable=void 0,setTimeout(()=>a?.dispose(),0),r?.(s,n),this._onDragEnd.fire(s)}_teardown(){var t,n,s,o,r;this._currentTarget=void 0,this._active=void 0,this._lastPointerEvent=void 0,this._onDragMoveCallback=void 0,this._onDragEndCallback=void 0,(t=this._ghost)===null||t===void 0||t.dispose(),this._ghost=void 0,(n=this._iframeShield)===null||n===void 0||n.release(),this._iframeShield=void 0,(s=this._moveListener)===null||s===void 0||s.dispose(),(o=this._upListener)===null||o===void 0||o.dispose(),(r=this._cancelListener)===null||r===void 0||r.dispose(),this._moveListener=void 0,this._upListener=void 0,this._cancelListener=void 0}};const wne={value:20,type:"percentage"};var yne=class extends ct{get disabled(){return this._disabled}set disabled(e){this._disabled=e,e&&this._removeOverlay()}get state(){return this._state}constructor(e,t){super(),this.element=e,this.options=t,this._edge=!1,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._disabled=!1,this._acceptedTargetZonesSet=new Set(t.acceptedTargetZones);const n={element:this.element,handleDragOver:s=>this._onDragOver(s),handleDragLeave:()=>this._onDragLeave(),handleDrop:s=>this._onDropEvent(s)};this.addDisposables(this._onDrop,this._onWillShowOverlay,Gu.getInstance().registerTarget(n))}setTargetZones(e){this._acceptedTargetZonesSet=new Set(e)}setOverlayModel(e){this.options.overlayModel=e}dispose(){this._removeOverlay(),super.dispose()}_onDragOver(e){var t,n,s,o,r;if(this._disabled){this._clearOwnOverlay();return}const a=(t=(n=this.options).getOverrideTarget)===null||t===void 0?void 0:t.call(n);if(this._acceptedTargetZonesSet.size===0){this._clearOwnOverlay();return}const l=(s=(o=(r=this.options).getOverlayOutline)===null||o===void 0?void 0:o.call(r))!==null&&s!==void 0?s:this.element,d=l.offsetWidth,c=l.offsetHeight;if(d===0||c===0)return;const u=l.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top,f=this._resolvePosition(h,p,d,c,e.pointerEvent);if(f===null){this._clearOwnOverlay();return}const g=f.position;if(!this.options.canDisplayOverlay(e.pointerEvent,g)){this._clearOwnOverlay();return}const x=new vE({nativeEvent:e.pointerEvent,position:g,edge:f.edge});if(this._onWillShowOverlay.fire(x),x.defaultPrevented){this._clearOwnOverlay();return}if(f.edge){this._clearOwnOverlay(),this._state=g,this._edge=!0;return}if(this._edge=!1,a){xE({outlineElement:l,targetModel:a,quadrant:g,width:d,height:c,overlayModel:this.options.overlayModel,className:this.options.className}),this._state=g;return}if(!this._targetElement){const v=Jm();this._targetElement=v.dropzone,this._overlayElement=v.selection,this._state="center",this.element.classList.add("dv-drop-target"),this.element.append(this._targetElement)}this._overlayElement&&gE(this._overlayElement,g,d,c,this.options.overlayModel),this._state=g}_onDragLeave(){var e,t;const n=(e=(t=this.options).getOverrideTarget)===null||e===void 0?void 0:e.call(t);if(n){this._state=void 0,n.clear();return}this._removeOverlay()}_onDropEvent(e){var t,n;const s=this._state,o=this._edge,r=(t=(n=this.options).getOverrideTarget)===null||t===void 0?void 0:t.call(n);this._removeOverlay(),r?.clear(),s&&this._onDrop.fire({position:s,nativeEvent:e.pointerEvent,edge:o})}_resolvePosition(e,t,n,s,o){var r,a;const l=(r=(a=this.options).getPositionResolver)===null||r===void 0?void 0:r.call(a);if(l){const c=l.resolve({x:e,y:t,width:n,height:s,zones:this._acceptedTargetZonesSet,event:o});return c?{position:c.position,edge:!!c.edge}:null}const d=this._calculateQuadrant(e,t,n,s);return d?{position:d,edge:!1}:null}_calculateQuadrant(e,t,n,s){var o,r;const a=(o=(r=this.options.overlayModel)===null||r===void 0?void 0:r.activationSize)!==null&&o!==void 0?o:wne;return a.type==="percentage"?bE(this._acceptedTargetZonesSet,e,t,n,s,a.value):wE(this._acceptedTargetZonesSet,e,t,n,s,a.value)}_clearOwnOverlay(){const e=this._state!==void 0;if(this._removeOverlay(),e){var t,n;(t=(n=this.options).getOverrideTarget)===null||t===void 0||(t=t.call(n))===null||t===void 0||t.clear()}}_removeOverlay(){if(this._edge=!1,this._targetElement){var e;this._state=void 0,(e=this._targetElement.parentElement)===null||e===void 0||e.classList.remove("dv-drop-target"),this._targetElement.remove(),this._targetElement=void 0,this._overlayElement=void 0}else this._state=void 0}};const Sne=5,Cne=250,kne=8;var jne=class extends ct{constructor(e,t){var n;super(),this.element=e,this.options=t,this._disabled=!1,this._armed=!1,this._startX=0,this._startY=0,this._touchOnly=(n=t.touchOnly)!==null&&n!==void 0?n:!0,this.addDisposables(ot(this.element,"pointerdown",s=>{this._onPointerDown(s)}))}setDisabled(e){this._disabled=e,e&&this._cancelPending()}setTouchOnly(e){this._touchOnly!==e&&(this._touchOnly=e,e&&this._cancelPending())}_shouldHandle(e){var t,n;return!(this._disabled||this._touchOnly&&e.pointerType!=="touch"&&e.pointerType!=="pen"||!((t=(n=this.options).isCancelled)===null||t===void 0)&&t.call(n,e))}_onPointerDown(e){var t,n,s,o,r;if(!this._shouldHandle(e))return;this._cancelPending(),this._pendingPointerId=e.pointerId,this._startX=e.clientX,this._startY=e.clientY,this._startEvent=e;const a=e.pointerType==="touch"||e.pointerType==="pen",l=this.options.touchInitiationDelay,d=(t=typeof l=="function"?l():l)!==null&&t!==void 0?t:Cne;this._armed=!a||d<=0,a&&d>0&&Number.isFinite(d)&&(this._armTimer=setTimeout(()=>{this._armTimer=void 0,this._armed=!0},d));const c=(n=this.options.threshold)!==null&&n!==void 0?n:Sne,u=this.options.pressTolerance,h=(s=typeof u=="function"?u():u)!==null&&s!==void 0?s:kne,p=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._pendingMoveListener=ot(p,"pointermove",f=>{if(f.pointerId!==this._pendingPointerId)return;const g=f.clientX-this._startX,x=f.clientY-this._startY,v=Math.hypot(g,x);if(this._armed){v>=c&&this._beginDrag(f);return}v>h&&this._beginDrag(f)}),this._pendingUpListener=ot(p,"pointerup",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()}),this._pendingCancelListener=ot(p,"pointercancel",f=>{f.pointerId===this._pendingPointerId&&this._cancelPending()})}cancelPending(){this._cancelPending()}_cancelPending(){var e,t,n;this._pendingPointerId=void 0,this._armTimer!==void 0&&(clearTimeout(this._armTimer),this._armTimer=void 0),this._armed=!1,(e=this._pendingMoveListener)===null||e===void 0||e.dispose(),(t=this._pendingUpListener)===null||t===void 0||t.dispose(),(n=this._pendingCancelListener)===null||n===void 0||n.dispose(),this._pendingMoveListener=void 0,this._pendingUpListener=void 0,this._pendingCancelListener=void 0,this._startEvent=void 0}_beginDrag(e){var t,n,s,o,r;const a=(t=this._startEvent)!==null&&t!==void 0?t:e;this._cancelPending(),(n=(s=this.options).onDragStart)===null||n===void 0||n.call(s,a);const l=(o=(r=this.options).createGhost)===null||o===void 0?void 0:o.call(r,a);Gu.getInstance().beginDrag({pointerEvent:e,source:this.element,getData:()=>this.options.getData(a),ghost:l,onDragMove:this.options.onDragMove,onDragEnd:this.options.onDragEnd})}dispose(){this._cancelPending(),super.dispose()}},_ne=class{constructor(e){var t,n,s,o,r;this._disposed=!1,this.element=e.element,this.offsetX=(t=e.offsetX)!==null&&t!==void 0?t:0,this.offsetY=(n=e.offsetY)!==null&&n!==void 0?n:0,this.element.style.position="fixed",this.element.style.left="0px",this.element.style.top="0px",this.element.style.pointerEvents="none",this.element.style.zIndex="99999",this.element.style.opacity=String((s=e.opacity)!==null&&s!==void 0?s:.8),this.element.style.willChange="transform",this.element.style.transform=`translate3d(${e.initialX-this.offsetX}px, ${e.initialY-this.offsetY}px, 0)`,((o=(r=e.owner)===null||r===void 0?void 0:r.ownerDocument)!==null&&o!==void 0?o:document).body.appendChild(this.element)}update(e,t){this._disposed||(this.element.style.transform=`translate3d(${e-this.offsetX}px, ${t-this.offsetY}px, 0)`)}dispose(){this._disposed||(this._disposed=!0,this.element.remove())}},Nne=class extends ct{constructor(e,t){super(),this.el=e,this.opts=t,this._dataDisposable=new Fn,this._pointerEventsDisposable=new Fn,this._disabled=!!t.disabled,this.addDisposables(this._dataDisposable,this._pointerEventsDisposable,ot(this.el,"dragstart",n=>{var s,o,r,a,l,d,c;if(n.defaultPrevented||this._disabled||!((s=(o=this.opts).isCancelled)===null||s===void 0)&&s.call(o,n)){n.preventDefault();return}const u=Jl((r=this.el.ownerDocument)!==null&&r!==void 0?r:document);this._pointerEventsDisposable.value={dispose:()=>u.release()},this.el.classList.add("dv-dragged"),setTimeout(()=>this.el.classList.remove("dv-dragged"),0),this._dataDisposable.value=this.opts.getData(n);const h=(a=(l=this.opts).createGhost)===null||a===void 0?void 0:a.call(l,n);if(h&&n.dataTransfer){var p,f,g;if(bne(n.dataTransfer,h.element,{x:(p=h.offsetX)!==null&&p!==void 0?p:0,y:(f=h.offsetY)!==null&&f!==void 0?f:0,ownerDocument:(g=this.el.ownerDocument)!==null&&g!==void 0?g:void 0}),h.dispose){const x=h.dispose;setTimeout(()=>x(),0)}}n.dataTransfer&&(n.dataTransfer.effectAllowed="move",n.dataTransfer.items.length===0&&n.dataTransfer.setData("text/plain","")),(d=(c=this.opts).onDragStart)===null||d===void 0||d.call(c,n)}),ot(this.el,"dragend",n=>{var s,o;this._pointerEventsDisposable.dispose(),setTimeout(()=>this._dataDisposable.dispose(),0),(s=(o=this.opts).onDragEnd)===null||s===void 0||s.call(o,n)}))}setDisabled(e){this._disabled=e}setTouchOnly(e){}cancelPending(){}},Tne=class{constructor(){this.kind="html5"}createDropTarget(e,t){return new Oh(e,t)}createDragSource(e,t){return new Nne(e,t)}},Dne=class{constructor(){this.kind="pointer"}createDropTarget(e,t){return new yne(e,t)}createDragSource(e,t){const n=t.createGhost?o=>{const r=t.createGhost(o);if(!r)return;const a=new _ne({element:r.element,initialX:o.clientX,initialY:o.clientY,offsetX:r.offsetX,offsetY:r.offsetY,owner:e});if(r.dispose){const l=a.dispose.bind(a),d=r.dispose;a.dispose=()=>{l(),d()}}return a}:void 0,s=new jne(e,{getData:t.getData,isCancelled:t.isCancelled,onDragStart:t.onDragStart,onDragEnd:t.onDragEnd?o=>t.onDragEnd(o.pointerEvent):void 0,createGhost:n,touchOnly:t.touchOnly,touchInitiationDelay:t.touchInitiationDelay,pressTolerance:t.pressTolerance,threshold:t.threshold});return t.disabled&&s.setDisabled(!0),s}};const zo=new Tne,vo=new Dne,Qm=Object.keys({disableAutoResizing:void 0,disableDnd:void 0,className:void 0});var Ine=class extends QI{constructor(e,t,n,s){super(),this.nativeEvent=e,this.position=t,this.getData=n,this.panel=s}},yE=class extends gv{constructor(){super()}},SE=class extends ct{get isFocused(){return this._isFocused}get isActive(){return this._isActive}get isVisible(){return this._isVisible}get width(){return this._width}get height(){return this._height}constructor(e,t){super(),this.id=e,this.component=t,this._isFocused=!1,this._isActive=!1,this._isVisible=!0,this._width=0,this._height=0,this._parameters={},this.panelUpdatesDisposable=new Fn,this._onDidDimensionChange=new ve,this.onDidDimensionsChange=this._onDidDimensionChange.event,this._onDidChangeFocus=new ve,this.onDidFocusChange=this._onDidChangeFocus.event,this._onWillFocus=new ve,this.onWillFocus=this._onWillFocus.event,this._onDidVisibilityChange=new ve,this.onDidVisibilityChange=this._onDidVisibilityChange.event,this._onWillVisibilityChange=new ve,this.onWillVisibilityChange=this._onWillVisibilityChange.event,this._onDidActiveChange=new ve,this.onDidActiveChange=this._onDidActiveChange.event,this._onActiveChange=new ve,this.onActiveChange=this._onActiveChange.event,this._onDidParametersChange=new ve,this.onDidParametersChange=this._onDidParametersChange.event,this.addDisposables(this.onDidFocusChange(n=>{this._isFocused=n.isFocused}),this.onDidActiveChange(n=>{this._isActive=n.isActive}),this.onDidVisibilityChange(n=>{this._isVisible=n.isVisible}),this.onDidDimensionsChange(n=>{this._width=n.width,this._height=n.height}),this.panelUpdatesDisposable,this._onDidDimensionChange,this._onDidChangeFocus,this._onDidVisibilityChange,this._onDidActiveChange,this._onWillFocus,this._onActiveChange,this._onWillFocus,this._onWillVisibilityChange,this._onDidParametersChange)}getParameters(){return this._parameters}initialize(e){this.panelUpdatesDisposable.value=this._onDidParametersChange.event(t=>{this._parameters=t,e.update({params:t})})}setVisible(e){this._onWillVisibilityChange.fire({isVisible:e})}setActive(){this._onActiveChange.fire()}updateParameters(e){this._onDidParametersChange.fire(e)}},CE=class extends SE{constructor(e,t){super(e,t),this._onDidConstraintsChangeInternal=new ve,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new ve({replay:!0}),this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new ve,this.onDidSizeChange=this._onDidSizeChange.event,this.addDisposables(this._onDidConstraintsChangeInternal,this._onDidConstraintsChange,this._onDidSizeChange)}setConstraints(e){this._onDidConstraintsChangeInternal.fire(e)}setSize(e){this._onDidSizeChange.fire(e)}},Ene=class extends CE{set pane(e){this._pane=e}constructor(e,t){super(e,t),this._onDidExpansionChange=new ve({replay:!0}),this.onDidExpansionChange=this._onDidExpansionChange.event,this._onMouseEnter=new ve({}),this.onMouseEnter=this._onMouseEnter.event,this._onMouseLeave=new ve({}),this.onMouseLeave=this._onMouseLeave.event,this.addDisposables(this._onDidExpansionChange,this._onMouseEnter,this._onMouseLeave)}setExpanded(e){var t;(t=this._pane)===null||t===void 0||t.setExpanded(e)}get isExpanded(){var e;return!!(!((e=this._pane)===null||e===void 0)&&e.isExpanded())}},wv=class extends ct{get element(){return this._element}get width(){return this._width}get height(){return this._height}get params(){var e;return(e=this._params)===null||e===void 0?void 0:e.params}constructor(e,t,n){super(),this.id=e,this.component=t,this.api=n,this._height=0,this._width=0,this._element=document.createElement("div"),this._element.tabIndex=-1,this._element.style.outline="none",this._element.style.height="100%",this._element.style.width="100%",this._element.style.overflow="hidden";const s=tE(this._element);this.addDisposables(this.api,s.onDidFocus(()=>{this.api._onDidChangeFocus.fire({isFocused:!0})}),s.onDidBlur(()=>{this.api._onDidChangeFocus.fire({isFocused:!1})}),s)}focus(){const e=new yE;this.api._onWillFocus.fire(e),!e.defaultPrevented&&this._element.focus()}layout(e,t){this._width=e,this._height=t,this.api._onDidDimensionChange.fire({width:e,height:t}),this.part&&this._params&&this.part.update(this._params.params)}init(e){this._params=e,this.part=this.getComponent()}update(e){var t,n;this._params=pt(pt({},this._params),{},{params:pt(pt({},(t=this._params)===null||t===void 0?void 0:t.params),e.params)});for(const s of Object.keys(e.params))e.params[s]===void 0&&delete this._params.params[s];(n=this.part)===null||n===void 0||n.update({params:this._params.params})}toJSON(){var e,t;const n=(e=(t=this._params)===null||t===void 0?void 0:t.params)!==null&&e!==void 0?e:{};return{id:this.id,component:this.component,params:Object.keys(n).length>0?n:void 0}}dispose(){var e;this.api.dispose(),(e=this.part)===null||e===void 0||e.dispose(),super.dispose()}},Pne=class extends wv{set orientation(e){this._orientation=e}get orientation(){return this._orientation}get minimumSize(){return this.headerSize+(this.isExpanded()?this._minimumBodySize:0)}get maximumSize(){return this.headerSize+(this.isExpanded()?this._maximumBodySize:0)}get size(){return this._size}get orthogonalSize(){return this._orthogonalSize}set orthogonalSize(e){this._orthogonalSize=e}get minimumBodySize(){return this._minimumBodySize}set minimumBodySize(e){this._minimumBodySize=typeof e=="number"?e:0}get maximumBodySize(){return this._maximumBodySize}set maximumBodySize(e){this._maximumBodySize=typeof e=="number"?e:Number.POSITIVE_INFINITY}get headerVisible(){return this._headerVisible}set headerVisible(e){this._headerVisible=e,this.header.style.display=e?"":"none"}constructor(e){super(e.id,e.component,new Ene(e.id,e.component)),this._onDidChangeExpansionState=new ve({replay:!0}),this.onDidChangeExpansionState=this._onDidChangeExpansionState.event,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._orthogonalSize=0,this._size=0,this._isExpanded=!1,this.api.pane=this,this.api.initialize(this),this.headerSize=e.headerSize,this.headerComponent=e.headerComponent,this._minimumBodySize=e.minimumBodySize,this._maximumBodySize=e.maximumBodySize,this._isExpanded=e.isExpanded,this._headerVisible=e.isHeaderVisible,this._onDidChangeExpansionState.fire(this.isExpanded()),this._orientation=e.orientation,this.element.classList.add("dv-pane"),this.addDisposables(this.api.onWillVisibilityChange(t=>{const{isVisible:n}=t,{accessor:s}=this._params;s.setVisible(this,n)}),this.api.onDidSizeChange(t=>{this._onDidChange.fire({size:t.size})}),ot(this.element,"mouseenter",t=>{this.api._onMouseEnter.fire(t)}),ot(this.element,"mouseleave",t=>{this.api._onMouseLeave.fire(t)})),this.addDisposables(this._onDidChangeExpansionState,this.onDidChangeExpansionState(t=>{this.api._onDidExpansionChange.fire({isExpanded:t})}),this.api.onDidFocusChange(t=>{this.header&&(t.isFocused?wi(this.header,"focused"):bi(this.header,"focused"))})),this.renderOnce()}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}isExpanded(){return this._isExpanded}setExpanded(e){var t;this._isExpanded!==e&&(this._isExpanded=e,e?(this.animationTimer&&clearTimeout(this.animationTimer),this.body&&this.element.appendChild(this.body)):(this._expandedSize=this._size,this.animationTimer=setTimeout(()=>{var n;(n=this.body)===null||n===void 0||n.remove()},200)),this._onDidChange.fire(e?{size:(t=this._expandedSize)!==null&&t!==void 0?t:this.width}:{}),this._onDidChangeExpansionState.fire(e))}layout(e,t){this._size=e,this._orthogonalSize=t;const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){var t,n;super.init(e),typeof e.minimumBodySize=="number"&&(this.minimumBodySize=e.minimumBodySize),typeof e.maximumBodySize=="number"&&(this.maximumBodySize=e.maximumBodySize),this.bodyPart=this.getBodyComponent(),this.headerPart=this.getHeaderComponent(),this.bodyPart.init(pt(pt({},e),{},{api:this.api})),this.headerPart.init(pt(pt({},e),{},{api:this.api})),(t=this.body)===null||t===void 0||t.append(this.bodyPart.element),(n=this.header)===null||n===void 0||n.append(this.headerPart.element),typeof e.isExpanded=="boolean"&&this.setExpanded(e.isExpanded)}toJSON(){const e=this._params;return pt(pt({},super.toJSON()),{},{headerComponent:this.headerComponent,title:e.title})}renderOnce(){this.header=document.createElement("div"),this.header.tabIndex=0,this.header.className="dv-pane-header",this.header.style.height=`${this.headerSize}px`,this.header.style.lineHeight=`${this.headerSize}px`,this.header.style.minHeight=`${this.headerSize}px`,this.header.style.maxHeight=`${this.headerSize}px`,this.element.appendChild(this.header),this.body=document.createElement("div"),this.body.className="dv-pane-body",this.element.appendChild(this.body)}getComponent(){return{update:e=>{var t,n;(t=this.bodyPart)===null||t===void 0||t.update({params:e}),(n=this.headerPart)===null||n===void 0||n.update({params:e})},dispose:()=>{var e,t;(e=this.bodyPart)===null||e===void 0||e.dispose(),(t=this.headerPart)===null||t===void 0||t.dispose()}}}},Ane=class extends Pne{constructor(e){super({id:e.id,component:e.component,headerComponent:e.headerComponent,orientation:e.orientation,isExpanded:e.isExpanded,isHeaderVisible:!0,headerSize:e.headerSize,minimumBodySize:e.minimumBodySize,maximumBodySize:e.maximumBodySize}),this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this.accessor=e.accessor,this.addDisposables(this._onDidDrop,this._onUnhandledDragOver),e.disableDnd||this.initDragFeatures()}initDragFeatures(){if(!this.header)return;const e=this.id,t=this.accessor.id;this.header.draggable=!0;const n={getData:()=>(xo.getInstance().setData([new _l(t,e)],_l.prototype),{dispose:()=>{xo.getInstance().clearData(_l.prototype)}})};this.html5DragSource=zo.createDragSource(this.header,n),this.pointerDragSource=vo.createDragSource(this.header,n);const o={acceptedTargetZones:["top","bottom"],overlayModel:{activationSize:{type:"percentage",value:50}},canDisplayOverlay:(r,a)=>{const l=Ka();if(l&&l.paneId!==this.id&&l.viewId===this.accessor.id)return!0;const d=new Ine(r,a,Ka,this);return this._onUnhandledDragOver.fire(d),d.isAccepted}};this.target=zo.createDropTarget(this.element,o),this.pointerTarget=vo.createDropTarget(this.element,o),this.addDisposables(this._onDidDrop,this.html5DragSource,this.pointerDragSource,this.target,this.pointerTarget,this.target.onDrop(r=>{this.onDrop(r)}),this.pointerTarget.onDrop(r=>{this.onDrop(r)}))}onDrop(e){const t=Ka();if(t?.viewId!==this.accessor.id){this._onDidDrop.fire(pt(pt({},e),{},{panel:this,api:new ed(this.accessor),getData:Ka}));return}const n=this._params.containerApi,s=t.paneId,o=n.getPanel(s);if(!o){this._onDidDrop.fire(pt(pt({},e),{},{panel:this,getData:Ka,api:new ed(this.accessor)}));return}const r=n.panels,a=r.indexOf(o);let l=n.panels.indexOf(this);(e.position==="left"||e.position==="top")&&(l=Math.max(0,l-1)),(e.position==="right"||e.position==="bottom")&&(a>l&&l++,l=Math.min(r.length-1,l)),n.movePanel(a,l)}};let Mne=0;const Rne=()=>`dv-tabpanel-${Mne++}`;var Lne=class extends ct{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,d;super(),this.accessor=e,this.group=t,this.disposable=new Fn,this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-content-container",this._element.tabIndex=-1,this._element.id=Rne(),this._element.setAttribute("role","tabpanel"),this.addDisposables(this._onDidFocus,this._onDidBlur);const c=()=>{var h;return(h=t.dropTargetContainer)===null||h===void 0?void 0:h.model},u=(h,p)=>this.group.canDisplayContentOverlay(h,p);this.dropTarget=new Oh(this.element,{getOverlayOutline:()=>{var h;return((h=e.options.theme)===null||h===void 0?void 0:h.dndPanelOverlay)==="group"?this.element.parentElement:null},className:"dv-drop-target-content",acceptedTargetZones:["top","bottom","left","right","center"],canDisplayOverlay:u,getOverrideTarget:c,overlayModel:(n=(s=this.accessor).resolveDropOverlayModel)===null||n===void 0?void 0:n.call(s,"content"),getPositionResolver:()=>{var h;return(h=e.getDropPositionResolver)===null||h===void 0?void 0:h.call(e)}}),this.pointerDropTarget=vo.createDropTarget(this.element,{acceptedTargetZones:["top","bottom","left","right","center"],canDisplayOverlay:u,getOverlayOutline:()=>{var h;return((h=e.options.theme)===null||h===void 0?void 0:h.dndPanelOverlay)==="group"?this.element.parentElement:null},className:"dv-drop-target-content",getOverrideTarget:c,overlayModel:(o=(r=this.accessor).resolveDropOverlayModel)===null||o===void 0?void 0:o.call(r,"content"),getPositionResolver:()=>{var h;return(h=e.getDropPositionResolver)===null||h===void 0?void 0:h.call(e)}}),this.addDisposables(this.dropTarget,this.pointerDropTarget,(a=(l=(d=this.accessor).onDidOptionsChange)===null||l===void 0?void 0:l.call(d,()=>{var h,p,f;const g=(h=(p=(f=this.accessor).resolveDropOverlayModel)===null||p===void 0?void 0:p.call(f,"content"))!==null&&h!==void 0?h:{};this.dropTarget.setOverlayModel(g),this.pointerDropTarget.setOverlayModel(g)}))!==null&&a!==void 0?a:rn.NONE)}show(){this.element.style.display=""}hide(){this.element.style.display="none"}setLabelledBy(e){e?this._element.setAttribute("aria-labelledby",e):this._element.removeAttribute("aria-labelledby")}renderPanel(e,t){var n,s;const o=((n=t?.asActive)!==null&&n!==void 0?n:!0)||this.panel&&this.group.isPanelActive(this.panel);if(((s=this.panel)===null||s===void 0?void 0:s.view.content.element.parentElement)===this._element){var r,a;this.panel.view.content.element.remove(),(r=(a=this.panel.view.content).onHide)===null||r===void 0||r.call(a)}this.panel=e;let l;switch(e.api.renderer){case"onlyWhenVisible":if(this.group.renderContainer.detatch(e),this.panel&&o){var d,c;this._element.appendChild(this.panel.view.content.element),(d=(c=this.panel.view.content).onShow)===null||d===void 0||d.call(c)}l=this._element;break;case"always":e.view.content.element.parentElement===this._element&&e.view.content.element.remove(),l=this.group.renderContainer.attach({panel:e,referenceContainer:this});break;default:throw new Error(`dockview: invalid renderer type '${e.api.renderer}'`)}if(o){const u=tE(l);this.focusTracker=u;const h=new ct;h.addDisposables(u,u.onDidFocus(()=>this._onDidFocus.fire()),u.onDidBlur(()=>this._onDidBlur.fire())),this.disposable.value=h}}openPanel(e){this.panel!==e&&this.renderPanel(e)}layout(e,t){}closePanel(){if(this.panel&&this.panel.api.renderer==="onlyWhenVisible"){var e,t;this.panel.view.content.element.remove(),(e=(t=this.panel.view.content).onHide)===null||e===void 0||e.call(t)}this.panel=void 0}dispose(){this.disposable.dispose(),super.dispose()}refreshFocusState(){var e;!((e=this.focusTracker)===null||e===void 0)&&e.refreshState&&this.focusTracker.refreshState()}};const zh=e=>{const t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttributeNS(null,"height",e.height),t.setAttributeNS(null,"width",e.width),t.setAttributeNS(null,"viewBox",e.viewbox),t.setAttributeNS(null,"aria-hidden","false"),t.setAttributeNS(null,"focusable","false"),t.classList.add("dv-svg");const n=document.createElementNS("http://www.w3.org/2000/svg","path");return n.setAttributeNS(null,"d",e.path),t.appendChild(n),t},One=()=>zh({width:"11",height:"11",viewbox:"0 0 28 28",path:"M2.1 27.3L0 25.2L11.55 13.65L0 2.1L2.1 0L13.65 11.55L25.2 0L27.3 2.1L15.75 13.65L27.3 25.2L25.2 27.3L13.65 15.75L2.1 27.3Z"}),kE=()=>zh({width:"11",height:"11",viewbox:"0 0 24 24",path:"M16 9V4h1c.55 0 1-.45 1-1s-.45-1-1-1H6c-.55 0-1 .45-1 1s.45 1 1 1h1v5c0 1.66-1.34 3-3 3v2h5.97v7l1 1 1-1v-7H19v-2c-1.66 0-3-1.34-3-3z"}),zne=()=>zh({width:"11",height:"11",viewbox:"0 0 24 15",path:"M12 14.15L0 2.15L2.15 0L12 9.9L21.85 0.0499992L24 2.2L12 14.15Z"}),jE=()=>zh({width:"11",height:"11",viewbox:"0 0 15 25",path:"M2.15 24.1L0 21.95L9.9 12.05L0 2.15L2.15 0L14.2 12.05L2.15 24.1Z"}),Gne=500,Fne=8;var yv=class extends ct{constructor(e,t){super(),this.element=e,this.options=t,this._startX=0,this._startY=0,this.addDisposables(ot(this.element,"pointerdown",n=>{this._onPointerDown(n)}))}_onPointerDown(e){var t,n,s,o,r;if((!((t=this.options.touchOnly)!==null&&t!==void 0)||t)&&e.pointerType!=="touch"&&e.pointerType!=="pen")return;this._cancelPending(),this._pointerId=e.pointerId,this._startX=e.clientX,this._startY=e.clientY;const a=(n=this.options.delay)!==null&&n!==void 0?n:Gne,l=(s=this.options.tolerance)!==null&&s!==void 0?s:Fne,d=(o=(r=this.element.ownerDocument)===null||r===void 0?void 0:r.defaultView)!==null&&o!==void 0?o:globalThis.window;this._timer=setTimeout(()=>{this._timer=void 0,this._cancelPending(),this._installContextMenuGuard(d),this._installClickGuard(d),this.options.onLongPress(e)},a),this._moveListener=ot(d,"pointermove",c=>{if(c.pointerId!==this._pointerId)return;const u=c.clientX-this._startX,h=c.clientY-this._startY;Math.hypot(u,h)>l&&this._cancelPending()}),this._upListener=ot(d,"pointerup",c=>{c.pointerId===this._pointerId&&this._cancelPending()}),this._cancelListener=ot(d,"pointercancel",c=>{c.pointerId===this._pointerId&&this._cancelPending()})}_installContextMenuGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=ot(e,"contextmenu",s=>{s.preventDefault(),clearTimeout(n),t?.dispose()},{capture:!0})}_installClickGuard(e){let t;const n=setTimeout(()=>t?.dispose(),500);t=ot(e,"click",s=>{const o=s.target;o&&this.element.contains(o)&&(s.preventDefault(),s.stopPropagation()),clearTimeout(n),t?.dispose()},{capture:!0})}_cancelPending(){var e,t,n;this._timer!==void 0&&(clearTimeout(this._timer),this._timer=void 0),this._pointerId=void 0,(e=this._moveListener)===null||e===void 0||e.dispose(),(t=this._upListener)===null||t===void 0||t.dispose(),(n=this._cancelListener)===null||n===void 0||n.dispose(),this._moveListener=void 0,this._upListener=void 0,this._cancelListener=void 0}dispose(){this._cancelPending(),super.dispose()}};function ci(e){if(e.disableDnd)return{html5:!1,pointer:!1,pointerHandlesMouse:!1};switch(e.dndStrategy){case"pointer":return{html5:!1,pointer:!0,pointerHandlesMouse:!0};case"html5":return{html5:!0,pointer:!1,pointerHandlesMouse:!1};default:return Hne()?{html5:!1,pointer:!0,pointerHandlesMouse:!0}:{html5:!0,pointer:!0,pointerHandlesMouse:!1}}}function Hne(){if(globalThis.window===void 0||!globalThis.matchMedia)return!1;const e=globalThis.matchMedia("(pointer: coarse)").matches,t=globalThis.matchMedia("(pointer: fine)").matches;return e&&!t}let Bne=0;const Vne=()=>`dv-tab-${Bne++}`;var $ne=class extends ct{get element(){return this._element}constructor(e,t,n){var s,o,r,a,l,d,c,u;super(),this.panel=e,this.accessor=t,this.group=n,this.content=void 0,this.panelTransfer=xo.getInstance(),this._direction="horizontal",this._pinIndicator=void 0,this._onPointDown=new ve,this.onPointerDown=this._onPointDown.event,this._onTabClick=new ve,this.onTabClick=this._onTabClick.event,this._onDropped=new ve,this.onDrop=this._onDropped.event,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._onDragEnd=new ve,this.onDragEnd=this._onDragEnd.event;const h=ci(this.accessor.options);this._element=document.createElement("div"),this._element.className="dv-tab",this._element.tabIndex=-1,this._element.draggable=h.html5,this._element.id=Vne(),this._element.setAttribute("role","tab"),this._element.setAttribute("aria-selected","false"),this._element.setAttribute("aria-label",(s=this.panel.title)!==null&&s!==void 0?s:this.panel.id),this._element.dataset.tabPanelId=this.panel.id;const p=(o=this.group)===null||o===void 0||(o=o.model)===null||o===void 0?void 0:o.contentContainerId;p&&this._element.setAttribute("aria-controls",p),Ze(this.element,"dv-inactive-tab",!0),this._updatePinnedClasses();const f=(x,v)=>{if(this.group.locked)return!1;const y=Ln();if(this.accessor.id===y?.viewId){var w;return((w=this.accessor.options.theme)===null||w===void 0?void 0:w.tabAnimation)!=="smooth"}return this.group.model.canDisplayOverlay(x,v,"tab")};this.dropTarget=zo.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var x;return(x=n.model.dropTargetContainer)===null||x===void 0?void 0:x.model}}),this.pointerDropTarget=vo.createDropTarget(this._element,{acceptedTargetZones:["left","right"],overlayModel:this._buildOverlayModel(),canDisplayOverlay:f,getOverrideTarget:()=>{var x;return(x=n.model.dropTargetContainer)===null||x===void 0?void 0:x.model}});const g={getData:()=>(this.panelTransfer.setData([new Zs(this.accessor.id,this.group.id,this.panel.id)],Zs.prototype),{dispose:()=>{this.panelTransfer.clearData(Zs.prototype)}}),createGhost:()=>({element:this._buildGhostElement(),offsetX:30,offsetY:-10}),onDragStart:x=>{var v;this._onDragStart.fire(x),!(x instanceof PointerEvent)&&((v=this.accessor.options.theme)===null||v===void 0?void 0:v.tabAnimation)==="smooth"&&requestAnimationFrame(()=>{Ze(this.element,"dv-tab--dragging",!0)})},onDragEnd:x=>{this._onDragEnd.fire(x)}};this.html5DragSource=zo.createDragSource(this._element,pt(pt({},g),{},{disabled:!h.html5})),this.pointerDragSource=vo.createDragSource(this._element,pt(pt({},g),{},{disabled:!h.pointer,touchOnly:!h.pointerHandlesMouse,isCancelled:()=>!ci(this.accessor.options).pointer})),this.onWillShowOverlay=Qs.any(this.dropTarget.onWillShowOverlay,this.pointerDropTarget.onWillShowOverlay),this.addDisposables(this._onPointDown,this._onTabClick,this._onDropped,this._onDragStart,this._onDragEnd,this.accessor.onDidOptionsChange(()=>{const x=this._buildOverlayModel();this.dropTarget.setOverlayModel(x),this.pointerDropTarget.setOverlayModel(x),this._updatePinnedClasses()}),(r=(a=this.panel.api)===null||a===void 0||(l=a.onDidChangePinned)===null||l===void 0?void 0:l.call(a,()=>{this._updatePinnedClasses()}))!==null&&r!==void 0?r:{dispose:()=>{}},(d=(c=this.panel.api)===null||c===void 0||(u=c.onDidTitleChange)===null||u===void 0?void 0:u.call(c,x=>{var v;this._element.setAttribute("aria-label",(v=x.title)!==null&&v!==void 0?v:this.panel.id)}))!==null&&d!==void 0?d:{dispose:()=>{}},ot(this._element,"dragend",()=>{Ze(this.element,"dv-tab--dragging",!1)}),this.html5DragSource,ot(this._element,"pointerdown",x=>{this._onPointDown.fire(x)}),ot(this._element,"click",x=>{this._onTabClick.fire(x)}),ot(this._element,"contextmenu",x=>{var v;(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}),new yv(this._element,{onLongPress:x=>{var v;this.pointerDragSource.cancelPending(),(v=this.accessor.contextMenuService)===null||v===void 0||v.show(this.panel,this.group,x)}}),this.dropTarget.onDrop(x=>{this._onDropped.fire(x)}),this.pointerDropTarget.onDrop(x=>{this._onDropped.fire(x)}),this.dropTarget,this.pointerDropTarget,this.pointerDragSource)}_updatePinnedClasses(){var e,t,n,s;const o=(e=(t=this.panel.api)===null||t===void 0?void 0:t.isPinned)!==null&&e!==void 0?e:!1,r=o&&((n=this.accessor.options.pinnedTabs)===null||n===void 0?void 0:n.compact)===!0;Ze(this.element,"dv-tab--pinned",o),Ze(this.element,"dv-tab--pinned-compact",r);const a=o&&!(!((s=this.panel.api)===null||s===void 0)&&s.tabComponent);if(a&&!this._pinIndicator){const l=document.createElement("div");l.className="dv-tab-pin",l.appendChild(kE()),this._element.insertBefore(l,this._element.firstChild),this._pinIndicator=l}else!a&&this._pinIndicator&&(this._pinIndicator.remove(),this._pinIndicator=void 0)}setActive(e){Ze(this.element,"dv-active-tab",e),Ze(this.element,"dv-inactive-tab",!e),this._element.setAttribute("aria-selected",e?"true":"false"),this._element.tabIndex=e?0:-1}setContent(e){this.content&&this.content.element.remove(),this.content=e,this._element.appendChild(this.content.element)}_buildOverlayModel(){var e,t,n;const s=(e=(t=this.accessor).resolveDropOverlayModel)===null||e===void 0?void 0:e.call(t,"tab",this.group);if(s)return s;const o=((n=this.accessor.options.theme)===null||n===void 0?void 0:n.dndTabIndicator)==="line"?Number.POSITIVE_INFINITY:0;return{activationSize:{value:50,type:"percentage"},smallWidthBoundary:o,smallHeightBoundary:o}}setDirection(e){this._direction=e;const t=e==="vertical"?["top","bottom"]:["left","right"];this.dropTarget.setTargetZones(t),this.pointerDropTarget.setTargetZones(t)}updateDragAndDropState(){const e=ci(this.accessor.options);this._element.draggable=e.html5,this.html5DragSource.setDisabled(!e.html5),this.pointerDragSource.setDisabled(!e.pointer),this.pointerDragSource.setTouchOnly(!e.pointerHandlesMouse)}_buildGhostElement(){const e=getComputedStyle(this.element),t=this.element.cloneNode(!0),n=this._direction==="vertical",s=new Set(["writing-mode","inline-size","block-size","min-inline-size","min-block-size","max-inline-size","max-block-size","margin-inline","margin-inline-start","margin-inline-end","margin-block","margin-block-start","margin-block-end","padding-inline","padding-inline-start","padding-inline-end","padding-block","padding-block-start","padding-block-end"]);return Array.from(e).forEach(o=>{n&&s.has(o)||t.style.setProperty(o,e.getPropertyValue(o),e.getPropertyPriority(o))}),n&&(t.style.setProperty("writing-mode","horizontal-tb"),t.style.setProperty("width",e.height),t.style.setProperty("height",e.width)),t.style.position="absolute",t.classList.add("dv-tab-ghost-drag"),t}},td=class{get kind(){return this.options.kind}get nativeEvent(){return this.event.nativeEvent}get position(){return this.event.position}get edge(){return this.event.edge}get edgeGroup(){return this.event.edgeGroup}get defaultPrevented(){return this.event.defaultPrevented}get panel(){return this.options.panel}get api(){return this.options.api}get group(){return this.options.group}preventDefault(){this.event.preventDefault()}getData(){return this.options.getData()}constructor(e,t){this.event=e,this.options=t}},_E=class extends ct{get group(){return this.groupAccessor()}constructor(e){var t,n;super(),this.panelTransfer=xo.getInstance(),this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._element=e.element,this.accessor=e.accessor;const s=e.group;this.groupAccessor=typeof s=="function"?s:()=>s,this.isFloatingMoveHandle=(t=e.isFloatingMoveHandle)!==null&&t!==void 0?t:(()=>!0);const o=ci(this.accessor.options);this._element.draggable=o.html5,Ze(this._element,"dv-draggable",o.html5||o.pointer),this.addDisposables(this._onDragStart);const r=()=>{const p=document.createElement("div"),f=globalThis.getComputedStyle(this._element),g=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-background-color"),x=f.getPropertyValue("--dv-activegroup-visiblepanel-tab-color");return p.style.backgroundColor=g,p.style.color=x,p.style.padding="2px 8px",p.style.height="24px",p.style.fontSize="11px",p.style.lineHeight="20px",p.style.borderRadius="12px",p.style.whiteSpace="nowrap",p.style.boxSizing="border-box",p.style.display="inline-block",p.textContent=`Multiple Panels (${this.group.size})`,p},l={getData:()=>(this.panelTransfer.setData([new Zs(this.accessor.id,this.group.id,null)],Zs.prototype),{dispose:()=>{this.panelTransfer.clearData(Zs.prototype)}}),createGhost:()=>{var p,f;const g=(p=(f=this.accessor).buildGroupDragGhost)===null||p===void 0?void 0:p.call(f,this.group);return g||{element:r(),offsetX:30,offsetY:-10}},onDragStart:p=>{this._onDragStart.fire(p)}};this.html5DragSource=zo.createDragSource(this._element,pt(pt({},l),{},{disabled:!o.html5,isCancelled:p=>!!(this.group.api.location.type==="floating"&&this.isFloatingMoveHandle()&&!p.shiftKey||this.group.api.location.type==="edge"&&this.group.size===0)}));const d=()=>{var p;return((p=this.group)===null||p===void 0||(p=p.api)===null||p===void 0||(p=p.location)===null||p===void 0?void 0:p.type)==="floating"&&this.isFloatingMoveHandle()};this.pointerDragSource=vo.createDragSource(this._element,pt(pt({},l),{},{disabled:!o.pointer,touchOnly:!o.pointerHandlesMouse,touchInitiationDelay:()=>d()?500:250,pressTolerance:()=>d()?1/0:8,isCancelled:()=>!ci(this.accessor.options).pointer||this.group.api.location.type==="edge"&&this.group.size===0,onDragStart:p=>{var f;(f=this.getFloatingOverlay())===null||f===void 0||f.cancelPendingDrag(),this._onDragStart.fire(p)}}));const c=new Fn,u=()=>{const p=this.getFloatingOverlay();c.value=p?p.onDidStartMoving(()=>{this.pointerDragSource.cancelPending()}):rn.NONE};u(),this.addDisposables(c);const h=(n=this.group)===null||n===void 0||(n=n.api)===null||n===void 0?void 0:n.onDidLocationChange;h&&this.addDisposables(h(u)),this.addDisposables(this.html5DragSource,this.pointerDragSource)}updateDragAndDropState(){const e=ci(this.accessor.options);this._element.draggable=e.html5,Ze(this._element,"dv-draggable",e.html5||e.pointer),this.html5DragSource.setDisabled(!e.html5),this.pointerDragSource.setDisabled(!e.pointer),this.pointerDragSource.setTouchOnly(!e.pointerHandlesMouse)}getFloatingOverlay(){var e;if(this.group)return(e=this.accessor.floatingGroups)===null||e===void 0||(e=e.find(t=>t.group===this.group))===null||e===void 0?void 0:e.overlay}},Wne=class extends ct{get element(){return this._element}constructor(e,t){var n,s,o,r,a,l,d;super(),this.accessor=e,this.group=t,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._element=document.createElement("div"),this._element.className="dv-void-container",this.addDisposables(this._onDrop,this._onDragStart,ot(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this.group)}),ot(this._element,"pointerdown",u=>{u.shiftKey&&sE(u)},!0)),this.dragSource=new _E({element:this._element,accessor:this.accessor,group:this.group,isFloatingMoveHandle:()=>!this._element.closest(".dv-resize-container-with-titlebar")});const c=(u,h)=>{if(this.group.api.locked)return!1;const p=Ln();return this.accessor.id===p?.viewId?!0:t.model.canDisplayOverlay(u,h,"header_space")};this.dropTarget=zo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:c,getOverrideTarget:()=>{var u;return(u=t.model.dropTargetContainer)===null||u===void 0?void 0:u.model},overlayModel:(n=(s=this.accessor).resolveDropOverlayModel)===null||n===void 0?void 0:n.call(s,"header_space",this.group)}),this.pointerDropTarget=vo.createDropTarget(this._element,{acceptedTargetZones:["center"],canDisplayOverlay:c,getOverrideTarget:()=>{var u;return(u=t.model.dropTargetContainer)===null||u===void 0?void 0:u.model},overlayModel:(o=(r=this.accessor).resolveDropOverlayModel)===null||o===void 0?void 0:o.call(r,"header_space",this.group)}),this.onWillShowOverlay=Qs.any(this.dropTarget.onWillShowOverlay,this.pointerDropTarget.onWillShowOverlay),this.addDisposables(this.dragSource,this.dragSource.onDragStart(u=>{this._onDragStart.fire(u)}),this.dropTarget.onDrop(u=>{this._onDrop.fire(u)}),this.pointerDropTarget.onDrop(u=>{this._onDrop.fire(u)}),this.dropTarget,this.pointerDropTarget,(a=(l=(d=this.accessor).onDidOptionsChange)===null||l===void 0?void 0:l.call(d,()=>{var u,h,p;const f=(u=(h=(p=this.accessor).resolveDropOverlayModel)===null||h===void 0?void 0:h.call(p,"header_space",this.group))!==null&&u!==void 0?u:{};this.dropTarget.setOverlayModel(f),this.pointerDropTarget.setOverlayModel(f)}))!==null&&a!==void 0?a:rn.NONE)}updateDragAndDropState(){this.dragSource.updateDragAndDropState()}},NE=class TE extends ct{get element(){return this._element}get orientation(){return this._orientation}set orientation(t){this._orientation!==t&&(this._scrollOffset=0,this._orientation=t,bi(this._scrollbar,"dv-scrollbar-vertical","dv-scrollbar-horizontal"),t==="vertical"?wi(this._scrollbar,"dv-scrollbar-vertical"):wi(this._scrollbar,"dv-scrollbar-horizontal"))}constructor(t){super(),this.scrollableElement=t,this._scrollOffset=0,this._orientation="horizontal",this._element=document.createElement("div"),this._element.className="dv-scrollable",this._scrollbar=document.createElement("div"),this._scrollbar.className="dv-scrollbar dv-scrollbar-horizontal",this.element.appendChild(t),this.element.appendChild(this._scrollbar),this.addDisposables(ot(this.element,"wheel",n=>{this._scrollOffset+=n.deltaY*TE.MouseWheelSpeed,this.scheduleStyleUpdate()}),ot(this._scrollbar,"pointerdown",n=>{var s;n.preventDefault();const o=(s=this._scrollbar.ownerDocument)!==null&&s!==void 0?s:document;Ze(this.element,"dv-scrollable-scrolling",!0);const r=this._orientation==="horizontal"?n.clientX:n.clientY,a=this._scrollOffset,l=c=>{const u=this._orientation==="horizontal"?c.clientX-r:c.clientY-r,h=(this._orientation==="horizontal"?this.element.clientWidth:this.element.clientHeight)/(this._orientation==="horizontal"?this.scrollableElement.scrollWidth:this.scrollableElement.scrollHeight);this._scrollOffset=a+u/h,this.scheduleStyleUpdate()},d=()=>{Ze(this.element,"dv-scrollable-scrolling",!1),o.removeEventListener("pointermove",l),o.removeEventListener("pointerup",d),o.removeEventListener("pointercancel",d)};o.addEventListener("pointermove",l),o.addEventListener("pointerup",d),o.addEventListener("pointercancel",d)}),ot(this.element,"scroll",()=>{this.scheduleStyleUpdate()}),ot(this.scrollableElement,"scroll",()=>{this._scrollOffset=this._orientation==="horizontal"?this.scrollableElement.scrollLeft:this.scrollableElement.scrollTop,this.scheduleStyleUpdate()}),kr(this.element,()=>{Ze(this.element,"dv-scrollable-resizing",!0),this._animationTimer&&clearTimeout(this._animationTimer),this._animationTimer=setTimeout(()=>{clearTimeout(this._animationTimer),Ze(this.element,"dv-scrollable-resizing",!1)},500),this.scheduleStyleUpdate()}),rn.from(()=>{this._pendingStyleFrame!==void 0&&(cancelAnimationFrame(this._pendingStyleFrame),this._pendingStyleFrame=void 0)}))}scheduleStyleUpdate(){this._pendingStyleFrame===void 0&&(this._pendingStyleFrame=requestAnimationFrame(()=>{this._pendingStyleFrame=void 0,this.calculateScrollbarStyles()}))}calculateScrollbarStyles(){const t=this._orientation==="horizontal"?this.element.clientWidth:this.element.clientHeight,n=this._orientation==="horizontal"?this.scrollableElement.scrollWidth:this.scrollableElement.scrollHeight;if(n>t){const s=t*(t/n);this._orientation==="horizontal"?(this._scrollbar.style.width=`${s}px`,this._scrollbar.style.height=""):(this._scrollbar.style.height=`${s}px`,this._scrollbar.style.width=""),this._scrollOffset=En(this._scrollOffset,0,n-t),this._orientation==="horizontal"?this.scrollableElement.scrollLeft=this._scrollOffset:this.scrollableElement.scrollTop=this._scrollOffset;const o=this._scrollOffset/(n-t);this._orientation==="horizontal"?(this._scrollbar.style.left=`${(t-s)*o}px`,this._scrollbar.style.top=""):(this._scrollbar.style.top=`${(t-s)*o}px`,this._scrollbar.style.left="")}else this._orientation==="horizontal"?(this._scrollbar.style.width="0px",this._scrollbar.style.left="0px"):(this._scrollbar.style.height="0px",this._scrollbar.style.top="0px"),this._scrollOffset=0}};NE.MouseWheelSpeed=1;const DE="dv-tabs-container--wrap";function Une(e,t){return typeof e=="boolean"?e:!!e?.[t]}function eg(e){return typeof e=="boolean"?e:e?Object.values(e).some(Boolean):!1}var IE=class extends QI{constructor(e,t,n,s,o){super(),this.nativeEvent=e,this.target=t,this.position=n,this.getData=s,this.group=o}};const tg=Object.keys({disableAutoResizing:void 0,hideBorders:void 0,singleTabMode:void 0,disableFloatingGroups:void 0,floatingGroupBounds:void 0,transformFloatingGroupDrag:void 0,smartGuides:void 0,floatingGroupDragHandle:void 0,popoutUrl:void 0,nonce:void 0,defaultRenderer:void 0,defaultHeaderPosition:void 0,debug:void 0,locked:void 0,disableDnd:void 0,dndStrategy:void 0,className:void 0,noPanelsOverlay:void 0,dndEdges:void 0,dropPositionResolver:void 0,dndCompass:void 0,theme:void 0,disableTabsOverflowList:void 0,overflow:void 0,scrollbars:void 0,getTabContextMenuItems:void 0,getTabGroupChipContextMenuItems:void 0,createTabGroupChipComponent:void 0,createGroupDragGhostComponent:void 0,dropOverlayModel:void 0,announcements:void 0,getAnnouncement:void 0,announcer:void 0,messages:void 0,keyboardNavigation:void 0,layoutHistory:void 0,autoHideEdgeGroups:void 0,dockToEdgeGroups:void 0,edgeGroupPeek:void 0,tabGroupColors:void 0,tabGroupAccent:void 0,pinnedTabs:void 0});function Kne(e){return!!e.referencePanel}function qne(e){return!!e.referenceGroup}function Yne(e){return!!e.referencePanel}function Xne(e){return!!e.referenceGroup}const Sv=[{id:"grey",value:"var(--dv-tab-group-color-grey)",label:"Grey"},{id:"blue",value:"var(--dv-tab-group-color-blue)",label:"Blue"},{id:"red",value:"var(--dv-tab-group-color-red)",label:"Red"},{id:"yellow",value:"var(--dv-tab-group-color-yellow)",label:"Yellow"},{id:"green",value:"var(--dv-tab-group-color-green)",label:"Green"},{id:"pink",value:"var(--dv-tab-group-color-pink)",label:"Pink"},{id:"purple",value:"var(--dv-tab-group-color-purple)",label:"Purple"},{id:"cyan",value:"var(--dv-tab-group-color-cyan)",label:"Cyan"},{id:"orange",value:"var(--dv-tab-group-color-orange)",label:"Orange"}];var EE=class{constructor(e,t=!0){this._entries=e.slice(),this._byId=new Map(e.map(n=>[n.id,n])),this._enabled=t}get enabled(){return this._enabled}set enabled(e){this._enabled=e}setEntries(e){this._entries=e.slice(),this._byId=new Map(e.map(t=>[t.id,t]))}entries(){return this._entries}has(e){return this._byId.has(e)}get(e){return this._byId.get(e)}defaultId(){var e;return(e=this._entries[0])===null||e===void 0?void 0:e.id}resolveValue(e){if(!this._enabled||!e)return;const t=this._byId.get(e);return t?t.value:e}};let rf;function PE(){var e;return(e=rf)!==null&&e!==void 0||(rf=new EE(Sv,!0)),rf}function Cv(e,t,n){const s=(n??PE()).resolveValue(t);s===void 0?e.style.removeProperty("--dv-tab-group-color"):e.style.setProperty("--dv-tab-group-color",s)}function kv(e,t){return(t??PE()).resolveValue(e)}var uC=class extends ct{get element(){return this._element}constructor(e){super(),this._palette=e,this._onClick=new ve,this.onClick=this._onClick.event,this._onContextMenu=new ve,this.onContextMenu=this._onContextMenu.event,this._element=document.createElement("div"),this._element.className="dv-tab-group-chip",this._element.tabIndex=0,this._label=document.createElement("span"),this._label.className="dv-tab-group-chip-label",this._element.appendChild(this._label),this.addDisposables(this._onClick,this._onContextMenu,new yv(this._element,{onLongPress:t=>{this._onContextMenu.fire(t)}}),ot(this._element,"click",t=>{this._onClick.fire(t)}),ot(this._element,"contextmenu",t=>{this._onContextMenu.fire(t)}))}init(e){this._tabGroup=e.tabGroup,this.updateColor(e.tabGroup.color),this.updateLabel(e.tabGroup.label),this.updateCollapsed(e.tabGroup.collapsed),this.addDisposables(e.tabGroup.onDidChange(()=>{this._tabGroup&&(this.updateColor(this._tabGroup.color),this.updateLabel(this._tabGroup.label))}),e.tabGroup.onDidCollapseChange(t=>{this.updateCollapsed(t)}),this._onClick.event(()=>{var t;(t=this._tabGroup)===null||t===void 0||t.toggle()}))}update(e){this._tabGroup=e.tabGroup,this.updateColor(e.tabGroup.color),this.updateLabel(e.tabGroup.label),this.updateCollapsed(e.tabGroup.collapsed)}updateColor(e){var t;Cv(this._element,e,this._palette),Ze(this._element,"dv-tab-group-chip--accent-off",((t=this._palette)===null||t===void 0?void 0:t.enabled)===!1)}updateLabel(e){this._label.textContent=e,Ze(this._label,"dv-tab-group-chip-label--empty",!e)}updateCollapsed(e){Ze(this._element,"dv-tab-group-chip--collapsed",e)}};const Zne="dv-tab-group-chip-continuation",hC=8;var AE=class{get underlines(){return this._underlines}constructor(e){this._ctx=e,this._underlines=new Map,this._continuationMarkers=new Map,this._rafId=null}positionUnderlines(){requestAnimationFrame(()=>{this._positionUnderlinesSync()})}trackUnderlines(){this._rafId!==null&&cancelAnimationFrame(this._rafId);const e=performance.now(),t=250,n=()=>{this._positionUnderlinesSync(),performance.now()-e<t?this._rafId=requestAnimationFrame(n):this._rafId=null};this._rafId=requestAnimationFrame(n)}syncUnderlineElements(e){for(const t of e)if(!this._underlines.has(t)){const n=document.createElement("div");n.className="dv-tab-group-underline",this._ctx.tabsList.appendChild(n),this._underlines.set(t,n)}for(const[t,n]of this._underlines)e.has(t)||(n.remove(),this._underlines.delete(t),this._clearContinuationMarkers(t))}getUnderline(e){return this._underlines.get(e)}dispose(){this._rafId!==null&&(cancelAnimationFrame(this._rafId),this._rafId=null);for(const[,e]of this._underlines)e.remove();this._underlines.clear(),this._clearContinuationMarkers()}_syncContinuationMarkers(e,t){let n=this._continuationMarkers.get(e);for(n||(n=[],this._continuationMarkers.set(e,n));n.length<t;){const s=document.createElement("div");s.className=Zne,this._ctx.tabsList.appendChild(s),n.push(s)}for(;n.length>t;){const s=n.pop();s?.remove()}return n}_clearContinuationMarkers(e){if(e===void 0){for(const[,n]of this._continuationMarkers)for(const s of n)s.remove();this._continuationMarkers.clear();return}const t=this._continuationMarkers.get(e);if(t){for(const n of t)n.remove();this._continuationMarkers.delete(e)}}_positionUnderlinesSync(){const e=this._ctx.tabsList.getBoundingClientRect(),t=this._ctx.getTabGroups(),n=this._ctx.getDirection()==="vertical",s=this._ctx.tabsList.classList.contains(DE);s||this._clearContinuationMarkers();const o=n?e.width:e.height,r=this._ctx.getActivePanelId(),a=this._ctx.getTabMap();for(const l of t){const d=this._underlines.get(l.id);if(!d)continue;const c=l.panelIds;if(c.length===0){d.style.display="none";continue}if(d.style.display="",s){this._positionWrappedUnderline(d,l,e,a,n);continue}const u=this._ctx.getChipElement(l.id);let h;if(u){const y=u.getBoundingClientRect(),w=getComputedStyle(u),b=n?Number.parseFloat(w.marginTop)||0:Number.parseFloat(w.marginLeft)||0;h=n?y.top-e.top-b:y.left-e.left-b}else{const y=c[0],w=a.get(y);if(w){const b=w.value.element.getBoundingClientRect();h=n?b.top-e.top:b.left-e.left}else h=0}const p=c[c.length-1],f=a.get(p);if(!f){n?(d.style.top=`${h}px`,d.style.height="0px",d.style.left="",d.style.width=""):(d.style.left=`${h}px`,d.style.width="0px",d.style.top="",d.style.height="");continue}const g=f.value.element.getBoundingClientRect();let x=n?g.bottom-e.top:g.right-e.left,v=x-h;if((l.collapsed||l.panelIds.some(y=>{const w=a.get(y);return w?.value.element.classList.contains("dv-tab--group-expanding")}))&&u){const y=u.getBoundingClientRect(),w=n?y.top+y.height/2-e.top:y.left+y.width/2-e.left;let b=0,_=0;for(const N of l.panelIds){const C=a.get(N);if(!C)continue;const S=C.value.element;n?(b+=S.getBoundingClientRect().height,_+=S.scrollHeight):(b+=S.getBoundingClientRect().width,_+=S.scrollWidth)}const j=_>0?Math.min(1,b/_):0;h=w+(h-w)*j,x=w+(x-w)*j,v=Math.max(0,x-h)}n?(d.style.top=`${h}px`,d.style.height=`${Math.max(0,v)}px`,d.style.left="",d.style.width="",d.style.bottom=""):(d.style.left=`${h}px`,d.style.width=`${Math.max(0,v)}px`,d.style.top="",d.style.height="",d.style.bottom=""),this.applyShape(d,l,h,v,o,r,e,n)}}_positionWrappedUnderline(e,t,n,s,o){const a=kv(t.color,this._ctx.getColorPalette());if(a===void 0){e.style.display="none",this._clearContinuationMarkers(t.id);return}const{runs:l,firstRun:d}=this._computeWrappedRuns(t,n,s,o);if(l.length===0){e.style.display="none",this._clearContinuationMarkers(t.id);return}this._positionContinuationMarkers(t.id,l,d,a,o);const c=Math.min(...l.map(b=>b.left)),u=Math.max(...l.map(b=>b.right)),h=Math.min(...l.map(b=>b.top)),p=Math.max(...l.map(b=>b.bottom)),f=o?Math.max(0,u-c):n.width,g=o?n.height:Math.max(0,p-h);e.style.left=o?`${c}px`:"0px",e.style.top=o?"0px":`${h}px`,e.style.bottom="auto",e.style.width=`${f}px`,e.style.height=`${g}px`,e.style.backgroundColor="";const{svg:x,path:v}=this.ensureSvgPath(e);x.setAttribute("width",String(f)),x.setAttribute("height",String(g)),v.setAttribute("stroke",a),v.setAttribute("stroke-width",String(2));const y=this._ctx.getHeaderPosition(),w=o?y==="right":y==="bottom";v.setAttribute("d",this._wrappedPathData(l,o,w,c,h,2))}_computeWrappedRuns(e,t,n,s){const o=[];let r;for(const l of e.panelIds){var a;const d=n.get(l);if(!d)continue;const c=d.value.element.getBoundingClientRect();if(c.width===0&&c.height===0)continue;const u=c.top-t.top,h=c.bottom-t.top,p=c.left-t.left,f=c.right-t.left,g=s?p:u;let x=o.find(v=>Math.abs((s?v.left:v.top)-g)<=2);x?(x.top=Math.min(x.top,u),x.bottom=Math.max(x.bottom,h),x.left=Math.min(x.left,p),x.right=Math.max(x.right,f)):(x={top:u,bottom:h,left:p,right:f},o.push(x)),(a=r)!==null&&a!==void 0||(r=x)}return{runs:o,firstRun:r}}_wrappedPathData(e,t,n,s,o,r){let a="";for(const l of e)if(t){const d=n?l.right-s-r/2:l.left-s+r/2;a+=`M ${d},${l.top} L ${d},${l.bottom} `}else{const d=n?l.top-o+r/2:l.bottom-o-r/2;a+=`M ${l.left},${d} L ${l.right},${d} `}return a.trim()}_positionContinuationMarkers(e,t,n,s,o){const r=t.filter(l=>l!==n),a=this._syncContinuationMarkers(e,r.length);r.forEach((l,d)=>{const c=a[d];if(c.style.backgroundColor=s,o){const u=(l.left+l.right)/2;c.style.left=`${u-hC/2}px`,c.style.top=`${l.top}px`}else{const u=(l.top+l.bottom)/2;c.style.left=`${l.left}px`,c.style.top=`${u-hC/2}px`}})}ensureSvgPath(e){const t=e.firstElementChild;if(t?.tagName==="svg")return{svg:t,path:t.firstElementChild};e.replaceChildren();const n=document.createElementNS("http://www.w3.org/2000/svg","svg");n.style.display="block";const s=document.createElementNS("http://www.w3.org/2000/svg","path");return s.setAttribute("fill","none"),n.appendChild(s),e.appendChild(n),{svg:n,path:s}}},Jne=class extends AE{_applyStraightLine(e,t,n,s,o,r,a){const l=a?o:s,d=a?s:o;e.setAttribute("width",String(l)),e.setAttribute("height",String(d)),n.style.width=`${l}px`,n.style.height=`${d}px`,t.setAttribute("d",a?`M ${r},0 L ${r},${s}`:`M 0,${r} L ${s},${r}`)}applyShape(e,t,n,s,o,r,a,l){const c=o,u=s,h=kv(t.color,this._ctx.getColorPalette());if(u<=0||c<=0||h===void 0){e.style.display="none";return}e.style.display="";let p;r&&t.panelIds.includes(r)&&(p=this._ctx.getTabMap().get(r));const{svg:f,path:g}=this.ensureSvgPath(e);g.setAttribute("stroke",h),g.setAttribute("stroke-width",String(2));const x=2,v=this._ctx.getHeaderPosition(),y=!l&&v==="bottom",w=l&&v==="right";let b,_;if(l?(b=w?c-x:x,_=w?x:c-x):(b=y?x:c-x,_=y?c-x:x),!p){this._applyStraightLine(f,g,e,u,c,b,l);return}const j=p.value.element.getBoundingClientRect();let N,C;if(l?(N=Math.max(0,j.top-a.top-n),C=Math.min(u,j.bottom-a.top-n)):(N=Math.max(0,j.left-a.left-n),C=Math.min(u,j.right-a.left-n)),C<=N){this._applyStraightLine(f,g,e,u,c,b,l);return}const S=6,A=_>b?1:-1;if(l){const E=c,I=u;f.setAttribute("width",String(E)),f.setAttribute("height",String(I)),e.style.width=`${E}px`,e.style.height=`${I}px`;const D=[`M ${b},0`,`L ${b},${N-S}`,`Q ${b},${N} ${b+A*S},${N}`,`L ${_-A*S},${N}`,`Q ${_},${N} ${_},${N+S}`,`L ${_},${C-S}`,`Q ${_},${C} ${_-A*S},${C}`,`L ${b+A*S},${C}`,`Q ${b},${C} ${b},${C+S}`,`L ${b},${I}`].join(" ");g.setAttribute("d",D)}else{const E=u,I=c;f.setAttribute("width",String(E)),f.setAttribute("height",String(I)),e.style.width=`${E}px`,e.style.height=`${I}px`;const D=[`M 0,${b}`,`L ${N-S},${b}`,`Q ${N},${b} ${N},${b+A*S}`,`L ${N},${_-A*S}`,`Q ${N},${_} ${N+S},${_}`,`L ${C-S},${_}`,`Q ${C},${_} ${C},${_-A*S}`,`L ${C},${b+A*S}`,`Q ${C},${b} ${C+S},${b}`,`L ${E},${b}`].join(" ");g.setAttribute("d",D)}}},Qne=class extends AE{applyShape(e,t,n,s,o,r,a,l){const c=kv(t.color,this._ctx.getColorPalette());if(s<=0||c===void 0){e.style.display="none";return}e.style.display="",e.firstElementChild&&e.replaceChildren(),e.style.backgroundColor=c,l?(e.style.width="2px",e.style.height=`${s}px`):(e.style.width=`${s}px`,e.style.height="2px")}};const ese=new Map;var tse=class{get chipRenderers(){return this._chipRenderers}get groupUnderlines(){var e,t;return(e=(t=this._indicator)===null||t===void 0?void 0:t.underlines)!==null&&e!==void 0?e:ese}get skipNextCollapseAnimation(){return this._skipNextCollapseAnimation}set skipNextCollapseAnimation(e){this._skipNextCollapseAnimation=e}constructor(e,t){this._ctx=e,this._callbacks=t,this._chipRenderers=new Map,this._indicator=null,this._skipNextCollapseAnimation=!1,this._pendingTransitionCleanups=new Map}update(){const e=this._ctx.group.model.getTabGroups(),t=new Set;for(const s of e)t.add(s.id),this._ensureChipForGroup(s),this._positionChipForGroup(s);for(const[s,o]of this._chipRenderers)if(!t.has(s)){var n;o.chip.element.remove(),o.chip.dispose(),(n=o.dragSourcesDisposable)===null||n===void 0||n.dispose(),o.disposable.dispose(),this._chipRenderers.delete(s)}this._updateTabGroupClasses()}refreshAccents(){for(const n of this._ctx.group.model.getTabGroups()){var e,t;const s=this._chipRenderers.get(n.id);s==null||(t=(e=s.chip).update)===null||t===void 0||t.call(e,{tabGroup:n})}this._updateTabGroupClasses()}positionAllChips(){if(this._chipRenderers.size!==0)for(const e of this._ctx.group.model.getTabGroups())this._positionChipForGroup(e)}updateDirection(){const e=this._ctx.getDirection()==="vertical";for(const[,t]of this._chipRenderers)t.dropTarget.setTargetZones(e?["top"]:["left"])}snapshotChipWidths(){const e=new Map;for(const[t,n]of this._chipRenderers)e.set(t,n.chip.element.getBoundingClientRect().width);return e}positionUnderlines(){var e;(e=this._indicator)===null||e===void 0||e.positionUnderlines()}trackUnderlines(){var e;(e=this._indicator)===null||e===void 0||e.trackUnderlines()}setGroupDragImage(e,t,n){if(!e.dataTransfer)return;const s=this._ctx.getDirection()==="vertical",o=this._ctx.tabsList.cloneNode(!0);s?(o.classList.remove("dv-tabs-container-vertical","dv-vertical"),o.classList.add("dv-horizontal"),o.style.writingMode="horizontal-tb",o.style.height=`${this._ctx.tabsList.offsetWidth}px`):o.style.height=`${this._ctx.tabsList.offsetHeight}px`,o.style.width="auto",o.style.overflow="visible",o.style.pointerEvents="none";const r=Array.from(o.children),a=Array.from(this._ctx.tabsList.children);for(let f=r.length-1;f>=0;f--)a[f]!==n&&r[f].remove();const l=document.createElement("div");l.className="dv-groupview dv-active-group",l.style.position="fixed",l.style.top="-10000px",l.style.left="0px",l.style.height="auto",l.style.width="auto",l.style.pointerEvents="none";const d=document.createElement("div");d.className="dv-tabs-and-actions-container",d.style.height="auto",d.style.width="auto",l.appendChild(d),d.appendChild(o),this._ctx.accessor.element.appendChild(l);const c=o.querySelector(".dv-tab-group-chip"),u=n.getBoundingClientRect(),h=e.clientX-u.left,p=e.clientY-u.top;if(c){const f=c.getBoundingClientRect(),g=l.getBoundingClientRect(),x=f.left-g.left+h,v=f.top-g.top+p;e.dataTransfer.setDragImage(l,x,v)}else e.dataTransfer.setDragImage(l,h,p);requestAnimationFrame(()=>{l.remove()})}cleanupTransition(e){var t;(t=this._pendingTransitionCleanups.get(e))===null||t===void 0||t(),this._pendingTransitionCleanups.delete(e)}updateDragAndDropState(){const e=ci(this._ctx.accessor.options);for(const o of this._chipRenderers.values()){var t,n,s;o.chip.element.draggable=e.html5,(t=o.html5DragSource)===null||t===void 0||t.setDisabled(!e.html5),(n=o.pointerDragSource)===null||n===void 0||n.setDisabled(!e.pointer),(s=o.pointerDragSource)===null||s===void 0||s.setTouchOnly(!e.pointerHandlesMouse)}}disposeChipDrag(e){var t;const n=this._chipRenderers.get(e);n&&((t=n.dragSourcesDisposable)===null||t===void 0||t.dispose(),n.html5DragSource=void 0,n.pointerDragSource=void 0,n.dragSourcesDisposable=void 0)}_buildChipGhostElement(e){const t=getComputedStyle(e),n=e.cloneNode(!0);return Array.from(t).forEach(s=>{n.style.setProperty(s,t.getPropertyValue(s),t.getPropertyPriority(s))}),n.style.position="absolute",n}disposeAll(){var e;(e=this._indicator)===null||e===void 0||e.dispose(),this._indicator=null;for(const[,n]of this._pendingTransitionCleanups)n();this._pendingTransitionCleanups.clear();for(const[,n]of this._chipRenderers){var t;n.chip.element.remove(),n.chip.dispose(),(t=n.dragSourcesDisposable)===null||t===void 0||t.dispose(),n.disposable.dispose()}this._chipRenderers.clear()}_ensureIndicator(){var e,t,n;const s=((e=(t=this._ctx.accessor.options.theme)===null||t===void 0?void 0:t.tabGroupIndicator)!==null&&e!==void 0?e:"wrap")==="none"?Qne:Jne;this._indicator&&!(this._indicator instanceof s)&&(this._indicator.dispose(),this._indicator=null),(n=this._indicator)!==null&&n!==void 0||(this._indicator=new s({tabsList:this._ctx.tabsList,getTabGroups:()=>this._ctx.group.model.getTabGroups(),getActivePanelId:()=>{var o;return(o=this._ctx.group.activePanel)===null||o===void 0?void 0:o.id},getTabMap:()=>this._ctx.getTabMap(),getChipElement:o=>{var r;return(r=this._chipRenderers.get(o))===null||r===void 0?void 0:r.chip.element},getDirection:()=>this._ctx.getDirection(),getHeaderPosition:()=>this._ctx.group.model.headerPosition,getColorPalette:()=>this._ctx.accessor.tabGroupColorPalette}))}_createChipDragSources(e,t){const n=ci(this._ctx.accessor.options);e.element.draggable=n.html5;const s=xo.getInstance(),o=()=>(s.setData([new Zs(this._ctx.accessor.id,this._ctx.group.id,null,t.id)],Zs.prototype),{dispose:()=>{s.clearData(Zs.prototype)}}),r=zo.createDragSource(e.element,{getData:o,disabled:!n.html5,isCancelled:()=>!ci(this._ctx.accessor.options).html5,onDragStart:d=>{"dataTransfer"in d&&d.dataTransfer&&this.setGroupDragImage(d,t,e.element),this._callbacks.onChipDragStart(t,e,d)},onDragEnd:d=>{var c,u;(c=(u=this._callbacks).onChipDragEnd)===null||c===void 0||c.call(u,t,e,d)}}),a=()=>{s.clearData(Zs.prototype)};e.element.addEventListener("dragend",a,{once:!0});const l=vo.createDragSource(e.element,{getData:o,disabled:!n.pointer,touchOnly:!n.pointerHandlesMouse,isCancelled:()=>!ci(this._ctx.accessor.options).pointer,createGhost:()=>({element:this._buildChipGhostElement(e.element),offsetX:8,offsetY:8}),onDragStart:d=>{this._callbacks.onChipDragStart(t,e,d)}});return{html5DragSource:r,pointerDragSource:l,disposable:{dispose:()=>{r.dispose(),l.dispose(),e.element.removeEventListener("dragend",a)}}}}_ensureChipForGroup(e){const t=this._chipRenderers.get(e.id);if(t){if(!t.html5DragSource){const u=this._createChipDragSources(t.chip,e);t.html5DragSource=u.html5DragSource,t.pointerDragSource=u.pointerDragSource,t.dragSourcesDisposable=u.disposable}return}const n=this._ctx.accessor.options.createTabGroupChipComponent,s=n?n(e):new uC(this._ctx.accessor.tabGroupColorPalette);s.init({tabGroup:e,api:this._ctx.accessor.api});const o=this._createChipDragSources(s,e),r=[e.onDidChange(()=>{var u;(u=s.update)===null||u===void 0||u.call(s,{tabGroup:e}),this._updateTabGroupClasses()}),e.onDidPanelChange(()=>{this._positionChipForGroup(e),this._updateTabGroupClasses()}),e.onDidCollapseChange(()=>{this._updateTabGroupClasses()})],a=u=>{var h;(h=this._chipRenderers.get(e.id))===null||h===void 0||(h=h.pointerDragSource)===null||h===void 0||h.cancelPending(),this._callbacks.onChipContextMenu(e,u)};s instanceof uC?r.push(s.onContextMenu(a)):r.push(new yv(s.element,{onLongPress:a}),ot(s.element,"contextmenu",a));const l=this._ctx.getDirection()==="vertical",d=new Oh(s.element,{acceptedTargetZones:l?["top"]:["left"],overlayModel:{activationSize:{value:100,type:"percentage"}},canDisplayOverlay:(u,h)=>{if(this._ctx.group.locked||this._ctx.accessor.options.disableDnd)return!1;const p=Ln();if(this._ctx.accessor.id===p?.viewId){var f;return((f=this._ctx.accessor.options.theme)===null||f===void 0?void 0:f.tabAnimation)!=="smooth"}return this._ctx.group.model.canDisplayOverlay(u,h,"tab")}});r.push(d,d.onDrop(u=>{this._callbacks.onChipDrop(e,u)}));const c=new ct(...r);this._chipRenderers.set(e.id,{chip:s,html5DragSource:o.html5DragSource,pointerDragSource:o.pointerDragSource,dragSourcesDisposable:o.disposable,disposable:c,dropTarget:d}),e.collapsed&&(this._skipNextCollapseAnimation=!0)}_positionChipForGroup(e){const t=this._chipRenderers.get(e.id);if(!t)return;const n=t.chip.element,s=e.panelIds;if(s.length===0){n.remove();return}const o=s[0],r=this._ctx.getTabMap().get(o);if(!r){n.remove();return}const a=r.value.element;n.nextSibling!==a&&this._ctx.tabsList.insertBefore(n,a)}_updateTabGroupClasses(){const e=this._ctx.group.model.getTabGroups(),t=this._ctx.getTabs(),n=this._ctx.getTabMap();let s=!1;const o=new Map;for(const l of e)for(const d of l.panelIds)o.set(d,l);for(const l of t){const d=l.value,c=d.panel.id,u=o.get(c),h=!!u;if(Ze(d.element,"dv-tab--grouped",h),u){const p=u.panelIds,f=p[0]===c,g=p[p.length-1]===c;Ze(d.element,"dv-tab--group-first",f),Ze(d.element,"dv-tab--group-last",g),Cv(d.element,u.color,this._ctx.accessor.tabGroupColorPalette);const x=d.element.classList.contains("dv-tab--group-collapsed");if(!u.collapsed&&x){var r;s=!0,d.element.classList.remove("dv-tab--group-collapsed"),d.element.classList.add("dv-tab--group-expanding"),(r=this._pendingTransitionCleanups.get(c))===null||r===void 0||r();const v=()=>{d.element.classList.remove("dv-tab--group-expanding"),d.element.style.removeProperty("width"),d.element.removeEventListener("transitionend",v),clearTimeout(y),this._pendingTransitionCleanups.delete(c)},y=setTimeout(v,300);this._pendingTransitionCleanups.set(c,v),d.element.addEventListener("transitionend",v)}}else Ze(d.element,"dv-tab--group-first",!1),Ze(d.element,"dv-tab--group-last",!1),d.element.classList.remove("dv-tab--group-collapsed","dv-tab--group-expanding"),d.element.style.removeProperty("width"),d.element.style.removeProperty("--dv-tab-group-color")}const a=new Set;for(const l of e)if(a.add(l.id),l.collapsed&&l.panelIds.some(d=>{const c=n.get(d);return c&&!c.value.element.classList.contains("dv-tab--group-collapsed")}))if(this._skipNextCollapseAnimation){const d=[];for(const c of l.panelIds){const u=n.get(c);u&&(u.value.element.style.transition="none",u.value.element.classList.add("dv-tab--group-collapsed"),d.push(u.value.element))}if(d.length>0){d[0].offsetHeight;for(const c of d)c.style.removeProperty("transition")}}else{s=!0;const d=this._ctx.getDirection()==="vertical";for(const c of l.panelIds){const u=n.get(c);if(u&&!u.value.element.classList.contains("dv-tab--group-collapsed")){const h=u.value.element.getBoundingClientRect();d?u.value.element.style.height=`${h.height}px`:u.value.element.style.width=`${h.width}px`,u.value.element.offsetHeight,u.value.element.classList.add("dv-tab--group-collapsed")}}}this._skipNextCollapseAnimation=!1,this._ensureIndicator(),this._indicator&&(this._indicator.syncUnderlineElements(a),s?this._indicator.trackUnderlines():this._indicator.positionUnderlines())}},nse=class extends ct{get _tabs(){return this.host.tabItems}get _tabMap(){return this.host.tabMap}get _tabsList(){return this.host.tabsList}get _direction(){return this.host.direction}get group(){return this.host.groupPanel}get accessor(){return this.host.component}get _tabGroupManager(){return this.host.tabGroupManager}get _wrapMode(){return this._tabsList.classList.contains(DE)}get animState(){return this._animState}set animState(e){this._animState=e}get pendingCollapse(){return this._pendingCollapse}set pendingCollapse(e){this._pendingCollapse=e}set voidContainerElement(e){this._voidContainer=e}constructor(e){super(),this.host=e,this._animState=null,this._pendingMarginCleanups=new Map,this._pendingCollapse=!1,this._flipTransitionCleanup=null,this._voidContainer=null,this._extendedDropZone=null,this._pointerInsideTabsList=!1,this._wrapIndicatorEl=null,this.addDisposables({dispose:()=>{var t;(t=this._flipTransitionCleanup)===null||t===void 0||t.call(this)}})}setExtendedDropZone(e){this._extendedDropZone=e}setExternalInsertionIndex(e){this._animState&&e!==this._animState.currentInsertionIndex&&(this._animState.currentInsertionIndex=e,this.applyDragOverTransforms())}clearExternalAnimState(){this._animState&&(this.resetTabTransforms(),this._animState.sourceIndex===-1?this._animState=null:this._animState.currentInsertionIndex=null)}snapshotTabPositions(){const e=new Map;for(const t of this._tabs)e.set(t.value.panel.id,t.value.element.getBoundingClientRect());return e}getAverageTabWidth(){if(this._tabs.length===0)return 0;const e=this._direction==="vertical";let t=0;for(const n of this._tabs){const s=n.value.element.getBoundingClientRect();t+=e?s.height:s.width}return t/this._tabs.length}handlePointerDragMove(e,t){var n;const s=((n=this._tabsList.ownerDocument)!==null&&n!==void 0?n:document).elementFromPoint(e,t);if(!(s&&(this._tabsList.contains(s)||this._extendedDropZone&&this._extendedDropZone.contains(s)))){this._pointerInsideTabsList&&(this._pointerInsideTabsList=!1,this.processDragLeave(s));return}this._pointerInsideTabsList=!0,this.processDragOver(e,t)}handlePointerDragEnd(e){e&&this._animState&&this._animState.sourceIndex!==-1&&!this._animState.sourceTabGroupId&&this._animState.currentInsertionIndex!==null&&this.isPointInsideTabsList(e.clientX,e.clientY)&&this.commitPointerReorder(e.pointerEvent),this._pointerInsideTabsList=!1,this.resetDragAnimation()}isPointInsideTabsList(e,t){var n;const s=((n=this._tabsList.ownerDocument)!==null&&n!==void 0?n:document).elementFromPoint(e,t);return!!s&&this._tabsList.contains(s)}commitPointerReorder(e){const t=this._animState;if(t?.currentInsertionIndex==null)return;const n=t.currentInsertionIndex,s=t.sourceIndex,o=n-(s!==-1&&s<n?1:0);this._animState=null,this.clearWrapDropIndicator(),this.uncollapseSourceTab(t.sourceTabId),o!==s&&this.host.fireDrop({event:e,index:o,targetTabGroupId:null})}processDragOver(e,t){if(this.accessor.options.disableDnd||(this._dropStaleAnimState(),!this._animState&&!this._initAnimStateForExternalDrag()))return!1;if(this._animState.sourceIndex!==-1){var n;(n=this.group.model.dropTargetContainer)===null||n===void 0||(n=n.model)===null||n===void 0||n.clear()}return this.handleDragOver({clientX:e,clientY:t}),!0}_dropStaleAnimState(){if(!this._animState)return;const e=Ln();e?.tabGroupId&&e.groupId!==this.group.id&&this._animState.sourceTabGroupId!==e.tabGroupId&&(this._animState=null)}_initAnimStateForExternalDrag(){var e;const t=Ln();if(((e=this.accessor.options.theme)===null||e===void 0?void 0:e.tabAnimation)==="default"&&!t?.tabGroupId||!t||!(t.panelId||t.tabGroupId)||t.groupId===this.group.id)return!1;const n=this.getAverageTabWidth();return this._animState=t.tabGroupId?this._makeGroupDragAnimState(t,n):this._makeTabDragAnimState(t,n),!0}_makeGroupDragAnimState(e,t){var n;const s=this.accessor.getPanel(e.groupId),o=s?.model.getTabGroups().find(a=>a.id===e.tabGroupId),r=t*((n=o?.panelIds.length)!==null&&n!==void 0?n:1)+t;return{sourceTabId:"",sourceIndex:-1,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:e.tabGroupId,sourceGroupPanelIds:o?new Set(o.panelIds):new Set,sourceChipWidth:t,cursorOffsetFromDragLeft:r/2,sourceGapWidth:r,containerLeft:this._tabsList.getBoundingClientRect().left}}_makeTabDragAnimState(e,t){return{sourceTabId:e.panelId,sourceIndex:-1,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:null,sourceGroupPanelIds:null,sourceChipWidth:0,cursorOffsetFromDragLeft:t/2,sourceGapWidth:t,containerLeft:this._tabsList.getBoundingClientRect().left}}processDragLeave(e){var t;if(this._animState&&!(e&&this._tabsList.contains(e))){if(e&&(!((t=this._extendedDropZone)===null||t===void 0)&&t.contains(e))){this.resetTabTransforms(),this._animState.currentInsertionIndex=null;return}if(!(this._voidContainer&&e&&(e===this._voidContainer||this._voidContainer.contains(e))))if(this.resetTabTransforms(),this._animState.sourceIndex===-1){var n;(n=this.group.model.dropTargetContainer)===null||n===void 0||(n=n.model)===null||n===void 0||n.clear(),this._animState=null}else this._animState.currentInsertionIndex=null}}handleDragOver(e){var t;if(!this._animState)return;if(this._wrapMode&&!this._animState.sourceTabGroupId){var n;this.handleWrappedDragOver(e.clientX,(n=e.clientY)!==null&&n!==void 0?n:0);return}const s=e.clientX,o=this._buildFirstPanelToGroupMap();let r=this._computeDragOverInsertionIndex(s,o),a=null;if(r!==null&&this._tabGroupManager.chipRenderers.size>0){const l=this._resolveInsertionAgainstTabGroups(s,r,o);r=l.insertionIndex,a=l.targetTabGroupId}r===this._animState.currentInsertionIndex&&a===this._animState.targetTabGroupId||(this._animState.currentInsertionIndex=r,this._animState.targetTabGroupId=a,((t=this.accessor.options.theme)===null||t===void 0?void 0:t.tabAnimation)==="smooth"&&this.applyDragOverTransforms())}_buildFirstPanelToGroupMap(){const e=new Map;if(this._tabGroupManager.chipRenderers.size===0)return e;for(const t of this.group.model.getTabGroups())t.id!==this._animState.sourceTabGroupId&&t.panelIds.length>0&&e.set(t.panelIds[0],t.id);return e}_computeDragOverInsertionIndex(e,t){const n=this._animState,s=n.sourceGroupPanelIds,o=e-n.cursorOffsetFromDragLeft-n.containerLeft;let r=0,a=null;for(let u=0;u<this._tabs.length;u++){const h=this._tabs[u].value;if(h.panel.id===n.sourceTabId||s?.has(h.panel.id))continue;const p=t.get(h.panel.id);if(p){var l;const x=(l=n.chipPositions.get(p))!==null&&l!==void 0?l:0;if(r+x>o){var d;(d=a)!==null&&d!==void 0||(a=u);break}r+=x}const f=n.tabPositions.get(h.panel.id),g=f?f.width:h.element.getBoundingClientRect().width;if(r+g/2<=o)r+=g,a=u+1;else{var c;(c=a)!==null&&c!==void 0||(a=u);break}}return a}_accumulatedWidthUpTo(e,t){const n=this._animState,s=n.sourceGroupPanelIds;let o=0;for(let a=0;a<this._tabs.length;a++){const l=this._tabs[a].value;if(l.panel.id===n.sourceTabId||s?.has(l.panel.id))continue;if(a>=e)break;const d=t.get(l.panel.id);if(d){var r;o+=(r=n.chipPositions.get(d))!==null&&r!==void 0?r:0}const c=n.tabPositions.get(l.panel.id);o+=c?c.width:l.element.getBoundingClientRect().width}return o}_resolveInsertionAgainstTabGroups(e,t,n){const s=!!this._animState.sourceTabGroupId,o=this._accumulatedWidthUpTo(t,n);for(const r of this.group.model.getTabGroups()){const a=this._evaluateTabGroupForInsertion(r,e,t,o,s);if(a)return a}return{insertionIndex:t,targetTabGroupId:null}}_evaluateTabGroupForInsertion(e,t,n,s,o){const r=this._resolveGroupRange(e);if(!r)return null;const{firstIdx:a,lastIdx:l}=r,d=n>=a&&n<=l,c=!d&&n===a-1;return!d&&!c?null:o?this._resolveGroupDragTarget(n,a,l,d):this._resolveTabDragTarget(e,t,n,s,a,c)}_resolveGroupRange(e){const t=this._animState,n=t.sourceGroupPanelIds,s=e.panelIds.filter(a=>a!==t.sourceTabId&&!n?.has(a));if(s.length===0)return null;const o=this._tabs.findIndex(a=>a.value.panel.id===s[0]),r=this._tabs.findIndex(a=>a.value.panel.id===s[s.length-1]);return o===-1||r===-1?null:{firstIdx:o,lastIdx:r}}_resolveGroupDragTarget(e,t,n,s){return s?{insertionIndex:e<(t+n+1)/2?t:n+1,targetTabGroupId:null}:{insertionIndex:e,targetTabGroupId:null}}_resolveTabDragTarget(e,t,n,s,o,r){var a;const l=this._animState,d=(a=l.chipPositions.get(e.id))!==null&&a!==void 0?a:0;if(r)return this._onlySourceBetween(n,o)?t>=(e.collapsed?l.containerLeft+s+d/2:l.containerLeft+s+d)?{insertionIndex:o,targetTabGroupId:e.id}:{insertionIndex:n,targetTabGroupId:null}:null;const c=l.containerLeft+s+d;return n===o?{insertionIndex:n,targetTabGroupId:t>=c?e.id:null}:{insertionIndex:n,targetTabGroupId:e.id}}_onlySourceBetween(e,t){const n=this._animState;for(let o=e;o<t;o++){var s;const r=this._tabs[o].value.panel.id;if(r!==n.sourceTabId&&!(!((s=n.sourceGroupPanelIds)===null||s===void 0)&&s.has(r)))return!1}return!0}handleWrappedDragOver(e,t){if(!this._animState)return;const n=this.computeWrappedInsertionIndex(e,t);n===this._animState.currentInsertionIndex&&this._animState.targetTabGroupId===null||(this._animState.currentInsertionIndex=n,this._animState.targetTabGroupId=null,this.updateWrapDropIndicator(n))}computeWrappedInsertionIndex(e,t){var n;const s=this._direction==="vertical",o=this._wrappedDragEntries();if(o.length===0)return this._tabs.length;const r=s?e:t,a=s?t:e,l=f=>s?f.left:f.top,d=f=>s?f.right:f.bottom,c=f=>s?f.top:f.left,u=f=>s?f.height:f.width,h=this._bucketWrappedLines(o,l,d),p=[...((n=h.find(f=>r>=f.start&&r<=f.end))!==null&&n!==void 0?n:this._nearestWrappedLine(h,r)).items].sort((f,g)=>c(f.rect)-c(g.rect));for(const f of p)if(a<c(f.rect)+u(f.rect)/2)return f.index;return p[p.length-1].index+1}_wrappedDragEntries(){var e,t;const n=(e=this._animState)===null||e===void 0?void 0:e.sourceTabId,s=(t=this._animState)===null||t===void 0?void 0:t.sourceGroupPanelIds,o=[];for(let r=0;r<this._tabs.length;r++){const a=this._tabs[r].value;a.panel.id!==n&&(s?.has(a.panel.id)||o.push({index:r,rect:a.element.getBoundingClientRect()}))}return o}_bucketWrappedLines(e,t,n){const s=[];for(const o of e){const r=t(o.rect),a=s.find(l=>Math.abs(l.start-r)<=2);a?(a.items.push(o),a.end=Math.max(a.end,n(o.rect))):s.push({start:r,end:n(o.rect),items:[o]})}return s.sort((o,r)=>o.start-r.start),s}_nearestWrappedLine(e,t){const n=s=>t<s.start?s.start-t:t-s.end;return e.reduce((s,o)=>n(o)<n(s)?o:s,e[0])}updateWrapDropIndicator(e){var t;this.clearWrapDropIndicator();const n=this._tabs.length;if(n===0)return;const s=(t=this._animState)===null||t===void 0?void 0:t.sourceTabId;if(e<n){const o=this._tabs[e].value.element;if(this._tabs[e].value.panel.id===s)return;o.classList.add("dv-tab--reorder-before"),this._wrapIndicatorEl=o}else{const o=this._tabs[n-1].value.element;o.classList.add("dv-tab--reorder-after"),this._wrapIndicatorEl=o}}clearWrapDropIndicator(){var e;(e=this._wrapIndicatorEl)===null||e===void 0||e.classList.remove("dv-tab--reorder-before","dv-tab--reorder-after"),this._wrapIndicatorEl=null}_removeClassInstantlyBatch(e,t){const n=[];for(const s of e)s.classList.contains(t)&&(s.style.transition="none",Ze(s,t,!1),n.push(s));if(n.length>0){n[0].getBoundingClientRect();for(const s of n)s.style.removeProperty("transition")}}uncollapseSourceTab(e){const t=this._tabMap.get(e);t&&this._removeClassInstantlyBatch([t.value.element],"dv-tab--dragging")}applyDragOverTransforms(e=!1){var t;if(this._wrapMode)return;if(((t=this._animState)===null||t===void 0?void 0:t.currentInsertionIndex)==null){this.resetTabTransforms();return}if(this._pendingCollapse)return;const n=this._animState.currentInsertionIndex,s=this._computeGapWidth(),o=this._computeChipToShift(n);this._applyGapMargins(n,s,o,e)}_computeGapWidth(){const e=this._animState;if(e.sourceTabGroupId&&e.sourceGroupPanelIds)return e.sourceGapWidth;const t=e.tabPositions.get(e.sourceTabId);return t?t.width:this.getAverageTabWidth()}_computeChipToShift(e){if(this._tabGroupManager.chipRenderers.size===0)return null;for(const t of this.group.model.getTabGroups()){const n=this._chipToShiftForGroup(t,e);if(n!==void 0)return n}return null}_chipToShiftForGroup(e,t){const n=this._animState;if(e.id===n.sourceTabGroupId||e.panelIds.includes(n.sourceTabId))return;const s=e.panelIds.filter(r=>{var a;return r!==n.sourceTabId&&!(!((a=n.sourceGroupPanelIds)===null||a===void 0)&&a.has(r))});if(s.length===0)return;const o=this._tabs.findIndex(r=>r.value.panel.id===s[0]);if((!n.targetTabGroupId||n.targetTabGroupId===e.id&&e.collapsed)&&!(o<t)){if(this._onlySourceBetween(t,o)){const r=this._tabGroupManager.chipRenderers.get(e.id);if(r)return r.chip.element}return null}}_applyGapMargins(e,t,n,s){const o=this._animState,r=o.sourceGroupPanelIds;let a=!1;for(const[l,d]of this._tabGroupManager.chipRenderers)l!==o.sourceTabGroupId&&this._clearMargin(d.chip.element,s);n&&(this._setMargin(n,`${t}px`,s),a=!0);for(let l=0;l<this._tabs.length;l++){const d=this._tabs[l].value;d.panel.id!==o.sourceTabId&&(r?.has(d.panel.id)||(!a&&l>=e?(this._setMargin(d.element,`${t}px`,s),a=!0):this._clearMargin(d.element,s)))}this._tabGroupManager.trackUnderlines()}_shiftingClass(e){return e.classList.contains("dv-tab-group-chip")?"dv-tab-group-chip--shifting":"dv-tab--shifting"}_setMargin(e,t,n){n?(e.style.transition="none",e.style.marginLeft=t,e.getBoundingClientRect(),e.style.removeProperty("transition")):e.style.marginLeft=t,Ze(e,this._shiftingClass(e),!0)}_clearMargin(e,t){const n=this._shiftingClass(e),s=this._pendingMarginCleanups.get(e);if(s&&s(),t||!e.style.marginLeft)e.style.removeProperty("margin-left"),Ze(e,n,!1);else{e.style.marginLeft="0px",Ze(e,n,!0);const o=()=>{e.style.removeProperty("margin-left"),Ze(e,n,!1),e.removeEventListener("transitionend",o),clearTimeout(r),this._pendingMarginCleanups.delete(e)},r=setTimeout(o,300);this._pendingMarginCleanups.set(e,o),e.addEventListener("transitionend",o)}}resetTabTransforms(){this.clearWrapDropIndicator();for(const[,e]of this._pendingMarginCleanups)e();this._pendingMarginCleanups.clear();for(const e of this._tabs)e.value.element.style.removeProperty("margin-left"),e.value.element.style.removeProperty("margin-right"),e.value.element.style.removeProperty("margin-top"),e.value.element.style.removeProperty("margin-bottom"),e.value.element.style.removeProperty("transform"),Ze(e.value.element,"dv-tab--shifting",!1);for(const[,e]of this._tabGroupManager.chipRenderers)e.chip.element.style.removeProperty("margin-left"),Ze(e.chip.element,"dv-tab-group-chip--shifting",!1);this._tabGroupManager.positionUnderlines()}commitGroupMove(e,t){const n=Ln();if(this._tabGroupManager.disposeChipDrag(e),this.group.model.getTabGroups().some(r=>r.id===e)){var s;if(((s=this.accessor.options.theme)===null||s===void 0?void 0:s.tabAnimation)==="smooth"){this._clearGroupDragClasses(e);const r=this.snapshotTabPositions();this.resetTabTransforms(),this.group.model.moveTabGroup(e,t),this.runFlipAnimation(r,"",!1)}else this._tabGroupManager.skipNextCollapseAnimation=!0,this.group.model.moveTabGroup(e,t)}else if(n){var o;this.resetTabTransforms(),this.accessor.moveGroupOrPanel({from:{groupId:n.groupId,tabGroupId:(o=n.tabGroupId)!==null&&o!==void 0?o:e},to:{group:this.group,position:"center",index:t}})}}_clearGroupDragClasses(e){const t=this._tabGroupManager.chipRenderers.get(e);t&&this._removeClassInstantlyBatch([t.chip.element],"dv-tab-group-chip--dragging"),this._removeClassInstantlyBatch(this._tabs.map(s=>s.value.element),"dv-tab--dragging");const n=this._tabGroupManager.groupUnderlines.get(e);n&&n.style.removeProperty("display"),this._tabGroupManager.skipNextCollapseAnimation=!0}resetDragAnimation(){if(this._pendingCollapse=!1,this._animState){this.resetTabTransforms(),this._animState.sourceTabGroupId?this._clearGroupDragClasses(this._animState.sourceTabGroupId):this._removeClassInstantlyBatch(this._tabs.map(e=>e.value.element),"dv-tab--dragging"),this._animState=null;for(const[,e]of this._tabGroupManager.groupUnderlines)e.style.removeProperty("display")}}runFlipAnimation(e,t,n=!1,s){if(this._wrapMode)return;let o=!1;for(let r=0;r<this._tabs.length;r++)this._applyFlipTransform(this._tabs[r],r,t,n,e,s)&&(o=!0);o&&this._scheduleFlipReset()}_applyFlipTransform(e,t,n,s,o,r){const a=this._direction==="vertical",l=e.value.panel.id;if(l===n){if(!s)return!1;const h=e.value.element.getBoundingClientRect();return e.value.element.style.transform=a?`translateY(${h.height}px)`:`translateX(${h.width}px)`,Ze(e.value.element,"dv-tab--shifting",!0),!0}if(r!==void 0&&(t<r.from||t>r.to))return!1;const d=o.get(l);if(!d)return!1;const c=e.value.element.getBoundingClientRect(),u=a?d.top-c.top:d.left-c.left;return Math.abs(u)<1?!1:(e.value.element.style.transform=a?`translateY(${u}px)`:`translateX(${u}px)`,Ze(e.value.element,"dv-tab--shifting",!0),!0)}_scheduleFlipReset(){requestAnimationFrame(()=>{var e;for(const s of this._tabs)s.value.element.style.transform&&(s.value.element.style.transform="");this._tabGroupManager.trackUnderlines(),(e=this._flipTransitionCleanup)===null||e===void 0||e.call(this);const t=s=>{if(s.propertyName==="transform"){n();for(const o of this._tabs)Ze(o.value.element,"dv-tab--shifting",!1);this._tabGroupManager.positionUnderlines()}},n=()=>{this._tabsList.removeEventListener("transitionend",t),this._flipTransitionCleanup=null};this._flipTransitionCleanup=n,this._tabsList.addEventListener("transitionend",t)})}},sse=class extends ct{get _animState(){return this._reorder.animState}set _animState(e){this._reorder.animState=e}get _pendingCollapse(){return this._reorder.pendingCollapse}set _pendingCollapse(e){this._reorder.pendingCollapse=e}get tabItems(){return this._tabs}get tabMap(){return this._tabMap}get tabsList(){return this._tabsList}get groupPanel(){return this.group}get component(){return this.accessor}get tabGroupManager(){return this._tabGroupManager}fireDrop(e){this._onDrop.fire(e)}setOverflowExclude(e){this._overflowExclude=e,this.refreshOverflow()}setForcedOverflow(e){this._forcedOverflow=e,this.refreshOverflow()}refreshOverflow(){this._showTabsOverflowControl&&this.toggleDropdown({reset:!1}),this._applyPinnedSticky()}setPinnedSticky(e){this._pinnedSticky!==e&&(this._pinnedSticky=e,this._applyPinnedSticky())}_applyPinnedSticky(){const e=this._pinnedSticky?this._tabs.filter(n=>this._overflowExclude(n.value.panel.id)):[];if(e.length===0&&!this._hasPinnedStickyStyling)return;for(const n of this._tabs){const s=n.value.element;s.classList.contains("dv-tab--pinned-sticky")&&(s.classList.remove("dv-tab--pinned-sticky"),s.style.removeProperty("--dv-pinned-sticky-left"))}if(e.length===0){this._hasPinnedStickyStyling=!1;return}const t=e.map(n=>n.value.element.offsetLeft);e.forEach((n,s)=>{const o=n.value.element;o.classList.add("dv-tab--pinned-sticky"),o.style.setProperty("--dv-pinned-sticky-left",`${t[s]}px`)}),this._hasPinnedStickyStyling=!0}get showTabsOverflowControl(){return this._showTabsOverflowControl}set showTabsOverflowControl(e){if(this._showTabsOverflowControl!=e)if(this._showTabsOverflowControl=e,e){const t=new $te(this._tabsList);this._observerDisposable.value=new ct(t,t.onDidChange(n=>{const s=n.hasScrollX||n.hasScrollY;this.toggleDropdown({reset:!s}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}),ot(this._tabsList,"scroll",()=>{this.toggleDropdown({reset:!1}),this._applyPinnedSticky(),this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}))}else this._observerDisposable.value=rn.NONE}get element(){return this._element}get tabsListElement(){return this._tabsList}set voidContainer(e){var t;(t=this._voidContainerListeners)===null||t===void 0||t.dispose(),this._voidContainerListeners=null,this._reorder.voidContainerElement=e,e&&(this._voidContainerListeners=new ct(ot(e,"dragover",n=>{this._animState&&n.preventDefault()}),ot(e,"drop",n=>{var s;!((s=this._animState)===null||s===void 0)&&s.sourceTabGroupId&&this._animState.currentInsertionIndex!==null&&(n.preventDefault(),n.stopPropagation(),this.handleVoidDrop())})))}handleVoidDrop(){var e,t;if(!(!((e=this._animState)===null||e===void 0)&&e.sourceTabGroupId))return!1;const n=this._animState.sourceTabGroupId,s=(t=this._animState.currentInsertionIndex)!==null&&t!==void 0?t:this._tabs.length;return this._animState=null,this._commitGroupMove(n,s),!0}get panels(){return this._tabs.map(e=>e.value.panel.id)}get size(){return this._tabs.length}get tabs(){return this._tabs.map(e=>e.value)}get direction(){return this._direction}set direction(e){if(this._direction!==e){this._direction=e,this._tabsList.setAttribute("aria-orientation",e==="vertical"?"vertical":"horizontal"),this._scrollbar&&(this._scrollbar.orientation=e),bi(this._tabsList,"dv-horizontal","dv-vertical"),e==="vertical"?wi(this._tabsList,"dv-tabs-container-vertical","dv-vertical"):(bi(this._tabsList,"dv-tabs-container-vertical"),wi(this._tabsList,"dv-horizontal"));for(const t of this._tabs)t.value.setDirection(e);this._tabGroupManager.updateDirection()}}constructor(e,t,n){super(),this.group=e,this.accessor=t,this._observerDisposable=new Fn,this._pointerActivation=new Fn,this._scrollbar=null,this._tabs=[],this._tabMap=new Map,this.selectedIndex=-1,this._showTabsOverflowControl=!1,this._overflowExclude=()=>!1,this._forcedOverflow=()=>!1,this._pinnedSticky=!1,this._hasPinnedStickyStyling=!1,this._direction="horizontal",this._voidContainerListeners=null,this._onTabDragStart=new ve,this.onTabDragStart=this._onTabDragStart.event,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onOverflowTabsChange=new ve,this.onOverflowTabsChange=this._onOverflowTabsChange.event,this._tabsList=document.createElement("div"),this._tabsList.className="dv-tabs-container",this._tabsList.setAttribute("role","tablist"),this._tabsList.setAttribute("aria-orientation",this._direction==="vertical"?"vertical":"horizontal"),this.showTabsOverflowControl=n.showTabsOverflowControl,t.options.scrollbars==="native"?this._element=this._tabsList:(this._scrollbar=new NE(this._tabsList),this._scrollbar.orientation=this.direction,this._element=this._scrollbar.element,this.addDisposables(this._scrollbar)),this._tabGroupManager=new tse({group:this.group,accessor:this.accessor,tabsList:this._tabsList,getTabs:()=>this._tabs,getTabMap:()=>this._tabMap,getDirection:()=>this._direction},{onChipContextMenu:(s,o)=>{var r;(r=this.accessor.contextMenuService)===null||r===void 0||r.showForChip(s,this.group,o)},onChipDragStart:(s,o,r)=>{this._handleChipDragStart(s,o,r)},onChipDragEnd:()=>{this._reorder.resetDragAnimation()},onChipDrop:(s,o)=>{this._handleChipDrop(s,o)}}),this._reorder=new nse(this),this.addDisposables(this._onOverflowTabsChange,this._observerDisposable,this._pointerActivation,this._onWillShowOverlay,this._onDrop,this._onTabDragStart,this._reorder,Gu.getInstance().onDragEnd(s=>{this._reorder.handlePointerDragEnd(s)}),Gu.getInstance().onDragMove(s=>{this._reorder.handlePointerDragMove(s.clientX,s.clientY)}),ot(this.element,"pointerdown",s=>{s.defaultPrevented||s.button===0&&this.accessor.doSetGroupActive(this.group)}),ot(this._tabsList,"wheel",s=>{const o=this._direction==="vertical",r=o?s.deltaY||s.deltaX:s.deltaX||s.deltaY;if(r===0)return;const a=o?this._tabsList.scrollHeight-this._tabsList.clientHeight:this._tabsList.scrollWidth-this._tabsList.clientWidth;if(a<=0)return;const l=o?this._tabsList.scrollTop:this._tabsList.scrollLeft;r<0&&l<=0||r>0&&l>=a||(s.preventDefault(),s.stopPropagation(),o?this._tabsList.scrollTop=l+r:this._tabsList.scrollLeft=l+r)},{passive:!1}),ot(this._tabsList,"keydown",s=>{this._onKeyDown(s)}),ot(this._tabsList,"dragover",s=>{this._reorder.processDragOver(s.clientX,s.clientY)&&s.preventDefault()},!0),ot(this._tabsList,"dragleave",s=>{this._reorder.processDragLeave(s.relatedTarget)},!0),ot(this._tabsList,"dragend",()=>{this._reorder.resetDragAnimation()}),ot(this._tabsList,"drop",s=>{var o,r,a;if(((o=this._animState)===null||o===void 0?void 0:o.currentInsertionIndex)==null||((r=this.accessor.options.theme)===null||r===void 0?void 0:r.tabAnimation)!=="smooth"&&!this._animState.sourceTabGroupId)return;s.stopPropagation(),s.preventDefault(),(a=this.group.model.dropTargetContainer)===null||a===void 0||(a=a.model)===null||a===void 0||a.clear();const l=this._animState;if(this._animState=null,this._pendingCollapse=!1,l.sourceTabGroupId){this._commitGroupMove(l.sourceTabGroupId,l.currentInsertionIndex);return}const d=l.currentInsertionIndex,c=l.sourceIndex,u=d-(c!==-1&&c<d?1:0),h=this.group.model.getTabGroupForPanel(l.sourceTabId);if(u===c&&!l.targetTabGroupId&&!h){this._reorder.uncollapseSourceTab(l.sourceTabId),this.resetTabTransforms();return}this._reorder.uncollapseSourceTab(l.sourceTabId);const p=this.snapshotTabPositions();this.resetTabTransforms(),this._onDrop.fire({event:s,index:u,targetTabGroupId:l.targetTabGroupId}),this.runFlipAnimation(p,l.sourceTabId,l.sourceIndex===-1,{from:Math.min(c,u),to:Math.max(c,u)})},!0),rn.from(()=>{var s;(s=this._voidContainerListeners)===null||s===void 0||s.dispose(),this._reorder.resetDragAnimation(),this._tabGroupManager.disposeAll();for(const{value:o,disposable:r}of this._tabs)r.dispose(),o.dispose();this._tabs=[],this._tabMap.clear()}))}indexOf(e){return this._tabs.findIndex(t=>t.value.panel.id===e)}getTabId(e){var t;return(t=this._tabMap.get(e))===null||t===void 0?void 0:t.value.element.id}getPanelForTab(e){for(const{value:t}of this._tabs)if(t.element===e||t.element.contains(e))return t.panel}isActive(e){return this.selectedIndex>-1&&this._tabs[this.selectedIndex].value===e}_onKeyDown(e){const t=this._tabs.findIndex(a=>a.value.element===e.target);if(t===-1)return;const n=this._direction==="vertical",s=n?"ArrowDown":"ArrowRight",o=n?"ArrowUp":"ArrowLeft",r=this._tabs.length-1;switch(e.key){case s:e.preventDefault(),this._focusTab(Math.min(t+1,r));break;case o:e.preventDefault(),this._focusTab(Math.max(t-1,0));break;case"Home":e.preventDefault(),this._focusTab(0);break;case"End":e.preventDefault(),this._focusTab(r);break;case"Enter":case" ":e.preventDefault(),this.accessor.withOrigin("user",()=>this._tabs[t].value.panel.api.setActive());break;case"Delete":case"Backspace":e.preventDefault(),this._closeTab(t);break}}_closeTab(e){var t,n,s,o,r;const a=(t=this._tabs[e])===null||t===void 0?void 0:t.value;if(!a)return;const l=(n=(s=(o=this._tabs[e+1])===null||o===void 0?void 0:o.value)!==null&&s!==void 0?s:(r=this._tabs[e-1])===null||r===void 0?void 0:r.value)===null||n===void 0?void 0:n.panel.id;if(a.panel.api.close(),l!==void 0){const d=this._tabs.findIndex(c=>c.value.panel.id===l);d>-1&&this._focusTab(d)}}_focusTab(e){for(let t=0;t<this._tabs.length;t++)this._tabs[t].value.element.tabIndex=t===e?0:-1;this._tabs[e].value.element.focus()}focusActiveTab(){var e;if(this._tabs.length===0)return;const t=(e=this.group.activePanel)===null||e===void 0?void 0:e.id,n=t?this._tabs.findIndex(s=>s.value.panel.id===t):-1;this._focusTab(n>-1?n:0)}setActivePanel(e){const t=this._direction==="vertical";for(const n of this._tabs){const s=e.id===n.value.panel.id;n.value.setActive(s),s&&this._scrollTabIntoView(n.value.element,t)}this._tabGroupManager.groupUnderlines.size>0&&this._tabGroupManager.positionUnderlines()}_scrollTabIntoView(e,t){const n=e.parentElement;if(!n)return;const s=t?e.offsetTop:e.offsetLeft,o=t?e.offsetHeight:e.offsetWidth,r=t?n.scrollTop:n.scrollLeft,a=t?n.clientHeight:n.clientWidth;(s<r||s+o>r+a)&&(t?n.scrollTop=s:n.scrollLeft=s)}_activateOnPointerDown(e){if(!ci(this.accessor.options).html5){this.group.model.openPanel(e);return}const t=requestAnimationFrame(()=>{this._tabMap.has(e.id)&&this.group.model.openPanel(e)});this._pointerActivation.value={dispose:()=>cancelAnimationFrame(t)}}openPanel(e,t=this._tabs.length){if(this._tabMap.has(e.id))return;const n=new $ne(e,this.accessor,this.group);n.setContent(e.view.tab),this._direction!=="horizontal"&&n.setDirection(this._direction);const s={value:n,disposable:new ct(n.onDragStart(o=>{var r;if(this._onTabDragStart.fire({nativeEvent:o,panel:e}),((r=this.accessor.options.theme)===null||r===void 0?void 0:r.tabAnimation)==="smooth"){const a=n.element.getBoundingClientRect().width,l=this._tabs.findIndex(d=>d.value===n);this._animState={sourceTabId:e.id,sourceIndex:l,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:null,sourceGroupPanelIds:null,sourceChipWidth:0,cursorOffsetFromDragLeft:a/2,sourceGapWidth:a,containerLeft:this._tabsList.getBoundingClientRect().left},this._pendingCollapse=!0,requestAnimationFrame(()=>{var d,c;this._pendingCollapse=!1,this._animState&&(this._tabsList.classList.contains("dv-tabs-container--wrap")||(n.element.style.transition="none",Ze(n.element,"dv-tab--dragging",!0),n.element.offsetHeight),(c=(d=this._animState).currentInsertionIndex)!==null&&c!==void 0||(d.currentInsertionIndex=l),this.applyDragOverTransforms(!0),n.element.style.removeProperty("transition"))})}}),n.onTabClick(o=>{o.defaultPrevented||this.group.api.location.type==="edge"&&(this.group.activePanel===e?this.group.api.isCollapsed()?this.group.api.expand():this.group.api.collapse():(this.group.model.openPanel(e),this.group.api.isCollapsed()&&this.group.api.expand()))}),n.onPointerDown(o=>{if(o.defaultPrevented)return;const r=!this.accessor.options.disableFloatingGroups,a=this.group.api.location.type==="floating"&&this.size===1;if(r&&!a&&o.shiftKey){o.preventDefault();const l=this.accessor.getGroupPanel(n.panel.id),{top:d,left:c}=n.element.getBoundingClientRect(),{top:u,left:h}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(l,{x:c-h,y:d-u,inDragMode:!0});return}o.button===0&&this.group.api.location.type!=="edge"&&this.group.activePanel!==e&&this._activateOnPointerDown(e)}),n.onDrop(o=>{const r=this._animState;this._animState=null,this._pendingCollapse=!1;const a=this._tabs.findIndex(h=>h.value===n);if(r){var l;const h=o.position==="right"?a+1:a;if(r.sourceTabGroupId){var d;this._commitGroupMove(r.sourceTabGroupId,(d=r.currentInsertionIndex)!==null&&d!==void 0?d:h);return}this._reorder.uncollapseSourceTab(r.sourceTabId);const p=this.snapshotTabPositions();this.resetTabTransforms(),this._onDrop.fire({event:o.nativeEvent,index:h,targetTabGroupId:r.targetTabGroupId}),((l=this.accessor.options.theme)===null||l===void 0?void 0:l.tabAnimation)==="smooth"&&this.runFlipAnimation(p,r.sourceTabId,r.sourceIndex===-1,r.sourceIndex===-1?void 0:{from:Math.min(r.sourceIndex,h),to:Math.max(r.sourceIndex,h)})}else{var c,u;const h=this._direction==="vertical"?"bottom":"right",p=o.position===h?a+1:a,f=Ln(),g=f?this._tabs.findIndex(y=>y.value.panel.id===f.panelId):-1,x=p-(g!==-1&&g<p?1:0),v=(c=(u=this.group.model.getTabGroupForPanel(n.panel.id))===null||u===void 0?void 0:u.id)!==null&&c!==void 0?c:null;this._onDrop.fire({event:o.nativeEvent,index:x,targetTabGroupId:v})}}),n.onWillShowOverlay(o=>{this._onWillShowOverlay.fire(new td(o,{kind:"tab",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:Ln}))}))};this.addTab(s,t),this._tabGroupManager.positionAllChips(),this._animState&&(this._animState.tabPositions=this.snapshotTabPositions(),this._animState.chipPositions=this._tabGroupManager.snapshotChipWidths(),this.applyDragOverTransforms())}delete(e){var t;((t=this._animState)===null||t===void 0?void 0:t.sourceTabId)===e&&(this.resetTabTransforms(),this._animState=null),this._tabGroupManager.cleanupTransition(e);const n=this.indexOf(e),s=this._tabs.splice(n,1)[0];if(this._tabMap.delete(e),s){const{value:o,disposable:r}=s;r.dispose(),o.dispose(),o.element.remove()}this._animState&&(this._animState.tabPositions=this.snapshotTabPositions(),this._animState.chipPositions=this._tabGroupManager.snapshotChipWidths(),this.applyDragOverTransforms())}addTab(e,t=this._tabs.length){if(t<0||t>this._tabs.length)throw new Error("invalid location");const n=t<this._tabs.length?this._tabs[t].value.element:null;this._tabsList.insertBefore(e.value.element,n),this._tabs=[...this._tabs.slice(0,t),e,...this._tabs.slice(t)],this._tabMap.set(e.value.panel.id,e),this.selectedIndex<0&&(this.selectedIndex=t)}toggleDropdown(e){const t=this._tabs.some(a=>!this._overflowExclude(a.value.panel.id)&&this._forcedOverflow(a.value.panel.id));if(e.reset&&!t){this._onOverflowTabsChange.fire({tabs:[],tabGroups:[],pinnedTabs:[],reset:!0});return}const n=this._tabs.filter(a=>!this._overflowExclude(a.value.panel.id)&&(this._forcedOverflow(a.value.panel.id)||!e.reset&&!sf(a.value.element,this._tabsList))).map(a=>a.value.panel.id),s=e.reset?[]:this._tabs.filter(a=>this._overflowExclude(a.value.panel.id)&&a.value.element.getBoundingClientRect().width>0&&!sf(a.value.element,this._tabsList)).map(a=>a.value.panel.id),o=new Set(n),r=[];for(const a of this.group.model.getTabGroups()){const l=this._tabGroupManager.chipRenderers.get(a.id),d=l&&!sf(l.chip.element,this._tabsList),c=a.panelIds.length>0&&a.panelIds.every(u=>o.has(u));if((d||c)&&(r.push(a.id),a.collapsed))for(const u of a.panelIds)o.has(u)||(o.add(u),n.push(u))}this._onOverflowTabsChange.fire({tabs:n,tabGroups:r,pinnedTabs:s,reset:!1})}updateDragAndDropState(){for(const e of this._tabs)e.value.updateDragAndDropState();this._tabGroupManager.updateDragAndDropState()}updateTabGroups(){this._tabGroupManager.update()}refreshTabGroupAccent(){this._tabGroupManager.refreshAccents()}_handleChipDragStart(e,t,n){var s;const o=e.panelIds[0],r=o?this._tabs.findIndex(c=>c.value.panel.id===o):-1,a=t.element.getBoundingClientRect();let l=a.width;for(const c of e.panelIds){const u=this._tabMap.get(c);u&&(l+=u.value.element.getBoundingClientRect().width)}if(this._animState={sourceTabId:"",sourceIndex:r,tabPositions:this.snapshotTabPositions(),chipPositions:this._tabGroupManager.snapshotChipWidths(),currentInsertionIndex:null,targetTabGroupId:null,sourceTabGroupId:e.id,sourceGroupPanelIds:new Set(e.panelIds),sourceChipWidth:a.width,cursorOffsetFromDragLeft:n.clientX-a.left,sourceGapWidth:l,containerLeft:this._tabsList.getBoundingClientRect().left},((s=this.accessor.options.theme)===null||s===void 0?void 0:s.tabAnimation)!=="smooth")return;const d=new Set(e.panelIds);this._pendingCollapse=!0,requestAnimationFrame(()=>{var c,u;if(this._pendingCollapse=!1,!this._animState)return;for(const f of this._tabs)d.has(f.value.panel.id)&&(f.value.element.style.transition="none",Ze(f.value.element,"dv-tab--dragging",!0));const h=this._tabGroupManager.chipRenderers.get(e.id);h&&(h.chip.element.style.transition="none",Ze(h.chip.element,"dv-tab-group-chip--dragging",!0)),this._tabsList.offsetHeight;const p=this._tabGroupManager.groupUnderlines.get(e.id);p&&(p.style.display="none"),(u=(c=this._animState).currentInsertionIndex)!==null&&u!==void 0||(c.currentInsertionIndex=r),this.applyDragOverTransforms(!0);for(const f of this._tabs)d.has(f.value.panel.id)&&f.value.element.style.removeProperty("transition");h&&h.chip.element.style.removeProperty("transition")})}_handleChipDrop(e,t){const n=e.panelIds[0];if(!n)return;const s=this._tabs.findIndex(l=>l.value.panel.id===n);if(s===-1)return;const o=Ln(),r=o?.groupId===this.group.id&&o?.panelId?this._tabs.findIndex(l=>l.value.panel.id===o.panelId):-1,a=s-(r!==-1&&r<s?1:0);this._onDrop.fire({event:t.nativeEvent,index:a,targetTabGroupId:null})}setExtendedDropZone(e){this._reorder.setExtendedDropZone(e)}setExternalInsertionIndex(e){this._reorder.setExternalInsertionIndex(e)}clearExternalAnimState(){this._reorder.clearExternalAnimState()}snapshotTabPositions(){return this._reorder.snapshotTabPositions()}handleDragOver(e){this._reorder.handleDragOver(e)}applyDragOverTransforms(e=!1){this._reorder.applyDragOverTransforms(e)}resetTabTransforms(){this._reorder.resetTabTransforms()}_commitGroupMove(e,t){this._reorder.commitGroupMove(e,t)}runFlipAnimation(e,t,n=!1,s){this._reorder.runFlipAnimation(e,t,n,s)}};function ise(){const e=document.createElement("div");e.className="dv-tabs-overflow-dropdown-default";const t=document.createElement("span");t.textContent="";const n=jE();return e.appendChild(n),e.appendChild(t),{element:e,update:s=>{t.textContent=`${s.tabs}`}}}var ose=class extends ct{get onTabDragStart(){return this.tabs.onTabDragStart}get panels(){return this.tabs.panels}get size(){return this.tabs.size}get hidden(){return this._hidden}set hidden(e){this._hidden=e,this.element.style.display=e?"none":""}get direction(){return this._direction}set direction(e){this._direction=e,e==="vertical"?(wi(this._element,"dv-groupview-header-vertical"),wi(this.rightActionsContainer,"dv-right-actions-container-vertical"),this.tabs.direction=e):(bi(this._element,"dv-groupview-header-vertical"),bi(this.rightActionsContainer,"dv-right-actions-container-vertical"),this.tabs.direction=e)}get element(){return this._element}get tabsListElement(){return this.tabs.tabsListElement}constructor(e,t){super(),this.accessor=e,this.group=t,this._hidden=!1,this._direction="horizontal",this._dropIndexResolver=(n,s)=>s,this._pinnedRow=void 0,this.dropdownPart=null,this._overflowTabs=[],this._overflowTabGroups=[],this._overflowPinnedTabs=[],this._dropdownDisposable=new Fn,this._onDrop=new ve,this.onDrop=this._onDrop.event,this._onGroupDragStart=new ve,this.onGroupDragStart=this._onGroupDragStart.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._element=document.createElement("div"),this._element.className="dv-tabs-and-actions-container",Ze(this._element,"dv-full-width-single-tab",this.accessor.options.singleTabMode==="fullwidth"),this.rightActionsContainer=document.createElement("div"),this.rightActionsContainer.className="dv-right-actions-container",this.leftActionsContainer=document.createElement("div"),this.leftActionsContainer.className="dv-left-actions-container",this.preActionsContainer=document.createElement("div"),this.preActionsContainer.className="dv-pre-actions-container",this.tabs=new sse(t,e,{showTabsOverflowControl:!e.options.disableTabsOverflowList}),this.voidContainer=new Wne(this.accessor,this.group),this.tabs.voidContainer=this.voidContainer.element,this._element.appendChild(this.preActionsContainer),this._element.appendChild(this.tabs.element),this._element.appendChild(this.leftActionsContainer),this._element.appendChild(this.voidContainer.element),this._element.appendChild(this.rightActionsContainer),this.tabs.setExtendedDropZone(this._element),this.addDisposables(this.tabs.onDrop(n=>this._onDrop.fire(n)),this.tabs.onWillShowOverlay(n=>this._onWillShowOverlay.fire(n)),e.onDidOptionsChange(()=>{this.tabs.showTabsOverflowControl=!e.options.disableTabsOverflowList}),this.tabs.onOverflowTabsChange(n=>{this.toggleDropdown(n)}),this.tabs,this._onWillShowOverlay,this._onDrop,this._onGroupDragStart,this.voidContainer,this.voidContainer.onDragStart(n=>{this._onGroupDragStart.fire({nativeEvent:n,group:this.group})}),this.voidContainer.onDrop(n=>{this.tabs.handleVoidDrop()||this._onDrop.fire({event:n.nativeEvent,index:this.tabs.size})}),this.voidContainer.onWillShowOverlay(n=>{this._onWillShowOverlay.fire(new td(n,{kind:"header_space",panel:this.group.activePanel,api:this.accessor.api,group:this.group,getData:Ln}))}),ot(this.leftActionsContainer,"dragleave",n=>{const s=n.relatedTarget;!this.leftActionsContainer.contains(s)&&!this._element.contains(s)&&this.tabs.clearExternalAnimState()}),ot(this.voidContainer.element,"dragleave",n=>{const s=n.relatedTarget;this.voidContainer.element.contains(s)||(this._element.contains(s)?this.tabs.setExternalInsertionIndex(null):this.tabs.clearExternalAnimState())}),ot(this.voidContainer.element,"pointerdown",n=>{if(!n.defaultPrevented&&!this.accessor.options.disableFloatingGroups&&n.shiftKey&&this.group.api.location.type!=="floating"&&this.group.api.location.type!=="edge"){n.preventDefault();const{top:s,left:o}=this.element.getBoundingClientRect(),{top:r,left:a}=this.accessor.element.getBoundingClientRect();this.accessor.addFloatingGroup(this.group,{x:o-a+20,y:s-r+20,inDragMode:!0})}}))}show(){this.hidden||(this.element.style.display="")}hide(){this._element.style.display="none"}setRightActionsElement(e){this.rightActions!==e&&(this.rightActions&&(this.rightActions.remove(),this.rightActions=void 0),e&&(this.rightActionsContainer.appendChild(e),this.rightActions=e))}setLeftActionsElement(e){this.leftActions!==e&&(this.leftActions&&(this.leftActions.remove(),this.leftActions=void 0),e&&(this.leftActionsContainer.appendChild(e),this.leftActions=e))}setPrefixActionsElement(e){this.preActions!==e&&(this.preActions&&(this.preActions.remove(),this.preActions=void 0),e&&(this.preActionsContainer.appendChild(e),this.preActions=e))}isActive(e){return this.tabs.isActive(e)}indexOf(e){return this.tabs.indexOf(e)}getTabId(e){return this.tabs.getTabId(e)}getPanelForTab(e){return this.tabs.getPanelForTab(e)}setActive(e){}delete(e){this.tabs.delete(e),this.updateClassnames()}setActivePanel(e){this.tabs.setActivePanel(e)}focusActiveTab(){this.tabs.focusActiveTab()}openPanel(e,t=this.tabs.size){this.tabs.openPanel(e,t),this.updateClassnames()}closePanel(e){this.delete(e.id)}setOverflowExclude(e){this.tabs.setOverflowExclude(e)}setForcedOverflow(e){this.tabs.setForcedOverflow(e)}setPinnedSticky(e){this.tabs.setPinnedSticky(e)}refreshOverflow(){this.tabs.refreshOverflow()}setPinnedRow(e){this._pinnedRow!==e&&(this._pinnedRow&&this._pinnedRow.remove(),this._pinnedRow=e,e&&(e.classList.add("dv-pinned-row"),this._element.insertBefore(e,this._element.firstChild)),Ze(this._element,"dv-tabs-and-actions-container--pinned-row",!!e))}setDropIndexResolver(e){this._dropIndexResolver=e}resolveDropIndex(e,t){return this._dropIndexResolver(e,t)}updateClassnames(){Ze(this._element,"dv-single-tab",this.size===1)}toggleDropdown(e){const t=e.reset?[]:e.tabs,n=e.reset?[]:e.tabGroups,s=e.reset?[]:e.pinnedTabs;this._overflowTabs=t,this._overflowTabGroups=n,this._overflowPinnedTabs=s;const o=this._overflowTabs.length+this._overflowPinnedTabs.length;if(o>0&&this.dropdownPart){this.dropdownPart.update({tabs:o});return}if(o===0){this._dropdownDisposable.dispose();return}const r=document.createElement("div");r.className="dv-tabs-overflow-dropdown-root";const a=ise();a.update({tabs:o}),this.dropdownPart=a,r.appendChild(a.element),this.rightActionsContainer.prepend(r),this._dropdownDisposable.value=new ct(rn.from(()=>{var l,d;r.remove(),(l=this.dropdownPart)===null||l===void 0||(d=l.dispose)===null||d===void 0||d.call(l),this.dropdownPart=null}),ot(r,"pointerdown",l=>{l.preventDefault()},{capture:!0}),ot(r,"click",l=>{const d=Qte(r),c={x:l.clientX,y:l.clientY,zIndex:d?.style.zIndex?`calc(${d.style.zIndex} * 2)`:void 0},u=this.createOverflowRenderContext(r,c),h=this.accessor.advancedOverflowService;h?h.renderOverflow({group:this.group,overflowTabs:[...this._overflowTabs],overflowTabGroups:[...this._overflowTabGroups],pinnedOverflowTabs:[...this._overflowPinnedTabs],context:u}):u.open(this.renderFreeOverflowList(u))}))}createOverflowRenderContext(e,t){const n=new Set(this._overflowTabGroups),s=this.group.model.getTabGroups(),o=new Map,r=new Map;for(const d of s)if(r.set(d.id,d),n.has(d.id))for(const c of d.panelIds)o.set(c,d);const a=()=>this.accessor.getPopupServiceForGroup(this.group),l=d=>{const c=document.createElement("div");c.className="dv-tabs-overflow-group-header";const u=document.createElement("span");u.className="dv-tabs-overflow-group-color",Cv(u,d.color,this.accessor.tabGroupColorPalette),c.appendChild(u);const h=document.createElement("span");if(h.className="dv-tabs-overflow-group-label",h.textContent=d.label||d.id,c.appendChild(h),d.collapsed){const p=document.createElement("span");p.className="dv-tabs-overflow-group-collapsed-badge",p.textContent=`${d.panelIds.length}`,c.appendChild(p)}return c.addEventListener("click",()=>{a().close(),d.collapsed&&d.expand();const p=d.panelIds[0];if(p){const f=this.group.panels.find(g=>g.id===p);this.accessor.withOrigin("user",()=>f?.api.setActive())}}),c};return{overflowGroupIdForPanel:d=>{var c;return(c=o.get(d))===null||c===void 0?void 0:c.id},buildGroupHeader:d=>{const c=r.get(d);if(!(!c||!n.has(c.id)))return l(c)},buildPinnedHeader:()=>{const d=document.createElement("div");d.className="dv-tabs-overflow-group-header dv-tabs-overflow-pinned-header";const c=kE();c.classList.add("dv-tabs-overflow-pinned-icon"),d.appendChild(c);const u=document.createElement("span");return u.className="dv-tabs-overflow-group-label",u.textContent="Pinned",d.appendChild(u),d},buildRow:d=>{const c=this.group.panels.find(x=>x.id===d);if(!c)return;const u=this.tabs.tabs.find(x=>x.panel.id===d),h=o.get(d),p=c.view.createTabRenderer("headerOverflow").element,f=document.createElement("div");Ze(f,"dv-tab",!0),Ze(f,"dv-active-tab",c.api.isActive),Ze(f,"dv-inactive-tab",!c.api.isActive),h&&Ze(f,"dv-tab--grouped",!0);const g=()=>{h?.collapsed&&h.expand(),u?.element.scrollIntoView({block:"nearest",inline:"nearest"}),this.accessor.withOrigin("user",()=>c.api.setActive())};return f.addEventListener("click",x=>{a().close(),!x.defaultPrevented&&g()}),f.appendChild(p),{element:f,panel:c,activate:()=>{a().close(),g()}}},open:d=>{a().openPopover(d,t)},close:()=>a().close(),focusTrigger:()=>{e.tabIndex=-1,e.focus()}}}renderFreeOverflowList(e){const t=document.createElement("div");t.style.overflow="auto",t.className="dv-tabs-overflow-container";const n=this._overflowPinnedTabs.map(o=>e.buildRow(o)).filter(o=>o!=null);if(n.length>0){t.appendChild(e.buildPinnedHeader());for(const o of n)t.appendChild(o.element)}const s=new Set;for(const o of this.tabs.tabs.filter(r=>this._overflowTabs.includes(r.panel.id))){const r=e.overflowGroupIdForPanel(o.panel.id);if(r&&!s.has(r)){s.add(r);const l=e.buildGroupHeader(r);l&&t.appendChild(l)}const a=e.buildRow(o.panel.id);a&&t.appendChild(a.element)}return t}updateDragAndDropState(){this.tabs.updateDragAndDropState(),this.voidContainer.updateDragAndDropState()}updateTabGroups(){this.tabs.updateTabGroups()}refreshTabGroupAccent(){this.tabs.refreshTabGroupAccent()}},rse=class extends ct{get label(){return this._label}get color(){return this._color}get componentParams(){return this._componentParams}setLabel(e){this.isDisposed||this._label===e||(this._label=e,this._onDidChange.fire())}setColor(e){if(this.isDisposed)return;const t=e===""?void 0:e;this._color!==t&&(this._color=t,this._onDidChange.fire())}setComponentParams(e){this.isDisposed||(this._componentParams=e,this._onDidChange.fire())}get collapsed(){return this._collapsed}get panelIds(){return this._panelIds}get size(){return this._panelIds.length}get isEmpty(){return this._panelIds.length===0}constructor(e,t){var n,s;super(),this.id=e,this._collapsed=!1,this._panelIds=[],this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidPanelChange=new ve,this.onDidPanelChange=this._onDidPanelChange.event,this._onDidCollapseChange=new ve,this.onDidCollapseChange=this._onDidCollapseChange.event,this._onDidDestroy=new ve,this.onDidDestroy=this._onDidDestroy.event,this._label=(n=t?.label)!==null&&n!==void 0?n:"",this._color=t?.color===""?void 0:t?.color,this._collapsed=(s=t?.collapsed)!==null&&s!==void 0?s:!1,this._componentParams=t?.componentParams,this.addDisposables(this._onDidChange,this._onDidPanelChange,this._onDidCollapseChange,this._onDidDestroy)}addPanel(e,t){if(this.isDisposed||this._panelIds.includes(e))return;const n=t===void 0?this._panelIds.length:Math.max(0,Math.min(t,this._panelIds.length));this._panelIds.splice(n,0,e),this._onDidPanelChange.fire({panelId:e,type:"add"})}removePanel(e){if(this.isDisposed)return!1;const t=this._panelIds.indexOf(e);return t===-1?!1:(this._panelIds.splice(t,1),this._onDidPanelChange.fire({panelId:e,type:"remove"}),!0)}indexOfPanel(e){return this._panelIds.indexOf(e)}containsPanel(e){return this._panelIds.includes(e)}collapse(){this.isDisposed||this._collapsed||(this._collapsed=!0,this._onDidCollapseChange.fire(!0))}expand(){this.isDisposed||!this._collapsed||(this._collapsed=!1,this._onDidCollapseChange.fire(!1))}toggle(){this._collapsed?this.expand():this.collapse()}toJSON(){const e={id:this.id,collapsed:this._collapsed,panelIds:[...this._panelIds]};return this._label&&(e.label=this._label),this._color!==void 0&&(e.color=this._color),this._componentParams!==void 0&&(e.componentParams=this._componentParams),e}dispose(){this._onDidDestroy.fire(),super.dispose()}},jv=class extends gv{get nativeEvent(){return this.options.nativeEvent}get position(){return this.options.position}get panel(){return this.options.panel}get group(){return this.options.group}get api(){return this.options.api}constructor(e){super(),this.options=e}getData(){return this.options.getData()}},ME=class extends jv{get kind(){return this._kind}constructor(e){super(e),this._kind=e.kind}},ase=class extends ct{get tabGroups(){return this._tabGroups}get element(){throw new Error("dockview: not supported")}get activePanel(){return this._activePanel}get contentContainerId(){return this.contentContainer.element.id}get contentDropTarget(){return this.contentContainer.dropTarget}get locked(){return this._locked}set locked(e){this._locked=e,Ze(this.container,"dv-locked-groupview",e==="no-drop-target"||e)}get isActive(){return this._isGroupActive}get panels(){return this._panels}get size(){return this._panels.length}get isEmpty(){return this._panels.length===0}get hasWatermark(){return!!(this.watermark&&this.container.contains(this.watermark.element))}get header(){return this.tabsContainer}get tabsListElement(){return this.tabsContainer.tabsListElement}getPanelForTab(e){return this.tabsContainer.getPanelForTab(e)}get isContentFocused(){return document.activeElement?$m(document.activeElement,this.contentContainer.element):!1}get headerPosition(){var e;return(e=this._headerPosition)!==null&&e!==void 0?e:"top"}set headerPosition(e){var t;this._headerPosition=e,this.invalidateHeaderSize(),bi(this.container,"dv-groupview-header-top","dv-groupview-header-bottom","dv-groupview-header-left","dv-groupview-header-right"),wi(this.container,`dv-groupview-header-${e}`);const n=e==="top"||e==="bottom"?"horizontal":"vertical",s=this._headerDirection;if(this._headerDirection=n,this.tabsContainer.direction=n,this.header.direction=n,!((t=this._activePanel)===null||t===void 0)&&t.layout){const{width:r,height:a}=this.contentDimensions();this._activePanel.layout(r,a)}if(this.updateHeaderActions(),s!==void 0&&s!==n){var o;(o=this.groupPanel)===null||o===void 0||o.api._onDidHeaderDirectionChange.fire({direction:n,position:e})}}get location(){return this._location}set location(e){this._location=e,Ze(this.container,"dv-groupview-floating",!1),Ze(this.container,"dv-groupview-popout",!1),Ze(this.container,"dv-groupview-edge",!1);const t=n=>{this.contentContainer.dropTarget.setTargetZones(n),this.contentContainer.pointerDropTarget.setTargetZones(n)};switch(e.type){case"grid":t(["top","bottom","left","right","center"]);break;case"floating":t(["top","bottom","left","right","center"]),Ze(this.container,"dv-groupview-floating",!0);break;case"popout":t(["top","bottom","left","right","center"]),Ze(this.container,"dv-groupview-popout",!0);break;case"edge":t(["center"]),Ze(this.container,"dv-groupview-edge",!0);break}this.groupPanel.api._onDidLocationChange.fire({location:this.location})}constructor(e,t,n,s,o){var r,a;super(),this.container=e,this.accessor=t,this.id=n,this.options=s,this.groupPanel=o,this._isGroupActive=!1,this._locked=!1,this._location={type:"grid"},this.mostRecentlyUsed=[],this._overwriteRenderContainer=null,this._overwriteDropTargetContainer=null,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._width=0,this._height=0,this._panels=[],this._panelDisposables=new Map,this._tabGroupDisposables=new Map,this._pendingMicrotaskDisposables=new Set,this._onMove=new ve,this.onMove=this._onMove.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new ve,this.onWillDrop=this._onWillDrop.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onTabDragStart=new ve,this.onTabDragStart=this._onTabDragStart.event,this._onGroupDragStart=new ve,this.onGroupDragStart=this._onGroupDragStart.event,this._onDidAddPanel=new ve,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPanelTitleChange=new ve,this.onDidPanelTitleChange=this._onDidPanelTitleChange.event,this._onDidPanelParametersChange=new ve,this.onDidPanelParametersChange=this._onDidPanelParametersChange.event,this._onDidRemovePanel=new ve,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidActivePanelChange=new ve,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._tabGroups=[],this._tabGroupMap=new Map,this._panelToTabGroup=new Map,this._tabGroupIdCounter=0,this._pendingTabGroupUpdate=!1,this._onDidCreateTabGroup=new ve,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new ve,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new ve,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new ve,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new ve,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new ve,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,Ze(this.container,"dv-groupview",!0),this.container.setAttribute("role","region"),this._api=new bv(this.accessor),this.tabsContainer=new ose(this.accessor,this.groupPanel),this.contentContainer=new Lne(this.accessor,this),e.append(this.tabsContainer.element,this.contentContainer.element),this.header.hidden=!!s.hideHeader,this.locked=(r=s.locked)!==null&&r!==void 0?r:!1,this.headerPosition=(a=s.headerPosition)!==null&&a!==void 0?a:t.defaultHeaderPosition,this.addDisposables(kr(this.tabsContainer.element,()=>{if(this.isDisposed)return;const l=this.measureHeaderSize();l!==this._cachedHeaderSize&&(this._cachedHeaderSize=l,this.layout(this._width,this._height))}),this._onDidPanelTitleChange.event(()=>this.updateAccessibleLabel()),this._onTabDragStart,this._onGroupDragStart,this._onWillShowOverlay,this.tabsContainer.onTabDragStart(l=>{this._onTabDragStart.fire(l)}),this.tabsContainer.onGroupDragStart(l=>{this._onGroupDragStart.fire(l)}),this.tabsContainer.onDrop(l=>{var d;const c=Ln(),u=(d=c?.panelId)!==null&&d!==void 0?d:null,h=u?this.tabsContainer.resolveDropIndex(u,l.index):l.index;if(this.handleDropEvent("header",l.event,"center",h),u&&l.targetTabGroupId){const p=this._tabGroupMap.get(l.targetTabGroupId);let f;if(p){const g=this._panels.findIndex(x=>x.id===u);if(g!==-1){f=0;for(const x of p.panelIds)this._panels.findIndex(v=>v.id===x)<g&&f++}}this.addPanelToTabGroup(l.targetTabGroupId,u,f)}else u&&l.targetTabGroupId===null&&this.removePanelFromTabGroup(u)}),this.contentContainer.onDidFocus(()=>{this.accessor.doSetGroupActive(this.groupPanel)}),this.contentContainer.onDidBlur(()=>{}),this.contentContainer.dropTarget.onDrop(l=>{this.handleDropEvent("content",l.nativeEvent,l.position,void 0,l.edge)}),this.contentContainer.pointerDropTarget.onDrop(l=>{this.handleDropEvent("content",l.nativeEvent,l.position,void 0,l.edge)}),this.tabsContainer.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(l)}),this.contentContainer.dropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new td(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:Ln}))}),this.contentContainer.pointerDropTarget.onWillShowOverlay(l=>{this._onWillShowOverlay.fire(new td(l,{kind:"content",panel:this.activePanel,api:this._api,group:this.groupPanel,getData:Ln}))}),this._onMove,this._onDidChange,this._onDidDrop,this._onWillDrop,this._onDidAddPanel,this._onDidRemovePanel,this._onDidActivePanelChange,this._onUnhandledDragOver,this._onDidPanelTitleChange,this._onDidPanelParametersChange,this._onDidCreateTabGroup,this._onDidDestroyTabGroup,this._onDidAddPanelToTabGroup,this._onDidRemovePanelFromTabGroup,this._onDidTabGroupChange,this._onDidTabGroupCollapsedChange,this._onDidCreateTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidDestroyTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidAddPanelToTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidRemovePanelFromTabGroup.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidTabGroupChange.event(()=>{this._scheduleTabGroupUpdate()}),this._onDidTabGroupCollapsedChange.event(()=>{this._scheduleTabGroupUpdate()}))}_scheduleTabGroupUpdate(){this._pendingTabGroupUpdate||(this._pendingTabGroupUpdate=!0,queueMicrotask(()=>{this._pendingTabGroupUpdate=!1,this.isDisposed||this.tabsContainer.updateTabGroups()}))}_bracketTabGroupMutation(e){return this.accessor.mutation?this.accessor.mutation("tab-group",e):e()}createTabGroup(e){return this._bracketTabGroupMutation(()=>this._doCreateTabGroup(e))}_doCreateTabGroup(e){var t;const n=(t=e?.id)!==null&&t!==void 0?t:`tg-${this.id}-${this._tabGroupIdCounter++}`,s=new rse(n,{label:e?.label,color:e?.color,collapsed:e?.collapsed,componentParams:e?.componentParams});return this._tabGroups.push(s),this._tabGroupMap.set(n,s),this._tabGroupDisposables.set(n,new ct(s.onDidChange(()=>{this._onDidTabGroupChange.fire({tabGroup:s})}),s.onDidCollapseChange(o=>{o?this._handleGroupCollapse(s):this._handleGroupExpand(s),this._onDidTabGroupCollapsedChange.fire({tabGroup:s})}),s.onDidDestroy(()=>{this._removeTabGroupInternal(s)}))),this._onDidCreateTabGroup.fire({tabGroup:s}),s}dissolveTabGroup(e){const t=this._tabGroupMap.get(e);t&&this._bracketTabGroupMutation(()=>{const n=[...t.panelIds];for(const s of n)t.removePanel(s),this._panelToTabGroup.delete(s),this._onDidRemovePanelFromTabGroup.fire({tabGroup:t,panelId:s});t.dispose()})}addPanelToTabGroup(e,t,n){const s=this._tabGroupMap.get(e);if(!s||!this._panels.some(r=>r.id===t))return;const o=this.getTabGroupForPanel(t);o?.id!==e&&this._bracketTabGroupMutation(()=>{o&&this.removePanelFromTabGroup(t),s.addPanel(t,n),this._panelToTabGroup.set(t,s),this._enforceContiguity(s,t),this._onDidAddPanelToTabGroup.fire({tabGroup:s,panelId:t})})}movePanelWithinGroup(e,t,n){const s=this._tabGroupMap.get(e);s?.containsPanel(t)&&(s.removePanel(t),s.addPanel(t,n),this._enforceContiguity(s,t),this.tabsContainer.updateTabGroups())}movePanelBetweenGroups(e,t,n){const s=this._findTabGroupForPanel(e),o=this._tabGroupMap.get(t);o&&(s&&(s.removePanel(e),this._panelToTabGroup.delete(e),this._onDidRemovePanelFromTabGroup.fire({tabGroup:s,panelId:e}),s.isEmpty&&s.dispose()),o.addPanel(e,n),this._panelToTabGroup.set(e,o),this._enforceContiguity(o,e),this._onDidAddPanelToTabGroup.fire({tabGroup:o,panelId:e}))}moveTabGroup(e,t){const n=this._tabGroupMap.get(e);if(!n||n.panelIds.length===0)return;const s=new Set(n.panelIds),o=n.panelIds.map(d=>this._panels.find(c=>c.id===d)).filter(d=>d!==void 0);if(o.length===0)return;let r=0;for(let d=0;d<Math.min(t,this._panels.length);d++)s.has(this._panels[d].id)&&r++;for(const d of o){const c=this._panels.indexOf(d);c!==-1&&this._panels.splice(c,1)}const a=t-r,l=Math.max(0,Math.min(a,this._panels.length));this._panels.splice(l,0,...o);for(const d of this._panels)this.tabsContainer.delete(d.id);for(let d=0;d<this._panels.length;d++)this.tabsContainer.openPanel(this._panels[d],d);this.tabsContainer.updateTabGroups()}_enforceContiguity(e,t){const n=this._panels.find(l=>l.id===t);if(!n)return;const s=e.indexOfPanel(t),o=this._computeGlobalIndex(e,s),r=this._panels.indexOf(n);if(r===o)return;this._panels.splice(r,1);const a=o>r?o-1:o;this._panels.splice(a,0,n),this.tabsContainer.delete(t),this.tabsContainer.openPanel(n,a)}_computeGlobalIndex(e,t){const n=e.panelIds;if(n.length<=1){const s=this._panels.find(o=>o.id===n[0]);return s?this._panels.indexOf(s):this._panels.length}for(let s=0;s<n.length;s++){if(s===t)continue;const o=this._panels.find(r=>r.id===n[s]);if(o){const r=this._panels.indexOf(o);return Math.max(0,r+(t-s))}}return this._panels.length}removePanelFromTabGroup(e){const t=this._findTabGroupForPanel(e);t&&this._bracketTabGroupMutation(()=>{t.removePanel(e),this._panelToTabGroup.delete(e),this._onDidRemovePanelFromTabGroup.fire({tabGroup:t,panelId:e}),t.isEmpty&&t.dispose()})}getTabGroups(){return this._tabGroups}updateTabGroups(){this.tabsContainer.updateTabGroups()}refreshTabGroupAccent(){this.tabsContainer.refreshTabGroupAccent()}refreshWatermark(){if(this.watermark){var e,t;this.watermark.element.remove(),(e=(t=this.watermark).dispose)===null||e===void 0||e.call(t),this.watermark=void 0}this.updateContainer()}getTabGroupForPanel(e){return this._findTabGroupForPanel(e)}_findTabGroupForPanel(e){return this._panelToTabGroup.get(e)}_removeTabGroupInternal(e){const t=this._tabGroups.indexOf(e);if(t!==-1){this._tabGroups.splice(t,1),this._tabGroupMap.delete(e.id);for(const s of e.panelIds)this._panelToTabGroup.delete(s);this._onDidDestroyTabGroup.fire({tabGroup:e});const n=this._tabGroupDisposables.get(e.id);this._tabGroupDisposables.delete(e.id),n&&(this._pendingMicrotaskDisposables.add(n),queueMicrotask(()=>{this._pendingMicrotaskDisposables.delete(n),n.dispose()}))}}_handleGroupCollapse(e){if(!this._activePanel||!e.containsPanel(this._activePanel.id))return;const t=this._panels.indexOf(this._activePanel);for(let n=t+1;n<this._panels.length;n++){const s=this._panels[n],o=this._findTabGroupForPanel(s.id);if(!o?.collapsed){this.doSetActivePanel(s),this.updateContainer();return}}for(let n=t-1;n>=0;n--){const s=this._panels[n],o=this._findTabGroupForPanel(s.id);if(!o?.collapsed){this.doSetActivePanel(s),this.updateContainer();return}}this.contentContainer.closePanel(),this.doSetActivePanel(void 0),this.updateContainer()}_handleGroupExpand(e){if(this._activePanel)return;const t=e.panelIds[0];if(t){const n=this._panels.find(s=>s.id===t);n&&(this.doSetActivePanel(n),this.updateContainer())}}restoreTabGroups(e){for(const t of e){const n=/-(\d+)$/.exec(t.id);if(n){const s=Number.parseInt(n[1],10)+1;s>this._tabGroupIdCounter&&(this._tabGroupIdCounter=s)}}for(const t of e){const n=this.createTabGroup({id:t.id,label:t.label,color:t.color,componentParams:t.componentParams}),s=this._tabGroupMap.get(n.id);for(const o of t.panelIds)this._panels.some(r=>r.id===o)&&(n.addPanel(o),this._panelToTabGroup.set(o,s),this._enforceContiguity(s,o));t.collapsed&&n.collapse(),n.isEmpty&&n.dispose()}}focusContent(){this.contentContainer.element.focus()}focusActiveTab(){this.tabsContainer.focusActiveTab()}set renderContainer(e){if(this.panels.forEach(t=>{this.renderContainer.detatch(t)}),this._overwriteRenderContainer=e,this.panels.forEach(t=>{this.rerender(t)}),this._activePanel){this.contentContainer.renderPanel(this._activePanel,{asActive:!0});const{width:t,height:n}=this.contentDimensions();this._activePanel.layout(t,n)}}get renderContainer(){var e;return(e=this._overwriteRenderContainer)!==null&&e!==void 0?e:this.accessor.overlayRenderContainer}set dropTargetContainer(e){this._overwriteDropTargetContainer=e}get dropTargetContainer(){var e;return this._location.type==="floating"&&this.accessor.rootDropTargetContainer.disabled?this.accessor.floatingDropTargetContainer:(e=this._overwriteDropTargetContainer)!==null&&e!==void 0?e:this.accessor.rootDropTargetContainer}initialize(){this.options.panels&&this.options.panels.forEach(e=>{this.doAddPanel(e)}),this.options.activePanel&&this.openPanel(this.options.activePanel),this.setActive(this.isActive,!0),this.updateContainer(),this.updateHeaderActions()}updateHeaderActions(){var e;(e=this.accessor.headerActionsService)===null||e===void 0||e.refresh(this.groupPanel)}attachHeaderAction(e,t){switch(e){case"left":this.tabsContainer.setLeftActionsElement(t);break;case"right":this.tabsContainer.setRightActionsElement(t);break;case"prefix":this.tabsContainer.setPrefixActionsElement(t);break}}rerender(e){this.contentContainer.renderPanel(e,{asActive:!1})}indexOf(e){return this.tabsContainer.indexOf(e.id)}toJSON(){var e;const t={views:this.tabsContainer.panels,activeView:(e=this._activePanel)===null||e===void 0?void 0:e.id,id:this.id};return this.locked!==!1&&(t.locked=this.locked),this.header.hidden&&(t.hideHeader=!0),this.headerPosition!=="top"&&(t.headerPosition=this.headerPosition),this._tabGroups.length>0&&(t.tabGroups=this._tabGroups.map(n=>n.toJSON())),t}moveToNext(e){var t,n,s;(t=e)!==null&&t!==void 0||(e={}),(s=(n=e).panel)!==null&&s!==void 0||(n.panel=this.activePanel);const o=e.panel?this.panels.indexOf(e.panel):-1;let r;if(o<this.panels.length-1)r=o+1;else{if(e.suppressRoll)return;r=0}this.openPanel(this.panels[r])}moveToPrevious(e){var t,n,s;if((t=e)!==null&&t!==void 0||(e={}),(s=(n=e).panel)!==null&&s!==void 0||(n.panel=this.activePanel),!e.panel)return;const o=this.panels.indexOf(e.panel);let r;if(o>0)r=o-1;else{if(e.suppressRoll)return;r=this.panels.length-1}this.openPanel(this.panels[r])}containsPanel(e){return this.panels.includes(e)}init(e){}update(e){}focus(){var e;(e=this._activePanel)===null||e===void 0||e.focus()}openPanel(e,t={}){(typeof t.index!="number"||t.index>this.panels.length)&&(t.index=this.panels.length);const n=!!t.skipSetActive;if(e.updateParentGroup(this.groupPanel,{skipSetActive:t.skipSetActive}),this.doAddPanel(e,t.index,{skipSetActive:n}),this.invalidateHeaderSize(),this._activePanel===e){this.contentContainer.renderPanel(e,{asActive:!0});return}n||this.doSetActivePanel(e),t.skipSetGroupActive||this.accessor.doSetGroupActive(this.groupPanel),t.skipSetActive||this.updateContainer()}removePanel(e,t){const n=typeof e=="string"?e:e.id,s=this._panels.find(o=>o.id===n);if(!s)throw new Error("invalid operation");return this._removePanel(s,t)}closeAllPanels(){if(this.panels.length>0){const e=[...this.panels];for(const t of e)this.doClose(t)}else this.accessor.removeGroup(this.groupPanel)}closePanel(e){this.doClose(e)}doClose(e){const t=this.panels.length===1&&this.accessor.groups.length===1;this.accessor.removePanel(e,t&&this.accessor.options.noPanelsOverlay==="emptyGroup"?{removeEmptyGroup:!1}:void 0)}isPanelActive(e){return this._activePanel===e}updateActions(e){this.tabsContainer.setRightActionsElement(e)}setActive(e,t=!1){if(!(!t&&this.isActive===e)){if(this._isGroupActive=e,Ze(this.container,"dv-active-group",e),Ze(this.container,"dv-inactive-group",!e),this.tabsContainer.setActive(this.isActive),!this._activePanel&&this.panels.length>0){const n=this._panels.find(s=>{const o=this._findTabGroupForPanel(s.id);return!o?.collapsed});n&&this.doSetActivePanel(n)}this.updateContainer()}}layout(e,t){var n;this._width=e,this._height=t;const{width:s,height:o}=this.contentDimensions();this.contentContainer.layout(s,o),!((n=this._activePanel)===null||n===void 0)&&n.layout&&this._activePanel.layout(s,o)}relayout(){this.invalidateHeaderSize(),this.layout(this._width,this._height)}measureHeaderSize(){const e=this.tabsContainer.element;return this.headerPosition==="top"||this.headerPosition==="bottom"?e.offsetHeight:e.offsetWidth}invalidateHeaderSize(){this._cachedHeaderSize=void 0}contentDimensions(){var e;const t=this.headerPosition==="top"||this.headerPosition==="bottom",n=(e=this._cachedHeaderSize)!==null&&e!==void 0?e:this._cachedHeaderSize=this.measureHeaderSize();return{width:t?this._width:Math.max(0,this._width-n),height:t?Math.max(0,this._height-n):this._height}}_removePanel(e,t){const n=this._activePanel===e;if(this.doRemovePanel(e),this.invalidateHeaderSize(),n&&this.panels.length>0){const s=this.mostRecentlyUsed[0];this.openPanel(s,{skipSetActive:t?.skipSetActive,skipSetGroupActive:t?.skipSetActiveGroup})}return this._activePanel&&this.panels.length===0&&this.doSetActivePanel(void 0),t?.skipSetActive||this.updateContainer(),e}doRemovePanel(e){const t=this.panels.indexOf(e);if(this._activePanel===e&&this.contentContainer.closePanel(),this.tabsContainer.delete(e.id),this._panels.splice(t,1),this.mostRecentlyUsed.includes(e)){const s=this.mostRecentlyUsed.indexOf(e);this.mostRecentlyUsed.splice(s,1)}const n=this._panelDisposables.get(e.id);n&&(n.dispose(),this._panelDisposables.delete(e.id)),this.removePanelFromTabGroup(e.id),this._onDidRemovePanel.fire({panel:e})}doAddPanel(e,t=this.panels.length,n){const s=this._panels.indexOf(e)>-1;this.tabsContainer.show(),this.contentContainer.show(),this.tabsContainer.openPanel(e,t),n?.skipSetActive?e.api.renderer==="always"&&this.contentContainer.renderPanel(e,{asActive:!1}):this.contentContainer.openPanel(e),!s&&(this.updateMru(e),this.panels.splice(t,0,e),this._panelDisposables.set(e.id,new ct(e.api.onDidTitleChange(o=>this._onDidPanelTitleChange.fire(o)),e.api.onDidParametersChange(o=>this._onDidPanelParametersChange.fire(o)))),this._onDidAddPanel.fire({panel:e}))}doSetActivePanel(e){if(this._activePanel!==e){if(this._activePanel=e,e){var t,n,s;this.tabsContainer.setActivePanel(e),this.contentContainer.setLabelledBy(this.tabsContainer.getTabId(e.id)),this.contentContainer.openPanel(e);const{width:o,height:r}=this.contentDimensions();e.layout(o,r),this.updateMru(e),this.contentContainer.refreshFocusState(),this._onDidActivePanelChange.fire({panel:e,origin:(t=(n=(s=this.accessor).currentOrigin)===null||n===void 0?void 0:n.call(s))!==null&&t!==void 0?t:"user"})}this.updateAccessibleLabel()}}updateAccessibleLabel(){var e;const t=(e=this._activePanel)===null||e===void 0?void 0:e.title;t?this.container.setAttribute("aria-label",t):this.container.removeAttribute("aria-label")}updateMru(e){this.mostRecentlyUsed.includes(e)&&this.mostRecentlyUsed.splice(this.mostRecentlyUsed.indexOf(e),1),this.mostRecentlyUsed=[e,...this.mostRecentlyUsed]}updateContainer(){this.panels.forEach(s=>s.runEvents());const e=this.isEmpty||!this._activePanel;if(e&&!this.watermark){const s=this.accessor.createWatermarkComponent();s.init({containerApi:this._api,group:this.groupPanel}),this.watermark=s,ot(this.watermark.element,"pointerdown",()=>{this.isActive||this.accessor.doSetGroupActive(this.groupPanel)}),this.contentContainer.element.appendChild(this.watermark.element)}if(!e&&this.watermark){var t,n;this.watermark.element.remove(),(t=(n=this.watermark).dispose)===null||t===void 0||t.call(n),this.watermark=void 0}}canDisplayOverlay(e,t,n){const s=new IE(e,n,t,Ln,this.accessor.getPanel(this.id));return this._onUnhandledDragOver.fire(s),s.isAccepted}canDisplayContentOverlay(e,t){if(this.locked==="no-drop-target"||this.locked&&t==="center")return!1;const n=Ln();return!n&&e.shiftKey&&this.location.type!=="floating"?!1:n?.viewId===this.accessor.id?!0:this.canDisplayOverlay(e,t,"content")}handleDropEvent(e,t,n,s,o){if(this.locked==="no-drop-target")return;if(e==="content"&&o){this.accessor.dockToLayoutEdge(t,n);return}function r(){switch(e){case"header":return typeof s=="number"?"tab":"header_space";case"content":return"content"}}const a=typeof s=="number"?this.panels[s]:void 0,l=new ME({nativeEvent:t,position:n,panel:a,getData:()=>Ln(),kind:r(),group:this.groupPanel,api:this._api});if(this._onWillDrop.fire(l),l.defaultPrevented)return;const d=Ln();if(d?.viewId===this.accessor.id){if(e==="content"&&d.groupId===this.id&&(n==="center"||d.panelId===null&&!d.tabGroupId)||e==="header"&&d.groupId===this.id&&d.panelId===null&&!d.tabGroupId)return;if(d.panelId===null){const{groupId:h}=d;this._onMove.fire({target:n,groupId:h,index:s,tabGroupId:d.tabGroupId});return}if(this.tabsContainer.indexOf(d.panelId)!==-1&&this.tabsContainer.size===1)return;const{groupId:c,panelId:u}=d;if(this.id===c&&!n&&this.tabsContainer.indexOf(u)===s)return;this._onMove.fire({target:n,groupId:d.groupId,itemId:d.panelId,index:s})}else this._onDidDrop.fire(new jv({nativeEvent:t,position:n,panel:a,getData:()=>Ln(),group:this.groupPanel,api:this._api}))}updateDragAndDropState(){this.tabsContainer.updateDragAndDropState()}dispose(){var e,t,n;super.dispose(),(e=this.watermark)===null||e===void 0||e.element.remove(),(t=this.watermark)===null||t===void 0||(n=t.dispose)===null||n===void 0||n.call(t),this.watermark=void 0;for(const s of[...this._tabGroups])s.dispose();for(const s of this._tabGroupDisposables.values())s.dispose();this._tabGroupDisposables.clear();for(const s of this._pendingMicrotaskDisposables)s.dispose();this._pendingMicrotaskDisposables.clear();for(const s of this.panels)s.dispose();this.tabsContainer.dispose(),this.contentContainer.dispose()}},_v=class extends SE{constructor(e,t,n){super(e,t),this._onDidConstraintsChangeInternal=new ve,this.onDidConstraintsChangeInternal=this._onDidConstraintsChangeInternal.event,this._onDidConstraintsChange=new ve,this.onDidConstraintsChange=this._onDidConstraintsChange.event,this._onDidSizeChange=new ve,this.onDidSizeChange=this._onDidSizeChange.event,this.addDisposables(this._onDidConstraintsChangeInternal,this._onDidConstraintsChange,this._onDidSizeChange),n&&this.initialize(n)}setConstraints(e){this._onDidConstraintsChangeInternal.fire(e)}setSize(e){this._onDidSizeChange.fire(e)}},RE=class extends wv{get priority(){return this._priority}get snap(){return this._snap}get minimumWidth(){return this.__minimumWidth()}get minimumHeight(){return this.__minimumHeight()}get maximumHeight(){return this.__maximumHeight()}get maximumWidth(){return this.__maximumWidth()}__minimumWidth(){const e=typeof this._minimumWidth=="function"?this._minimumWidth():this._minimumWidth;return e!==this._evaluatedMinimumWidth&&(this._evaluatedMinimumWidth=e,this.updateConstraints()),e}__maximumWidth(){const e=typeof this._maximumWidth=="function"?this._maximumWidth():this._maximumWidth;return e!==this._evaluatedMaximumWidth&&(this._evaluatedMaximumWidth=e,this.updateConstraints()),e}__minimumHeight(){const e=typeof this._minimumHeight=="function"?this._minimumHeight():this._minimumHeight;return e!==this._evaluatedMinimumHeight&&(this._evaluatedMinimumHeight=e,this.updateConstraints()),e}__maximumHeight(){const e=typeof this._maximumHeight=="function"?this._maximumHeight():this._maximumHeight;return e!==this._evaluatedMaximumHeight&&(this._evaluatedMaximumHeight=e,this.updateConstraints()),e}get isActive(){return this.api.isActive}get isVisible(){return this.api.isVisible}constructor(e,t,n,s){super(e,t,s??new _v(e,t)),this._evaluatedMinimumWidth=0,this._evaluatedMaximumWidth=Number.MAX_SAFE_INTEGER,this._evaluatedMinimumHeight=0,this._evaluatedMaximumHeight=Number.MAX_SAFE_INTEGER,this._minimumWidth=0,this._minimumHeight=0,this._maximumWidth=Number.MAX_SAFE_INTEGER,this._maximumHeight=Number.MAX_SAFE_INTEGER,this._snap=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,typeof n?.minimumWidth=="number"&&(this._minimumWidth=n.minimumWidth),typeof n?.maximumWidth=="number"&&(this._maximumWidth=n.maximumWidth),typeof n?.minimumHeight=="number"&&(this._minimumHeight=n.minimumHeight),typeof n?.maximumHeight=="number"&&(this._maximumHeight=n.maximumHeight),this.api.initialize(this),this.addDisposables(this.api.onWillVisibilityChange(o=>{const{isVisible:r}=o,{accessor:a}=this._params;a.setVisible(this,r)}),this.api.onActiveChange(()=>{const{accessor:o}=this._params;o.doSetGroupActive(this)}),this.api.onDidConstraintsChangeInternal(o=>{(typeof o.minimumWidth=="number"||typeof o.minimumWidth=="function")&&(this._minimumWidth=o.minimumWidth),(typeof o.minimumHeight=="number"||typeof o.minimumHeight=="function")&&(this._minimumHeight=o.minimumHeight),(typeof o.maximumWidth=="number"||typeof o.maximumWidth=="function")&&(this._maximumWidth=o.maximumWidth),(typeof o.maximumHeight=="number"||typeof o.maximumHeight=="function")&&(this._maximumHeight=o.maximumHeight),this._onDidChange.fire(void 0)}),this.api.onDidSizeChange(o=>{this._onDidChange.fire({height:o.height,width:o.width})}),this._onDidChange)}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}init(e){e.maximumHeight&&(this._maximumHeight=e.maximumHeight),e.minimumHeight&&(this._minimumHeight=e.minimumHeight),e.maximumWidth&&(this._maximumWidth=e.maximumWidth),e.minimumWidth&&(this._minimumWidth=e.minimumWidth),this._priority=e.priority,this._snap=!!e.snap,super.init(e),typeof e.isVisible=="boolean"&&this.setVisible(e.isVisible)}updateConstraints(){this.api._onDidConstraintsChange.fire({minimumWidth:this._evaluatedMinimumWidth,maximumWidth:this._evaluatedMaximumWidth,minimumHeight:this._evaluatedMinimumHeight,maximumHeight:this._evaluatedMaximumHeight})}toJSON(){const e=super.toJSON(),t=s=>s===Number.MAX_SAFE_INTEGER?void 0:s,n=s=>s<=0?void 0:s;return pt(pt({},e),{},{minimumHeight:n(this.minimumHeight),maximumHeight:t(this.maximumHeight),minimumWidth:n(this.minimumWidth),maximumWidth:t(this.maximumWidth),snap:this.snap,priority:this.priority})}};const Ji="dockview: DockviewGroupPanelApiImpl not initialized";var lse=class extends _v{get location(){if(!this._group)throw new Error(Ji);return this._group.model.location}get boundingBox(){if(!this._group||this._group.model.location.type==="popout")return;const e=this.accessor.element.getBoundingClientRect(),t=this._group.element.getBoundingClientRect();return{left:t.left-e.left,top:t.top-e.top,width:t.width,height:t.height}}get locked(){if(!this._group)throw new Error(Ji);return this._group.locked}set locked(e){if(!this._group)throw new Error(Ji);this._group.locked=e}constructor(e,t){super(e,"__dockviewgroup__"),this.accessor=t,this._onDidLocationChange=new ve,this.onDidLocationChange=this._onDidLocationChange.event,this._onDidActivePanelChange=new ve,this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidCollapsedChange=new ve,this.onDidCollapsedChange=this._onDidCollapsedChange.event,this._onDidPeekChange=new ve,this.onDidPeekChange=this._onDidPeekChange.event,this._onDidHeaderDirectionChange=new ve,this.onDidHeaderDirectionChange=this._onDidHeaderDirectionChange.event,this.addDisposables(this._onDidLocationChange,this._onDidActivePanelChange,this._onDidCollapsedChange,this._onDidPeekChange,this._onDidHeaderDirectionChange,this._onDidVisibilityChange.event(n=>{n.isVisible&&this._pendingSize&&(super.setSize(this._pendingSize),this._pendingSize=void 0)}))}setSize(e){this._pendingSize=pt({},e),super.setSize(e)}close(){if(this._group)return this.accessor.removeGroup(this._group)}getWindow(){return this.location.type==="popout"?this.location.getWindow():globalThis.window}setHeaderPosition(e){if(!this._group)throw new Error(Ji);this._group.model.headerPosition=e}getHeaderPosition(){if(!this._group)throw new Error(Ji);return this._group.model.headerPosition}moveTo(e){if(!this._group)throw new Error(Ji);this.accessor.withOrigin("api",()=>{var t,n,s,o;const r=(t=e.group)!==null&&t!==void 0?t:this.accessor.addGroup({direction:xne((n=e.position)!==null&&n!==void 0?n:"right"),skipSetActive:(s=e.skipSetActive)!==null&&s!==void 0?s:!1});this.accessor.moveGroupOrPanel({from:{groupId:this._group.id},to:{group:r,position:e.group&&(o=e.position)!==null&&o!==void 0?o:"center",index:e.index},skipSetActive:e.skipSetActive})})}maximize(){if(!this._group)throw new Error(Ji);this.location.type==="grid"&&this.accessor.maximizeGroup(this._group)}isMaximized(){if(!this._group)throw new Error(Ji);return this.accessor.isMaximizedGroup(this._group)}exitMaximized(){if(!this._group)throw new Error(Ji);this.isMaximized()&&this.accessor.exitMaximizedGroup()}collapse(){this._group&&this.accessor.setEdgeGroupCollapsed(this._group,!0)}expand(){this._group&&this.accessor.setEdgeGroupCollapsed(this._group,!1)}isCollapsed(){return this._group?this.accessor.isEdgeGroupCollapsed(this._group):!1}isPeeking(){return this._group?this.accessor.isEdgeGroupPeeking(this._group):!1}setAutoHide(e){this._group&&this.accessor.setEdgeGroupAutoHide(this._group,e)}isAutoHide(){return this._group?this.accessor.isEdgeGroupAutoHide(this._group):!1}initialize(e){this._group=e}};const dse=100,cse=100;var cc=class extends RE{get minimumWidth(){var e;if(typeof this._explicitConstraints.minimumWidth=="number")return this._explicitConstraints.minimumWidth;const t=(e=this.activePanel)===null||e===void 0?void 0:e.minimumWidth;return typeof t=="number"?t:super.__minimumWidth()}get minimumHeight(){var e;if(typeof this._explicitConstraints.minimumHeight=="number")return this._explicitConstraints.minimumHeight;const t=(e=this.activePanel)===null||e===void 0?void 0:e.minimumHeight;return typeof t=="number"?t:super.__minimumHeight()}get maximumWidth(){var e;if(typeof this._explicitConstraints.maximumWidth=="number")return this._explicitConstraints.maximumWidth;const t=(e=this.activePanel)===null||e===void 0?void 0:e.maximumWidth;return typeof t=="number"?t:super.__maximumWidth()}get maximumHeight(){var e;if(typeof this._explicitConstraints.maximumHeight=="number")return this._explicitConstraints.maximumHeight;const t=(e=this.activePanel)===null||e===void 0?void 0:e.maximumHeight;return typeof t=="number"?t:super.__maximumHeight()}get panels(){return this._model.panels}get activePanel(){return this._model.activePanel}get size(){return this._model.size}get model(){return this._model}get locked(){return this._model.locked}set locked(e){this._model.locked=e}get header(){return this._model.header}constructor(e,t,n){var s,o,r,a,l,d;super(t,"groupview_default",{minimumHeight:(s=(o=n.constraints)===null||o===void 0?void 0:o.minimumHeight)!==null&&s!==void 0?s:cse,minimumWidth:(r=(a=n.constraints)===null||a===void 0?void 0:a.minimumWidth)!==null&&r!==void 0?r:dse,maximumHeight:(l=n.constraints)===null||l===void 0?void 0:l.maximumHeight,maximumWidth:(d=n.constraints)===null||d===void 0?void 0:d.maximumWidth},new lse(t,e)),this._explicitConstraints={},this.api.initialize(this),this._model=new ase(this.element,e,t,n,this),this.addDisposables(this.model.onDidActivePanelChange(c=>{this.api._onDidActivePanelChange.fire(c)}),this.api.onDidConstraintsChangeInternal(c=>{c.minimumWidth!==void 0&&(this._explicitConstraints.minimumWidth=typeof c.minimumWidth=="function"?c.minimumWidth():c.minimumWidth),c.minimumHeight!==void 0&&(this._explicitConstraints.minimumHeight=typeof c.minimumHeight=="function"?c.minimumHeight():c.minimumHeight),c.maximumWidth!==void 0&&(this._explicitConstraints.maximumWidth=typeof c.maximumWidth=="function"?c.maximumWidth():c.maximumWidth),c.maximumHeight!==void 0&&(this._explicitConstraints.maximumHeight=typeof c.maximumHeight=="function"?c.maximumHeight():c.maximumHeight)}))}focus(){this.api.isActive||this.api.setActive(),super.focus()}initialize(){this._model.initialize()}setActive(e){super.setActive(e),this.model.setActive(e)}layout(e,t){super.layout(e,t),this.model.layout(e,t)}relayout(){this.model.relayout()}getComponent(){return this._model}toJSON(){return this.model.toJSON()}};const use={name:"dark",className:"dockview-theme-dark",colorScheme:"dark"},hse={name:"light",className:"dockview-theme-light",colorScheme:"light"},pse={className:"dockview-theme-abyss",tabGroupIndicator:"none"};var fse=class extends _v{get location(){return this.group.api.location}get title(){return this.panel.title}get isPinned(){return this.panel.isPinned}get isGroupActive(){return this.group.isActive}get renderer(){return this.panel.renderer}set group(e){const t=this._group;this._group!==e&&(this._group=e,this._onDidGroupChange.fire({}),this.setupGroupEventListeners(t),this.fireLocationChange())}get group(){return this._group}get tabComponent(){return this._tabComponent}constructor(e,t,n,s,o){super(e.id,s),this.panel=e,this.accessor=n,this._onDidTitleChange=new ve,this.onDidTitleChange=this._onDidTitleChange.event,this._onDidChangePinned=new ve,this.onDidChangePinned=this._onDidChangePinned.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._onDidGroupChange=new ve,this.onDidGroupChange=this._onDidGroupChange.event,this._onDidRendererChange=new ve,this.onDidRendererChange=this._onDidRendererChange.event,this._onDidLocationChange=new ve,this.onDidLocationChange=this._onDidLocationChange.event,this.groupEventsDisposable=new Fn,this._tabComponent=o,this.initialize(e),this._group=t,this.setupGroupEventListeners(),this.addDisposables(this.groupEventsDisposable,this._onDidRendererChange,this._onDidTitleChange,this._onDidChangePinned,this._onDidGroupChange,this._onDidActiveGroupChange,this._onDidLocationChange)}getWindow(){return this.group.api.getWindow()}setActive(){this.accessor.withOrigin("api",()=>super.setActive())}moveTo(e){this.accessor.withOrigin("api",()=>{var t,n;return this.accessor.moveGroupOrPanel({from:{groupId:this._group.id,panelId:this.panel.id},to:{group:(t=e.group)!==null&&t!==void 0?t:this._group,position:e.group&&(n=e.position)!==null&&n!==void 0?n:"center",index:e.index},skipSetActive:e.skipSetActive})})}setTitle(e){this.panel.setTitle(e)}setPinned(e){this.accessor.setPanelPinned(this.panel,e)}setRenderer(e){this.panel.setRenderer(e)}close(){this.group.model.closePanel(this.panel)}maximize(){this.group.api.maximize()}isMaximized(){return this.group.api.isMaximized()}exitMaximized(){this.group.api.exitMaximized()}fireLocationChange(){this.accessor.deferLocationChange(this,()=>{this.isDisposed||this._onDidLocationChange.fire({location:this.location})})}setupGroupEventListeners(e){var t;let n=(t=e?.isActive)!==null&&t!==void 0?t:!1;this.groupEventsDisposable.value=new ct(this.group.api.onDidVisibilityChange(s=>{const o=!s.isVisible&&this.isVisible,r=s.isVisible&&!this.isVisible,a=this.group.model.isPanelActive(this.panel);(o||r&&a)&&this._onDidVisibilityChange.fire(s)}),this.group.api.onDidLocationChange(()=>{this.group===this.panel.group&&this.fireLocationChange()}),this.group.api.onDidActiveChange(()=>{this.group===this.panel.group&&n!==this.isGroupActive&&(n=this.isGroupActive,this._onDidActiveGroupChange.fire({isActive:this.isGroupActive}))}))}},Gr=class extends ct{get params(){return this._params}get title(){return this._title}get isPinned(){return this._pinned}get group(){return this._group}get renderer(){var e;return(e=this._renderer)!==null&&e!==void 0?e:this.accessor.renderer}get minimumWidth(){return this._minimumWidth}get minimumHeight(){return this._minimumHeight}get maximumWidth(){return this._maximumWidth}get maximumHeight(){return this._maximumHeight}constructor(e,t,n,s,o,r,a,l){super(),this.id=e,this.accessor=s,this.containerApi=o,this.view=a,this._pinned=!1,this._renderer=l.renderer,this._group=r,this._minimumWidth=l.minimumWidth,this._minimumHeight=l.minimumHeight,this._maximumWidth=l.maximumWidth,this._maximumHeight=l.maximumHeight,this.api=new fse(this,this._group,s,t,n),this.addDisposables(this.api.onActiveChange(()=>{s.setActivePanel(this)}),this.api.onDidSizeChange(d=>{this.group.api.setSize(d)}),this.api.onDidRendererChange(()=>{this.group.model.rerender(this)}))}init(e){this._params=e.params,this.view.init(pt(pt({},e),{},{api:this.api,containerApi:this.containerApi})),this.setTitle(e.title)}focus(){const e=new yE;this.api._onWillFocus.fire(e),!e.defaultPrevented&&(this.api.isActive||this.api.setActive())}toJSON(){return{id:this.id,contentComponent:this.view.contentComponent,tabComponent:this.view.tabComponent,params:Object.keys(this._params||{}).length>0?this._params:void 0,title:this.title,renderer:this._renderer,minimumHeight:this._minimumHeight,maximumHeight:this._maximumHeight,minimumWidth:this._minimumWidth,maximumWidth:this._maximumWidth,pinned:this._pinned?!0:void 0}}setTitle(e){e!==this.title&&(this._title=e,this.view.setTitle(e),this.api._onDidTitleChange.fire({title:e}))}setPinned(e){this._pinned!==e&&(this._pinned=e,this.api._onDidChangePinned.fire({isPinned:e}))}setRenderer(e){e!==this.renderer&&(this._renderer=e,this.api._onDidRendererChange.fire({renderer:e}))}update(e){this._params=pt(pt({},this._params),e.params);for(const t of Object.keys(e.params))e.params[t]===void 0&&delete this._params[t];this.view.update({params:this._params})}updateFromStateModel(e){var t,n,s,o,r;this._maximumHeight=e.maximumHeight,this._minimumHeight=e.minimumHeight,this._maximumWidth=e.maximumWidth,this._minimumWidth=e.minimumWidth,this._params=(t=e.params)!==null&&t!==void 0?t:{},this.view.update({params:this._params}),this.setTitle((n=e.title)!==null&&n!==void 0?n:this.id),this.setRenderer((s=e.renderer)!==null&&s!==void 0?s:this.accessor.renderer),this.setPinned(((o=e.pinned)!==null&&o!==void 0?o:!1)&&!!(!((r=this.accessor.options.pinnedTabs)===null||r===void 0)&&r.enabled))}updateParentGroup(e,t){this._group=e,this.api.group=this._group;const n=this._group.model.isPanelActive(this),s=this.group.api.isActive&&n;t?.skipSetActive||this.api.isActive!==s&&this.api._onDidActiveChange.fire({isActive:this.group.api.isActive&&n}),this.api.isVisible!==n&&this.api._onDidVisibilityChange.fire({isVisible:n})}runEvents(){const e=this._group.model.isPanelActive(this),t=this.group.api.isActive&&e;this.api.isActive!==t&&this.api._onDidActiveChange.fire({isActive:this.group.api.isActive&&e}),this.api.isVisible!==e&&this.api._onDidVisibilityChange.fire({isVisible:e})}layout(e,t){this.api._onDidDimensionChange.fire({width:e,height:t}),this.view.layout(e,t)}dispose(){this.api.dispose(),this.view.dispose()}},pC=class extends ct{get element(){return this._element}constructor(){super(),this._messages=zu,this._element=document.createElement("div"),this._element.className="dv-default-tab",this._content=document.createElement("div"),this._content.className="dv-default-tab-content",this.action=document.createElement("div"),this.action.className="dv-default-tab-action",this.action.setAttribute("role","button"),this.action.setAttribute("tabindex","-1");const e=One();e.setAttribute("aria-hidden","true"),this.action.appendChild(e),this._element.appendChild(this._content),this._element.appendChild(this.action),this.render()}init(e){var t;this._title=e.title,this._messages=(t=e.containerApi.messages)!==null&&t!==void 0?t:zu,this.addDisposables(e.api.onDidTitleChange(n=>{this._title=n.title,this.render()}),ot(this.action,"pointerdown",n=>{n.preventDefault()}),ot(this.action,"click",n=>{n.defaultPrevented||(n.preventDefault(),e.api.close())})),this.render()}render(){if(this._content.textContent!==this._title){var e;this._content.textContent=(e=this._title)!==null&&e!==void 0?e:""}this.action.setAttribute("aria-label",this._title?this._messages.closeTab(this._title):this._messages.closeTabPlain())}},LE=class{get content(){return this._content}get tab(){return this._tab}constructor(e,t,n,s){this.accessor=e,this.id=t,this.contentComponent=n,this.tabComponent=s,this._content=this.createContentComponent(this.id,n),this._tab=this.createTabComponent(this.id,s)}createTabRenderer(e){const t=this.createTabComponent(this.id,this.tabComponent);if(this._params&&t.init(pt(pt({},this._params),{},{tabLocation:e})),this._updateEvent){var n;(n=t.update)===null||n===void 0||n.call(t,this._updateEvent)}return t}init(e){this._params=e,this.content.init(e),this.tab.init(pt(pt({},e),{},{tabLocation:"header"}))}setTitle(e){this._params&&(this._params.title=e)}layout(e,t){var n,s;(n=(s=this.content).layout)===null||n===void 0||n.call(s,e,t)}update(e){var t,n,s,o;this._updateEvent=e,(t=(n=this.content).update)===null||t===void 0||t.call(n,e),(s=(o=this.tab).update)===null||s===void 0||s.call(o,e)}dispose(){var e,t,n,s;(e=(t=this.content).dispose)===null||e===void 0||e.call(t),(n=(s=this.tab).dispose)===null||n===void 0||n.call(s)}createContentComponent(e,t){return this.accessor.options.createComponent({id:e,name:t})}createTabComponent(e,t){const n=t??this.accessor.options.defaultTabComponent;if(n){if(this.accessor.options.createTabComponent){const s=this.accessor.options.createTabComponent({id:e,name:n});return s||new pC}console.warn(`dockview: tabComponent '${t}' was not found. falling back to the default tab.`)}return new pC}},mse=class{constructor(e){this.accessor=e}fromJSON(e,t){var n,s,o;const r=e.id,a=e.params,l=e.title,d=e.view,c=d?d.content.id:(n=e.contentComponent)!==null&&n!==void 0?n:"unknown",u=d?(s=d.tab)===null||s===void 0?void 0:s.id:e.tabComponent,h=new LE(this.accessor,r,c,u),p=new Gr(r,c,u,this.accessor,new bv(this.accessor),t,h,{renderer:e.renderer,minimumWidth:e.minimumWidth,minimumHeight:e.minimumHeight,maximumWidth:e.maximumWidth,maximumHeight:e.maximumHeight});return p.init({title:l??r,params:a??{}}),e.pinned&&(!((o=this.accessor.options.pinnedTabs)===null||o===void 0)&&o.enabled)&&p.setPinned(!0),p}},gse=class extends ct{get element(){return this._element}constructor(){super(),this._element=document.createElement("div"),this._element.className="dv-watermark"}init(t){}},xse=class{constructor(){this._orderedList=[]}push(e){this._orderedList=[...this._orderedList.filter(t=>t!==e),e],this.update()}destroy(e){this._orderedList=this._orderedList.filter(t=>t!==e),this.update()}update(){for(let e=0;e<this._orderedList.length;e++)this._orderedList[e].setAttribute("aria-level",`${e}`),this._orderedList[e].style.zIndex=`calc(var(--dv-overlay-z-index, 999) + ${e*2})`}};const uc=new xse;var Nv=class ir extends ct{set minimumInViewportWidth(t){this.options.minimumInViewportWidth=t}set minimumInViewportHeight(t){this.options.minimumInViewportHeight=t}get element(){return this._element}get isVisible(){return this._isVisible}get headerHeight(){var t,n;return(t=(n=this.options.header)===null||n===void 0?void 0:n.offsetHeight)!==null&&t!==void 0?t:0}constructor(t){super(),this.options=t,this._element=document.createElement("div"),this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this._onDidChangeEnd=new ve,this.onDidChangeEnd=this._onDidChangeEnd.event,this._onDidStartMoving=new ve,this.onDidStartMoving=this._onDidStartMoving.event,this._dragMove=new Fn,this._dragCancelled=!1,this.addDisposables(this._onDidChange,this._onDidChangeEnd,this._onDidStartMoving,this._dragMove),this._element.className="dv-resize-container",this._element.setAttribute("role","dialog"),this._element.setAttribute("aria-modal","false"),this._isVisible=!0,this.setupResize("top"),this.setupResize("bottom"),this.setupResize("left"),this.setupResize("right"),this.setupResize("topleft"),this.setupResize("topright"),this.setupResize("bottomleft"),this.setupResize("bottomright"),this.options.header&&(Ze(this._element,"dv-resize-container-with-titlebar",!0),this._element.appendChild(this.options.header)),this._element.appendChild(this.options.content),this.options.container.appendChild(this._element),this.setBounds(pt(pt(pt(pt({height:this.options.height,width:this.options.width},"top"in this.options&&{top:this.options.top}),"bottom"in this.options&&{bottom:this.options.bottom}),"left"in this.options&&{left:this.options.left}),"right"in this.options&&{right:this.options.right})),uc.push(this._element)}setVisible(t){t!==this.isVisible&&(this._isVisible=t,Ze(this.element,"dv-hidden",!this.isVisible))}bringToFront(){uc.push(this._element)}setBounds(t={}){typeof t.height=="number"&&(this._element.style.height=`${t.height}px`),typeof t.width=="number"&&(this._element.style.width=`${t.width}px`),"top"in t&&typeof t.top=="number"&&(this._element.style.top=`${t.top}px`,this._element.style.bottom="auto",this.verticalAlignment="top"),"bottom"in t&&typeof t.bottom=="number"&&(this._element.style.bottom=`${t.bottom}px`,this._element.style.top="auto",this.verticalAlignment="bottom"),"left"in t&&typeof t.left=="number"&&(this._element.style.left=`${t.left}px`,this._element.style.right="auto",this.horiziontalAlignment="left"),"right"in t&&typeof t.right=="number"&&(this._element.style.right=`${t.right}px`,this._element.style.left="auto",this.horiziontalAlignment="right");const n=this.options.container.getBoundingClientRect(),s=this._element.getBoundingClientRect(),o=Math.max(0,this.getMinimumWidth(s.width)),r=Math.max(0,this.getMinimumHeight(s.height));if(this.verticalAlignment==="top"){const a=En(s.top-n.top,-r,Math.max(0,n.height-s.height+r));this._element.style.top=`${a}px`,this._element.style.bottom="auto"}if(this.verticalAlignment==="bottom"){const a=En(n.bottom-s.bottom,-r,Math.max(0,n.height-s.height+r));this._element.style.bottom=`${a}px`,this._element.style.top="auto"}if(this.horiziontalAlignment==="left"){const a=En(s.left-n.left,-o,Math.max(0,n.width-s.width+o));this._element.style.left=`${a}px`,this._element.style.right="auto"}if(this.horiziontalAlignment==="right"){const a=En(n.right-s.right,-o,Math.max(0,n.width-s.width+o));this._element.style.right=`${a}px`,this._element.style.left="auto"}this._onDidChange.fire()}toJSON(){const t=this.options.container.getBoundingClientRect(),n=this._element.getBoundingClientRect(),s={};return this.verticalAlignment==="top"?s.top=Number.parseFloat(this._element.style.top):this.verticalAlignment==="bottom"?s.bottom=Number.parseFloat(this._element.style.bottom):s.top=n.top-t.top,this.horiziontalAlignment==="left"?s.left=Number.parseFloat(this._element.style.left):this.horiziontalAlignment==="right"?s.right=Number.parseFloat(this._element.style.right):s.left=n.left-t.left,s.width=n.width,s.height=n.height,s}cancelPendingDrag(){this._dragMove.value&&(this._dragCancelled=!0,Ze(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=rn.NONE)}setupDrag(t,n){const s=(o,r)=>{var a,l,d;let c=null,u=!1;this._dragCancelled=!1;const h=this.options.transformDragPosition?(a=(l=(d=this.options).getSiblingBoxes)===null||l===void 0?void 0:l.call(d))!==null&&a!==void 0?a:[]:[],p=Jl();if(o&&typeof r=="number"&&typeof o.setPointerCapture=="function")try{o.setPointerCapture(r)}catch{}const f=()=>{Ze(this._element,"dv-resize-container-dragging",!1),this._dragMove.value=rn.NONE,this._onDidChangeEnd.fire()};this._dragMove.value=new ct({dispose:()=>{if(p.release(),o&&typeof r=="number"&&typeof o.releasePointerCapture=="function")try{o.releasePointerCapture(r)}catch{}}},ot(globalThis.window,"pointermove",g=>{var x;if(this._dragCancelled)return;const v=this.options.container.getBoundingClientRect(),y=g.clientX-v.left,w=g.clientY-v.top;Ze(this._element,"dv-resize-container-dragging",!0);const b=this._element.getBoundingClientRect();(x=c)!==null&&x!==void 0||(c={x:g.clientX-b.left,y:g.clientY-b.top});const _=Math.max(0,this.getMinimumWidth(b.width)),j=Math.max(0,this.getMinimumHeight(b.height));let N=w-c.y,C=y-c.x;if(this.options.transformDragPosition){const $=this.options.transformDragPosition({proposed:{top:N,left:C,width:b.width,height:b.height},container:{width:v.width,height:v.height},others:h,modifiers:{altKey:g.altKey,ctrlKey:g.ctrlKey,metaKey:g.metaKey,shiftKey:g.shiftKey}});$&&(N=$.top,C=$.left)}const S=Math.max(0,v.height-b.height+j),A=Math.max(0,v.width-b.width+_),E=En(N,-j,S),I=En(v.height-b.height-N,-j,S),D=En(C,-_,A),T=En(v.width-b.width-C,-_,A),z={};E<=I?z.top=E:z.bottom=I,D<=T?z.left=D:z.right=T,this.setBounds(z),u||(u=!0,this._onDidStartMoving.fire())}),ot(globalThis.window,"pointerup",f),ot(globalThis.window,"pointercancel",f))};this.addDisposables(ot(t,"pointerdown",o=>{if(o.defaultPrevented){o.preventDefault();return}rC(o)||s(t,o.pointerId)}),ot(this.options.content,"pointerdown",o=>{o.defaultPrevented||rC(o)||o.shiftKey&&s(this.options.content,o.pointerId)}),ot(this.options.content,"pointerdown",()=>{uc.push(this._element)},!0)),n?.inDragMode&&s()}setupResize(t){const n=document.createElement("div");n.className=`dv-resize-handle-${t}`,this._element.appendChild(n);const s=new Fn;this.addDisposables(s,ot(n,"pointerdown",o=>{o.preventDefault();let r=null;const a=Jl(),l=o.pointerId;if(typeof n.setPointerCapture=="function")try{n.setPointerCapture(l)}catch{}const d=()=>{s.dispose(),this._onDidChangeEnd.fire()};s.value=new ct(ot(globalThis.window,"pointermove",c=>{var u;const h=this.options.container.getBoundingClientRect(),p=this._element.getBoundingClientRect(),f=c.clientY-h.top,g=c.clientX-h.left;(u=r)!==null&&u!==void 0||(r={originalY:f,originalHeight:p.height,originalX:g,originalWidth:p.width});let x,v,y,w,b,_;const j=()=>{const E=r.originalY+r.originalHeight>h.height?Math.max(0,h.height-ir.MINIMUM_HEIGHT):Math.max(0,r.originalY+r.originalHeight-ir.MINIMUM_HEIGHT);x=En(f,0,E),y=r.originalY+r.originalHeight-x,v=h.height-x-y},N=()=>{x=r.originalY-r.originalHeight;const E=x<0&&typeof this.options.minimumInViewportHeight=="number"?-x+this.options.minimumInViewportHeight:ir.MINIMUM_HEIGHT,I=h.height-Math.max(0,x);y=En(f-x,E,I),v=h.height-x-y},C=()=>{const E=r.originalX+r.originalWidth>h.width?Math.max(0,h.width-ir.MINIMUM_WIDTH):Math.max(0,r.originalX+r.originalWidth-ir.MINIMUM_WIDTH);w=En(g,0,E),_=r.originalX+r.originalWidth-w,b=h.width-w-_},S=()=>{w=r.originalX-r.originalWidth;const E=w<0&&typeof this.options.minimumInViewportWidth=="number"?-w+this.options.minimumInViewportWidth:ir.MINIMUM_WIDTH,I=h.width-Math.max(0,w);_=En(g-w,E,I),b=h.width-w-_};switch(t){case"top":j();break;case"bottom":N();break;case"left":C();break;case"right":S();break;case"topleft":j(),C();break;case"topright":j(),S();break;case"bottomleft":N(),C();break;case"bottomright":N(),S();break}const A={};x<=v?A.top=x:A.bottom=v,w<=b?A.left=w:A.right=b,A.height=y,A.width=_,this.setBounds(A)}),{dispose:()=>{if(a.release(),typeof n.releasePointerCapture=="function")try{n.releasePointerCapture(l)}catch{}}},ot(globalThis.window,"pointerup",d),ot(globalThis.window,"pointercancel",d))}))}getMinimumWidth(t){return typeof this.options.minimumInViewportWidth=="number"?t-this.options.minimumInViewportWidth:0}getMinimumHeight(t){return typeof this.options.minimumInViewportHeight=="number"?t-this.options.minimumInViewportHeight:0}dispose(){uc.destroy(this._element),this._element.remove(),super.dispose()}};Nv.MINIMUM_HEIGHT=20;Nv.MINIMUM_WIDTH=20;var vse=class extends ct{get element(){return this._element}get group(){return this._group}setGroup(e){this._group=e}constructor(e,t){super(),this.accessor=e,this._onDragStart=new ve,this.onDragStart=this._onDragStart.event,this._group=t,this._element=document.createElement("div"),this._element.className="dv-floating-titlebar",this.addDisposables(this._onDragStart,ot(this._element,"pointerdown",()=>{this.accessor.doSetGroupActive(this._group)}),ot(this._element,"pointerdown",n=>{n.shiftKey&&sE(n)},!0)),this.dragSource=new _E({element:this._element,accessor:this.accessor,group:()=>this._group}),this.addDisposables(this.dragSource,this.dragSource.onDragStart(n=>{this._onDragStart.fire(n)}))}updateDragAndDropState(){this.dragSource.updateDragAndDropState()}};function yo(e){return{moduleName:e.name,options:e.options,services:{[e.serviceKey]:e.create},init:e.init?(t,n)=>e.init(t,n[e.serviceKey]):void 0,dependsOn:e.dependsOn}}const bse=new Set(["AdvancedOverflow","AutoEdgeGroup","AutoHideEdgeGroup","ContextMenu","DndCompass","KeyboardDocking","KeyboardNavigation","LayoutHistory","License","MultiRowTabs","PinnedTabs","SmartGuides"]),fC=new Set;function OE(e,t){const n=t===void 0?[]:[].concat(t),s=n.map(a=>`\`${a}\``).join(", "),o=n.length>1?"require":"requires",r=n.length?`${s} ${o} the "${e}" module`:`The "${e}" module is required`;return bse.has(e)?`dockview: ${r}, which ships in dockview-enterprise.
|
|
104
|
-
|
|
105
|
-
npm install dockview-enterprise
|
|
106
|
-
import 'dockview-enterprise'; // self-registers every enterprise module
|
|
107
|
-
`:`dockview: ${r}, but it is not registered.`}function zE(e,t){const n=`${e}|${(t===void 0?[]:[].concat(t)).join("|")}`;fC.has(n)||(fC.add(n),console.error(OE(e,t)))}function Ps(e,t,n){if(e!==void 0)return e;zE(t,n)}var wse=class{constructor(){this._modules=new Map,this._services={},this._initDisposables=[]}get services(){return this._services}register(e){if(!this._modules.has(e.moduleName)){if(e.dependsOn)for(const t of e.dependsOn)this.register(t);this._modules.set(e.moduleName,e)}}initialize(e){for(const t of this._modules.values())if(t.services)for(const[n,s]of Object.entries(t.services))this._services[n]=s(e)}postConstruct(e){for(const t of this._modules.values())t.init&&this._initDisposables.push(t.init(e,this._services))}has(e){return this._modules.has(e)}dispose(){for(const e of this._initDisposables)e.dispose();this._initDisposables.length=0;for(const e of Object.values(this._services))e!==void 0&&typeof e.dispose=="function"&&e.dispose()}};const yse=[];function Sse(){return[...yse]}const Cse=[{optionKey:"smartGuides",reason:"smartGuides",moduleName:"SmartGuides",when:e=>!!e.smartGuides&&e.smartGuides.enabled!==!1},{optionKey:"layoutHistory",reason:"layoutHistory.enabled: true",moduleName:"LayoutHistory",when:e=>{var t;return((t=e.layoutHistory)===null||t===void 0?void 0:t.enabled)===!0}},{optionKey:"pinnedTabs",reason:"pinnedTabs.enabled: true",moduleName:"PinnedTabs",when:e=>{var t;return((t=e.pinnedTabs)===null||t===void 0?void 0:t.enabled)===!0}},{optionKey:"overflow",reason:"overflow.mode: 'wrap'",moduleName:"MultiRowTabs",when:e=>{var t;return((t=e.overflow)===null||t===void 0?void 0:t.mode)==="wrap"}},{optionKey:"overflow",reason:"overflow.maxRows",moduleName:"MultiRowTabs",when:e=>{var t;return((t=e.overflow)===null||t===void 0?void 0:t.maxRows)!=null}},{optionKey:"overflow",reason:"overflow.search",moduleName:"AdvancedOverflow",when:e=>{var t;return!!(!((t=e.overflow)===null||t===void 0)&&t.search)}},{optionKey:"overflow",reason:"overflow.mru",moduleName:"AdvancedOverflow",when:e=>{var t;return!!(!((t=e.overflow)===null||t===void 0)&&t.mru)}},{optionKey:"autoHideEdgeGroups",reason:"autoHideEdgeGroups",moduleName:"AutoHideEdgeGroup",when:e=>eg(e.autoHideEdgeGroups)},{optionKey:"dockToEdgeGroups",reason:"dockToEdgeGroups",moduleName:"AutoEdgeGroup",when:e=>eg(e.dockToEdgeGroups)},{optionKey:"getTabContextMenuItems",reason:"getTabContextMenuItems",moduleName:"ContextMenu",when:e=>e.getTabContextMenuItems!=null},{optionKey:"getTabGroupChipContextMenuItems",reason:"getTabGroupChipContextMenuItems",moduleName:"ContextMenu",when:e=>e.getTabGroupChipContextMenuItems!=null},{optionKey:"dndCompass",reason:"dndCompass",moduleName:"DndCompass",when:e=>!!e.dndCompass},{optionKey:"keyboardNavigation",reason:"keyboardNavigation",moduleName:"KeyboardNavigation",when:e=>!!e.keyboardNavigation}];function kse(e,t){const n=new Map;for(const s of Cse){if(!s.when(e)||t(s.moduleName))continue;const o=n.get(s.moduleName);o?o.push(s.reason):n.set(s.moduleName,[s.reason])}for(const[s,o]of n)zE(s,o)}const _o={left:100,top:100,width:300,height:300};var jse=class extends ct{get group(){return this._group}setTitleBar(e){this._titleBar=e}setAnchorGroup(e){var t;this._group=e,(t=this._titleBar)===null||t===void 0||t.setGroup(e)}constructor(e,t,n){super(),this.overlay=t,this.gridview=n,this._group=e,this.addDisposables(t,{dispose:()=>this.gridview.dispose()})}position(e){this.overlay.setBounds(e)}},_se=class{get floatingGroups(){return this._floatingGroups}constructor(e){this._floatingGroups=[],this._host=e}add(e,t,n){const s=new jse(e,t,n),o=new ct(e.api.onDidActiveChange(a=>{a.isActive&&t.bringToFront()}),(()=>{let a=-1,l=-1;return kr(n.element,d=>{const c=Math.round(d.contentRect.width),u=Math.round(d.contentRect.height);c===a&&u===l||(a=c,l=u,n.layout(c,u))})})()),r=()=>{var a;const l=(a=e.activePanel)===null||a===void 0?void 0:a.title;l?t.element.setAttribute("aria-label",l):t.element.removeAttribute("aria-label")};return r(),s.addDisposables(e.api.onDidActivePanelChange(()=>r()),t.onDidChange(()=>{n.layout(n.width,n.height)}),t.onDidChangeEnd(()=>{this._host.fireLayoutChange()}),e.onDidChange(a=>{t.setBounds({height:typeof a?.height=="number"?a.height+t.headerHeight:a?.height,width:a?.width})}),{dispose:()=>{o.dispose(),aE(this._floatingGroups,s),e.model.location={type:"grid"}}}),this._floatingGroups.push(s),s}findByGroup(e){return this._floatingGroups.find(t=>t.group===e||t.gridview.element.contains(e.element))}serialize(){return this._floatingGroups.map(e=>{const t=e.gridview.serialize(),n=e.overlay.toJSON(),s=t.root;return s.type==="branch"&&s.data.length===1&&s.data[0].type==="leaf"?{data:s.data[0].data,position:n}:{grid:t,position:n}})}constrainBounds(){for(const e of this._floatingGroups)e.overlay.setBounds()}updateBounds(e){if("floatingGroupBounds"in e)for(const s of this._floatingGroups){switch(e.floatingGroupBounds){case"boundedWithinViewport":s.overlay.minimumInViewportHeight=void 0,s.overlay.minimumInViewportWidth=void 0;break;case void 0:s.overlay.minimumInViewportHeight=100,s.overlay.minimumInViewportWidth=100;break;default:var t,n;s.overlay.minimumInViewportHeight=(t=e.floatingGroupBounds)===null||t===void 0?void 0:t.minimumHeightWithinViewport,s.overlay.minimumInViewportWidth=(n=e.floatingGroupBounds)===null||n===void 0?void 0:n.minimumWidthWithinViewport}s.overlay.setBounds()}}disposeAll(){for(const e of[...this._floatingGroups])e.dispose()}dispose(){this.disposeAll()}};const Nse=yo({name:"FloatingGroup",serviceKey:"floatingGroupService",create:e=>new _se(e)});var Tse=class{constructor(e){this._entries=[],this._restorationCleanups=new Set,this._restorationPromise=Promise.resolve(),this._onDidRemove=new ve,this.onDidRemove=this._onDidRemove.event,this._host=e}get entries(){return this._entries}get restorationPromise(){return this._restorationPromise}add(e){this._entries.push(e)}remove(e){aE(this._entries,e)&&!this._host.isDisposed&&this._onDidRemove.fire(e)}findByGroup(e){return this._entries.find(t=>t.popoutGroup===e||t.gridview.element.contains(e.element))}findReferenceGroupId(e){var t;return(t=this._entries.find(n=>n.popoutGroup===e))===null||t===void 0?void 0:t.referenceGroup}observeGridviewSize(e,t,n){var s;const o=(s=e.window)===null||s===void 0?void 0:s.ResizeObserver;if(!o)return;let r=-1,a=-1;const l=()=>{const c=e.window;if(this._host.isDisposed||!c||c.closed)return;const u=Math.round(t.element.clientWidth),h=Math.round(t.element.clientHeight);u===r&&h===a||(r=u,a=h,u>0&&h>0&&t.layout(u,h),n.updateAllPositions())},d=new o(()=>{var c;const u=(c=e.window)===null||c===void 0?void 0:c.requestAnimationFrame;u?u.call(e.window,l):l()});return d.observe(t.element),{dispose:()=>d.disconnect()}}scheduleRestoration(e,t,n){return new Promise(s=>{const o=()=>{this._restorationCleanups.delete(o),clearTimeout(r),n?.(),s()},r=setTimeout(()=>{if(this._restorationCleanups.delete(o),this._host.isDisposed){s();return}t(),s()},e);this._restorationCleanups.add(o)})}finishRestoration(e){this._restorationPromise=Promise.all(e).then(()=>{})}cancelPendingRestorations(){for(const e of[...this._restorationCleanups])e();this._restorationCleanups.clear()}serialize(){return this._entries.map(e=>{const t=e.gridview.serialize(),n=t.root,s=e.popoutGroup.api.location.type==="popout"?e.popoutGroup.api.location.popoutUrl:void 0,o={gridReferenceGroup:e.referenceGroup,position:e.window.dimensions(),url:s};return n.type==="branch"&&n.data.length===1&&n.data[0].type==="leaf"?pt(pt({},o),{},{data:n.data[0].data}):pt(pt({},o),{},{grid:t})})}disposeAll(){for(const e of[...this._entries])e.disposable.dispose()}dispose(){this.cancelPendingRestorations(),this.disposeAll(),this._onDidRemove.dispose()}};const Dse=yo({name:"PopoutWindow",serviceKey:"popoutWindowService",create:e=>new Tse(e)});var Ise=class{constructor(e){this._watermark=null,this._host=e}update(){if(this._host.hasVisibleGridGroup()){this._unmount();return}if(this._watermark)return;this._watermark=this._host.createWatermarkComponent(),this._watermark.init({containerApi:this._host.api});const e=document.createElement("div");e.className="dv-watermark-container",Kte(e,"watermark-component"),e.appendChild(this._watermark.element),this._host.mountElement.appendChild(e)}refresh(){this._unmount(),this.update()}_unmount(){var e,t;this._watermark&&(this._watermark.element.parentElement.remove(),(e=(t=this._watermark).dispose)===null||e===void 0||e.call(t),this._watermark=null)}dispose(){this._unmount()}};const Ese=yo({name:"Watermark",serviceKey:"watermarkService",create:e=>new Ise(e),init:(e,t)=>(t.update(),new ct(Qs.any(e.onDidAdd,e.onDidRemove)(()=>{t.update()}),e.onDidViewVisibilityChangeMicroTaskQueue(()=>{t.update()})))});var Pse=class{constructor(){this._edgeGroups=new Map,this._edgeGroupDisposables=new Map,this._autoHide=new WeakMap,this._autoReveal=new WeakMap}add(e,t,n){this._edgeGroups.set(e,t),this._edgeGroupDisposables.set(e,n)}remove(e){var t;(t=this._edgeGroupDisposables.get(e))===null||t===void 0||t.dispose(),this._edgeGroupDisposables.delete(e),this._edgeGroups.delete(e)}get(e){return this._edgeGroups.get(e)}has(e){return this._edgeGroups.has(e)}hasAny(){return this._edgeGroups.size>0}entries(){return this._edgeGroups.entries()}includes(e){for(const t of this._edgeGroups.values())if(t===e)return!0;return!1}findPositionOf(e){for(const[t,n]of this._edgeGroups)if(n===e)return t}setAutoHide(e,t){t===void 0?this._autoHide.delete(e):this._autoHide.set(e,t)}isAutoHide(e){return this._autoHide.get(e)}setAutoReveal(e,t){this._autoReveal.set(e,t)}isAutoReveal(e){var t;return(t=this._autoReveal.get(e))!==null&&t!==void 0?t:!1}disposeAll(){for(const e of this._edgeGroupDisposables.values())e.dispose();this._edgeGroupDisposables.clear(),this._edgeGroups.clear()}dispose(){this.disposeAll()}};const Ase=yo({name:"EdgeGroup",serviceKey:"edgeGroupService",create:()=>new Pse}),Mse={activationSize:{type:"pixels",value:10},size:{type:"pixels",value:20}},Rse={activationSize:{type:"pixels",value:32},size:{type:"pixels",value:20}};function mC(e,t){return typeof e.dndEdges=="object"&&e.dndEdges!==null?e.dndEdges:t&&eg(e.dockToEdgeGroups)?Rse:Mse}var Lse=class{constructor(e){this._host=e;const t=(s,o)=>{const r=Ln();return r?r.viewId!==e.id?!1:o==="center"?e.isGridEmpty():!0:o==="center"&&!e.isGridEmpty()?!1:e.dispatchUnhandledDragOver(s,o)},n=mC(e.options,!1);this._html5Target=zo.createDropTarget(e.element,{className:"dv-drop-target-edge",canDisplayOverlay:t,acceptedTargetZones:["top","bottom","left","right","center"],overlayModel:n,getOverrideTarget:()=>e.rootDropTargetOverrideTarget(),getPositionResolver:()=>e.options.dropPositionResolver}),this._pointerTarget=vo.createDropTarget(e.element,{className:"dv-drop-target-edge",canDisplayOverlay:t,acceptedTargetZones:["top","bottom","left","right","center"],overlayModel:n,getOverrideTarget:()=>e.rootDropTargetOverrideTarget(),getPositionResolver:()=>e.options.dropPositionResolver}),this.onWillShowOverlay=Qs.any(this._html5Target.onWillShowOverlay,this._pointerTarget.onWillShowOverlay),this.onDrop=Qs.any(this._html5Target.onDrop,this._pointerTarget.onDrop),this.setOptions(e.options)}setOptions(e){if("dndEdges"in e){const t=typeof e.dndEdges=="boolean"&&e.dndEdges===!1;this._html5Target.disabled=t,this._pointerTarget.disabled=t}if("dndEdges"in e||"dockToEdgeGroups"in e){const t=mC({dndEdges:"dndEdges"in e?e.dndEdges:this._host.options.dndEdges,dockToEdgeGroups:"dockToEdgeGroups"in e?e.dockToEdgeGroups:this._host.options.dockToEdgeGroups},this._host.hasEdgeDragReveal);this._html5Target.setOverlayModel(t),this._pointerTarget.setOverlayModel(t)}}dispose(){this._html5Target.dispose(),this._pointerTarget.dispose()}};const Ose=yo({name:"RootDropTarget",serviceKey:"rootDropTargetService",create:e=>new Lse(e),init:(e,t)=>(t.setOptions(e.options),rn.NONE)}),zse={left:"createLeftHeaderActionComponent",right:"createRightHeaderActionComponent",prefix:"createPrefixHeaderActionComponent"};var Gse=class{constructor(e){this._perGroup=new Map,this._host=e}refresh(e){if(!e?.model)return;const t=this._ensureState(e);this._refreshSlot("left",e,t.left),this._refreshSlot("right",e,t.right),this._refreshSlot("prefix",e,t.prefix)}refreshAll(){for(const e of this._host.groups)this.refresh(e)}disposeGroup(e){const t=this._perGroup.get(e);t&&(t.left.dispose(),t.right.dispose(),t.prefix.dispose(),this._perGroup.delete(e))}dispose(){for(const e of[...this._perGroup.keys()])this.disposeGroup(e)}_ensureState(e){let t=this._perGroup.get(e);return t||(t={left:new Fn,right:new Fn,prefix:new Fn},this._perGroup.set(e,t)),t}_refreshSlot(e,t,n){const s=this._host.options[zse[e]];if(s){const o=s(t);n.value=o,o.init({containerApi:this._host.api,api:t.api,group:t}),t.model.attachHeaderAction(e,o.element)}else n.dispose(),t.model.attachHeaderAction(e,void 0)}};const Fse=yo({name:"HeaderActions",serviceKey:"headerActionsService",create:e=>new Gse(e),init:(e,t)=>new ct(e.onDidRemoveGroup(n=>{t.disposeGroup(n)}))}),gC=e=>e==="load"||e==="clear";function hc(e,t){const n=e.createElement("div");return n.className=t==="assertive"?"dv-live-region-assertive":"dv-live-region",n.setAttribute("role",t==="assertive"?"alert":"status"),n.setAttribute("aria-live",t),n.setAttribute("aria-atomic","true"),Object.assign(n.style,{position:"absolute",width:"1px",height:"1px",margin:"-1px",padding:"0",overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:"0"}),n}var Hse=class extends ct{constructor(e){var t;super(),this._regions=new Map,this._suppressDepth=0,this._locationSubs=new Map,this._host=e;const n=e.element.ownerDocument;this._mainWindow=(t=n.defaultView)!==null&&t!==void 0?t:window;const s={polite:hc(n,"polite"),assertive:hc(n,"assertive")};e.element.appendChild(s.polite),e.element.appendChild(s.assertive),this._regions.set(this._mainWindow,s),this._syncPopoutRegions(),this.addDisposables({dispose:()=>this._disposeRegions()},e.onDidChangePopouts(()=>this._syncPopoutRegions()),e.onDidAddPanel(o=>this._announce(o,"open")),e.onDidRemovePanel(o=>this._announce(o,"close")),e.onWillMutateLayout(o=>{gC(o.kind)&&this._suppressDepth++}),e.onDidMutateLayout(o=>{gC(o.kind)&&(this._suppressDepth=Math.max(0,this._suppressDepth-1))}),e.onDidMaximizedGroupChange(o=>{const r=o.group.activePanel;r&&this._announce(r,o.isMaximized?"maximize":"restore")}),e.onDidAddGroup(o=>this._trackLocation(o)),e.onDidRemoveGroup(o=>{var r;(r=this._locationSubs.get(o.id))===null||r===void 0||r.dispose(),this._locationSubs.delete(o.id)}),{dispose:()=>{this._locationSubs.forEach(o=>o.dispose()),this._locationSubs.clear()}})}_syncPopoutRegions(){const e=this._host.element.ownerDocument,t=new Set([this._mainWindow]);for(const s of this._host.getPopoutWindows()){var n;if(s.document===e||(t.add(s),this._regions.has(s)))continue;const o=s.document,r=(n=o.body)!==null&&n!==void 0?n:o.documentElement,a={polite:hc(o,"polite"),assertive:hc(o,"assertive")};r.appendChild(a.polite),r.appendChild(a.assertive),this._regions.set(s,a)}for(const[s,o]of this._regions)t.has(s)||(o.polite.remove(),o.assertive.remove(),this._regions.delete(s))}_disposeRegions(){for(const e of this._regions.values())e.polite.remove(),e.assertive.remove();this._regions.clear()}_focusedRegions(){for(const[e,t]of this._regions)if(e!==this._mainWindow)try{if(e.document.hasFocus())return t}catch{}return this._regions.get(this._mainWindow)}_trackLocation(e){let t=e.api.location.type;const n=e.api.onDidLocationChange(s=>{const o=s.location.type;if(o===t)return;t=o;const r=e.activePanel;if(!r)return;let a;switch(o){case"floating":a="float";break;case"popout":a="popout";break;default:a="dock";break}this._announce(r,a)});this._locationSubs.set(e.id,n)}announce(e,t="polite"){if(this._host.options.announcements===!1||this._suppressDepth>0||!e)return;const n=this._host.options.announcer;if(n){n({message:e,politeness:t});return}const s=this._focusedRegions(),o=t==="assertive"?s.assertive:s.polite;o.textContent="",o.textContent=e}_announce(e,t){var n,s;const o=(n=(s=this._host.options).getAnnouncement)===null||n===void 0?void 0:n.call(s,{kind:t,panel:e});o===null||o===""||this.announce(o??this._defaultMessage(e,t))}_defaultMessage(e,t){var n;const s=uE(this._host.options.messages),o=(n=e.title)!==null&&n!==void 0?n:e.id;switch(t){case"open":return s.panelOpened(o);case"close":return s.panelClosed(o);case"maximize":return s.groupMaximized(o);case"restore":return s.groupRestored(o);case"float":return s.groupFloated(o);case"dock":return s.groupDocked(o);case"popout":return s.groupPoppedOut(o)}}};const Bse=yo({name:"LiveRegion",serviceKey:"liveRegionService",create:e=>new Hse(e)}),Vse=30,$se=-10;var Wse=class{constructor(e){this.host=e}dispatchWillDragPanel(e){this.host.fireWillDragPanel(e)}dispatchWillDragGroup(e){this.host.fireWillDragGroup(e)}dispatchWillDrop(e){this.host.fireWillDrop(e)}dispatchWillShowOverlay(e){this.host.fireWillShowOverlay(e)}buildGroupDragGhost(e){const t=this.host.options.createGroupDragGhostComponent;if(!t)return;const n=t(e);return n.init({group:e,api:this.host.api}),{element:n.element,offsetX:Vse,offsetY:$se,dispose:n.dispose?()=>{var s;return(s=n.dispose)===null||s===void 0?void 0:s.call(n)}:void 0}}resolveOverlayModel(e,t){var n,s;return(n=(s=this.host.options).dropOverlayModel)===null||n===void 0?void 0:n.call(s,{location:e,group:t})}showPreviewOverlay(e,t){const n=e.model.contentDropTarget;return n.showOverlay(t),rn.from(()=>n.clearOverlay())}dispose(){}};const Use=yo({name:"AdvancedDnD",serviceKey:"advancedDnDService",create:e=>new Wse(e)});var Kse=class{constructor(e){this._host=e}attachToGroup(e){return new ct(e.model.onDidCreateTabGroup(t=>{this._host.fireDidCreateTabGroup(t)}),e.model.onDidDestroyTabGroup(t=>{this._host.fireDidDestroyTabGroup(t)}),e.model.onDidAddPanelToTabGroup(t=>{this._host.fireDidAddPanelToTabGroup(t)}),e.model.onDidRemovePanelFromTabGroup(t=>{this._host.fireDidRemovePanelFromTabGroup(t)}),e.model.onDidTabGroupChange(t=>{this._host.fireDidTabGroupChange(t)}),e.model.onDidTabGroupCollapsedChange(t=>{this._host.fireDidTabGroupCollapsedChange(t)}))}dispose(){}};const qse=yo({name:"TabGroupChips",serviceKey:"tabGroupChipsService",create:e=>new Kse(e),init:(e,t)=>{const n=new Map;return new ct(e.onDidAddGroup(s=>{n.set(s,t.attachToGroup(s))}),e.onDidRemoveGroup(s=>{var o;(o=n.get(s))===null||o===void 0||o.dispose(),n.delete(s)}),{dispose:()=>{for(const s of n.values())s.dispose();n.clear()}})}}),Yse=[Nse,Dse,Ese,Ase,Ose,Fse,Bse,Use,qse];var Xse=class{constructor(){this.cache=new WeakMap,this.currentFrameId=0,this.rafId=null}getPosition(e){const t=this.cache.get(e);if(t?.frameId===this.currentFrameId)return t.rect;this.scheduleFrameUpdate();const n=Wm(e);return this.cache.set(e,{rect:n,frameId:this.currentFrameId}),n}invalidate(){this.currentFrameId++}scheduleFrameUpdate(){this.rafId||(this.rafId=requestAnimationFrame(()=>{this.currentFrameId++,this.rafId=null}))}};const xC=-1;function Zse(){const e=document.createElement("div");return e.tabIndex=-1,e}var vC=class extends ct{constructor(e,t){super(),this.element=e,this.accessor=t,this.map={},this._disposed=!1,this._generation=0,this.positionCache=new Xse,this.addDisposables(rn.from(()=>{for(const n of Object.values(this.map))n.disposable.dispose(),n.destroy.dispose(),this.cancelPendingUpdate(n);this._disposed=!0}))}updateAllPositions(){if(!this._disposed){this.positionCache.invalidate();for(const e of Object.values(this.map))e.panel.api.isVisible&&e.resize&&e.resize()}}repositionPanelOverlay(e,t=!1,n){var s;if(this._disposed)return;const o=this.map[e];o&&(o.forceVisible=t,o.clip=n,this.positionCache.invalidate(),(s=o.resize)===null||s===void 0||s.call(o))}cancelPendingUpdate(e){e.pendingUpdate!==void 0&&(cancelAnimationFrame(e.pendingUpdate),e.pendingUpdate=void 0)}detatch(e){if(this.map[e.api.id]){const t=this.map[e.api.id];return t.disposable.dispose(),t.destroy.dispose(),this.cancelPendingUpdate(t),delete this.map[e.api.id],!0}return!1}attach(e){const{panel:t,referenceContainer:n}=e;if(!this.map[t.api.id]){const p=Zse();p.className="dv-render-overlay",p.style.visibility="hidden",this.map[t.api.id]={panel:t,disposable:rn.NONE,destroy:rn.NONE,element:p,retainPreviousGeometry:!1,positioned:!1,generation:++this._generation}}const s=this.map[t.api.id];s.referenceContainer!==n&&(s.generation=++this._generation,this.cancelPendingUpdate(s),s.referenceContainer=n,s.retainPreviousGeometry=s.positioned);const o=s.generation,r=s.element,a=t.view.content.element;a.parentElement!==r&&r.appendChild(a),r.parentElement!==this.element&&this.element.appendChild(r);const l=()=>{const p=t.api.id,f=this.map[p];if(f?.generation!==o||f.pendingUpdate!==void 0)return;f.pendingUpdate=xC;const g=requestAnimationFrame(()=>{var x;const v=this.map[p];if(v&&(v.pendingUpdate=void 0),this.isDisposed||v?.generation!==o)return;const y=(x=v.forceVisible)!==null&&x!==void 0?x:!1,w=v.clip,b=this.positionCache.getPosition(n.element),_=this.positionCache.getPosition(this.element),j=b.left-_.left,N=b.top-_.top,C=b.width,S=b.height;if(v.retainPreviousGeometry&&(C===0||S===0)){!t.api.isVisible&&!y&&(r.style.visibility="hidden",r.style.pointerEvents="none");return}if(v.retainPreviousGeometry=!1,v.positioned=!0,r.style.left=`${j}px`,r.style.top=`${N}px`,r.style.width=`${C}px`,r.style.height=`${S}px`,t.api.isVisible||y?(r.style.visibility="",r.style.pointerEvents=""):(r.style.visibility="hidden",r.style.pointerEvents="none"),y?r.style.zIndex="1000":t.api.location.type!=="floating"&&(r.style.zIndex=""),w){var A,E;const I=this.element.ownerDocument.defaultView,D=(A=I?.scrollX)!==null&&A!==void 0?A:0,T=(E=I?.scrollY)!==null&&E!==void 0?E:0,z=w.top+T,$=w.left+D,R=Math.max(0,z-b.top),B=Math.max(0,$-b.left),H=Math.max(0,b.left+C-(w.right+D)),oe=Math.max(0,b.top+S-(w.bottom+T));r.style.clipPath=`inset(${R}px ${H}px ${oe}px ${B}px)`}else r.style.clipPath="";Ze(r,"dv-render-overlay-float",t.group.api.location.type==="floating")});f.pendingUpdate===xC&&(f.pendingUpdate=g)},d=()=>{if(t.api.isVisible){var p;this.positionCache.invalidate(),l(),!((p=this.map[t.api.id])===null||p===void 0)&&p.retainPreviousGeometry&&(r.style.visibility=""),r.style.pointerEvents=""}else r.style.visibility="hidden",r.style.pointerEvents="none"},c=new Fn,u=()=>{t.api.location.type==="floating"?queueMicrotask(()=>{const p=this.accessor.getFloatingWindowForGroup(t.api.group);if(!p)return;const f=p.overlay.element,g=()=>{const v=Number(f.getAttribute("aria-level"));r.style.zIndex=`calc(var(--dv-overlay-z-index, 999) + ${v*2+1})`},x=new MutationObserver(()=>{g()});c.value=rn.from(()=>x.disconnect()),x.observe(f,{attributeFilter:["aria-level"],attributes:!0}),g()}):r.style.zIndex=""},h=new ct(c,new fE(r,{onDragEnd:p=>{n.dropTarget.dnd.onDragEnd(p)},onDragEnter:p=>{n.dropTarget.dnd.onDragEnter(p)},onDragLeave:p=>{n.dropTarget.dnd.onDragLeave(p)},onDrop:p=>{n.dropTarget.dnd.onDrop(p)},onDragOver:p=>{n.dropTarget.dnd.onDragOver(p)}}),t.api.onDidVisibilityChange(()=>{d()}),t.api.onDidDimensionsChange(()=>{t.api.isVisible&&l()}),t.api.onDidLocationChange(()=>{u()}));return this.map[t.api.id].destroy=rn.from(()=>{a.parentElement===r&&a.remove(),r.remove()}),u(),queueMicrotask(()=>{this.isDisposed||d()}),this.map[t.api.id].disposable.dispose(),this.map[t.api.id].disposable=h,this.map[t.api.id].resize=l,r}};function bC(e,t,n,s,o,r,a){try{var l=e[r](a),d=l.value}catch(c){n(c);return}l.done?t(d):Promise.resolve(d).then(s,o)}function GE(e){return function(){var t=this,n=arguments;return new Promise(function(s,o){var r=e.apply(t,n);function a(d){bC(r,s,o,a,l,"next",d)}function l(d){bC(r,s,o,a,l,"throw",d)}a(void 0)})}}function Jse(e){let t;try{t=new URL(e,globalThis.location.href)}catch{throw new Error(`dockview: invalid popout URL: ${e}`)}if(!(t.protocol==="http:"||t.protocol==="https:")||t.origin!==globalThis.location.origin)throw new Error(`dockview: popout URL must be same-origin http(s); got: ${e}`)}var Qse=class extends ct{get window(){var e,t;return(e=(t=this._window)===null||t===void 0?void 0:t.value)!==null&&e!==void 0?e:null}constructor(e,t,n){super(),this.target=e,this.className=t,this.options=n,this._onWillClose=new ve,this.onWillClose=this._onWillClose.event,this._onDidClose=new ve,this.onDidClose=this._onDidClose.event,this._window=null,this.addDisposables(this._onWillClose,this._onDidClose,{dispose:()=>{this.close()}})}dimensions(){if(!this._window)return null;const e=this._window.value.screenX;return{top:this._window.value.screenY,left:e,width:this._window.value.innerWidth,height:this._window.value.innerHeight}}close(){if(this._window){var e,t;this._onWillClose.fire(),(e=(t=this.options).onWillClose)===null||e===void 0||e.call(t,{id:this.target,window:this._window.value}),this._window.disposable.dispose(),this._window=null,this._onDidClose.fire()}}open(){var e=this;return GE(function*(){var t,n;if(e._window)throw new Error("instance of popout window is already open");const s=`${e.options.url}`;Jse(s);const o=Object.entries({top:e.options.top,left:e.options.left,width:e.options.width,height:e.options.height}).map(([d,c])=>`${d}=${c}`).join(","),r=window.open(s,e.target,o);if(!r)return null;const a=new ct;e._window={value:r,disposable:a},a.addDisposables(rn.from(()=>{r.close()}),ot(globalThis.window,"beforeunload",()=>{e.close()}));const l=e.createPopoutWindowContainer();return e.className&&l.classList.add(e.className),(t=(n=e.options).onDidOpen)===null||t===void 0||t.call(n,{id:e.target,window:r}),new Promise((d,c)=>{r.addEventListener("unload",()=>{}),a.addDisposables(e.onWillClose(()=>d(null))),r.addEventListener("load",()=>{try{const u=r.document;u.title=document.title,u.body.appendChild(l),Ute(u,globalThis.document.styleSheets,{nonce:e.options.nonce}),ot(r,"beforeunload",()=>{e.close()}),d(l)}catch(u){c(u)}})})})()}createPopoutWindowContainer(){const e=document.createElement("div");return e.classList.add("dv-popout-window"),e.id="dv-popout-window",e.style.position="absolute",e.style.width="100%",e.style.height="100%",e.style.top="0px",e.style.left="0px",e}},eie=class extends ct{constructor(e){super(),this.accessor=e,this.init()}init(){const e=new Set,t=new Set;this.addDisposables(this.accessor.onDidAddPanel(n=>{if(e.has(n.api.id))throw new Error(`dockview: Invalid event sequence. [onDidAddPanel] called for panel ${n.api.id} but panel already exists`);e.add(n.api.id)}),this.accessor.onDidRemovePanel(n=>{if(e.has(n.api.id))e.delete(n.api.id);else throw new Error(`dockview: Invalid event sequence. [onDidRemovePanel] called for panel ${n.api.id} but panel does not exists`)}),this.accessor.onDidAddGroup(n=>{if(t.has(n.api.id))throw new Error(`dockview: Invalid event sequence. [onDidAddGroup] called for group ${n.api.id} but group already exists`);t.add(n.api.id)}),this.accessor.onDidRemoveGroup(n=>{if(t.has(n.api.id))t.delete(n.api.id);else throw new Error(`dockview: Invalid event sequence. [onDidRemoveGroup] called for group ${n.api.id} but group does not exists`)}))}};function tie(e){if(!e.matchMedia)return!1;const t=e.matchMedia("(pointer: coarse)").matches,n=e.matchMedia("(pointer: fine)").matches;return t&&!n}function nie(e){var t,n,s,o,r,a,l;const d=(t=e.window)!==null&&t!==void 0?t:window,c=(n=e.capture)!==null&&n!==void 0?n:!1,u=(s=e.escape)!==null&&s!==void 0?s:!0,h=(o=e.keys)!==null&&o!==void 0?o:[],p=(r=e.outsidePointerDown)!==null&&r!==void 0?r:!0,f=(a=e.pointerDownGraceMs)!==null&&a!==void 0?a:0,g=(l=e.now)!==null&&l!==void 0?l:Date.now,x=g(),v=new ct,y=w=>{var b,_;if(e.isInside)return e.isInside(w);const j=w.target;return j instanceof Node?((b=(_=e.elements)===null||_===void 0?void 0:_.call(e))!==null&&b!==void 0?b:[]).some(N=>N.contains(j)):!1};if((u||h.length>0)&&v.addDisposables(ot(d,"keydown",w=>{(u&&w.key==="Escape"||h.includes(w.key))&&e.onDismiss()},c)),(p||e.onInsidePointerDown)&&v.addDisposables(ot(d,"pointerdown",w=>{if(y(w)){var b;(b=e.onInsidePointerDown)===null||b===void 0||b.call(e,w);return}!p||g()-x<f||e.onDismiss()},c)),e.resize&&v.addDisposables(ot(d,"resize",()=>{tie(d)||e.onDismiss()})),e.focusOut){const w=_=>{var j,N;return e.isFocusInside?e.isFocusInside(_):((j=(N=e.elements)===null||N===void 0?void 0:N.call(e))!==null&&j!==void 0?j:[]).some(C=>C.contains(_))},b=_=>{const j=_.target;j instanceof Element&&!w(j)&&e.onDismiss()};d.addEventListener("focusin",b,c),v.addDisposables({dispose:()=>d.removeEventListener("focusin",b,c)})}return v}var wC=class extends ct{constructor(e,t=globalThis.window){super(),this._active=null,this._activeDisposable=new Fn,this._root=e,this._window=t,this._element=t.document.createElement("div"),this._element.className="dv-popover-anchor",this._element.style.position="relative",this._root.prepend(this._element),this.addDisposables(rn.from(()=>{this.close()}),this._activeDisposable)}updateRoot(e){e.prepend(this._element),this._root=e}openPopover(e,t){var n;this.close();const s=this._window.document.createElement("div");s.style.position="absolute",s.style.zIndex=(n=t.zIndex)!==null&&n!==void 0?n:"var(--dv-overlay-z-index)",s.appendChild(e);const o=this._element.getBoundingClientRect(),r=o.left,a=o.top;s.style.top=`${t.y-a}px`,s.style.left=`${t.x-r}px`,this._element.appendChild(s),this._active=s;const l=200;this._activeDisposable.value=nie({window:this._window,onDismiss:()=>this.close(),elements:()=>this._active?[this._active]:[],keys:["Enter"],pointerDownGraceMs:l,resize:!0}),this._window.requestAnimationFrame(()=>{Jte(s,this._root)})}close(){this._active&&(this._active.remove(),this._activeDisposable.dispose(),this._active=null)}},af=class extends ct{get disabled(){return this._disabled}set disabled(e){this.disabled!==e&&(this._disabled=e,e&&this._clearNow())}_cancelPendingClear(){this._pendingClear!==void 0&&(clearTimeout(this._pendingClear),this._pendingClear=void 0)}_clearNow(){this._cancelPendingClear(),this._model&&this._model.root.remove(),this._model=void 0}get model(){if(!this.disabled)return{clear:()=>{this._clearNow()},scheduleClear:()=>{this._pendingClear!==void 0||!this._model||(this._pendingClear=setTimeout(()=>{this._pendingClear=void 0,this._clearNow()},0))},exists:()=>!!this._model,getElements:(e,t)=>{this._cancelPendingClear();const n=this._outline!==t;if(this._outline=t,this._model)return this._model.changed=n,this._model;const s=this.createContainer(),o=this.createAnchor();if(this._model={root:s,overlay:o,changed:n},s.appendChild(o),this.element.appendChild(s),e?.target instanceof HTMLElement){const r=e.target.getBoundingClientRect(),a=this.element.getBoundingClientRect();o.style.left=`${r.left-a.left}px`,o.style.top=`${r.top-a.top}px`}return this._model}}}constructor(e,t){super(),this.element=e,this._disabled=!1,this._disabled=t.disabled,this.addDisposables(rn.from(()=>{var n;(n=this.model)===null||n===void 0||n.clear()}))}createContainer(){const e=document.createElement("div");return e.className="dv-drop-target-container",e}createAnchor(){const e=document.createElement("div");return e.className="dv-drop-target-anchor",e.style.visibility="hidden",e}},sie=class{get _effectiveBaseCollapsed(){var e;return(e=this._measuredTabSize)!==null&&e!==void 0?e:this._baseCollapsedSize}get minimumSize(){return this._isCollapsed?this.collapsedSize:this._baseMinimumSize!==void 0?this._baseMinimumSize+this._gapAdd:this._effectiveBaseCollapsed+50+this._gapAdd}get maximumSize(){return this._isCollapsed?this.collapsedSize:this._expandedMaximumSize}get element(){return this._group.element}get isCollapsed(){return this._isCollapsed}get lastExpandedSize(){return this._lastExpandedSize}get collapsedSize(){return this._effectiveBaseCollapsed+this._gapAdd}get configuredMinimumSize(){return this._baseMinimumSize}get configuredMaximumSize(){return this._expandedMaximumSize}get configuredCollapsedSize(){return this._baseCollapsedSize}constructor(e,t,n,s=0){var o,r,a;this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.snap=!1,this.priority="low",this._isCollapsed=!1,this._tabSizeDisposables=new ct,this._group=t,this._orientation=n,t.element.classList.add("dv-edge-group"),t.element.dataset.testid=`dv-edge-group-${e.id}`,this._baseCollapsedSize=(o=e.collapsedSize)!==null&&o!==void 0?o:35,this._baseMinimumSize=e.minimumSize,this._gapAdd=s,this._expandedMaximumSize=(r=e.maximumSize)!==null&&r!==void 0?r:Number.POSITIVE_INFINITY,this._lastExpandedSize=(a=e.initialSize)!==null&&a!==void 0?a:200,e.collapsed&&(this._isCollapsed=!0,t.element.classList.add("dv-edge-collapsed")),this._observeTabStrip()}_observeTabStrip(){const e=this._group.element.querySelector(".dv-tabs-and-actions-container");e&&this._tabSizeDisposables.addDisposables(kr(e,()=>{this._applyMeasuredTabSize(this._orientation==="vertical"?e.offsetHeight:e.offsetWidth)}))}_applyMeasuredTabSize(e){e<=0||e===this._measuredTabSize||(this._measuredTabSize=e,this._isCollapsed&&this._onDidChange.fire({size:this.collapsedSize}))}layout(e,t){this._isCollapsed||(this._lastExpandedSize=e),this._orientation==="horizontal"?this._group.layout(e,t):this._group.layout(t,e)}setCollapsed(e){this._isCollapsed!==e&&(this._isCollapsed=e,this._group.element.classList.toggle("dv-edge-collapsed",e))}setVisible(e){}restoreExpandedSize(e){this._lastExpandedSize=e}updateSizing(e,t,n){this._baseCollapsedSize=e,this._baseMinimumSize=t,this._gapAdd=n}dispose(){this._tabSizeDisposables.dispose(),this._onDidChange.dispose()}},iie=class{get element(){return this._dockviewElement}constructor(e,t){this._dockviewElement=e,this._layoutDockview=t,this.priority="high",this.minimumSize=100,this.maximumSize=Number.POSITIVE_INFINITY,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event}layout(e,t){this._layoutDockview(t,e)}setVisible(e){}dispose(){this._onDidChange.dispose()}},oie=class{get element(){return this._element}constructor(e,t=0){this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.minimumSize=100,this.maximumSize=Number.POSITIVE_INFINITY,this.priority="high",this._element=document.createElement("div"),this._element.className="dv-shell-middle-column",this._element.style.height="100%",this._element.style.width="100%",this._splitview=new yr(this._element,{orientation:"VERTICAL",proportionalLayout:!1,margin:t}),this._centerIndex=0,this._splitview.addView(e,{type:"distribute"},0)}addTopView(e,t){this._splitview.addView(e,t,0),this._topIndex=0,this._centerIndex+=1,this._bottomIndex!==void 0&&(this._bottomIndex+=1)}addBottomView(e,t){const n=this._splitview.length;this._splitview.addView(e,t,n),this._bottomIndex=n}removeView(e){const t=e==="top"?this._topIndex:this._bottomIndex;t!==void 0&&(this._splitview.removeView(t),e==="top"?(this._topIndex=void 0,this._centerIndex-=1,this._bottomIndex!==void 0&&(this._bottomIndex-=1)):this._bottomIndex=void 0)}layout(e,t){this._splitview.layout(t,e)}setVisible(e){}setViewVisible(e,t){const n=e==="top"?this._topIndex:this._bottomIndex;n!==void 0&&this._splitview.setViewVisible(n,t)}isViewVisible(e){const t=e==="top"?this._topIndex:this._bottomIndex;return t!==void 0?this._splitview.isViewVisible(t):!1}getViewSize(e){const t=e==="top"?this._topIndex:this._bottomIndex;return t!==void 0?this._splitview.getViewSize(t):0}getViewCachedVisibleSize(e){const t=e==="top"?this._topIndex:this._bottomIndex;if(t!==void 0)return this._splitview.getViewCachedVisibleSize(t)}resizeView(e,t){const n=e==="top"?this._topIndex:this._bottomIndex;n!==void 0&&this._splitview.resizeView(n,t)}updateMargin(e){this._splitview.margin=e}dispose(){this._onDidChange.dispose(),this._splitview.dispose()}},rie=class{constructor(e,t,n,s=0,o=35){this._disposables=new ct,this._viewConfigs=new Map,this._currentWidth=0,this._currentHeight=0,this._gap=s,this._defaultCollapsedSize=o,this._shellElement=document.createElement("div"),this._shellElement.className="dv-shell",this._shellElement.style.height="100%",this._shellElement.style.width="100%",this._shellElement.style.position="relative",e.appendChild(this._shellElement);const r=new iie(t,n);this._middleColumn=new oie(r,s),this._outerSplitview=new yr(this._shellElement,{orientation:"HORIZONTAL",proportionalLayout:!1,margin:s}),this._middleIndex=0,this._outerSplitview.addView(this._middleColumn,{type:"distribute"},0),this._disposables.addDisposables(kr(this._shellElement,a=>{if(!this._shellElement.offsetParent||!iE(this._shellElement))return;const l=Math.round(a.contentRect.width),d=Math.round(a.contentRect.height);l===this._currentWidth&&d===this._currentHeight||(this._currentWidth=l,this._currentHeight=d,this.layout(l,d))}),this._outerSplitview,this._middleColumn,r)}get element(){return this._shellElement}addEdgeView(e,t,n){if(this.hasEdgeGroup(e))throw new Error(`dockview: edge group already registered at position '${e}'`);this._viewConfigs.set(e,t);const s=1+(this._viewConfigs.has("left")?1:0)+(this._viewConfigs.has("right")?1:0),o=1+(this._viewConfigs.has("top")?1:0)+(this._viewConfigs.has("bottom")?1:0),r=s>1?this._gap*(s-1)/s:0,a=o>1?this._gap*(o-1)/o:0,l=e==="left"||e==="right",d=l?r:a,c=l?"horizontal":"vertical",u=new sie(pt({collapsedSize:this._defaultCollapsedSize},t),n,c,d),h=u.isCollapsed?u.collapsedSize:u.lastExpandedSize;switch(e){case"left":this._outerSplitview.addView(u,h,0),this._leftIndex=0,this._middleIndex+=1,this._rightIndex!==void 0&&(this._rightIndex+=1),this._leftView=u;break;case"right":{const p=this._outerSplitview.length;this._outerSplitview.addView(u,h,p),this._rightIndex=p,this._rightView=u}break;case"top":this._middleColumn.addTopView(u,h),this._topView=u;break;case"bottom":this._middleColumn.addBottomView(u,h),this._bottomView=u;break}return this._disposables.addDisposables(u),this.updateTheme(this._gap,this._defaultCollapsedSize),u}layout(e,t){this._outerSplitview.layout(e,t)}updateTheme(e,t){var n,s,o,r;this._gap=e,this._defaultCollapsedSize=t;const a=1+(this._viewConfigs.has("left")?1:0)+(this._viewConfigs.has("right")?1:0),l=1+(this._viewConfigs.has("top")?1:0)+(this._viewConfigs.has("bottom")?1:0),d=a>1?e*(a-1)/a:0,c=l>1?e*(l-1)/l:0;this._outerSplitview.margin=e,this._middleColumn.updateMargin(e);const u=(x,v,y)=>{var w;const b=(w=v.collapsedSize)!==null&&w!==void 0?w:t;x.updateSizing(b,v.minimumSize,y)},h=this._viewConfigs.get("top");this._topView&&h&&u(this._topView,h,c);const p=this._viewConfigs.get("bottom");this._bottomView&&p&&u(this._bottomView,p,c);const f=this._viewConfigs.get("left");this._leftView&&f&&u(this._leftView,f,d);const g=this._viewConfigs.get("right");this._rightView&&g&&u(this._rightView,g,d),!((n=this._leftView)===null||n===void 0)&&n.isCollapsed&&this._leftIndex!==void 0&&this._outerSplitview.resizeView(this._leftIndex,this._leftView.collapsedSize),!((s=this._rightView)===null||s===void 0)&&s.isCollapsed&&this._rightIndex!==void 0&&this._outerSplitview.resizeView(this._rightIndex,this._rightView.collapsedSize),!((o=this._topView)===null||o===void 0)&&o.isCollapsed&&this._middleColumn.resizeView("top",this._topView.collapsedSize),!((r=this._bottomView)===null||r===void 0)&&r.isCollapsed&&this._middleColumn.resizeView("bottom",this._bottomView.collapsedSize),this._currentWidth>0&&this._currentHeight>0&&this.layout(this._currentWidth,this._currentHeight)}removeEdgeView(e){const t=this._getView(e);if(t){switch(e){case"left":this._outerSplitview.removeView(this._leftIndex),this._leftIndex=void 0,this._leftView=void 0,this._middleIndex-=1,this._rightIndex!==void 0&&(this._rightIndex-=1);break;case"right":this._outerSplitview.removeView(this._rightIndex),this._rightIndex=void 0,this._rightView=void 0;break;case"top":this._middleColumn.removeView("top"),this._topView=void 0;break;case"bottom":this._middleColumn.removeView("bottom"),this._bottomView=void 0;break}this._disposables.removeDisposable(t),t.dispose(),this._viewConfigs.delete(e),this.updateTheme(this._gap,this._defaultCollapsedSize)}}hasEdgeGroup(e){switch(e){case"top":return this._topView!==void 0;case"bottom":return this._bottomView!==void 0;case"left":return this._leftView!==void 0;case"right":return this._rightView!==void 0}}setEdgeGroupVisible(e,t){switch(e){case"left":this._leftIndex!==void 0&&this._outerSplitview.setViewVisible(this._leftIndex,t);break;case"right":this._rightIndex!==void 0&&this._outerSplitview.setViewVisible(this._rightIndex,t);break;case"top":case"bottom":this._middleColumn.setViewVisible(e,t);break}}isEdgeGroupVisible(e){switch(e){case"left":return this._leftIndex!==void 0?this._outerSplitview.isViewVisible(this._leftIndex):!1;case"right":return this._rightIndex!==void 0?this._outerSplitview.isViewVisible(this._rightIndex):!1;case"top":case"bottom":return this._middleColumn.isViewVisible(e)}}setEdgeGroupCollapsed(e,t){const n=this._getView(e);if(!n)return;n.setCollapsed(t);const s=t?n.collapsedSize:n.lastExpandedSize;switch(e){case"left":this._leftIndex!==void 0&&this._outerSplitview.resizeView(this._leftIndex,s);break;case"right":this._rightIndex!==void 0&&this._outerSplitview.resizeView(this._rightIndex,s);break;case"top":case"bottom":this._middleColumn.resizeView(e,s);break}}isEdgeGroupCollapsed(e){var t,n;return(t=(n=this._getView(e))===null||n===void 0?void 0:n.isCollapsed)!==null&&t!==void 0?t:!1}getEdgeGroupExpandedSize(e){var t,n;return(t=(n=this._getView(e))===null||n===void 0?void 0:n.lastExpandedSize)!==null&&t!==void 0?t:0}_getView(e){switch(e){case"top":return this._topView;case"bottom":return this._bottomView;case"left":return this._leftView;case"right":return this._rightView}}toJSON(){const e={},t=s=>({minimumSize:s.configuredMinimumSize,maximumSize:Number.isFinite(s.configuredMaximumSize)?s.configuredMaximumSize:void 0,collapsedSize:s.configuredCollapsedSize}),n=(s,o,r,a)=>s.isCollapsed?s.lastExpandedSize:o?r:a??s.lastExpandedSize;if(this._leftView&&this._leftIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._leftIndex);e.left=pt({size:n(this._leftView,s,this._outerSplitview.getViewSize(this._leftIndex),this._outerSplitview.getViewCachedVisibleSize(this._leftIndex)),visible:s,collapsed:this._leftView.isCollapsed||void 0},t(this._leftView))}if(this._rightView&&this._rightIndex!==void 0){const s=this._outerSplitview.isViewVisible(this._rightIndex);e.right=pt({size:n(this._rightView,s,this._outerSplitview.getViewSize(this._rightIndex),this._outerSplitview.getViewCachedVisibleSize(this._rightIndex)),visible:s,collapsed:this._rightView.isCollapsed||void 0},t(this._rightView))}if(this._topView){const s=this._middleColumn.isViewVisible("top");e.top=pt({size:n(this._topView,s,this._middleColumn.getViewSize("top"),this._middleColumn.getViewCachedVisibleSize("top")),visible:s,collapsed:this._topView.isCollapsed||void 0},t(this._topView))}if(this._bottomView){const s=this._middleColumn.isViewVisible("bottom");e.bottom=pt({size:n(this._bottomView,s,this._middleColumn.getViewSize("bottom"),this._middleColumn.getViewCachedVisibleSize("bottom")),visible:s,collapsed:this._bottomView.isCollapsed||void 0},t(this._bottomView))}return e}fromJSON(e){if(e.left&&this._leftIndex!==void 0){var t,n,s,o,r;(t=this._leftView)===null||t===void 0||t.restoreExpandedSize(e.left.size),(n=this._leftView)===null||n===void 0||n.setCollapsed((s=e.left.collapsed)!==null&&s!==void 0?s:!1),this._outerSplitview.resizeView(this._leftIndex,e.left.collapsed&&(o=(r=this._leftView)===null||r===void 0?void 0:r.collapsedSize)!==null&&o!==void 0?o:e.left.size),e.left.visible||this._outerSplitview.setViewVisible(this._leftIndex,!1)}if(e.right&&this._rightIndex!==void 0){var a,l,d,c,u;(a=this._rightView)===null||a===void 0||a.restoreExpandedSize(e.right.size),(l=this._rightView)===null||l===void 0||l.setCollapsed((d=e.right.collapsed)!==null&&d!==void 0?d:!1),this._outerSplitview.resizeView(this._rightIndex,e.right.collapsed&&(c=(u=this._rightView)===null||u===void 0?void 0:u.collapsedSize)!==null&&c!==void 0?c:e.right.size),e.right.visible||this._outerSplitview.setViewVisible(this._rightIndex,!1)}if(e.top){var h,p,f,g,x;(h=this._topView)===null||h===void 0||h.restoreExpandedSize(e.top.size),(p=this._topView)===null||p===void 0||p.setCollapsed((f=e.top.collapsed)!==null&&f!==void 0?f:!1),this._middleColumn.resizeView("top",e.top.collapsed&&(g=(x=this._topView)===null||x===void 0?void 0:x.collapsedSize)!==null&&g!==void 0?g:e.top.size),e.top.visible||this._middleColumn.setViewVisible("top",!1)}if(e.bottom){var v,y,w,b,_;(v=this._bottomView)===null||v===void 0||v.restoreExpandedSize(e.bottom.size),(y=this._bottomView)===null||y===void 0||y.setCollapsed((w=e.bottom.collapsed)!==null&&w!==void 0?w:!1),this._middleColumn.resizeView("bottom",e.bottom.collapsed&&(b=(_=this._bottomView)===null||_===void 0?void 0:_.collapsedSize)!==null&&b!==void 0?b:e.bottom.size),e.bottom.visible||this._middleColumn.setViewVisible("bottom",!1)}}dispose(){this._disposables.dispose(),this._shellElement.remove()}};function aie(e){var t;return new EE((t=e.tabGroupColors)!==null&&t!==void 0?t:Sv,e.tabGroupAccent!=="off")}function pc(e){const t=e.from.activePanel;[...e.from.panels].map(n=>{const s=e.from.model.removePanel(n);return e.from.model.renderContainer.detatch(n),s}).forEach(n=>{e.to.model.openPanel(n,{skipSetActive:t!==n,skipSetGroupActive:!0})})}const ng=()=>({dispose:()=>{}}),lie=ng;var die=class extends cE{fireDidCreateTabGroup(e){this._onDidCreateTabGroup.fire(e)}fireDidDestroyTabGroup(e){this._onDidDestroyTabGroup.fire(e)}fireDidAddPanelToTabGroup(e){this._onDidAddPanelToTabGroup.fire(e)}fireDidRemovePanelFromTabGroup(e){this._onDidRemovePanelFromTabGroup.fire(e)}fireDidTabGroupChange(e){this._onDidTabGroupChange.fire(e)}fireDidTabGroupCollapsedChange(e){this._onDidTabGroupCollapsedChange.fire(e)}get orientation(){return this.gridview.orientation}get totalPanels(){return this.panels.length}get panels(){return this.groups.flatMap(e=>e.panels)}get options(){return this._options}get tabGroupColorPalette(){return this._tabGroupColorPalette}get activePanel(){const e=this.activeGroup;if(e)return e.activePanel}get renderer(){var e;return(e=this.options.defaultRenderer)!==null&&e!==void 0?e:"onlyWhenVisible"}get defaultHeaderPosition(){var e;return(e=this.options.defaultHeaderPosition)!==null&&e!==void 0?e:"top"}get api(){return this._api}get floatingGroups(){var e,t;return(e=(t=this._moduleRegistry)===null||t===void 0||(t=t.services.floatingGroupService)===null||t===void 0?void 0:t.floatingGroups)!==null&&e!==void 0?e:[]}getFloatingWindowForGroup(e){var t;return(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e)}_gatherFloatingGroupBoxes(e){return this.getFloatingGroupSnapshots(e).map(t=>t.box)}getFloatingContainer(){var e;return(e=this._floatingOverlayHost)!==null&&e!==void 0?e:this.gridview.element}getFloatingGroupSnapshots(e){const t=this.getFloatingContainer().getBoundingClientRect();return this.floatingGroups.filter(n=>n.group!==e).map(n=>{const s=n.overlay.element.getBoundingClientRect();return{group:n.group,box:{left:s.left-t.left,top:s.top-t.top,width:s.width,height:s.height}}})}mergeFloatInto(e,t,n){e===t||!this.getPanel(t.id)||this.moveGroupOrPanel({from:{groupId:e.id},to:{group:t,position:n}})}getGridSplitterRects(){const e=this.getFloatingContainer().getBoundingClientRect(),t=[];return this.gridview.element.querySelectorAll(".dv-sash").forEach(n=>{const s=n.getBoundingClientRect();t.push({left:s.left-e.left,top:s.top-e.top,width:s.width,height:s.height})}),t}get _smartGuidesService(){return this._moduleRegistry.services.smartGuidesService}get smartGuidesEnabled(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.enabled)!==null&&e!==void 0?e:!1}setSmartGuidesEnabled(e){var t;(t=Ps(this._smartGuidesService,"SmartGuides","api.setSmartGuidesEnabled"))===null||t===void 0||t.setEnabled(e)}updateSmartGuidesOptions(e){var t;(t=Ps(this._smartGuidesService,"SmartGuides","api.updateSmartGuidesOptions"))===null||t===void 0||t.updateOptions(e)}get onDidSnapFloat(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapFloat)!==null&&e!==void 0?e:ng}get onDidSnapTogether(){var e,t;return(e=(t=this._smartGuidesService)===null||t===void 0?void 0:t.onDidSnapTogether)!==null&&e!==void 0?e:ng}_buildFloatingDragTransform(e,t){const n=this.options.transformFloatingGroupDrag,s=!t;if(!(!n&&!(s&&this._smartGuidesService)))return o=>{var r,a;const l=n?.({group:e,proposed:o.proposed,container:o.container,others:o.others,modifiers:o.modifiers}),d=l?pt(pt({},o.proposed),l):o.proposed,c=s?(r=this._smartGuidesService)===null||r===void 0?void 0:r.transformFloatingGroupDrag({group:e,proposed:d,container:o.container,others:o.others,modifiers:o.modifiers}):void 0;return(a=c??l)!==null&&a!==void 0?a:void 0}}get _floatingGroupService(){return this._moduleRegistry.services.floatingGroupService}get _popoutWindowService(){return this._moduleRegistry.services.popoutWindowService}get _watermarkService(){return this._moduleRegistry.services.watermarkService}get _edgeGroupService(){return this._moduleRegistry.services.edgeGroupService}get _rootDropTargetService(){return this._moduleRegistry.services.rootDropTargetService}get _advancedDnDService(){return this._moduleRegistry.services.advancedDnDService}get _dndCompassService(){return this._moduleRegistry.services.dndCompassService}canDropOnGroup(e,t,n){return e.model.canDisplayContentOverlay(n,t)}getDropOverlayElement(e){var t,n;const s=e.element.querySelector(".dv-content-container");if(s)return((t=this.options.theme)===null||t===void 0?void 0:t.dndPanelOverlay)==="group"&&(n=s.parentElement)!==null&&n!==void 0?n:s}getTabsListElement(e){return e.model.header.hidden?void 0:e.model.tabsListElement}relayoutGroup(e){e.relayout()}setForcedOverflow(e,t){e.model.header.setForcedOverflow(t)}getLayoutElement(){return this.gridview.element}getDropPositionResolver(){var e;if(this.options.dropPositionResolver)return this.options.dropPositionResolver;const t=(e=this._dndCompassService)===null||e===void 0?void 0:e.resolver,n=this._moduleRegistry.services.autoEdgeGroupService;return t&&n?{resolve:s=>{var o;return(o=n.resolveEdge(s))!==null&&o!==void 0?o:t.resolve(s)}}:t??n?.resolver}dockToLayoutEdge(e,t){const n=new ME({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:Ln,kind:"edge"});if(this._onWillDrop.fire(n),n.defaultPrevented)return;const s=Ln();if(s){var o;this.moveGroupOrPanel({from:{groupId:s.groupId,panelId:(o=s.panelId)!==null&&o!==void 0?o:void 0},to:{group:this.orthogonalize(t),position:"center"}})}else this._onDidDrop.fire(new jv({nativeEvent:e,position:t,panel:void 0,api:this._api,group:void 0,getData:Ln}))}get headerActionsService(){return this._moduleRegistry.services.headerActionsService}get _layoutHistoryService(){return this._moduleRegistry.services.layoutHistoryService}undo(){var e;(e=Ps(this._layoutHistoryService,"LayoutHistory","api.undo"))===null||e===void 0||e.undo()}redo(){var e;(e=Ps(this._layoutHistoryService,"LayoutHistory","api.redo"))===null||e===void 0||e.redo()}get canUndo(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.canUndo)!==null&&e!==void 0?e:!1}get canRedo(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.canRedo)!==null&&e!==void 0?e:!1}clearHistory(){var e;(e=this._layoutHistoryService)===null||e===void 0||e.clear()}get onDidChangeHistory(){var e,t;return(e=(t=this._layoutHistoryService)===null||t===void 0?void 0:t.onDidChangeHistory)!==null&&e!==void 0?e:lie}get hasEdgeDragReveal(){return!!this._moduleRegistry.services.autoEdgeGroupService}isGridEmpty(){return this.gridview.length===0}rootDropTargetOverrideTarget(){var e;return(e=this.rootDropTargetContainer)===null||e===void 0?void 0:e.model}dispatchUnhandledDragOver(e,t){const n=new IE(e,"edge",t,Ln);return this._onUnhandledDragOver.fire(n),n.isAccepted}fireWillDragPanel(e){this._onWillDragPanel.fire(e)}fireWillDragGroup(e){this._onWillDragGroup.fire(e)}fireWillDrop(e){this._onWillDrop.fire(e)}fireWillShowOverlay(e){this._onWillShowOverlay.fire(e)}buildGroupDragGhost(e){var t;return(t=this._advancedDnDService)===null||t===void 0?void 0:t.buildGroupDragGhost(e)}resolveDropOverlayModel(e,t){var n;return(n=this._advancedDnDService)===null||n===void 0?void 0:n.resolveOverlayModel(e,t)}get rootElement(){var e,t;return(e=(t=this._shellManager)===null||t===void 0?void 0:t.element)!==null&&e!==void 0?e:this.element}ownsElement(e){if(this.rootElement.contains(e))return!0;const t=this.rootElement.ownerDocument,n=e.ownerDocument;return!n||n===t?!1:this.getPopoutWindows().some(s=>s.document===n)}adjacentGroup(e,t){var n;if(e.api.location.type!=="grid")return;const s=Tn(e.element);return(n=t?this.gridview.previous(s):this.gridview.next(s))===null||n===void 0?void 0:n.view}adjacentGroupInDirection(e,t){if(e.api.location.type!=="grid")return;const n=e.element.getBoundingClientRect(),s=n.left+n.width/2,o=n.top+n.height/2;let r,a=Number.POSITIVE_INFINITY;for(const l of this.groups){if(l===e||l.api.location.type!=="grid")continue;const d=l.element.getBoundingClientRect(),c=d.left+d.width/2-s,u=d.top+d.height/2-o;let h;switch(t){case"left":h=c<0&&Math.abs(c)>=Math.abs(u);break;case"right":h=c>0&&Math.abs(c)>=Math.abs(u);break;case"up":h=u<0&&Math.abs(u)>=Math.abs(c);break;default:h=u>0&&Math.abs(u)>=Math.abs(c);break}if(!h)continue;const p=c*c+u*u;p<a&&(a=p,r=l)}return r}showDropPreview(e,t){var n,s;return(n=(s=this._advancedDnDService)===null||s===void 0?void 0:s.showPreviewOverlay(e,t))!==null&&n!==void 0?n:rn.NONE}announce(e){var t;(t=this._moduleRegistry.services.liveRegionService)===null||t===void 0||t.announce(e)}dockPanel(e,t,n){this.moveGroupOrPanel({from:{groupId:e.group.id,panelId:e.id},to:{group:t,position:n}})}floatPanel(e){this.addFloatingGroup(e)}get contextMenuService(){return this._moduleRegistry.services.contextMenuService}get pinnedTabsService(){return this._moduleRegistry.services.pinnedTabsService}get advancedOverflowService(){return this._moduleRegistry.services.advancedOverflowService}setPanelPinned(e,t){var n;e.isPinned!==t&&!((n=this.options.pinnedTabs)===null||n===void 0)&&n.enabled&&this.pinnedTabsService&&(e.setPinned(t),this._onDidPanelPinnedChange.fire({panel:e,isPinned:t}))}get mountElement(){return this.gridview.element}hasVisibleGridGroup(){return this.groups.some(e=>e.api.location.type==="grid"&&e.api.isVisible)}fireLayoutChange(){this._bufferOnDidLayoutChange.fire()}get popoutRestorationPromise(){var e,t;return(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.restorationPromise)!==null&&e!==void 0?e:Promise.resolve()}constructor(e,t){var n,s,o,r,a;super(e,{proportionalLayout:!0,orientation:"HORIZONTAL",styles:t.hideBorders?{separatorBorder:"transparent"}:void 0,disableAutoResizing:t.disableAutoResizing,locked:t.locked,margin:(n=(s=t.theme)===null||s===void 0?void 0:s.gap)!==null&&n!==void 0?n:0,className:t.className}),this.nextGroupId=xv(),this._deserializer=new mse(this),this._moduleRegistry=new wse,this._onWillDragPanel=new ve,this.onWillDragPanel=this._onWillDragPanel.event,this._onWillDragGroup=new ve,this.onWillDragGroup=this._onWillDragGroup.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onWillDrop=new ve,this.onWillDrop=this._onWillDrop.event,this._mutationDepth=0,this._pendingLocationChanges=new Map,this._origin="user",this._originDepth=0,this._onWillMutateLayout=new ve,this.onWillMutateLayout=this._onWillMutateLayout.event,this._onDidMutateLayout=new ve,this.onDidMutateLayout=this._onDidMutateLayout.event,this._onWillShowOverlay=new ve,this.onWillShowOverlay=this._onWillShowOverlay.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this._onDidRemovePanel=new ve,this.onDidRemovePanel=this._onDidRemovePanel.event,this._onDidAddPanel=new ve,this.onDidAddPanel=this._onDidAddPanel.event,this._onDidPopoutGroupSizeChange=new ve,this.onDidPopoutGroupSizeChange=this._onDidPopoutGroupSizeChange.event,this._onDidPopoutGroupPositionChange=new ve,this.onDidPopoutGroupPositionChange=this._onDidPopoutGroupPositionChange.event,this._onDidAddPopoutGroup=new ve,this.onDidAddPopoutGroup=this._onDidAddPopoutGroup.event,this._onDidRemovePopoutGroup=new ve,this.onDidRemovePopoutGroup=this._onDidRemovePopoutGroup.event,this._onDidChangePopouts=new ve,this.onDidChangePopouts=this._onDidChangePopouts.event,this._onDidOpenPopoutWindowFail=new ve,this.onDidOpenPopoutWindowFail=this._onDidOpenPopoutWindowFail.event,this._onDidStartFloatingGroupDrag=new ve,this.onDidStartFloatingGroupDrag=this._onDidStartFloatingGroupDrag.event,this._onDidEndFloatingGroupDrag=new ve,this.onDidEndFloatingGroupDrag=this._onDidEndFloatingGroupDrag.event,this._onDidLayoutFromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutFromJSON.event,this._onDidActivePanelChange=new ve({replay:!0}),this.onDidActivePanelChange=this._onDidActivePanelChange.event,this._onDidPanelPinnedChange=new ve,this.onDidPanelPinnedChange=this._onDidPanelPinnedChange.event,this._onDidMovePanel=new ve,this.onDidMovePanel=this._onDidMovePanel.event,this._onDidCreateTabGroup=new ve,this.onDidCreateTabGroup=this._onDidCreateTabGroup.event,this._onDidDestroyTabGroup=new ve,this.onDidDestroyTabGroup=this._onDidDestroyTabGroup.event,this._onDidAddPanelToTabGroup=new ve,this.onDidAddPanelToTabGroup=this._onDidAddPanelToTabGroup.event,this._onDidRemovePanelFromTabGroup=new ve,this.onDidRemovePanelFromTabGroup=this._onDidRemovePanelFromTabGroup.event,this._onDidTabGroupChange=new ve,this.onDidTabGroupChange=this._onDidTabGroupChange.event,this._onDidTabGroupCollapsedChange=new ve,this.onDidTabGroupCollapsedChange=this._onDidTabGroupCollapsedChange.event,this._onDidMaximizedGroupChange=new ve,this.onDidMaximizedGroupChange=this._onDidMaximizedGroupChange.event,this._inShellLayout=!1,this._onDidRemoveGroup=new ve,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidEdgeGroupAutoHideChange=new ve,this.onDidEdgeGroupAutoHideChange=this._onDidEdgeGroupAutoHideChange.event,this._onDidAddGroup=new ve,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidOptionsChange=new ve,this.onDidOptionsChange=this._onDidOptionsChange.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._peekingGroups=new Set,this._moving=!1,this._options=t,this._tabGroupColorPalette=aie(t);const l=t.modules,d=l??[...Yse,...Sse()];for(const h of d)this._moduleRegistry.register(h);this._moduleRegistry.initialize(this),this.reportMissingOptionModules(t);const c=this._popoutWindowService;c&&this.addDisposables(c.onDidRemove(h=>{this._onDidRemovePopoutGroup.fire({id:h.popoutGroup.id,group:h.popoutGroup,window:h.getWindow()})})),this.popupService=new wC(this.element),this._api=new bv(this),this.disableResizing=!0,this.element.remove(),this._shellManager=new rie(e,this.element,(h,p)=>this._layoutFromShell(h,p),(o=(r=t.theme)===null||r===void 0?void 0:r.gap)!==null&&o!==void 0?o:0,(a=t.theme)===null||a===void 0?void 0:a.edgeGroupCollapsedSize),this.popupService.updateRoot(this._shellManager.element),this._shellThemeClassnames=new Lh(this._shellManager.element),this.rootDropTargetContainer=new af(this._shellManager.element,{disabled:!0}),this.floatingDropTargetContainer=new af(this._shellManager.element,{disabled:!1}),this.overlayRenderContainer=new vC(this._shellManager.element,this),this._floatingOverlayHost=document.createElement("div"),this._floatingOverlayHost.className="dv-floating-overlay-host",this._shellManager.element.appendChild(this._floatingOverlayHost),Ze(this.gridview.element,"dv-dockview",!0),Ze(this.element,"dv-debug",!!t.debug),this.updateTheme(),t.debug&&this.addDisposables(new eie(this)),this.addDisposables(rn.from(()=>this._pendingLocationChanges.clear()),this.rootDropTargetContainer,this.floatingDropTargetContainer,ot(this._shellManager.element,"dragend",()=>{var h,p;(h=this.rootDropTargetContainer.model)===null||h===void 0||h.clear(),(p=this.floatingDropTargetContainer.model)===null||p===void 0||p.clear()},!0),this.overlayRenderContainer,this._onWillDragPanel,this._onWillDragGroup,this._onWillShowOverlay,this._onDidActivePanelChange,this._onDidPanelPinnedChange,this._onDidAddPanel,this._onDidRemovePanel,this._onDidLayoutFromJSON,this._onDidDrop,this._onWillDrop,this._onWillMutateLayout,this._onDidMutateLayout,this._onDidMovePanel,this._onDidMovePanel.event(()=>{this.debouncedUpdateAllPositions()}),this._onDidAddGroup,this._onDidRemoveGroup,this._onDidEdgeGroupAutoHideChange,this._onDidActiveGroupChange,this._onUnhandledDragOver,this._onDidMaximizedGroupChange,this._onDidPopoutGroupSizeChange,this._onDidPopoutGroupPositionChange,this._onDidAddPopoutGroup,this._onDidRemovePopoutGroup,this._onDidChangePopouts,this._onDidAddPopoutGroup.event(()=>this._onDidChangePopouts.fire()),this._onDidRemovePopoutGroup.event(()=>this._onDidChangePopouts.fire()),this._onDidOpenPopoutWindowFail,this._onDidStartFloatingGroupDrag,this._onDidEndFloatingGroupDrag,this._onDidCreateTabGroup,this._onDidDestroyTabGroup,this._onDidAddPanelToTabGroup,this._onDidRemovePanelFromTabGroup,this._onDidTabGroupChange,this._onDidTabGroupCollapsedChange,Qs.any(this.onDidPopoutGroupSizeChange,this.onDidPopoutGroupPositionChange,this.onDidCreateTabGroup,this.onDidDestroyTabGroup,this.onDidAddPanelToTabGroup,this.onDidRemovePanelFromTabGroup,this.onDidTabGroupChange,this.onDidTabGroupCollapsedChange)(()=>{this.fireLayoutChange()}),this._onDidOptionsChange,this.onDidAdd(h=>{this._moving||this._onDidAddGroup.fire(h)}),this.onDidRemove(h=>{this._moving||this._onDidRemoveGroup.fire(h)}),this.onDidActiveChange(h=>{this._moving||this._onDidActiveGroupChange.fire(h)}),this.onDidMaximizedChange(h=>{this._onDidMaximizedGroupChange.fire({group:h.panel,isMaximized:h.isMaximized})}),Qs.any(this.onDidAddPanel,this.onDidRemovePanel,this.onDidAddGroup,this.onDidRemove,this.onDidRemoveGroup,this.onDidMovePanel,this.onDidActivePanelChange)(()=>{this._bufferOnDidLayoutChange.fire()}),rn.from(()=>{var h;this._moduleRegistry.dispose(),(h=this._shellManager)===null||h===void 0||h.dispose()}));const u=this._rootDropTargetService;u&&this.addDisposables(u.onWillShowOverlay(h=>{this.gridview.length>0&&h.position==="center"||this._onWillShowOverlay.fire(new td(h,{kind:"edge",panel:void 0,api:this._api,group:void 0,getData:Ln}))}),u.onDrop(h=>this.dockToLayoutEdge(h.nativeEvent,h.position))),this._moduleRegistry.postConstruct(this)}setVisible(e,t){switch(e.api.location.type){case"grid":super.setVisible(e,t);break;case"floating":{const n=this.floatingGroups.find(s=>s.group===e);n&&(n.overlay.setVisible(t),e.api._onDidVisibilityChange.fire({isVisible:t}));break}case"popout":console.warn("dockview: You cannot hide a group that is in a popout window");break}}getPopupServiceForGroup(e){var t,n;return(t=(n=this._popoutWindowService)===null||n===void 0||(n=n.findByGroup(e))===null||n===void 0?void 0:n.popupService)!==null&&t!==void 0?t:this.popupService}addPopoutGroup(e,t){return this.mutationAsync("popout",()=>this._doAddPopoutGroup(e,t))}getPopouts(){var e,t;return(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.entries.map(n=>({id:n.popoutGroup.id,group:n.popoutGroup,window:n.getWindow()})))!==null&&e!==void 0?e:[]}getPopoutWindows(){return this.getPopouts().map(e=>e.window)}_doAddPopoutGroup(e,t){var n,s,o,r,a;const l=Ps(this._popoutWindowService,"PopoutWindow","api.addPopoutGroup");if(!l||e instanceof cc&&e.model.location.type==="edge")return Promise.resolve(!1);if(e instanceof Gr&&e.group.size===1)return this.addPopoutGroup(e.group,t);const d=Yte(this.gridview.element),c=this.element;function u(){var v,y;if(t?.position)return t.position;const w=(e instanceof cc?e.element:(v=(y=e.group)===null||y===void 0?void 0:y.element)!==null&&v!==void 0?v:c).getBoundingClientRect();return{left:window.screenX+w.left,top:window.screenY+w.top,width:w.width,height:w.height}}const h=u(),p=(n=t==null||(s=t.overridePopoutGroup)===null||s===void 0?void 0:s.id)!==null&&n!==void 0?n:this.getNextGroupId(),f=(o=t?.popoutUrl)!==null&&o!==void 0?o:(r=this.options)===null||r===void 0?void 0:r.popoutUrl,g=new Qse(`${this.id}-${p}`,d??"",{url:f??"/popout.html",left:h.left,top:h.top,width:h.width,height:h.height,onDidOpen:t?.onDidOpen,onWillClose:t?.onWillClose,nonce:(a=this.options)===null||a===void 0?void 0:a.nonce}),x=new ct(g,g.onDidClose(()=>{x.dispose()}));return g.open().then(v=>{var y,w;if(g.isDisposed)return!1;const b=(y=t?.referenceGroup)!==null&&y!==void 0?y:e instanceof Gr?e.group:e,_=e.api.location.type,j=b.element.parentElement!==null;let N;if(t?.overridePopoutGridview){var C;N=(C=t.overridePopoutGroup)!==null&&C!==void 0?C:b}else j?t?.overridePopoutGroup?N=t.overridePopoutGroup:(N=this.createGroup({id:p}),v&&this._onDidAddGroup.fire(N)):N=b;if(v===null)return this.handleBlockedPopout({group:N,referenceGroup:b,options:t,popoutWindowDisposable:x}),!1;const S=document.createElement("div");S.className="dv-overlay-render-container";const A=new vC(S,this);N.model.renderContainer=A;const E=(w=t?.overridePopoutGridview)!==null&&w!==void 0?w:this.createNestedGridview();t?.overridePopoutGridview||E.addView(N,ks.Distribute,[0]),E.element.style.width="100%",E.element.style.height="100%",E.layout(g.window.innerWidth,g.window.innerHeight);let I=!1;const D=()=>{I||(I=!0,E.dispose())};let T,z=[];if(!t?.overridePopoutGroup&&!t?.overridePopoutGridview&&j)if(e instanceof Gr){const _e=e.group;this.movingLock(()=>{const Ee=b.model.removePanel(e);N.model.openPanel(Ee)}),z=[{panel:e,from:_e}]}else switch(this.movingLock(()=>pc({from:b,to:N})),z=N.panels.map(_e=>({panel:_e,from:b})),_){case"grid":b.api.setVisible(!1);break;case"floating":case"popout":var $;T=($=this.floatingGroups.find(_e=>_e.group.api.id===e.api.id))===null||$===void 0?void 0:$.overlay.toJSON(),this.removeGroup(b);break}v.classList.add("dv-dockview"),v.style.overflow="hidden",v.appendChild(S),v.appendChild(E.element);const R=document.createElement("div"),B=new af(R,{disabled:this.rootDropTargetContainer.disabled});v.appendChild(R),N.model.dropTargetContainer=B;const H=new wC(v,g.window);if(x.addDisposables(H),N.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f},t?.overridePopoutGridview){const _e=this.groups.filter(Ee=>E.element.contains(Ee.element));for(const Ee of _e)Ee.model.renderContainer=A,Ee.model.dropTargetContainer=B,Ee.model.location={type:"popout",getWindow:()=>g.window,popoutUrl:f}}j&&e.api.location.type==="grid"&&e.api.setVisible(!1),this.doSetGroupAndPanelActive(N);const oe=l.observeGridviewSize(g,E,A);oe&&x.addDisposables(oe);const te=new Fn;x.addDisposables(te);const O=_e=>{te.value=new ct(_e.api.onDidActiveChange(Ee=>{if(Ee.isActive){var me;(me=g.window)===null||me===void 0||me.focus()}}),_e.api.onWillFocus(()=>{var Ee;(Ee=g.window)===null||Ee===void 0||Ee.focus()}))};O(N);const V={},J=j&&b&&this.getPanel(b.id),pe={window:g,popoutGroup:N,gridview:E,overlayRenderContainer:A,dropTargetContainer:B,getWindow:()=>g.window,popoutUrl:f,referenceGroup:J?b.id:void 0,popupService:H,setAnchorGroup:_e=>{pe.popoutGroup=_e,O(_e)},disposable:{dispose:()=>(x.dispose(),V.returnedGroup)}},fe=Xte(g.window);x.addDisposables(fe,Zte(g.window,()=>{this._onDidPopoutGroupSizeChange.fire({width:g.window.innerWidth,height:g.window.innerHeight,group:pe.popoutGroup})}),fe.event(()=>{this._onDidPopoutGroupPositionChange.fire({screenX:g.window.screenX,screenY:g.window.screenY,group:pe.popoutGroup})}),ot(g.window,"resize",()=>{E.layout(g.window.innerWidth,g.window.innerHeight)}),A,rn.from(()=>this.disposePopoutWindow({group:N,referenceGroup:b,popoutGridview:E,isGroupAddedToDom:j,floatingBox:T,disposePopoutGridview:D,closeResult:V}))),l.add(pe),this._onDidAddPopoutGroup.fire({id:pe.popoutGroup.id,group:pe.popoutGroup,window:pe.getWindow()});for(const{panel:_e,from:Ee}of z)this.fireDidMovePanel(_e,Ee);return!0}).catch(v=>(console.error("dockview: failed to create popout.",v),!1))}handleBlockedPopout(e){const{group:t,referenceGroup:n,options:s,popoutWindowDisposable:o}=e;if(console.error("dockview: failed to create popout. perhaps you need to allow pop-ups for this website"),o.dispose(),this._onDidOpenPopoutWindowFail.fire(),s?.overridePopoutGridview){const r=s.overridePopoutGridview,a=this.groups.filter(l=>r.element.contains(l.element));for(const l of a)this.movingLock(()=>{r.remove(l),this.redockGroupToMainGrid(l)});r.dispose(),n&&!n.api.isVisible&&n.api.setVisible(!0);return}t===n?this.gridview.element.contains(t.element)||(this.movingLock(()=>this.doAddGroup(t,[0])),t.model.location={type:"grid"}):(this.movingLock(()=>pc({from:t,to:n})),t.model.size===0&&this._groups.has(t.id)&&(t.dispose(),this._groups.delete(t.id),this._onDidRemoveGroup.fire(t))),n.api.isVisible||n.api.setVisible(!0)}redockGroupToMainGrid(e){e.model.renderContainer=this.overlayRenderContainer,e.model.dropTargetContainer=this.rootDropTargetContainer,e.model.location={type:"grid"},this.doAddGroup(e,[0])}disposePopoutWindow(e){var t;const{group:n,referenceGroup:s,popoutGridview:o,isGroupAddedToDom:r,floatingBox:a,disposePopoutGridview:l,closeResult:d}=e;if(this.isDisposed){l();return}const c=!!(!((t=this._popoutWindowService)===null||t===void 0)&&t.entries.find(g=>g.gridview===o)),u=this.groups.filter(g=>o.element.contains(g.element)),h=u.includes(n),p=h&&u.length===1,f=[];if(c){for(const g of u)if(g!==n){this.movingLock(()=>{this.doRemoveGroup(g,{skipDispose:!0,skipActive:!0,skipPopoutReturn:!0}),this.redockGroupToMainGrid(g)});for(const x of g.panels)f.push({panel:x,from:g})}}if(h&&r&&this.getPanel(s.id)){const g=[...n.panels];this.movingLock(()=>pc({from:n,to:s}));for(const x of g)f.push({panel:x,from:n});s.api.isVisible||s.api.setVisible(!0),this.getPanel(n.id)&&this.doRemoveGroup(n,{skipPopoutAssociated:!0})}else if(h&&this.getPanel(n.id)){if(n.model.renderContainer=this.overlayRenderContainer,n.model.dropTargetContainer=this.rootDropTargetContainer,d.returnedGroup=n,!c){l();return}if(a&&p)this.addFloatingGroup(n,{height:a.height,width:a.width,position:a});else{this.doRemoveGroup(n,{skipDispose:!0,skipActive:!0,skipPopoutReturn:!0}),n.model.location={type:"grid"},this.movingLock(()=>{this.doAddGroup(n,[0])});for(const g of n.panels)f.push({panel:g,from:n})}this.doSetGroupAndPanelActive(n)}l();for(const{panel:g,from:x}of f)this.fireDidMovePanel(g,x)}addFloatingGroup(e,t){this.mutation("float",()=>this._doAddFloatingGroup(e,t))}_doAddFloatingGroup(e,t){if(!Ps(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup")||e instanceof cc&&e.model.location.type==="edge")return;let n,s=[];if(e instanceof Gr){const d=e.group;n=this.createGroup(),this._onDidAddGroup.fire(n),this.movingLock(()=>this.removePanel(e,{removeEmptyGroup:!0,skipDispose:!0,skipSetActiveGroup:!0})),this.movingLock(()=>n.model.openPanel(e,{skipSetGroupActive:!0})),s=[{panel:e,from:d}]}else{var o;n=e;const d=(o=this._popoutWindowService)===null||o===void 0?void 0:o.findReferenceGroupId(n),c=d?this.getPanel(d):void 0;typeof t?.skipRemoveGroup=="boolean"&&t.skipRemoveGroup||(c?(this.movingLock(()=>pc({from:e,to:c})),this.doRemoveGroup(e,{skipPopoutReturn:!0,skipPopoutAssociated:!0}),this.doRemoveGroup(c,{skipDispose:!0}),n=c,s=n.panels.map(u=>({panel:u,from:e}))):(this.doRemoveGroup(e,{skipDispose:!0,skipPopoutReturn:!0,skipPopoutAssociated:!1}),s=n.panels.map(u=>({panel:u,from:n}))))}function r(){if(t?.position){const d={};return"left"in t.position?d.left=Math.max(t.position.left,0):"right"in t.position?d.right=Math.max(t.position.right,0):d.left=_o.left,"top"in t.position?d.top=Math.max(t.position.top,0):"bottom"in t.position?d.bottom=Math.max(t.position.bottom,0):d.top=_o.top,typeof t.width=="number"?d.width=Math.max(t.width,0):d.width=_o.width,typeof t.height=="number"?d.height=Math.max(t.height,0):d.height=_o.height,d}return{left:typeof t?.x=="number"?Math.max(t.x,0):_o.left,top:typeof t?.y=="number"?Math.max(t.y,0):_o.top,width:typeof t?.width=="number"?Math.max(t.width,0):_o.width,height:typeof t?.height=="number"?Math.max(t.height,0):_o.height}}const a=r(),l=this.createNestedGridview();l.addView(n,ks.Distribute,[0]),this.mountFloatingWindow(l,n,[n],a,{dragHandle:t?.dragHandle,inDragMode:t?.inDragMode,skipActiveGroup:t?.skipActiveGroup,disableSmartGuides:t?.disableSmartGuides});for(const{panel:d,from:c}of s)this.fireDidMovePanel(d,c)}createNestedGridview(e="HORIZONTAL"){var t,n;return new dE(!0,this.options.hideBorders?{separatorBorder:"transparent"}:void 0,e,!1,(t=(n=this.options.theme)===null||n===void 0?void 0:n.gap)!==null&&t!==void 0?t:0)}mountFloatingWindow(e,t,n,s,o){var r,a,l,d,c,u,h,p,f;const g=Ps(this._floatingGroupService,"FloatingGroup","api.addFloatingGroup");if(!g)return;const x=((r=(a=o?.dragHandle)!==null&&a!==void 0?a:this.options.floatingGroupDragHandle)!==null&&r!==void 0?r:"titlebar")==="titlebar"?new vse(this,t):void 0,v=new Nv(pt(pt({container:(l=this._floatingOverlayHost)!==null&&l!==void 0?l:this.gridview.element,content:e.element,header:x?.element},s),{},{minimumInViewportWidth:this.options.floatingGroupBounds==="boundedWithinViewport"?void 0:(d=(c=this.options.floatingGroupBounds)===null||c===void 0?void 0:c.minimumWidthWithinViewport)!==null&&d!==void 0?d:100,minimumInViewportHeight:this.options.floatingGroupBounds==="boundedWithinViewport"?void 0:(u=(h=this.options.floatingGroupBounds)===null||h===void 0?void 0:h.minimumHeightWithinViewport)!==null&&u!==void 0?u:100,transformDragPosition:this._buildFloatingDragTransform(t,(p=o?.disableSmartGuides)!==null&&p!==void 0?p:!1),getSiblingBoxes:()=>this._gatherFloatingGroupBoxes(t)})),y=(f=x?.element)!==null&&f!==void 0?f:t.element.querySelector(".dv-void-container");if(!y)throw new Error("dockview: failed to find drag handle");v.setupDrag(y,{inDragMode:typeof o?.inDragMode=="boolean"?o.inDragMode:!1});const w=g.add(t,v,e);w.addDisposables(v.onDidStartMoving(()=>this._onDidStartFloatingGroupDrag.fire(t)),v.onDidChangeEnd(()=>this._onDidEndFloatingGroupDrag.fire(t))),x&&(w.setTitleBar(x),w.addDisposables(x,rn.from(()=>w.setTitleBar(void 0)),x.onDragStart(b=>{this._onWillDragGroup.fire({nativeEvent:b,group:w.group})})));for(const b of n)b.model.location={type:"floating"};o?.skipActiveGroup||this.doSetGroupAndPanelActive(t)}orthogonalize(e,t){switch(this.gridview.normalize(),e){case"top":case"bottom":this.gridview.orientation==="HORIZONTAL"&&this.gridview.insertOrthogonalSplitviewAtRoot();break;case"left":case"right":this.gridview.orientation==="VERTICAL"&&this.gridview.insertOrthogonalSplitviewAtRoot();break}switch(e){case"top":case"left":case"center":return this.createGroupAtLocation([0],void 0,t);case"bottom":case"right":return this.createGroupAtLocation([this.gridview.length],void 0,t);default:throw new Error(`dockview: unsupported position ${e}`)}}updateOptions(e){var t,n;super.updateOptions(e),this.reportMissingOptionModules(e),(t=this._floatingGroupService)===null||t===void 0||t.updateBounds(e),(n=this._rootDropTargetService)===null||n===void 0||n.setOptions(e);const s=this.options.disableDnd,o=this.options.dndStrategy;this._options=pt(pt({},this.options),e);const r=this.options.disableDnd,a=this.options.dndStrategy;if((s!==r||o!==a)&&this.updateDragAndDropState(),"theme"in e&&this.updateTheme(),"createRightHeaderActionComponent"in e||"createLeftHeaderActionComponent"in e||"createPrefixHeaderActionComponent"in e){var l;(l=this.headerActionsService)===null||l===void 0||l.refreshAll()}if("createWatermarkComponent"in e){var d;(d=this._watermarkService)===null||d===void 0||d.refresh();for(const u of this.groups)u.model.refreshWatermark()}if("tabGroupColors"in e||"tabGroupAccent"in e){var c;this._tabGroupColorPalette.setEntries((c=this._options.tabGroupColors)!==null&&c!==void 0?c:Sv),this._tabGroupColorPalette.enabled=this._options.tabGroupAccent!=="off";for(const u of this.groups)u.model.refreshTabGroupAccent()}this._onDidOptionsChange.fire(),this._layoutFromShell(this.gridview.width,this.gridview.height)}reportMissingOptionModules(e){kse(e,t=>this._moduleRegistry.has(t))}layout(e,t,n){var s;this._shellManager&&!this._inShellLayout?this._shellManager.layout(e,t):super.layout(e,t,n),this._syncFloatingOverlayHost(),(s=this._moduleRegistry)===null||s===void 0||(s=s.services.floatingGroupService)===null||s===void 0||s.constrainBounds()}_syncFloatingOverlayHost(){if(!this._floatingOverlayHost||!this._shellManager)return;const e=this._shellManager.element.getBoundingClientRect(),t=this.element.getBoundingClientRect(),n=this._floatingOverlayHost;n.style.left=`${t.left-e.left}px`,n.style.top=`${t.top-e.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`}_layoutFromShell(e,t){this._inShellLayout=!0,this.layout(e,t,!0),this._inShellLayout=!1}forceRelayout(){this._shellManager?this._layoutFromShell(this.width,this.height):super.forceRelayout()}addEdgeGroup(e,t){const n=this._edgeGroupService;if(!n)throw new Error(OE("EdgeGroup","api.addEdgeGroup"));if(n.has(e))throw new Error(`dockview: edge group already exists at position '${e}'`);return this.mutation("add",()=>{const s=this.createGroup({id:t.id});s.model.location={type:"edge",position:e},s.model.headerPosition=e;const o=s.model.onDidRemovePanel(()=>{s.model.isEmpty&&(n.isAutoReveal(s)?queueMicrotask(()=>{var r;s.model.isEmpty&&(!((r=this._edgeGroupService)===null||r===void 0)&&r.includes(s))&&this.removeEdgeGroup(e)}):this.setEdgeGroupCollapsed(s,!0))});return n.add(e,s,o),t.autoHide!==void 0&&n.setAutoHide(s,t.autoHide),t.autoReveal!==void 0&&n.setAutoReveal(s,t.autoReveal),this._onDidAddGroup.fire(s),this._shellManager.addEdgeView(e,t,s),s.api})}revealEdgeGroupWithData(e,t,n){const s=this._edgeGroupService;s&&this.mutation("add",()=>{var o;let r=s.get(e);r||(this.addEdgeGroup(e,{id:this.getNextGroupId(),autoReveal:!0,autoHide:n?.autoHide,collapsed:!0}),r=s.get(e)),r&&this.moveGroupOrPanel({from:{groupId:t.groupId,panelId:(o=t.panelId)!==null&&o!==void 0?o:void 0},to:{group:r,position:"center"}})})}getEdgeGroup(e){var t;return(t=this._edgeGroupService)===null||t===void 0||(t=t.get(e))===null||t===void 0?void 0:t.api}getEdgeGroupPanel(e){var t;return(t=this._edgeGroupService)===null||t===void 0?void 0:t.get(e)}pinEdgeGroup(e){var t;(t=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.pinEdgeGroup"))===null||t===void 0||t.pin(e)}autoHideEdgeGroup(e){var t;(t=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.autoHideEdgeGroup"))===null||t===void 0||t.autoHide(e)}peekEdgeGroup(e,t){var n;(n=Ps(this._moduleRegistry.services.autoHideEdgeGroupService,"AutoHideEdgeGroup","api.peekEdgeGroup"))===null||n===void 0||n.peek(e,t)}get overlayRoot(){return this.rootElement}getDropZoneRect(){return this.element.getBoundingClientRect()}getEdgeGroupExpandedSize(e){var t,n;return(t=(n=this._shellManager)===null||n===void 0?void 0:n.getEdgeGroupExpandedSize(e))!==null&&t!==void 0?t:0}repositionPanelOverlay(e,t,n){this.overlayRenderContainer.repositionPanelOverlay(e.api.id,t,n)}setEdgeGroupVisible(e,t){this._shellManager.setEdgeGroupVisible(e,t)}isEdgeGroupVisible(e){return this._shellManager.isEdgeGroupVisible(e)}removeEdgeGroup(e){const t=Ps(this._edgeGroupService,"EdgeGroup","api.removeEdgeGroup");if(!t)return;const n=t.get(e);if(!n)throw new Error(`dockview: no edge group exists at position '${e}'`);this.mutation("remove",()=>{for(const s of[...n.panels])this.removePanel(s,{removeEmptyGroup:!1,skipDispose:!1});this._shellManager.removeEdgeView(e),t.remove(e),n.dispose(),this._groups.delete(n.id),this._onDidRemoveGroup.fire(n)})}setEdgeGroupCollapsed(e,t){var n;const s=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);s&&this._shellManager.isEdgeGroupCollapsed(s)!==t&&(this._shellManager.setEdgeGroupCollapsed(s,t),e.api._onDidCollapsedChange.fire({isCollapsed:t}))}isEdgeGroupCollapsed(e){var t;const n=(t=this._edgeGroupService)===null||t===void 0?void 0:t.findPositionOf(e);return n?this._shellManager.isEdgeGroupCollapsed(n):!1}isEdgeGroupPeeking(e){return this._peekingGroups.has(e)}setEdgeGroupPeeking(e,t){this._peekingGroups.has(e)!==t&&(t?this._peekingGroups.add(e):this._peekingGroups.delete(e),e.api._onDidPeekChange.fire({isPeeking:t}))}isEdgeGroupAutoHide(e){var t,n;const s=(t=this._edgeGroupService)===null||t===void 0?void 0:t.isAutoHide(e);if(s!==void 0)return s;const o=(n=this._edgeGroupService)===null||n===void 0?void 0:n.findPositionOf(e);return o===void 0?!1:Une(this.options.autoHideEdgeGroups,o)}setEdgeGroupAutoHide(e,t){const n=this._edgeGroupService;n?.includes(e)&&(n.setAutoHide(e,t),this._onDidEdgeGroupAutoHideChange.fire(e))}updateDragAndDropState(){for(const e of this.groups)e.model.updateDragAndDropState()}focus(){var e;(e=this.activeGroup)===null||e===void 0||e.focus()}getGroupPanel(e){return this.panels.find(t=>t.id===e)}setActivePanel(e){e.group.model.openPanel(e),this.doSetGroupAndPanelActive(e.group)}activateNext(e={}){var t;if(!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}if(e.includePanel&&e.group&&e.group.activePanel!==e.group.panels[e.group.panels.length-1]){e.group.model.moveToNext({suppressRoll:!0});return}const n=Tn(e.group.element),s=(t=this.gridview.next(n))===null||t===void 0?void 0:t.view;this.doSetGroupAndPanelActive(s)}activatePrevious(e={}){var t;if(!e.group){if(!this.activeGroup)return;e.group=this.activeGroup}if(e.includePanel&&e.group&&e.group.activePanel!==e.group.panels[0]){e.group.model.moveToPrevious({suppressRoll:!0});return}const n=Tn(e.group.element),s=(t=this.gridview.previous(n))===null||t===void 0?void 0:t.view;s&&this.doSetGroupAndPanelActive(s)}toJSON(){var e,t,n,s,o;const r=this.gridview.serialize(),a=this.panels.reduce((h,p)=>(h[p.id]=p.toJSON(),h),{}),l=(e=(t=this._floatingGroupService)===null||t===void 0?void 0:t.serialize())!==null&&e!==void 0?e:[],d=(n=(s=this._popoutWindowService)===null||s===void 0?void 0:s.serialize())!==null&&n!==void 0?n:[],c={grid:r,panels:a,activeGroup:(o=this.activeGroup)===null||o===void 0?void 0:o.id};l.length>0&&(c.floatingGroups=l),d.length>0&&(c.popoutGroups=d);const u=this._serializeEdgeGroups();return u&&(c.edgeGroups=u),c}_serializeEdgeGroups(){var e;if(!(!((e=this._edgeGroupService)===null||e===void 0)&&e.hasAny()))return;const t=this._shellManager.toJSON();for(const[n,s]of this._edgeGroupService.entries()){const o=t[n];if(!o)continue;if(this._edgeGroupService.isAutoReveal(s)&&s.model.isEmpty){delete t[n];continue}o.group=s.toJSON(),this._edgeGroupService.isAutoReveal(s)&&(o.autoReveal=!0);const r=this._edgeGroupService.isAutoHide(s);r!==void 0&&(o.autoHide=r)}return t}fromJSON(e,t){this.mutation("load",()=>this._doFromJSON(e,t))}_doFromJSON(e,t){var n,s;if((n=this._popoutWindowService)===null||n===void 0||n.cancelPendingRestorations(),typeof e!="object"||e===null)throw new Error("dockview: serialized layout must be a non-null object");if(!e.grid||((s=e.grid.root)===null||s===void 0?void 0:s.type)!=="branch"||!Array.isArray(e.grid.root.data))throw new Error("dockview: root must be of type branch");const o=new Map,r=new Map,a=[],l=[],d=()=>{for(const b of l)try{b.dispose()}catch(_){console.error("dockview: failed to dispose a temporary group created for reuseExistingPanels",_)}l.length=0};if(t?.reuseExistingPanels){const b=Object.keys(e.panels);let _;const j=()=>{const N=this.createGroup(),C=this._groups.get(N.api.id);return this._groups.delete(N.api.id),l.push(rn.from(()=>{this.movingLock(()=>{for(const S of N.panels.slice())N.model.removePanel(S)}),C?.disposable.dispose(),N.dispose()})),N};try{for(const N of this.panels)if(b.includes(N.api.id)){o.set(N.api.id,N);let C;if(N.api.renderer==="always"&&N.api.isVisible)C=j();else{var c;(c=_)!==null&&c!==void 0||(_=j()),C=_}r.set(N.api.id,C),a.push({panel:N,temporaryGroup:C})}this.movingLock(()=>{a.forEach(({panel:N,temporaryGroup:C})=>{this.moveGroupOrPanel({from:{groupId:N.api.group.api.id,panelId:N.api.id},to:{group:C,position:"center"},keepEmptyGroups:!0})})}),this.clear()}catch(N){throw d(),N}}else this.clear();const{grid:u,panels:h,activeGroup:p}=e;try{var f,g,x,v,y;const b=this.width,_=this.height,j=C=>{const{id:S,locked:A,hideHeader:E,headerPosition:I,views:D,activeView:T}=C;if(typeof S!="string")throw new TypeError("dockview: group id must be of type string");const z=this.createGroup({id:S,locked:!!A,hideHeader:!!E,headerPosition:I});this._onDidAddGroup.fire(z);const $=[],R=D.filter(B=>h[B]);for(const B of R){const H=o.get(B),oe=r.get(B);if(oe&&H)this.movingLock(()=>{oe.model.removePanel(H)}),$.push(H),H.updateFromStateModel(h[B]);else{const te=this._deserializer.fromJSON(h[B],z);$.push(te)}}for(const B of $){const H=typeof T=="string"&&T===B.id;o.has(B.api.id)?this.movingLock(()=>{z.model.openPanel(B,{skipSetActive:!H,skipSetGroupActive:!0})}):z.model.openPanel(B,{skipSetActive:!H,skipSetGroupActive:!0})}return C.tabGroups&&C.tabGroups.length>0&&z.model.restoreTabGroups(C.tabGroups),!z.activePanel&&z.panels.length>0&&z.model.openPanel(z.panels[z.panels.length-1],{skipSetGroupActive:!0}),z};this.gridview.deserialize(u,{fromJSON:C=>j(C.data)}),this._layoutFromShell(b,_),e.edgeGroups&&this.deserializeEdgeGroups(e.edgeGroups,h,o,r),this.deserializeFloatingWindows((f=e.floatingGroups)!==null&&f!==void 0?f:[],j);const N=this.deserializePopoutWindows((g=e.popoutGroups)!==null&&g!==void 0?g:[],j);if((x=this._popoutWindowService)===null||x===void 0||x.finishRestoration(N),(v=this._floatingGroupService)===null||v===void 0||v.constrainBounds(),typeof p=="string"){const C=this.getPanel(p);C&&this.doSetGroupAndPanelActive(C)}(y=this._watermarkService)===null||y===void 0||y.update()}catch(b){var w;console.error("dockview: failed to deserialize layout. Reverting changes",b);for(const _ of this.groups)for(const j of _.panels)this.removePanel(j,{removeEmptyGroup:!1,skipDispose:!1});for(const _ of this.groups)_.dispose(),this._groups.delete(_.id),this._onDidRemoveGroup.fire(_);throw(w=this._floatingGroupService)===null||w===void 0||w.disposeAll(),this.clear(),b}finally{d()}this.debouncedUpdateAllPositions(),this._onDidLayoutFromJSON.fire()}deserializeNestedGridview(e,t){const n=this.createNestedGridview(e.orientation),s=[];return n.deserialize(e,{fromJSON:o=>{const r=t(o.data);return s.push(r),r}}),{gridview:n,members:s}}deserializeEdgeGroups(e,t,n,s){const o=Ps(this._edgeGroupService,"EdgeGroup","fromJSON edge restoration");if(o){for(const a of["top","bottom","left","right"]){const l=e[a];if(l&&!o.has(a)){var r;const d=l.group,c=(r=d?.id)!==null&&r!==void 0?r:`${a}-group`;this.addEdgeGroup(a,{id:c,autoReveal:l.autoReveal,autoHide:l.autoHide,minimumSize:l.minimumSize,maximumSize:l.maximumSize,collapsedSize:l.collapsedSize})}}for(const[a,l]of o.entries()){const d=e[a],c=d?.group;if(c){const{views:u,activeView:h}=c,p=[];for(const f of u){if(!t[f])continue;const g=n.get(f),x=s.get(f);if(x&&g)this.movingLock(()=>{x.model.removePanel(g)}),p.push(g),g.updateFromStateModel(t[f]);else{const v=this._deserializer.fromJSON(t[f],l);p.push(v)}}for(const f of p){const g=h===f.id;n.has(f.api.id)?this.movingLock(()=>{l.model.openPanel(f,{skipSetActive:!g,skipSetGroupActive:!0})}):l.model.openPanel(f,{skipSetActive:!g,skipSetGroupActive:!0})}c.tabGroups&&c.tabGroups.length>0&&l.model.restoreTabGroups(c.tabGroups),!l.activePanel&&l.panels.length>0&&l.model.openPanel(l.panels[l.panels.length-1],{skipSetGroupActive:!0})}}this._shellManager.fromJSON(e)}}deserializeFloatingWindows(e,t){for(const n of e){const{data:s,grid:o,position:r}=n;if(o){const{gridview:a,members:l}=this.deserializeNestedGridview(o,t);if(l.length===0)continue;this.mountFloatingWindow(a,l[0],l,r,{inDragMode:!1})}else if(s){const a=t(s);this.addFloatingGroup(a,{position:r,width:r.width,height:r.height,skipRemoveGroup:!0,inDragMode:!1})}}}deserializePopoutWindows(e,t){const n=e.length>0?Ps(this._popoutWindowService,"PopoutWindow","fromJSON popout restoration"):this._popoutWindowService;return n?e.flatMap((s,o)=>{const{data:r,grid:a,position:l,gridReferenceGroup:d,url:c}=s;let u,h=[];if(a){const f=this.deserializeNestedGridview(a,t);if(u=f.gridview,h=f.members,h.length===0)return u.dispose(),[]}const p=a?h[0]:t(r);return n.scheduleRestoration(o*100,()=>{this.addPopoutGroup(p,{position:l??void 0,overridePopoutGroup:d?p:void 0,overridePopoutGridview:u,referenceGroup:d?this.getPanel(d):void 0,popoutUrl:c})},()=>{for(const f of h.length>0?h:[p])if(!this.isDisposed&&this._groups.has(f.id)&&f.element.parentElement===null){for(const g of[...f.panels])this.removePanel(g,{removeEmptyGroup:!1});f.dispose(),this._groups.delete(f.id),this._onDidRemoveGroup.fire(f)}})}):[]}clear(){this.mutation("clear",()=>this._doClear())}_doClear(){const e=Array.from(this._groups.values()).map(s=>s.value),t=!!this.activeGroup;for(const s of e){var n;if(!((n=this._edgeGroupService)===null||n===void 0)&&n.includes(s)){const o=[...s.panels];for(const r of o)this.removePanel(r,{removeEmptyGroup:!1});continue}this.removeGroup(s,{skipActive:!0})}t&&this.doSetGroupAndPanelActive(void 0),this.gridview.clear()}closeAllGroups(){this.mutation("remove",()=>{for(const e of this._groups.entries()){const[t,n]=e;n.value.model.closeAllPanels()}})}addPanel(e){return this.mutation("add",()=>this._doAddPanel(e))}_doAddPanel(e){if(this.panels.some(u=>u.id===e.id))throw new Error(`dockview: panel with id ${e.id} already exists`);let t;if(e.position&&e.floating)throw new Error("dockview: you can only provide one of: position, floating as arguments to .addPanel(...)");const n={width:e.initialWidth,height:e.initialHeight};let s;const o=u=>!!e.inactive&&u.model.size>0;if(e.position)if(Kne(e.position)){const u=typeof e.position.referencePanel=="string"?this.getGroupPanel(e.position.referencePanel):e.position.referencePanel;if(s=e.position.index,!u){var r;const h=typeof e.position.referencePanel=="string"?e.position.referencePanel:(r=e.position.referencePanel)===null||r===void 0?void 0:r.id;throw new Error(`dockview: referencePanel '${h}' does not exist`)}t=this.findGroup(u)}else if(qne(e.position)){var a;if(t=typeof e.position.referenceGroup=="string"?(a=this._groups.get(e.position.referenceGroup))===null||a===void 0?void 0:a.value:e.position.referenceGroup,s=e.position.index,!t){var l;const u=typeof e.position.referenceGroup=="string"?e.position.referenceGroup:(l=e.position.referenceGroup)===null||l===void 0?void 0:l.id;throw new Error(`dockview: referenceGroup '${u}' does not exist`)}}else{const u=this.orthogonalize(cC(e.position.direction)),h=this.createPanel(e,u);return u.model.openPanel(h,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(u),u.api.setSize({height:n?.height,width:n?.width}),h}else t=this.activeGroup;let d;if(t){var c;const u=Ou(((c=e.position)===null||c===void 0?void 0:c.direction)||"within");if(e.floating){const h=this.createGroup();this._onDidAddGroup.fire(h);const p=typeof e.floating=="object"&&e.floating!==null?e.floating:{};this.addFloatingGroup(h,pt(pt({},p),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),d=this.createPanel(e,h),h.model.openPanel(d,{skipSetActive:o(h),skipSetGroupActive:e.inactive,index:s})}else if(t.api.location.type==="floating"||t.api.location.type==="edge"||u==="center")d=this.createPanel(e,t),t.model.openPanel(d,{skipSetActive:o(t),skipSetGroupActive:e.inactive,index:s}),t.api.setSize({width:n?.width,height:n?.height}),e.inactive||this.doSetGroupAndPanelActive(t);else{const h=Tn(t.element),p=Vs(this.gridview.orientation,h,u),f=this.createGroupAtLocation(p,this.orientationAtLocation(p)==="VERTICAL"?n?.height:n?.width);d=this.createPanel(e,f),f.model.openPanel(d,{skipSetActive:o(f),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(f)}}else if(e.floating){const u=this.createGroup();this._onDidAddGroup.fire(u);const h=typeof e.floating=="object"&&e.floating!==null?e.floating:{};this.addFloatingGroup(u,pt(pt({},h),{},{inDragMode:!1,skipRemoveGroup:!0,skipActiveGroup:!0})),d=this.createPanel(e,u),u.model.openPanel(d,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s})}else{const u=this.createGroupAtLocation([0],this.gridview.orientation==="VERTICAL"?n?.height:n?.width);d=this.createPanel(e,u),u.model.openPanel(d,{skipSetActive:o(u),skipSetGroupActive:e.inactive,index:s}),e.inactive||this.doSetGroupAndPanelActive(u)}return d}removePanel(e,t){this.mutation("remove",()=>{var n;return this._doRemovePanel(e,{removeEmptyGroup:(n=t?.removeEmptyGroup)!==null&&n!==void 0?n:!0,skipDispose:t?.skipDispose,skipSetActiveGroup:t?.skipSetActiveGroup})})}_doRemovePanel(e,t){const n=e.group;if(!n)throw new Error(`dockview: cannot remove panel ${e.id}. it's missing a group.`);n.model.removePanel(e,{skipSetActiveGroup:t.skipSetActiveGroup}),t.skipDispose||(e.group.model.renderContainer.detatch(e),e.dispose()),n.size===0&&t.removeEmptyGroup&&this.removeGroup(n,{skipActive:t.skipSetActiveGroup})}createWatermarkComponent(){return this.options.createWatermarkComponent?this.options.createWatermarkComponent():new gse}addGroup(e){return this.mutation("add",()=>this._doAddGroup(e))}_doAddGroup(e){if(e){let o;if(Yne(e)){var t;const u=typeof e.referencePanel=="string"?this.panels.find(p=>p.id===e.referencePanel):e.referencePanel,h=typeof e.referencePanel=="string"?e.referencePanel:(t=e.referencePanel)===null||t===void 0?void 0:t.id;if(!u)throw new Error(`dockview: reference panel ${h} does not exist`);if(o=this.findGroup(u),!o)throw new Error(`dockview: reference group for reference panel ${h} does not exist`)}else if(Xne(e)){var n;if(o=typeof e.referenceGroup=="string"?(n=this._groups.get(e.referenceGroup))===null||n===void 0?void 0:n.value:e.referenceGroup,!o){var s;const u=typeof e.referenceGroup=="string"?e.referenceGroup:(s=e.referenceGroup)===null||s===void 0?void 0:s.id;throw new Error(`dockview: reference group ${u} does not exist`)}}else{const u=this.orthogonalize(cC(e.direction),e);return e.skipSetActive||this.doSetGroupAndPanelActive(u),u}const r=Ou(e.direction||"within"),a=Tn(o.element),l=Vs(this.gridview.orientation,a,r),d=this.createGroup(e),c=this.getLocationOrientation(l)==="VERTICAL"?e.initialHeight:e.initialWidth;return this.doAddGroup(d,l,c),e.skipSetActive||this.doSetGroupAndPanelActive(d),d}else{const o=this.createGroup(e);return this.doAddGroup(o),this.doSetGroupAndPanelActive(o),o}}getLocationOrientation(e){return e.length%2==0&&this.gridview.orientation==="HORIZONTAL"?"HORIZONTAL":"VERTICAL"}removeGroup(e,t){this.mutation("remove",()=>this.doRemoveGroup(e,t))}detachFromNestedWindow(e){var t,n;const s=(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e);if(s){const r=this.nestedWindowMembers(e);return r.length<=1?!1:(s.gridview.remove(e),s.group===e&&s.setAnchorGroup(r.find(a=>a!==e)),!0)}const o=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);if(o){const r=this.nestedWindowMembers(e);return r.length<=1?!1:(o.gridview.remove(e),o.popoutGroup===e&&o.setAnchorGroup(r.find(a=>a!==e)),!0)}return!1}disposeGroupRecord(e){e.dispose(),this._groups.delete(e.id),this._onDidRemoveGroup.fire(e)}activateFallbackGroupIfRemoved(e,t){if(!t&&this._activeGroup===e){const n=Array.from(this._groups.values());this.doSetGroupAndPanelActive(n.length>0?n[0].value:void 0)}}doRemoveGroup(e,t){var n;if(!((n=this._edgeGroupService)===null||n===void 0)&&n.includes(e))return e;const s=[...e.panels];if(!t?.skipDispose)for(const u of s){var o;this.removePanel(u,{removeEmptyGroup:!1,skipDispose:(o=t?.skipDispose)!==null&&o!==void 0?o:!1})}const r=this.activePanel;if(e.api.location.type==="floating"){var a;const u=(a=this._floatingGroupService)===null||a===void 0?void 0:a.findByGroup(e);if(!u)throw new Error("dockview: failed to find floating group");return this.detachFromNestedWindow(e)?(t?.skipDispose?e.model.location={type:"grid"}:this.disposeGroupRecord(e),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e):(t?.skipDispose||this.disposeGroupRecord(e),u.dispose(),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e)}if(e.api.location.type==="popout"){var l,d;const u=(l=this._popoutWindowService)===null||l===void 0?void 0:l.findByGroup(e);if(!u)throw new Error("dockview: failed to find popout group");if(this.detachFromNestedWindow(e))return t?.skipDispose?e.model.location={type:"grid"}:this.disposeGroupRecord(e),this.activateFallbackGroupIfRemoved(e,t?.skipActive),e;if(!t?.skipDispose){if(!t?.skipPopoutAssociated){const p=u.referenceGroup?this.getPanel(u.referenceGroup):void 0;p?.panels.length===0&&this.removeGroup(p)}u.popoutGroup.dispose(),this._groups.delete(e.id),this._onDidRemoveGroup.fire(e)}(d=this._popoutWindowService)===null||d===void 0||d.remove(u);const h=u.disposable.dispose();return!t?.skipPopoutReturn&&h&&(this.doAddGroup(h,[0]),this.doSetGroupAndPanelActive(h)),this.activateFallbackGroupIfRemoved(e,t?.skipActive),u.popoutGroup}if(!this.gridview.element.contains(e.element)){if(!t?.skipDispose){const u=this._groups.get(e.id);u?.disposable.dispose(),this.disposeGroupRecord(e)}return this.activateFallbackGroupIfRemoved(e,t?.skipActive),e}const c=super.doRemoveGroup(e,t);return t?.skipActive||this.activePanel!==r&&this.fireActivePanelChange(this.activePanel),c}debouncedUpdateAllPositions(){this._updatePositionsFrameId!==void 0&&cancelAnimationFrame(this._updatePositionsFrameId),this._updatePositionsFrameId=requestAnimationFrame(()=>{var e,t;this._updatePositionsFrameId=void 0,this.overlayRenderContainer.updateAllPositions();for(const n of(e=(t=this._popoutWindowService)===null||t===void 0?void 0:t.entries)!==null&&e!==void 0?e:[])n.overlayRenderContainer.updateAllPositions()})}movingLock(e){const t=this._moving;try{return this._moving=!0,e()}finally{this._moving=t}}mutation(e,t){const n=this.openMutation(e);try{return t()}finally{n()}}mutationAsync(e,t){var n=this;return GE(function*(){const s=n.openMutation(e);try{return yield t()}finally{s()}})()}openMutation(e){const t=this._origin;return this._mutationDepth===0&&this._onWillMutateLayout.fire({kind:e,origin:t}),this._mutationDepth++,()=>{this._mutationDepth--,this._mutationDepth===0&&(this.flushLocationChanges(),this._onDidMutateLayout.fire({kind:e,origin:t}))}}deferLocationChange(e,t){if(this._mutationDepth===0){t();return}this._pendingLocationChanges.set(e,t)}flushLocationChanges(){if(this._pendingLocationChanges.size===0)return;const e=Array.from(this._pendingLocationChanges.values());this._pendingLocationChanges.clear();for(const t of e)t()}currentOrigin(){return this._origin}withOrigin(e,t){if(this._originDepth>0||this._mutationDepth>0)return t();const n=this._origin;this._origin=e,this._originDepth++;try{return t()}finally{this._originDepth--,this._origin=n}}fireActivePanelChange(e){this._onDidActivePanelChange.fire({panel:e,origin:this._origin})}fireDidMovePanel(e,t){this._onDidMovePanel.fire({panel:e,from:t,to:e.group})}moveGroupOrPanel(e){this.mutation("move",()=>this._doMoveGroupOrPanel(e))}_doMoveGroupOrPanel(e){var t;const n=e.to.group,s=e.from.groupId,o=e.from.panelId,r=e.to.position,a=e.to.index,l=s?(t=this._groups.get(s))===null||t===void 0?void 0:t.value:void 0;if(!l)throw new Error(`dockview: Failed to find group id ${s}`);if(o===void 0){e.from.tabGroupId?this.moveTabGroupToGroup({sourceGroup:l,tabGroupId:e.from.tabGroupId,destinationGroup:n,destinationTarget:r,destinationIndex:a,skipSetActive:e.skipSetActive,keepEmptyGroups:e.keepEmptyGroups}):this.moveGroup({from:{group:l},to:{group:n,position:r},skipSetActive:e.skipSetActive});return}if(!r||r==="center"){const c=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!c)throw new Error(`dockview: No panel with id ${o}`);!e.keepEmptyGroups&&l.model.size===0&&this.doRemoveGroup(l,{skipActive:!0});const u=n.model.size===0;this.movingLock(()=>{var h;return n.model.openPanel(c,{index:a,skipSetActive:((h=e.skipSetActive)!==null&&h!==void 0?h:!1)&&!u,skipSetGroupActive:!0})}),e.skipSetActive||this.doSetGroupAndPanelActive(n),this.fireDidMovePanel(c,l)}else{const c=this.getGridviewForGroup(n),u=Tn(n.element),h=Vs(c.orientation,u,r);if(l.size<2){const[p,f]=ao(h);if(l.api.location.type==="grid"&&c===this.gridview){const[y,w]=ao(Tn(l.element));if(rE(y,p)){this.gridview.moveView(y,w,f),this.fireDidMovePanel(this.getGroupPanel(o),l);return}}if(l.api.location.type==="popout"&&this.nestedWindowMembers(l).length<=1){var d;const y=(d=this._popoutWindowService)===null||d===void 0?void 0:d.findByGroup(l);if(!y)return;const w=this.movingLock(()=>y.popoutGroup.model.removePanel(y.popoutGroup.panels[0],{skipSetActive:!0,skipSetActiveGroup:!0}));this.doRemoveGroup(l,{skipActive:!0});const b=Vs(c.orientation,Tn(n.element),r),_=this.createGroupAtLocation(b,void 0,void 0,c);this.movingLock(()=>_.model.openPanel(w,{skipSetActive:!0})),this.doSetGroupAndPanelActive(_),this.fireDidMovePanel(this.getGroupPanel(o),l);return}if(l.api.location.type==="edge"){const y=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!y)throw new Error(`dockview: No panel with id ${o}`);const w=this.createGroupAtLocation(h,void 0,void 0,c);this.movingLock(()=>w.model.openPanel(y,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(w),this.fireDidMovePanel(y,l);return}const g=this.movingLock(()=>this.doRemoveGroup(l,{skipActive:!0,skipDispose:!0})),x=Tn(n.element),v=Vs(c.orientation,x,r);this.movingLock(()=>this.doAddGroup(g,v,void 0,c)),this.setGroupLocationForRoot(g,c),this.doSetGroupAndPanelActive(g),this.fireDidMovePanel(this.getGroupPanel(o),l)}else{const p=this.movingLock(()=>l.model.removePanel(o,{skipSetActive:!1,skipSetActiveGroup:!0}));if(!p)throw new Error(`dockview: No panel with id ${o}`);const f=Vs(c.orientation,u,r),g=this.createGroupAtLocation(f,void 0,void 0,c);this.movingLock(()=>g.model.openPanel(p,{skipSetGroupActive:!0})),this.doSetGroupAndPanelActive(g),this.fireDidMovePanel(p,l)}}}moveTabGroupToGroup(e){const{sourceGroup:t,tabGroupId:n,destinationGroup:s,destinationTarget:o,destinationIndex:r}=e,a=t.model.getTabGroups().find(v=>v.id===n);if(!a||a.panelIds.length===0)return;const l=a.label,d=a.color,c=a.collapsed,u=a.componentParams,h=[...a.panelIds],p=o&&o!=="center"?Tn(s.element):void 0,f=this.movingLock(()=>h.map(v=>t.model.removePanel(v,{skipSetActive:!1,skipSetActiveGroup:!0})).filter(v=>v!==void 0));if(f.length===0)return;const g=v=>{this.movingLock(()=>{for(const w of f)v.model.openPanel(w,{index:r,skipSetActive:!0,skipSetGroupActive:!0})});const y=v.model.createTabGroup({label:l,color:d,collapsed:c,componentParams:u});for(const w of f)v.model.addPanelToTabGroup(y.id,w.id);e.skipSetActive||this.doSetGroupAndPanelActive(v);for(const w of f)this.fireDidMovePanel(w,t)};let x;if(!o||o==="center"||!p)x=s;else{const v=Vs(this.gridview.orientation,p,o);x=this.createGroupAtLocation(v)}!e.keepEmptyGroups&&t.model.size===0&&t!==x&&this.doRemoveGroup(t,{skipActive:!0}),g(x)}moveGroup(e){this.mutation("move",()=>this._doMoveGroup(e))}maximizeGroup(e){this.mutation("maximize",()=>super.maximizeGroup(e))}exitMaximizedGroup(){this.mutation("maximize",()=>super.exitMaximizedGroup())}_doMoveGroup(e){var t;const n=e.from.group,s=e.to.group,o=e.to.position;let r=n,a;if(o==="center"){const u=n.activePanel,h=n.model.getTabGroups().map(f=>({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams,panelIds:[...f.panelIds]})),p=this.movingLock(()=>[...n.panels].map(f=>n.model.removePanel(f.id,{skipSetActive:!0})));n?.model.size===0&&this.doRemoveGroup(n,{skipActive:!0}),this.movingLock(()=>{for(const f of p)s.model.openPanel(f,{skipSetActive:f!==u,skipSetGroupActive:!0})}),a=p;for(const f of h){const g=s.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const x of f.panelIds)s.model.addPanelToTabGroup(g.id,x)}e.skipSetActive!==!0?this.doSetGroupAndPanelActive(s):this.activePanel||this.doSetGroupAndPanelActive(s)}else{if(n.api.location.type==="edge"){const u=n.activePanel,h=n.model.getTabGroups().map(f=>({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams,panelIds:[...f.panelIds]})),p=this.movingLock(()=>[...n.panels].map(f=>n.model.removePanel(f.id,{skipSetActive:!0})));r=this.createGroup(),this._onDidAddGroup.fire(r),this.movingLock(()=>{for(const f of p)r.model.openPanel(f,{skipSetActive:f!==u,skipSetGroupActive:!0})});for(const f of h){const g=r.model.createTabGroup({label:f.label,color:f.color,collapsed:f.collapsed,componentParams:f.componentParams});for(const x of f.panelIds)r.model.addPanelToTabGroup(g.id,x)}}else switch(n.api.location.type){case"grid":this.gridview.removeView(Tn(n.element));break;case"floating":{var l;const u=(l=this._floatingGroupService)===null||l===void 0?void 0:l.findByGroup(n);if(!u)throw new Error("dockview: failed to find floating group");this.detachFromNestedWindow(n)||u.dispose();break}case"popout":{var d,c;const u=(d=this._popoutWindowService)===null||d===void 0?void 0:d.findByGroup(n);if(!u)throw new Error("dockview: failed to find popout group");if(this.detachFromNestedWindow(n))break;if((c=this._popoutWindowService)===null||c===void 0||c.remove(u),u.referenceGroup){const h=this.getPanel(u.referenceGroup);h&&!h.api.isVisible&&this.doRemoveGroup(h,{skipActive:!0})}u.window.dispose();break}}if(s.api.location.type==="grid"||s.api.location.type==="floating"||s.api.location.type==="popout"){const u=this.getGridviewForGroup(s),h=Tn(s.element),p=Vs(u.orientation,h,o);let f;switch(u.orientation){case"VERTICAL":f=h.length%2==0?n.api.width:n.api.height;break;case"HORIZONTAL":f=h.length%2==0?n.api.height:n.api.width;break}u.addView(r,f,p),this.setGroupLocationForRoot(r,u)}}if(((t=a)!==null&&t!==void 0?t:r.panels).forEach(u=>{this.fireDidMovePanel(u,n)}),this.debouncedUpdateAllPositions(),e.skipSetActive===!1){const u=s??n;this.doSetGroupAndPanelActive(u)}else r!==n&&e.skipSetActive!==!0&&this.doSetGroupAndPanelActive(r)}doSetGroupActive(e){var t;super.doSetGroupActive(e);const n=this.activePanel;!this._moving&&n!==((t=this._onDidActivePanelChange.value)===null||t===void 0?void 0:t.panel)&&this.fireActivePanelChange(n)}doSetGroupAndPanelActive(e){var t;super.doSetGroupActive(e);const n=this.activePanel;e&&this.hasMaximizedGroup()&&!this.isMaximizedGroup(e)&&this.exitMaximizedGroup(),!this._moving&&n!==((t=this._onDidActivePanelChange.value)===null||t===void 0?void 0:t.panel)&&this.fireActivePanelChange(n)}getNextGroupId(){let e=this.nextGroupId.next();for(;this._groups.has(e);)e=this.nextGroupId.next();return e}createGroup(e){var t;(t=e)!==null&&t!==void 0||(e={});let n=e?.id;if(n&&this._groups.has(e.id)&&(console.warn(`dockview: Duplicate group id ${e?.id}. reassigning group id to avoid errors`),n=void 0),!n)for(n=this.nextGroupId.next();this._groups.has(n);)n=this.nextGroupId.next();const s=new cc(this,n,e);if(s.init({params:{},accessor:this}),!this._groups.has(s.id)){const o=new ct(s.model.onTabDragStart(r=>{var a;(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillDragPanel(r)}),s.model.onGroupDragStart(r=>{var a;(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillDragGroup(r)}),s.model.onMove(r=>{const{groupId:a,itemId:l,target:d,index:c,tabGroupId:u}=r;this.moveGroupOrPanel({from:{groupId:a,panelId:l,tabGroupId:u},to:{group:s,position:d,index:c}})}),s.model.onDidDrop(r=>{this._onDidDrop.fire(r)}),s.model.onWillDrop(r=>{var a;(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillDrop(r)}),s.model.onWillShowOverlay(r=>{var a;if(this.options.disableDnd){r.preventDefault();return}(a=this._advancedDnDService)===null||a===void 0||a.dispatchWillShowOverlay(r)}),s.model.onUnhandledDragOver(r=>{this._onUnhandledDragOver.fire(r)}),s.model.onDidAddPanel(r=>{this._moving||this._onDidAddPanel.fire(r.panel)}),s.model.onDidRemovePanel(r=>{this._moving||this._onDidRemovePanel.fire(r.panel)}),s.model.onDidActivePanelChange(r=>{var a;this._moving||r.panel===this.activePanel&&((a=this._onDidActivePanelChange.value)===null||a===void 0?void 0:a.panel)!==r.panel&&this.fireActivePanelChange(r.panel)}),Qs.any(s.model.onDidPanelTitleChange,s.model.onDidPanelParametersChange)(()=>{this._bufferOnDidLayoutChange.fire()}));this._groups.set(s.id,{value:s,disposable:o})}return s.initialize(),s}createPanel(e,t){var n,s,o;const r=e.component,a=(n=e.tabComponent)!==null&&n!==void 0?n:this.options.defaultTabComponent,l=new LE(this,e.id,r,a),d=new Gr(e.id,r,a,this,this._api,t,l,{renderer:e.renderer,minimumWidth:e.minimumWidth,minimumHeight:e.minimumHeight,maximumWidth:e.maximumWidth,maximumHeight:e.maximumHeight});return d.init({title:(s=e.title)!==null&&s!==void 0?s:e.id,params:(o=e?.params)!==null&&o!==void 0?o:{}}),d}createGroupAtLocation(e,t,n,s=this.gridview){const o=this.createGroup(n);return this.doAddGroup(o,e,t,s),this.setGroupLocationForRoot(o,s),o}setGroupLocationForRoot(e,t){var n;const s=(n=this._popoutWindowService)===null||n===void 0?void 0:n.entries.find(o=>o.gridview===t);if(s){e.model.renderContainer!==s.overlayRenderContainer&&(e.model.renderContainer=s.overlayRenderContainer),e.model.dropTargetContainer=s.dropTargetContainer,e.model.location={type:"popout",getWindow:s.getWindow,popoutUrl:s.popoutUrl};return}e.model.renderContainer!==this.overlayRenderContainer&&(e.model.renderContainer=this.overlayRenderContainer),e.model.dropTargetContainer=this.rootDropTargetContainer,e.model.location=t===this.gridview?{type:"grid"}:{type:"floating"}}getGridviewForGroup(e){var t,n;const s=(t=this._floatingGroupService)===null||t===void 0?void 0:t.findByGroup(e);if(s)return s.gridview;const o=(n=this._popoutWindowService)===null||n===void 0?void 0:n.findByGroup(e);return o?o.gridview:this.gridview}nestedWindowMembers(e){const t=this.getGridviewForGroup(e);return t===this.gridview?[]:this.groups.filter(n=>t.element.contains(n.element))}findGroup(e){var t;return(t=Array.from(this._groups.values()).find(n=>n.value.model.containsPanel(e)))===null||t===void 0?void 0:t.value}orientationAtLocation(e){const t=this.gridview.orientation;return e.length%2==1?t:Ni(t)}updateTheme(){var e,t,n,s,o,r,a,l;const d=(e=this._options.theme)!==null&&e!==void 0?e:pse;(t=this._shellThemeClassnames)===null||t===void 0||t.setClassNames(d.className);const c=(n=d.gap)!==null&&n!==void 0?n:0;this.gridview.margin=c;for(const f of this.floatingGroups)f.gridview.margin=c;for(const f of(s=(o=this._popoutWindowService)===null||o===void 0?void 0:o.entries)!==null&&s!==void 0?s:[])f.gridview.margin=c;if((r=this._shellManager)===null||r===void 0||r.updateTheme(c,(a=d.edgeGroupCollapsedSize)!==null&&a!==void 0?a:35),d.dndOverlayBorder===void 0){var u;this.element.style.removeProperty("--dv-drag-over-border"),(u=this._shellManager)===null||u===void 0||u.element.style.removeProperty("--dv-drag-over-border")}else{var h;this.element.style.setProperty("--dv-drag-over-border",d.dndOverlayBorder),(h=this._shellManager)===null||h===void 0||h.element.style.setProperty("--dv-drag-over-border",d.dndOverlayBorder)}d.dndOverlayMounting==="absolute"?this.rootDropTargetContainer.disabled=!1:this.rootDropTargetContainer.disabled=!0;const p=((l=d.tabGroupIndicator)!==null&&l!==void 0?l:"wrap")==="none";Ze(this.element,"dv-tab-group-indicator-none",p),this._shellManager&&Ze(this._shellManager.element,"dv-tab-group-indicator-none",p);for(const f of this.groups)f.model.updateTabGroups()}},cie=class extends cE{get orientation(){return this.gridview.orientation}set orientation(e){this.gridview.orientation=e}get options(){return this._options}get deserializer(){return this._deserializer}set deserializer(e){this._deserializer=e}constructor(e,t){var n;super(e,{proportionalLayout:(n=t.proportionalLayout)!==null&&n!==void 0?n:!0,orientation:t.orientation,styles:t.hideBorders?{separatorBorder:"transparent"}:void 0,disableAutoResizing:t.disableAutoResizing,className:t.className}),this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidRemoveGroup=new ve,this.onDidRemoveGroup=this._onDidRemoveGroup.event,this._onDidAddGroup=new ve,this.onDidAddGroup=this._onDidAddGroup.event,this._onDidActiveGroupChange=new ve,this.onDidActiveGroupChange=this._onDidActiveGroupChange.event,this._options=t,this.addDisposables(this._onDidAddGroup,this._onDidRemoveGroup,this._onDidActiveGroupChange,this.onDidAdd(s=>{this._onDidAddGroup.fire(s)}),this.onDidRemove(s=>{this._onDidRemoveGroup.fire(s)}),this.onDidActiveChange(s=>{this._onDidActiveGroupChange.fire(s)}))}updateOptions(e){super.updateOptions(e);const t=typeof e.orientation=="string"&&this.gridview.orientation!==e.orientation;this._options=pt(pt({},this.options),e),t&&(this.gridview.orientation=e.orientation),this.layout(this.gridview.width,this.gridview.height,!0)}removePanel(e){this.removeGroup(e)}toJSON(){var e;return{grid:this.gridview.serialize(),activePanel:(e=this.activeGroup)===null||e===void 0?void 0:e.id}}setVisible(e,t){this.gridview.setViewVisible(Tn(e.element),t)}setActive(e){this._groups.forEach((t,n)=>{t.value.setActive(e===t.value)})}focus(){var e;(e=this.activeGroup)===null||e===void 0||e.focus()}fromJSON(e){this.clear();const{grid:t,activePanel:n}=e;try{const s=[],o=this.width,r=this.height;if(this.gridview.deserialize(t,{fromJSON:a=>{const{data:l}=a,d=this.options.createComponent({id:l.id,name:l.component});return s.push(()=>d.init({params:l.params,minimumWidth:l.minimumWidth,maximumWidth:l.maximumWidth,minimumHeight:l.minimumHeight,maximumHeight:l.maximumHeight,priority:l.priority,snap:!!l.snap,accessor:this,isVisible:a.visible})),this._onDidAddGroup.fire(d),this.registerPanel(d),d}}),this.layout(o,r,!0),s.forEach(a=>a()),typeof n=="string"){const a=this.getPanel(n);a&&this.doSetGroupActive(a)}}catch(s){for(const o of this.groups)o.dispose(),this._groups.delete(o.id),this._onDidRemoveGroup.fire(o);throw this.clear(),s}this._onDidLayoutfromJSON.fire()}clear(){const e=this.activeGroup,t=Array.from(this._groups.values());for(const n of t)n.disposable.dispose(),this.doRemoveGroup(n.value,{skipActive:!0});e&&this.doSetGroupActive(void 0),this.gridview.clear()}movePanel(e,t){var n;const s=(n=this._groups.get(t.reference))===null||n===void 0?void 0:n.value;if(!s)throw new Error(`reference group ${t.reference} does not exist`);const o=Ou(t.direction);if(o==="center")throw new Error(`${o} not supported as an option`);const r=Tn(s.element),a=Vs(this.gridview.orientation,r,o),l=this.gridview.remove(e);this.doAddGroup(l,a,t.size)}addPanel(e){var t,n,s;let o=(t=e.location)!==null&&t!==void 0?t:[0];if(!((n=e.position)===null||n===void 0)&&n.referencePanel){var r;const l=(r=this._groups.get(e.position.referencePanel))===null||r===void 0?void 0:r.value;if(!l)throw new Error(`reference group ${e.position.referencePanel} does not exist`);const d=Ou(e.position.direction);if(d==="center")throw new Error(`${d} not supported as an option`);{const c=Tn(l.element);o=Vs(this.gridview.orientation,c,d)}}const a=this.options.createComponent({id:e.id,name:e.component});return a.init({params:(s=e.params)!==null&&s!==void 0?s:{},minimumWidth:e.minimumWidth,maximumWidth:e.maximumWidth,minimumHeight:e.minimumHeight,maximumHeight:e.maximumHeight,priority:e.priority,snap:!!e.snap,accessor:this,isVisible:!0}),this.doAddGroup(a,o,e.size),this.registerPanel(a),this.doSetGroupActive(a),a}registerPanel(e){const t=new ct(e.api.onDidFocusChange(n=>{n.isFocused&&this._groups.forEach(s=>{const o=s.value;o.setActive(o===e)})}));this._groups.set(e.id,{value:e,disposable:t})}moveGroup(e,t,n){const s=this.getPanel(t);if(!s)throw new Error("invalid operation");const o=Tn(e.element),[r,a]=ao(Vs(this.gridview.orientation,o,n)),[l,d]=ao(Tn(s.element));if(rE(l,r)){this.gridview.moveView(l,d,a);return}const c=this.doRemoveGroup(s,{skipActive:!0,skipDispose:!0}),u=Tn(e.element),h=Vs(this.gridview.orientation,u,n);this.doAddGroup(c,h)}removeGroup(e){super.removeGroup(e)}dispose(){super.dispose(),this._onDidLayoutfromJSON.dispose()}},uie=class extends vv{get panels(){return this.splitview.getViews()}get options(){return this._options}get length(){return this._panels.size}get orientation(){return this.splitview.orientation}get splitview(){return this._splitview}set splitview(e){this._splitview&&this._splitview.dispose(),this._splitview=e,this._splitviewChangeDisposable.value=new ct(this._splitview.onDidSashEnd(()=>{this._onDidLayoutChange.fire(void 0)}),this._splitview.onDidAddView(t=>this._onDidAddView.fire(t)),this._splitview.onDidRemoveView(t=>this._onDidRemoveView.fire(t)))}get minimumSize(){return this.splitview.minimumSize}get maximumSize(){return this.splitview.maximumSize}get height(){return this.splitview.orientation==="HORIZONTAL"?this.splitview.orthogonalSize:this.splitview.size}get width(){return this.splitview.orientation==="HORIZONTAL"?this.splitview.size:this.splitview.orthogonalSize}constructor(e,t){var n;super(document.createElement("div"),t.disableAutoResizing),this._splitviewChangeDisposable=new Fn,this._panels=new Map,this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this._onDidLayoutChange=new ve,this.onDidLayoutChange=this._onDidLayoutChange.event,this.element.style.height="100%",this.element.style.width="100%",this._classNames=new Lh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.splitview=new yr(this.element,t),this.addDisposables(this._onDidAddView,this._onDidLayoutfromJSON,this._onDidRemoveView,this._onDidLayoutChange)}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}typeof e.orientation=="string"&&(this.splitview.orientation=e.orientation),this._options=pt(pt({},this.options),e),this.splitview.layout(this.splitview.size,this.splitview.orthogonalSize)}focus(){var e;(e=this._activePanel)===null||e===void 0||e.focus()}movePanel(e,t){this.splitview.moveView(e,t)}setVisible(e,t){const n=this.panels.indexOf(e);this.splitview.setViewVisible(n,t)}setActive(e,t){this._activePanel=e,this.panels.filter(n=>n!==e).forEach(n=>{n.api._onDidActiveChange.fire({isActive:!1}),t||n.focus()}),e.api._onDidActiveChange.fire({isActive:!0}),t||e.focus()}removePanel(e,t){const n=this._panels.get(e.id);if(!n)throw new Error(`unknown splitview panel ${e.id}`);n.dispose(),this._panels.delete(e.id);const s=this.panels.indexOf(e);this.splitview.removeView(s,t).dispose();const o=this.panels;o.length>0&&this.setActive(o[o.length-1])}getPanel(e){return this.panels.find(t=>t.id===e)}addPanel(e){var t;if(this._panels.has(e.id))throw new Error(`panel ${e.id} already exists`);const n=this.options.createComponent({id:e.id,name:e.component});n.orientation=this.splitview.orientation,n.init({params:(t=e.params)!==null&&t!==void 0?t:{},minimumSize:e.minimumSize,maximumSize:e.maximumSize,snap:e.snap,priority:e.priority,accessor:this});const s=typeof e.size=="number"?e.size:ks.Distribute,o=typeof e.index=="number"?e.index:void 0;return this.splitview.addView(n,s,o),this.doAddView(n),this.setActive(n),n}layout(e,t){const[n,s]=this.splitview.orientation==="HORIZONTAL"?[e,t]:[t,e];this.splitview.layout(n,s)}doAddView(e){const t=e.api.onDidFocusChange(n=>{n.isFocused&&this.setActive(e,!0)});this._panels.set(e.id,t)}toJSON(){var e;return{views:this.splitview.getViews().map((t,n)=>({size:this.splitview.getViewSize(n),data:t.toJSON(),snap:!!t.snap,priority:t.priority})),activeView:(e=this._activePanel)===null||e===void 0?void 0:e.id,size:this.splitview.size,orientation:this.splitview.orientation}}fromJSON(e){this.clear();const{views:t,orientation:n,size:s,activeView:o}=e,r=[],a=this.width,l=this.height;if(this.splitview=new yr(this.element,{orientation:n,proportionalLayout:this.options.proportionalLayout,descriptor:{size:s,views:t.map(d=>{const c=d.data;if(this._panels.has(c.id))throw new Error(`panel ${c.id} already exists`);const u=this.options.createComponent({id:c.id,name:c.component});return r.push(()=>{var h;u.init({params:(h=c.params)!==null&&h!==void 0?h:{},minimumSize:c.minimumSize,maximumSize:c.maximumSize,snap:d.snap,priority:d.priority,accessor:this})}),u.orientation=n,this.doAddView(u),setTimeout(()=>{this._onDidAddView.fire(u)},0),{size:d.size,view:u}})}}),this.layout(a,l),r.forEach(d=>d()),typeof o=="string"){const d=this.getPanel(o);d&&this.setActive(d)}this._onDidLayoutfromJSON.fire()}clear(){for(const e of this._panels.values())e.dispose();for(this._panels.clear();this.splitview.length>0;)this.splitview.removeView(0,ks.Distribute,!0).dispose()}dispose(){for(const t of this._panels.values())t.dispose();this._panels.clear();const e=this.splitview.getViews();this._splitviewChangeDisposable.dispose(),this.splitview.dispose();for(const t of e)t.dispose();this.element.remove(),super.dispose()}},yC=class extends ct{get element(){return this._element}constructor(){super(),this._expandedIcon=zne(),this._collapsedIcon=jE(),this.disposable=new Fn,this.apiRef={api:null},this._element=document.createElement("div"),this.element.className="dv-default-header",this._content=document.createElement("span"),this._expander=document.createElement("div"),this._expander.className="dv-pane-header-icon",this.element.appendChild(this._expander),this.element.appendChild(this._content),this.addDisposables(ot(this._element,"click",()=>{var e;(e=this.apiRef.api)===null||e===void 0||e.setExpanded(!this.apiRef.api.isExpanded)}))}init(e){this.apiRef.api=e.api,this._content.textContent=e.title,this.updateIcon(),this.disposable.value=e.api.onDidExpansionChange(()=>{this.updateIcon()})}updateIcon(){var e;const t=!!(!((e=this.apiRef.api)===null||e===void 0)&&e.isExpanded);Ze(this._expander,"collapsed",!t),t?(this._expander.contains(this._collapsedIcon)&&this._collapsedIcon.remove(),this._expander.contains(this._expandedIcon)||this._expander.appendChild(this._expandedIcon)):(this._expander.contains(this._expandedIcon)&&this._expandedIcon.remove(),this._expander.contains(this._collapsedIcon)||this._expander.appendChild(this._collapsedIcon))}update(e){}dispose(){this.disposable.dispose(),super.dispose()}};const hie=xv(),SC=22,CC=0,kC=Number.MAX_SAFE_INTEGER;var jC=class extends Ane{constructor(e){super({accessor:e.accessor,id:e.id,component:e.component,headerComponent:e.headerComponent,orientation:e.orientation,isExpanded:e.isExpanded,disableDnd:e.disableDnd,headerSize:e.headerSize,minimumBodySize:e.minimumBodySize,maximumBodySize:e.maximumBodySize}),this.options=e}getBodyComponent(){return this.options.body}getHeaderComponent(){return this.options.header}},pie=class extends vv{get id(){return this._id}get panels(){return this.paneview.getPanes()}set paneview(e){this._paneview=e,this._disposable.value=new ct(this._paneview.onDidChange(()=>{this._onDidLayoutChange.fire(void 0)}),this._paneview.onDidAddView(t=>this._onDidAddView.fire(t)),this._paneview.onDidRemoveView(t=>this._onDidRemoveView.fire(t)))}get paneview(){return this._paneview}get minimumSize(){return this.paneview.minimumSize}get maximumSize(){return this.paneview.maximumSize}get height(){return this.paneview.orientation==="HORIZONTAL"?this.paneview.orthogonalSize:this.paneview.size}get width(){return this.paneview.orientation==="HORIZONTAL"?this.paneview.size:this.paneview.orthogonalSize}get options(){return this._options}constructor(e,t){var n;super(document.createElement("div"),t.disableAutoResizing),this._id=hie.next(),this._disposable=new Fn,this._viewDisposables=new Map,this._onDidLayoutfromJSON=new ve,this.onDidLayoutFromJSON=this._onDidLayoutfromJSON.event,this._onDidLayoutChange=new ve,this.onDidLayoutChange=this._onDidLayoutChange.event,this._onDidDrop=new ve,this.onDidDrop=this._onDidDrop.event,this._onDidAddView=new ve,this.onDidAddView=this._onDidAddView.event,this._onDidRemoveView=new ve,this.onDidRemoveView=this._onDidRemoveView.event,this._onUnhandledDragOver=new ve,this.onUnhandledDragOver=this._onUnhandledDragOver.event,this.element.style.height="100%",this.element.style.width="100%",this.addDisposables(this._onDidLayoutChange,this._onDidLayoutfromJSON,this._onDidDrop,this._onDidAddView,this._onDidRemoveView,this._onUnhandledDragOver),this._classNames=new Lh(this.element),this._classNames.setClassNames((n=t.className)!==null&&n!==void 0?n:""),e.appendChild(this.element),this._options=t,this.paneview=new lC(this.element,{orientation:"VERTICAL"}),this.addDisposables(this._disposable)}setVisible(e,t){const n=this.panels.indexOf(e);this.paneview.setViewVisible(n,t)}focus(){}updateOptions(e){if("className"in e){var t;this._classNames.setClassNames((t=e.className)!==null&&t!==void 0?t:"")}if("disableAutoResizing"in e){var n;this.disableResizing=(n=e.disableAutoResizing)!==null&&n!==void 0?n:!1}this._options=pt(pt({},this.options),e)}addPanel(e){var t,n,s;const o=this.options.createComponent({id:e.id,name:e.component});let r;e.headerComponent&&this.options.createHeaderComponent&&(r=this.options.createHeaderComponent({id:e.id,name:e.headerComponent})),(t=r)!==null&&t!==void 0||(r=new yC);const a=new jC({id:e.id,component:e.component,headerComponent:e.headerComponent,header:r,body:o,orientation:"VERTICAL",isExpanded:!!e.isExpanded,disableDnd:!!this.options.disableDnd,accessor:this,headerSize:(n=e.headerSize)!==null&&n!==void 0?n:SC,minimumBodySize:CC,maximumBodySize:kC});this.doAddPanel(a);const l=typeof e.size=="number"?e.size:ks.Distribute,d=typeof e.index=="number"?e.index:void 0;return a.init({params:(s=e.params)!==null&&s!==void 0?s:{},minimumBodySize:e.minimumBodySize,maximumBodySize:e.maximumBodySize,isExpanded:e.isExpanded,title:e.title,containerApi:new ed(this),accessor:this}),this.paneview.addPane(a,l,d),a.orientation=this.paneview.orientation,a}removePanel(e){const t=this.panels.indexOf(e);this.paneview.removePane(t),this.doRemovePanel(e)}movePanel(e,t){this.paneview.moveView(e,t)}getPanel(e){return this.panels.find(t=>t.id===e)}layout(e,t){const[n,s]=this.paneview.orientation==="HORIZONTAL"?[e,t]:[t,e];this.paneview.layout(n,s)}toJSON(){const e=n=>n===Number.MAX_SAFE_INTEGER||n===Number.POSITIVE_INFINITY?void 0:n,t=n=>n<=0?void 0:n;return{views:this.paneview.getPanes().map((n,s)=>{const o=this.paneview.getViewCachedVisibleSize(s),r=typeof o=="number";return pt({size:r?o:this.paneview.getViewSize(s),data:n.toJSON(),minimumSize:t(n.minimumBodySize),maximumSize:e(n.maximumBodySize),headerSize:n.headerSize,expanded:n.isExpanded()},r?{visible:!1}:{})}),size:this.paneview.size}}fromJSON(e){this.clear();const{views:t,size:n}=e,s=[],o=this.width,r=this.height;this.paneview=new lC(this.element,{orientation:"VERTICAL",descriptor:{size:n,views:t.map(a=>{var l,d,c,u;const h=a.data,p=this.options.createComponent({id:h.id,name:h.component});let f;h.headerComponent&&this.options.createHeaderComponent&&(f=this.options.createHeaderComponent({id:h.id,name:h.headerComponent})),(l=f)!==null&&l!==void 0||(f=new yC);const g=new jC({id:h.id,component:h.component,headerComponent:h.headerComponent,header:f,body:p,orientation:"VERTICAL",isExpanded:!!a.expanded,disableDnd:!!this.options.disableDnd,accessor:this,headerSize:(d=a.headerSize)!==null&&d!==void 0?d:SC,minimumBodySize:(c=a.minimumSize)!==null&&c!==void 0?c:CC,maximumBodySize:(u=a.maximumSize)!==null&&u!==void 0?u:kC});return this.doAddPanel(g),s.push(()=>{var x;g.init({params:(x=h.params)!==null&&x!==void 0?x:{},minimumBodySize:a.minimumSize,maximumBodySize:a.maximumSize,title:h.title,isExpanded:!!a.expanded,containerApi:new ed(this),accessor:this}),g.orientation=this.paneview.orientation}),setTimeout(()=>{this._onDidAddView.fire(g)},0),{size:a.size,view:g,visible:a.visible}})}}),this.layout(o,r),s.forEach(a=>a()),this._onDidLayoutfromJSON.fire()}clear(){for(const[e,t]of this._viewDisposables.entries())t.dispose();this._viewDisposables.clear(),this.paneview.dispose()}doAddPanel(e){const t=new ct(e.onDidDrop(n=>{this._onDidDrop.fire(n)}),e.onUnhandledDragOver(n=>{this._onUnhandledDragOver.fire(n)}));this._viewDisposables.set(e.id,t)}doRemovePanel(e){const t=this._viewDisposables.get(e.id);t&&(t.dispose(),this._viewDisposables.delete(e.id))}dispose(){super.dispose();for(const[e,t]of this._viewDisposables.entries())t.dispose();this._viewDisposables.clear(),this.element.remove(),this.paneview.dispose()}},fie=class extends wv{get priority(){return this._priority}set orientation(e){this._orientation=e}get orientation(){return this._orientation}get minimumSize(){const e=typeof this._minimumSize=="function"?this._minimumSize():this._minimumSize;return e!==this._evaluatedMinimumSize&&(this._evaluatedMinimumSize=e,this.updateConstraints()),e}get maximumSize(){const e=typeof this._maximumSize=="function"?this._maximumSize():this._maximumSize;return e!==this._evaluatedMaximumSize&&(this._evaluatedMaximumSize=e,this.updateConstraints()),e}get snap(){return this._snap}constructor(e,t){super(e,t,new CE(e,t)),this._evaluatedMinimumSize=0,this._evaluatedMaximumSize=Number.POSITIVE_INFINITY,this._minimumSize=0,this._maximumSize=Number.POSITIVE_INFINITY,this._snap=!1,this._onDidChange=new ve,this.onDidChange=this._onDidChange.event,this.api.initialize(this),this.addDisposables(this._onDidChange,this.api.onWillVisibilityChange(n=>{const{isVisible:s}=n,{accessor:o}=this._params;o.setVisible(this,s)}),this.api.onActiveChange(()=>{const{accessor:n}=this._params;n.setActive(this)}),this.api.onDidConstraintsChangeInternal(n=>{(typeof n.minimumSize=="number"||typeof n.minimumSize=="function")&&(this._minimumSize=n.minimumSize),(typeof n.maximumSize=="number"||typeof n.maximumSize=="function")&&(this._maximumSize=n.maximumSize),this.updateConstraints()}),this.api.onDidSizeChange(n=>{this._onDidChange.fire({size:n.size})}))}setVisible(e){this.api._onDidVisibilityChange.fire({isVisible:e})}setActive(e){this.api._onDidActiveChange.fire({isActive:e})}layout(e,t){const[n,s]=this.orientation==="HORIZONTAL"?[e,t]:[t,e];super.layout(n,s)}init(e){super.init(e),this._priority=e.priority,e.minimumSize&&(this._minimumSize=e.minimumSize),e.maximumSize&&(this._maximumSize=e.maximumSize),e.snap&&(this._snap=e.snap)}toJSON(){const e=n=>n===Number.MAX_SAFE_INTEGER||n===Number.POSITIVE_INFINITY?void 0:n,t=n=>n<=0?void 0:n;return pt(pt({},super.toJSON()),{},{minimumSize:t(this.minimumSize),maximumSize:e(this.maximumSize)})}updateConstraints(){this.api._onDidConstraintsChange.fire({maximumSize:this._evaluatedMaximumSize,minimumSize:this._evaluatedMinimumSize})}};function mie(e,t){return new die(e,t).api}function gie(e,t){return new hE(new uie(e,t))}function xie(e,t){return new pE(new cie(e,t))}function vie(e,t){return new ed(new pie(e,t))}function nd(e){"@babel/helpers - typeof";return nd=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},nd(e)}function bie(e,t){if(nd(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var s=n.call(e,t);if(nd(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function wie(e){var t=bie(e,"string");return nd(t)=="symbol"?t:t+""}function yie(e,t,n){return(t=wie(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _C(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(o){return Object.getOwnPropertyDescriptor(e,o).enumerable})),n.push.apply(n,s)}return n}function Is(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?_C(Object(n),!0).forEach(function(s){yie(e,s,n[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_C(Object(n)).forEach(function(s){Object.defineProperty(e,s,Object.getOwnPropertyDescriptor(n,s))})}return e}const FE=(e,t)=>{const[,n]=Ne.useState(0),s=Ne.useRef(e.componentProps);return Ne.useImperativeHandle(t,()=>({update:o=>{s.current=Is(Is({},s.current),o),n(r=>r+1)}}),[]),Ne.createElement(e.component,s.current)};FE.displayName="DockviewReactJsBridge";const Sie=(()=>{let e=1;return{next:()=>`dockview_react_portal_key_${(e++).toString()}`}})(),Cie=Ne.createContext({});var Ui=class{constructor(e,t,n,s,o){this.parent=e,this.portalStore=t,this.component=n,this.parameters=s,this.context=o,this._initialProps={},this.disposed=!1,this.createPortal()}update(e){if(this.disposed)throw new Error("invalid operation: resource is already disposed");this.componentInstance?this.componentInstance.update(e):this._initialProps=Is(Is({},this._initialProps),e)}createPortal(){if(this.disposed)throw new Error("invalid operation: resource is already disposed");if(!kie(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=Ne.createElement(Ne.forwardRef(FE),{component:this.component,componentProps:this.parameters,ref:s=>{this.componentInstance=s,Object.keys(this._initialProps).length>0&&(this.componentInstance.update(this._initialProps),this._initialProps={})}}),t=this.context?Ne.createElement(Cie.Provider,{value:this.context},e):e,n=ck.createPortal(t,this.parent,Sie.next());this.ref={portal:n,disposable:this.portalStore.addPortal(n)}}dispose(){var e;(e=this.ref)===null||e===void 0||e.disposable.dispose(),this.disposed=!0}};const Gh=()=>{const[e,t]=Ne.useState([]);return Ne.useDebugValue(`Portal count: ${e.length}`),[e,Ne.useCallback(n=>{t(o=>[...o,n]);let s=!1;return rn.from(()=>{if(s)throw new Error("invalid operation: resource already disposed");s=!0,t(o=>o.filter(r=>r!==n))})},[])]};function kie(e){return typeof e=="function"||!!e?.$$typeof}var NC=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new ve,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}focus(){}init(e){this.part=new Ui(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,containerApi:e.containerApi})}update(e){var t;(t=this.part)===null||t===void 0||t.update({params:e.params})}layout(e,t){}dispose(){var e;this._onDidFocus.dispose(),this._onDidBlur.dispose(),(e=this.part)===null||e===void 0||e.dispose()}},TC=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}focus(){}init(e){this.part=new Ui(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,containerApi:e.containerApi,tabLocation:e.tabLocation})}update(e){var t;(t=this.part)===null||t===void 0||t.update({params:e.params})}layout(e,t){}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},DC=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new Ui(this.element,this.reactPortalStore,this.component,{group:e.group,containerApi:e.containerApi})}focus(){}update(e){var t,n,s;this.parameters&&(this.parameters.params=e.params),(t=this.part)===null||t===void 0||t.update({params:(n=(s=this.parameters)===null||s===void 0?void 0:s.params)!==null&&n!==void 0?n:{}})}layout(e,t){}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},jie=class{get element(){return this._element}get part(){return this._part}constructor(e,t,n){this.component=e,this.reactPortalStore=t,this._group=n,this.mutableDisposable=new Fn,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.mutableDisposable.value=new ct(this._group.model.onDidAddPanel(()=>{this.updatePanels()}),this._group.model.onDidRemovePanel(()=>{this.updatePanels()}),this._group.model.onDidActivePanelChange(()=>{this.updateActivePanel()}),e.api.onDidActiveChange(()=>{this.updateGroupActive()}),e.api.onDidLocationChange(t=>{this.updateLocation(t.location)})),this._part=new Ui(this.element,this.reactPortalStore,this.component,{api:e.api,containerApi:e.containerApi,panels:this._group.model.panels,activePanel:this._group.model.activePanel,isGroupActive:this._group.api.isActive,group:this._group,headerPosition:this._group.model.headerPosition,location:e.api.location})}dispose(){var e;this.mutableDisposable.dispose(),(e=this._part)===null||e===void 0||e.dispose()}update(e){var t;(t=this._part)===null||t===void 0||t.update(e.params)}updatePanels(){this.update({params:{panels:this._group.model.panels}})}updateActivePanel(){this.update({params:{activePanel:this._group.model.activePanel}})}updateGroupActive(){this.update({params:{isGroupActive:this._group.api.isActive}})}updateLocation(e){this.update({params:{location:e}})}},_ie=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new Ui(this._element,this.reactPortalStore,this.component,e)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},IC=class{get element(){return this._element}constructor(e,t){this.component=e,this.reactPortalStore=t,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.display="inline-flex"}init(e){this.part=new Ui(this._element,this.reactPortalStore,this.component,{tabGroup:e.tabGroup,api:e.api})}update(e){var t;(t=this.part)===null||t===void 0||t.update({tabGroup:e.tabGroup})}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}},EC=class{get element(){return this._element}constructor(e,t){this.component=e,this.reactPortalStore=t,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.display="inline-flex"}init(e){this.part=new Ui(this._element,this.reactPortalStore,this.component,{group:e.group,api:e.api})}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}};function Mr(e,t){return e?n=>new jie(e,t,n):void 0}const fc="props.defaultTabComponent";function Nie(e){return tg.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const HE=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Gh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};tg.forEach(d=>{const c=d,u=e[c];c in e&&u!==a.current[c]&&(l[c]=u)}),s.current&&s.current.updateOptions(l),a.current=e},tg.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return;const l=Is({},e.tabComponents);e.defaultTabComponent&&(l[fc]=e.defaultTabComponent);const d={createLeftHeaderActionComponent:Mr(e.leftHeaderActionsComponent,{addPortal:r}),createRightHeaderActionComponent:Mr(e.rightHeaderActionsComponent,{addPortal:r}),createPrefixHeaderActionComponent:Mr(e.prefixHeaderActionsComponent,{addPortal:r}),createComponent:f=>new NC(f.id,e.components[f.name],{addPortal:r}),createTabComponent(f){return new TC(f.id,l[f.name],{addPortal:r})},createWatermarkComponent:e.watermarkComponent?()=>new DC("watermark",e.watermarkComponent,{addPortal:r}):void 0,defaultTabComponent:e.defaultTabComponent?fc:void 0,createContextMenuItemComponent:f=>{if(f.component)return new _ie(f.id,f.component,{addPortal:r})}},c=Nie(e);if(e.tabGroupChipComponent){const f=e.tabGroupChipComponent;c.createTabGroupChipComponent=()=>new IC(f,{addPortal:r})}if(e.groupDragGhostComponent){const f=e.groupDragGhostComponent;c.createGroupDragGhostComponent=()=>new EC(f,{addPortal:r})}const u=mie(n.current,Is(Is({},c),d)),{clientWidth:h,clientHeight:p}=n.current;return u.layout(h,p),e.onReady&&e.onReady({api:u}),s.current=u,()=>{s.current=void 0,u.dispose()}},[]),Ne.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(d=>{e.onDidDrop&&e.onDidDrop(d)});return()=>{l.dispose()}},[e.onDidDrop]),Ne.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onWillDrop(d=>{e.onWillDrop&&e.onWillDrop(d)});return()=>{l.dispose()}},[e.onWillDrop]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createTabGroupChipComponent:e.tabGroupChipComponent?()=>new IC(e.tabGroupChipComponent,{addPortal:r}):void 0})},[e.tabGroupChipComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createGroupDragGhostComponent:e.groupDragGhostComponent?()=>new EC(e.groupDragGhostComponent,{addPortal:r}):void 0})},[e.groupDragGhostComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new NC(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ne.useEffect(()=>{if(!s.current)return;const l=Is({},e.tabComponents);e.defaultTabComponent&&(l[fc]=e.defaultTabComponent),s.current.updateOptions({defaultTabComponent:e.defaultTabComponent?fc:void 0,createTabComponent(d){return new TC(d.id,l[d.name],{addPortal:r})}})},[e.tabComponents,e.defaultTabComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createWatermarkComponent:e.watermarkComponent?()=>new DC("watermark",e.watermarkComponent,{addPortal:r}):void 0})},[e.watermarkComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createRightHeaderActionComponent:Mr(e.rightHeaderActionsComponent,{addPortal:r})})},[e.rightHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createLeftHeaderActionComponent:Mr(e.leftHeaderActionsComponent,{addPortal:r})})},[e.leftHeaderActionsComponent]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createPrefixHeaderActionComponent:Mr(e.prefixHeaderActionsComponent,{addPortal:r})})},[e.prefixHeaderActionsComponent]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});HE.displayName="DockviewComponent";var PC=class extends fie{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Ui(this.element,this.reactPortalStore,this.reactComponent,{params:(e=(t=this._params)===null||t===void 0?void 0:t.params)!==null&&e!==void 0?e:{},api:this.api,containerApi:new hE(this._params.accessor)})}};function Tie(e){return Um.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Die=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Gh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};Um.forEach(d=>{const c=d,u=e[c];c in e&&u!==a.current[c]&&(l[c]=u)}),s.current&&s.current.updateOptions(l),a.current=e},Um.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=gie(n.current,Is(Is({},Tie(e)),{createComponent:u=>new PC(u.id,u.name,e.components[u.name],{addPortal:r})})),{clientWidth:d,clientHeight:c}=n.current;return l.layout(d,c),e.onReady&&e.onReady({api:l}),s.current=l,()=>{s.current=void 0,l.dispose()}},[]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new PC(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Die.displayName="SplitviewComponent";var AC=class extends RE{constructor(e,t,n,s){super(e,t),this.reactComponent=n,this.reactPortalStore=s}getComponent(){var e,t;return new Ui(this.element,this.reactPortalStore,this.reactComponent,{params:(e=(t=this._params)===null||t===void 0?void 0:t.params)!==null&&e!==void 0?e:{},api:this.api,containerApi:new pE(this._params.accessor)})}};function Iie(e){return Zm.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Eie=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Gh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};Zm.forEach(d=>{const c=d,u=e[c];c in e&&u!==a.current[c]&&(l[c]=u)}),s.current&&s.current.updateOptions(l),a.current=e},Zm.map(l=>e[l])),Ne.useEffect(()=>{if(!n.current)return()=>{};const l=xie(n.current,Is(Is({},Iie(e)),{createComponent:u=>new AC(u.id,u.name,e.components[u.name],{addPortal:r})})),{clientWidth:d,clientHeight:c}=n.current;return l.layout(d,c),e.onReady&&e.onReady({api:l}),s.current=l,()=>{s.current=void 0,l.dispose()}},[]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new AC(l.id,l.name,e.components[l.name],{addPortal:r})})},[e.components]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Eie.displayName="GridviewComponent";var mc=class{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new Ui(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,title:e.title,containerApi:e.containerApi})}toJSON(){return{id:this.id}}update(e){var t;(t=this.part)===null||t===void 0||t.update(e.params)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}};function Pie(e){return Qm.reduce((t,n)=>(n in e&&(t[n]=e[n]),t),{})}const Aie=Ne.forwardRef((e,t)=>{const n=Ne.useRef(null),s=Ne.useRef(void 0),[o,r]=Gh();Ne.useImperativeHandle(t,()=>n.current,[]);const a=Ne.useRef({});return Ne.useEffect(()=>{const l={};Qm.forEach(d=>{const c=d,u=e[c];c in e&&u!==a.current[c]&&(l[c]=u)}),s.current&&s.current.updateOptions(l),a.current=e},Qm.map(l=>e[l])),Ne.useEffect(()=>{var l;if(!n.current)return()=>{};const d=(l=e.headerComponents)!==null&&l!==void 0?l:{},c=vie(n.current,Is(Is({},Pie(e)),{createComponent:p=>new mc(p.id,e.components[p.name],{addPortal:r}),createHeaderComponent:p=>new mc(p.id,d[p.name],{addPortal:r})})),{clientWidth:u,clientHeight:h}=n.current;return c.layout(u,h),e.onReady&&e.onReady({api:c}),s.current=c,()=>{s.current=void 0,c.dispose()}},[]),Ne.useEffect(()=>{s.current&&s.current.updateOptions({createComponent:l=>new mc(l.id,e.components[l.name],{addPortal:r})})},[e.components]),Ne.useEffect(()=>{var l;if(!s.current)return;const d=(l=e.headerComponents)!==null&&l!==void 0?l:{};s.current.updateOptions({createHeaderComponent:c=>new mc(c.id,d[c.name],{addPortal:r})})},[e.headerComponents]),Ne.useEffect(()=>{if(!s.current)return()=>{};const l=s.current.onDidDrop(d=>{e.onDidDrop&&e.onDidDrop(d)});return()=>{l.dispose()}},[e.onDidDrop]),Ne.createElement("div",{style:{height:"100%",width:"100%"},ref:n},o)});Aie.displayName="PaneviewComponent";function ea(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Mie(e,t,n){if(!ea(t))return!1;const s=typeof t.contentComponent=="string"?t.contentComponent:typeof t.component=="string"?t.component:void 0;return s&&n.has(s)?!0:e==="browser"||e.startsWith("browser:")}function BE(e,t){if(ea(e)){if(e.type==="leaf"){const n=ea(e.data)?e.data:void 0,s=Array.isArray(n?.views)?n.views.filter(r=>typeof r=="string"&&t.has(r)):[];if(s.length===0)return;const o=typeof n?.activeView=="string"&&t.has(n.activeView)?n.activeView:s[0];return{type:"leaf",data:{...n,views:s,activeView:o},size:e.size}}if(e.type==="branch"){const n=Array.isArray(e.data)?e.data.flatMap(s=>{const o=BE(s,t);return o?[o]:[]}):[];return n.length===0?void 0:{type:"branch",data:n,size:e.size}}}}function Rie(e,t){if(!ea(e)||!ea(e.panels))return;const n={};for(const[a,l]of Object.entries(e.panels))Mie(a,l,t)&&(n[a]=l);const s=new Set(Object.keys(n));if(s.size===0)return;const o=ea(e.grid)?e.grid:void 0,r=o?BE(o.root,s):void 0;if(r)return{...e,panels:n,grid:{...o,root:r}}}function MC(e){return typeof e!="string"||e.length===0||e.length>256||e.includes("\\")||e.includes("\0")||e.startsWith("/")||/^[a-zA-Z]:/.test(e)?!1:e.split("/").every(t=>t!=="..")}function Lie(e,t){const n=t.trim();if(n.length===0||n.length>512||n.startsWith("/")||n.startsWith("\\")||n.includes("\\")||n.includes("\0")||n.includes("?")||n.includes("#")||/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(n))return null;const s=MC(e)&&e!=="."?e:e.split("/").pop()??"",o=s.lastIndexOf("/"),r=o===-1?"":s.slice(0,o),a=r?`${r}/${n}`:n,l=[];for(const c of a.split("/"))if(!(c===""||c===".")){if(c===".."){if(l.length===0)return null;l.pop();continue}l.push(c)}const d=l.join("/");return!d||!MC(d)?null:d}function RC(e,t){const n=new RegExp(`\\b${t}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>]+))`,"i").exec(e);return n?n[1]??n[2]??n[3]??"":null}function Oie(e,t,n){return e.replace(new RegExp(`\\b${t}\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s"'=<>]+)`,"i"),`${t}="${n}"`)}function zie(e){return e?.trim().toLowerCase().split(/\s+/).includes("stylesheet")??!1}function Gie(e){try{return new TextDecoder().decode(Uint8Array.from(atob(e),t=>t.charCodeAt(0)))}catch{return null}}function Fie(e,t){const n=[],s=(o,r,a,l)=>{const d=r[1]??"";if(!l(d))return;const c=RC(d,a);if(c===null)return;const u=Lie(t,c);u&&n.push({start:r.index,end:r.index+r[0].length,kind:o,rel:u,attrs:d,full:r[0]})};for(const o of e.matchAll(/<script\b([^>]*)>[\s\S]*?<\/script>/gi))s("script",o,"src",()=>!0);for(const o of e.matchAll(/<link\b([^>]*?)\/?>/gi))s("style",o,"href",r=>zie(RC(r,"rel")));for(const o of e.matchAll(/<img\b([^>]*?)\/?>/gi))s("img",o,"src",()=>!0);return n.sort((o,r)=>o.start-r.start),n}async function Hie(e,t,n){const s=Fie(e,t),o=new Map;await Promise.all([...new Set(s.map(l=>l.rel))].map(async l=>{o.set(l,await n(l))}));let r=0,a="";for(const l of s){a+=e.slice(r,l.start),r=l.end;const d=o.get(l.rel);if(!d){a+=l.full;continue}if(l.kind==="img"){const u=d.mime||"application/octet-stream";a+=`<img${Oie(l.attrs,"src",`data:${u};base64,${d.base64}`)}>`;continue}const c=Gie(d.base64);if(c===null){a+=l.full;continue}a+=l.kind==="script"?`<script>${c.replace(/<\/script/gi,"<\\/script")}<\/script>`:`<style>${c.replace(/<\/style/gi,"<\\/style")}</style>`}return a+e.slice(r)}const Bie="plugin-view.html";function LC(){return document.documentElement.classList.contains("dark")?"dark":"light"}function Vie({pluginId:e,viewId:t,sessionId:n}){const{t:s}=Q(),o=Hj().find(u=>u.pluginId===e&&u.id===t),r=m.useRef(null),[a,l]=m.useState(null),d=o?.entry,c=m.useRef(n);return c.current=n,m.useEffect(()=>{const u=r.current;if(!u||!d)return;l(null);let h=!1,p=null;const f=()=>{try{p?.port1.postMessage(p5(LC()))}catch{}},g=new MutationObserver(f);g.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const x=window.electronAPI.extensionPlugins.onViewEvent(w=>{if(!(w.pluginId!==e||typeof w.name!="string"))try{p?.port1.postMessage(h5(w.name,w.data))}catch{}}),v=g5(async(w,b)=>{const _=await window.electronAPI.extensionPlugins.call({pluginId:e,method:"renderer.call",payload:{method:w,args:b},sessionId:c.current});if(!_.ok)throw new Error(_.error);return _.value}),y=async w=>{if(w.source!==u.contentWindow||w.data?.type!=="enso-view-ready")return;p?.port1.close();const b=new MessageChannel;p=b,b.port1.onmessage=C=>{const S=f5(C.data);if(S){window.electronAPI.extensionPlugins.viewStateSet(e,S);return}v(C.data).then(A=>{A&&!h&&p===b&&b.port1.postMessage(A)})};const[_,j]=await Promise.all([window.electronAPI.extensionPlugins.asset(e,d),window.electronAPI.extensionPlugins.viewStateGet(e)]);if(h||p!==b)return;if(!_.ok){l(_.error);return}const N=await Hie(m5(_.base64),d,async C=>{const S=await window.electronAPI.extensionPlugins.asset(e,C);return S.ok?{mime:S.mime,base64:S.base64}:null});h||p!==b||u.contentWindow?.postMessage({type:"enso-view-init",html:N,theme:LC(),storage:j.ok?j.state:{}},"*",[b.port2])};return window.addEventListener("message",y),u.src=new URL(Bie,document.baseURI).href,()=>{h=!0,g.disconnect(),x(),window.removeEventListener("message",y),p?.port1.close(),u.removeAttribute("src")}},[e,d]),o?i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[a&&i.jsx("div",{className:"shrink-0 px-3 py-2 text-xs text-destructive",children:a}),i.jsx("iframe",{ref:r,title:o.title,className:"min-h-0 w-full flex-1 border-0 bg-background"})]}):i.jsx("div",{className:"flex h-full items-center justify-center p-6 text-sm text-muted-foreground",children:s("Plugin is not enabled")})}function $ie({conversationId:e,panelApi:t}){const{t:n}=Q(),s=t.id.startsWith("btw:")?t.id.slice(4):t.id,o=wa(),r=Ce(R=>R.virtualModels),a=Ce(R=>R.defaultModel),l=Ce(R=>R.projects),d=Ce(R=>R.projectGroups),c=Fi(R=>R.snapshot),u=Tg(),[h,p]=m.useState("contextual"),[f,g]=m.useState(!1),[x]=m.useState(()=>GW(re.getState().conversations[e]?.messages??[])),v=re(jf(R=>R.conversations[s]??null)),y=v?.title,w=v?.projectId,b=m.useMemo(()=>l.find(R=>R.id===w),[w,l]),_=m.useMemo(()=>Zc(b,d),[b,d]),j=m.useMemo(()=>Al({defaultModel:a,..._,lastProviderId:v?.lastProviderId,lastModelId:v?.lastModelId,providers:o,credentials:aa(c),virtualModels:r}),[r,v?.lastModelId,v?.lastProviderId,_,a,c,o]),N=j.source==="none"?void 0:u.find(R=>R.id===j.providerId),C=j.source==="none"?"":j.modelId,S=j.source==="none"?"":_f(j)?j.providerId:N?.id??"",A=m.useMemo(()=>FW(v?.messages??[]),[v?.messages]),E=m.useRef(null),I=v?.status==="running",D=f||(v?yj({started:v.started,sessionFile:v.sessionFile,messages:v.messages,spawning:v.spawning,status:v.status,historyLoadAttempted:v.historyLoadAttempted}):!0),T=m.useMemo(()=>{const R={name:"/compact",description:n("Compact the context now (/compact [summary focus])")},B=new Set([R.name]);return[R,...(v?.commands??[]).filter(H=>!B.has(H.name))]},[v?.commands,n]);m.useEffect(()=>{const R=re.getState().conversations[e],B=Ce.getState();re.getState().ensureBtwConversation({id:s,projectId:R?.projectId??"",btwParentId:e,rolePrompt:Tw("contextual",x),lastProviderId:R?.lastProviderId??B.defaultModel?.providerId,lastModelId:R?.lastModelId??B.defaultModel?.modelId,reasoningEnabled:R?.reasoningEnabled??B.defaultReasoningEnabled,thinkingLevel:R?.thinkingLevel??B.defaultThinkingLevel,approvalMode:R?.approvalMode??"full",presetId:R?.presetId})},[e,s,x]),m.useEffect(()=>{y&&t.setTitle(y)},[t,y]);const z=R=>{R===h||f||(g(!0),(async()=>(re.getState().abort(s),await re.getState().resetBtwSession(s,Tw(R,x)),p(R),t.setTitle(n("Btw")),g(!1)))())},$=()=>{const R=BW(A);if(R){if(!wh(R)){Be({type:"warning",title:n("No Composer for this selection")});return}wo()}};return i.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[i.jsx(OC,{label:n("Contextual"),active:h==="contextual",onClick:()=>z("contextual")}),i.jsx(OC,{label:n("Tangent"),active:h==="tangent",onClick:()=>z("tangent")}),i.jsx("button",{type:"button",className:"ml-auto rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-40",disabled:!A,onClick:$,children:n("Insert into chat")})]}),v?i.jsx(cI,{conversationId:s,cwd:b?.path,emptyTitle:n("Btw"),timelineRef:E}):i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-2 text-center text-muted-foreground",children:[i.jsx(vr,{className:"h-5 w-5"}),i.jsx("p",{className:"text-xs",children:n("Ask a side question without sending it to the main agent.")})]}),i.jsx("div",{className:"@container pt-1",children:i.jsxs("div",{className:yi,children:[v?.retry?i.jsx(Ih,{retry:v.retry,onCancel:()=>{window.electronAPI.agent.abortRetry(s)}}):null,i.jsx(jg.Provider,{value:w?{conversationId:s,projectId:w,...b?.path?{cwd:b.path}:{}}:null,children:i.jsx(cv,{sessionId:s,tasks:v?.backgroundTasks??[],subagents:v?.subagents??[]},s)}),i.jsx(Bl,{approvals:v?.pendingApprovals??[],allowSession:!0,onRespond:(R,B)=>{window.electronAPI.agent.respondApproval(s,R,B)}}),i.jsx(mh,{asks:v?.pendingAsks??[],onAnswer:(R,B)=>{window.electronAPI.agent.respondAsk(s,R,B)}}),i.jsx(yI,{conversationId:s,queued:v?.queuedMessages??[]}),i.jsx(lv,{isolated:!0,cwd:b?.path,commands:T,running:I,busy:D,locked:(v?.pendingApprovals??[]).length>0,focusKey:s,injectedDraft:v?.draftText,injectedImages:v?.draftImages,injectedDraftAppend:v?.draftAppend,onDraftConsumed:()=>re.getState().clearDraft(s),queuedCount:v?.queuedMessages?.length??0,onSteerQueued:()=>re.getState().steerQueued(s),autoFocus:!1,placeholder:n("Ask aside…"),toolbar:i.jsx(Ju,{providers:u,activeAccount:Ng(o,v??void 0),virtualModels:r,providerId:S,modelId:C,reasoningEnabled:v?.reasoningEnabled??!1,thinkingLevel:v?.thinkingLevel??"medium",onSelect:(R,B)=>re.getState().setModel(s,R,B),onReasoningChange:R=>re.getState().setReasoning(s,R),onThinkingChange:R=>re.getState().setThinking(s,R),side:"top"}),onSend:R=>!S||!C||!b?!1:(E.current?.scrollToBottom(),re.getState().send(R.text,{providerId:S,modelId:C,cwd:b.path},R.images,s),!0),onAbort:()=>{re.getState().abort(s)}}),i.jsx(_I,{conversationId:s})]})})]})}function OC({label:e,active:t,onClick:n}){return i.jsx("button",{type:"button",className:q("rounded-md px-2 py-1 text-xs transition-colors",t?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:n,children:e})}function VE(e,t,n,s={}){const o=new Set,r=e.map(a=>{const l=`diff:${a.path}`;o.add(l);const d=t.has(l),c=n.get(l),u=s.ignoreLineEndings?a.oldText.replace(/\r\n/g,`
|
|
108
|
-
`):a.oldText,h=s.ignoreLineEndings?a.newText.replace(/\r\n/g,`
|
|
109
|
-
`):a.newText,p=!c||c.oldText!==u||c.newText!==h,f=p||!c?go({name:a.path,contents:u},{name:a.path,contents:h}):c.fileDiff;(p||!c)&&(f.cacheKey=Rx(a.path,u,h));const g=c?p||c.collapsed!==d?c.version+1:c.version:0;return n.set(l,{oldText:u,newText:h,collapsed:d,version:g,fileDiff:f}),{id:l,type:"diff",fileDiff:f,version:g,collapsed:d}});for(const a of n.keys())o.has(a)||n.delete(a);return r}const Wie={theme:xa,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0},Uie={height:"100%",overflow:"auto"},Kie=new Set;function $E({result:e,loading:t}){const{t:n}=Q(),s=id(Wie),[o,r]=m.useState(!1),[a,l]=m.useState(!1),d=m.useRef(new Map);m.useEffect(()=>{let h=!0;return ia().then(()=>{h&&r(!0)},()=>{h&&l(!0)}),()=>{h=!1}},[]);const c=m.useMemo(()=>VE(e?.ok?[e]:[],Kie,d.current,{ignoreLineEndings:!0}),[e]),u=t?n("Loading..."):a?n("Could not load the diff viewer."):e?e.ok?o?e.oldText===e.newText?n("No text changes to display."):c[0]?.fileDiff.hunks.length===0?n("Only line endings changed."):null:n("Loading..."):n(e.error):n("Select a file to view its diff.");return i.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:u?i.jsx("div",{className:"flex h-full items-center justify-center px-4 py-8 text-center text-xs text-muted-foreground",role:"status",children:u}):i.jsx(xT,{className:"min-h-0 w-full flex-1",items:c,style:Uie,options:s})})}function WE({tree:e,onToggle:t}){const{t:n}=Q(),s=n(e?"List view":"Tree view");return i.jsx(ge,{variant:"ghost",size:"icon-xs",title:s,"aria-label":s,onClick:t,children:e?i.jsx(bx,{className:"size-3.5"}):i.jsx(E$,{className:"size-3.5"})})}function UE({files:e,tree:t,children:n}){const s=m.useId(),[o,r]=m.useState(()=>new Set),a=m.useMemo(()=>{const d={name:"",path:"",directories:new Map,files:[]};if(!t)return d;for(const c of e){const u=c.path.split("/");let h=d;for(const p of u.slice(0,-1)){let f=h.directories.get(p);f||(f={name:p,path:h.path?`${h.path}/${p}`:p,directories:new Map,files:[]},h.directories.set(p,f)),h=f}h.files.push(c)}return d},[e,t]),l=d=>i.jsxs(i.Fragment,{children:[[...d.directories.values()].sort((c,u)=>c.name.localeCompare(u.name)).map(c=>{const u=!o.has(c.path),h=`${s}-${encodeURIComponent(c.path)}`;return i.jsxs("div",{children:[i.jsxs("button",{type:"button",title:c.path,"aria-expanded":u,"aria-controls":u?h:void 0,className:"flex w-full min-w-0 items-center gap-1.5 rounded-md px-2 py-1.5 text-left text-xs hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",onClick:()=>r(p=>{const f=new Set(p);return f.has(c.path)?f.delete(c.path):f.add(c.path),f}),children:[i.jsx(Vn,{"aria-hidden":"true",className:q("size-3 shrink-0 text-muted-foreground",!u&&"-rotate-90")}),u?i.jsx(ni,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}):i.jsx(yd,{"aria-hidden":"true",className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"truncate",children:c.name})]}),u&&i.jsx("div",{id:h,className:"ml-3 min-w-0 border-l pl-1",children:l(c)})]},`directory:${c.path}`)}),d.files.slice().sort((c,u)=>c.path.localeCompare(u.path)).map(c=>i.jsx(m.Fragment,{children:n(c)},`file:${c.path}`))]});return t?l(a):e.map(d=>i.jsx(m.Fragment,{children:n(d)},d.path))}const qie={added:{label:"A",color:"text-success"},modified:{label:"M",color:"text-info"},deleted:{label:"D",color:"text-destructive"},untracked:{label:"?",color:"text-success"},conflicted:{label:"!",color:"text-warning"}};function KE({file:e,selected:t,onSelect:n,actions:s,showDirectory:o=!0}){const{t:r}=Q(),a=e.path.lastIndexOf("/"),l=e.path.slice(a+1),d=e.path.slice(0,Math.max(0,a)),c=qie[e.status];return i.jsxs("div",{className:q("group flex min-w-0 items-center rounded-md pr-1 hover:bg-muted/50",t&&"bg-brand/10 dark:bg-brand/15"),children:[i.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",title:e.path,"aria-pressed":t,onClick:n,children:[i.jsx(bo,{"aria-hidden":"true",className:q("size-3.5 shrink-0",c.color)}),i.jsx("span",{className:q("truncate",!o&&"flex-1"),children:l}),o&&i.jsx("span",{className:"min-w-0 flex-1 truncate text-[11px] text-muted-foreground",children:d}),i.jsxs("span",{className:q("shrink-0 font-mono text-[11px]",c.color),title:r(e.status),children:[i.jsx("span",{"aria-hidden":"true",children:c.label}),i.jsx("span",{className:"sr-only",children:r(e.status)})]})]}),s&&i.jsx("div",{className:"flex shrink-0 items-center opacity-0 group-focus-within:opacity-100 group-hover:opacity-100 [@media(hover:none)]:opacity-100",children:s})]})}function qE({title:e,hasSelection:t,navigation:n,actions:s,children:o}){const{t:r}=Q(),a=m.useId(),[l,d]=m.useState(!0),c=!t||l;return i.jsx("div",{className:"@container/git flex min-h-0 min-w-0 flex-1 flex-col",children:i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex-row",children:[i.jsxs("div",{className:q("flex min-h-0 min-w-0 flex-col overflow-hidden border-b @min-[720px]/git:h-full @min-[720px]/git:max-h-none @min-[720px]/git:flex-none @min-[720px]/git:border-r @min-[720px]/git:border-b-0",c?"flex-1 @min-[720px]/git:w-[280px]":"shrink-0 @min-[720px]/git:w-8",c&&t&&"max-h-[45%] basis-[45%] shrink-0"),children:[i.jsxs("div",{className:"flex shrink-0 items-center",children:[i.jsxs("button",{type:"button",className:"flex min-h-7 min-w-0 flex-1 items-center gap-1.5 px-2 py-1 text-left text-[11px] font-medium text-muted-foreground hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring","aria-expanded":c,"aria-controls":a,disabled:!t,title:r(c?"Collapse list":"Expand list"),onClick:()=>d(!c),children:[i.jsx(Vn,{className:q("size-3.5 shrink-0",!c&&"-rotate-90")}),i.jsx("span",{className:q("truncate",!c&&"@min-[720px]/git:hidden"),children:e})]}),c&&s&&i.jsx("div",{className:"mr-1 flex shrink-0 items-center",children:s})]}),i.jsx("div",{id:a,className:q("flex min-h-0 flex-1 flex-col overflow-hidden",!c&&"hidden"),children:n})]}),i.jsx("div",{className:q("min-h-0 min-w-0 flex-1 flex-col overflow-hidden @min-[720px]/git:flex",t?"flex":"hidden"),children:o})]})})}function Yie({request:e,head:t,tree:n,onToggleTree:s}){const{t:o}=Q(),r=m.useId(),[a,l]=m.useState([]),[d,c]=m.useState(0),[u,h]=m.useState(0),[p,f]=m.useState(!1),[g,x]=m.useState(!0),[v,y]=m.useState(null),[w,b]=m.useState(null),[_,j]=m.useState([]),[N,C]=m.useState(!1),[S,A]=m.useState(null),[E,I]=m.useState(null),[D,T]=m.useState(null),[z,$]=m.useState(!1);return m.useEffect(()=>{let R=!0;return x(!0),y(null),window.electronAPI.git.history({...e,head:t??void 0,skip:d,limit:20}).then(B=>{R&&(B.ok?(l(H=>d===0?B.commits:[...H,...B.commits]),f(B.hasMore)):y(B.error))}).catch(()=>{R&&y("Could not load Git history.")}).finally(()=>{R&&x(!1)}),()=>{R=!1}},[e,t,d,u]),m.useEffect(()=>{if(!w)return;let R=!0;return C(!0),A(null),window.electronAPI.git.commitFiles({...e,hash:w.hash}).then(B=>{R&&(B.ok?j(B.files):A(B.error))}).catch(()=>{R&&A("Could not load the changed files.")}).finally(()=>{R&&C(!1)}),()=>{R=!1}},[e,w]),m.useEffect(()=>{if(!E||!w)return;let R=!0;return $(!0),window.electronAPI.git.commitDiff({...e,hash:w.hash,path:E}).then(B=>{R&&T(B)}).catch(()=>{R&&T({ok:!1,error:"Could not load the diff."})}).finally(()=>{R&&$(!1)}),()=>{R=!1}},[e,w,E]),i.jsxs(qE,{title:o("History"),hasSelection:E!==null,actions:i.jsx(WE,{tree:n,onToggle:s}),navigation:i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[a.map(R=>{const B=w?.hash===R.hash;return i.jsxs("div",{children:[i.jsxs("button",{type:"button","aria-expanded":B,"aria-controls":B?`${r}-${R.hash}`:void 0,className:q("flex w-full min-w-0 items-start gap-1.5 rounded-md px-2 py-1.5 text-left hover:bg-muted/50 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring",B&&"bg-brand/10 dark:bg-brand/15"),title:`${R.subject}
|
|
110
|
-
${R.hash}
|
|
111
|
-
${R.author} · ${R.date}`,onClick:()=>{b(B?null:R),j([]),C(!B),A(null),I(null),T(null),$(!1)},children:[i.jsx(Vn,{"aria-hidden":"true",className:q("mt-0.5 size-3.5 shrink-0 text-muted-foreground",!B&&"-rotate-90")}),i.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[i.jsx("span",{className:"truncate text-xs",children:R.subject}),i.jsxs("span",{className:"flex min-w-0 gap-2 text-[11px] text-muted-foreground",children:[i.jsx("span",{className:"shrink-0 font-mono",children:R.hash.slice(0,7)}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:R.author}),i.jsx("time",{className:"shrink-0",dateTime:R.date,children:new Date(R.date).toLocaleDateString()})]})]})]}),B&&i.jsx("div",{id:`${r}-${R.hash}`,className:"my-1 ml-3 border-l pl-1",children:N?i.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:o("Loading...")}):S?i.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:o(S)}):_.length===0?i.jsx("p",{className:"px-2 py-3 text-xs text-muted-foreground",children:o("No file changes in this commit.")}):i.jsx(UE,{files:_,tree:n,children:H=>i.jsx(KE,{file:H,showDirectory:!n,selected:E===H.path,onSelect:()=>{E!==H.path&&(I(H.path),T(null),$(!0))}})},R.hash)})]},R.hash)}),g&&i.jsx("div",{className:"flex justify-center p-3",children:i.jsx(qt,{className:"size-4 animate-spin","aria-label":o("Loading...")})}),v&&i.jsx("p",{role:"alert",className:"px-2 py-3 text-xs text-destructive",children:o(v)}),!g&&!v&&a.length===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:o("No commits yet.")}),p&&!g&&!v&&i.jsx(ge,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>c(a.length),children:o("Load more commits")}),v&&i.jsx(ge,{variant:"ghost",size:"xs",className:"w-full",onClick:()=>h(R=>R+1),children:o("Retry")})]}),children:[w&&E&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:`${w.subject} · ${E}`,children:[w.hash.slice(0,7)," · ",E]}),i.jsx($E,{result:D,loading:z})]})}function Xie({conversationId:e,projectId:t,disabled:n,unavailable:s,editWriteKey:o}){const{t:r}=Q(),a=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),[l,d]=m.useState(null),[c,u]=m.useState(!0),[h,p]=m.useState(null),[f,g]=m.useState(null),[x,v]=m.useState(null),[y,w]=m.useState("changes"),[b,_]=m.useState(!0),[j,N]=m.useState(""),[C,S]=m.useState(""),A=m.useRef(null),[E,I]=m.useState(null),[D,T]=m.useState(null),[z,$]=m.useState(null),[R,B]=m.useState(!1),[H,oe]=m.useState(0),te=m.useRef(!1),O=m.useRef(!1),V=m.useRef(0),J=m.useRef(0),pe=m.useCallback(async(Z=!1)=>{if(n||s||O.current||J.current!==0&&!Z)return;const le=++V.current;J.current=le,Z&&u(!0);try{const be=await window.electronAPI.git.status(a);if(!te.current||le!==V.current)return;be.ok?(d(be),p(null)):(d(null),p(be.error))}catch{te.current&&le===V.current&&(d(null),p("Could not read Git status."))}finally{J.current===le&&(J.current=0),te.current&&le===V.current&&u(!1)}},[n,s,a]);m.useEffect(()=>{te.current=!0;const Z=()=>{pe()},le=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&pe()},5e3);return window.addEventListener("focus",Z),()=>{te.current=!1,V.current+=1,window.clearInterval(le),window.removeEventListener("focus",Z)}},[pe]),m.useEffect(()=>{pe(!0)},[pe,o]),m.useEffect(()=>{if(!E||!l)return;(E.staged?l.staged:l.unstaged).some(le=>le.path===E.path)||(I(null),$(null),B(!1))},[E,l]),m.useEffect(()=>{if(!E||n||s||x!==null||y!=="changes")return;let Z=!0,le=!1;const be=async()=>{if(!le){le=!0;try{const We=await window.electronAPI.git.fileDiff({...a,...E});Z&&$(We)}catch{Z&&$({ok:!1,error:"Could not load the diff."})}finally{le=!1,Z&&B(!1)}}};be();const Fe=()=>{be()},Je=window.setInterval(()=>{document.visibilityState==="visible"&&document.hasFocus()&&be()},5e3);return window.addEventListener("focus",Fe),()=>{Z=!1,window.clearInterval(Je),window.removeEventListener("focus",Fe)}},[a,E,H,n,s,y,x]);const fe=async(Z,le,be)=>{if(!(O.current||n||s||c||!l)){O.current=!0,V.current+=1,v(Z),g(null);try{const Fe=await le();if(!te.current)return;Fe.ok?be?.():g(Fe.error)}catch{te.current&&g("Could not complete the Git operation.")}finally{O.current=!1,te.current&&(v(null),oe(Fe=>Fe+1),pe(!0),re.getState().refreshWorktreeStatuses().catch(()=>{}))}}},_e=n||s||c||x!==null||!l,Ee=!_e&&!!j.trim()&&!!l?.staged.length,me=(Z,le)=>{E?.path===Z.path&&E.staged===le||($(null),B(!0),I({path:Z.path,staged:le}))},W=[{id:"staged",staged:!0,title:r("Staged changes"),files:l?.staged??[]},{id:"unstaged",staged:!1,title:r("Unstaged changes"),files:l?.unstaged.filter(Z=>Z.status!=="untracked")??[]},{id:"untracked",staged:!1,title:r("Untracked changes"),files:l?.unstaged.filter(Z=>Z.status==="untracked")??[]}],G=C.trim().toLowerCase(),de=W.map(Z=>({...Z,files:Z.files.filter(le=>le.path.toLowerCase().includes(G))})),X=de.reduce((Z,le)=>Z+le.files.length,0),ie=()=>{Ee&&fe("Commit",()=>window.electronAPI.git.commit({...a,message:j}),()=>N(""))};return i.jsxs("div",{className:"flex h-full min-h-0 min-w-0 flex-col",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[l&&!n&&!s&&!h&&i.jsxs("div",{className:"flex shrink-0 items-center gap-1",role:"tablist","aria-label":r("Git views"),children:[i.jsxs(ge,{role:"tab","aria-selected":y==="changes",variant:y==="changes"?"secondary":"ghost",size:"xs",onClick:()=>w("changes"),children:[i.jsx(e$,{className:"size-3.5"}),r("Changes")]}),i.jsxs(ge,{role:"tab","aria-selected":y==="history",variant:y==="history"?"secondary":"ghost",size:"xs",onClick:()=>w("history"),children:[i.jsx(Bo,{className:"size-3.5"}),r("History")]})]}),i.jsx(Ei,{className:"size-3.5 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate text-xs",title:l?.branch??void 0,children:l?.branch??r(l?"Detached HEAD":"Git")}),l?.upstream&&i.jsxs("span",{className:"shrink-0 text-[11px] text-muted-foreground",title:l.upstream,children:["↓",l.behind," ↑",l.ahead]}),l&&!l.upstream&&i.jsx("span",{className:"max-w-20 truncate text-[11px] text-muted-foreground",title:r("No upstream branch configured."),children:r("No upstream")}),i.jsx(Qo,{title:r("Fetch"),disabled:_e,onClick:()=>{fe("Fetch",()=>window.electronAPI.git.fetch(a))},children:i.jsx(sd,{className:"size-3.5"})}),i.jsx(Qo,{title:r("Pull"),disabled:_e||!l?.upstream,onClick:()=>{fe("Pull",()=>window.electronAPI.git.pull(a))},children:i.jsx(uh,{className:"size-3.5"})}),i.jsx(Qo,{title:r("Push"),disabled:_e||!l?.upstream,onClick:()=>{fe("Push",()=>window.electronAPI.git.push(a))},children:i.jsx(wd,{className:"size-3.5"})}),i.jsx(Qo,{title:r("Refresh"),disabled:n||s||x!==null||c,onClick:()=>{oe(Z=>Z+1),pe(!0)},children:i.jsx(Fo,{className:q("size-3.5",c&&!s&&!n&&"animate-spin")})})]}),x&&i.jsxs("p",{role:"status",className:"flex shrink-0 items-center gap-2 px-3 py-1 text-xs text-muted-foreground",children:[i.jsx(qt,{className:"size-3 animate-spin"}),r(x),"…"]}),f&&i.jsx("p",{role:"alert",className:"max-h-24 shrink-0 overflow-auto whitespace-pre-wrap break-words border-b px-3 py-2 text-xs text-destructive",children:r(f)}),s||n||h||!l?i.jsx("div",{role:"status",className:"m-3 flex min-h-0 flex-1 items-center justify-center rounded-md border border-dashed p-4 text-center text-xs text-muted-foreground",children:r(s?"Git diff is not available for this workspace.":n?"Workspace is changing. Please wait.":h??"Loading...")}):i.jsx(i.Fragment,{children:y==="history"?i.jsx(Yie,{request:a,head:l.head,tree:b,onToggleTree:()=>_(Z=>!Z)},`${l.head}:${H}`):i.jsxs(qE,{title:r("Changed files"),hasSelection:E!==null,actions:i.jsx(WE,{tree:b,onToggle:()=>_(Z=>!Z)}),navigation:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"shrink-0 px-2 pb-1.5",children:i.jsxs(qu,{className:"text-xs",children:[i.jsx(Xu,{ref:A,size:"sm",type:"search",value:C,onChange:Z=>S(Z.target.value),placeholder:r("Filter changed files…"),"aria-label":r("Filter changed files…")}),C.length>0&&i.jsx(Yu,{align:"inline-end",children:i.jsx(ge,{type:"button",variant:"ghost",size:"icon-xs",title:r("Clear"),"aria-label":r("Clear"),onClick:()=>{S(""),A.current?.focus()},children:i.jsx(an,{className:"size-3.5"})})})]})}),i.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-1 pb-1",children:[de.map(Z=>Z.files.length===0?null:i.jsxs("section",{className:"mb-2 last:mb-0",children:[i.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 text-[11px] font-medium text-muted-foreground",children:[i.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[Z.title," ",i.jsx("span",{className:"ml-1 font-normal",children:Z.files.length})]}),i.jsx(Qo,{title:r(Z.staged?"Unstage all":"Stage all"),disabled:_e,onClick:()=>{fe(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...a,paths:Z.files.map(le=>le.path)}))},children:Z.staged?i.jsx(h0,{className:"size-3.5"}):i.jsx(ds,{className:"size-3.5"})})]}),i.jsx(UE,{files:Z.files,tree:b,children:le=>i.jsx(KE,{file:le,showDirectory:!b,selected:E?.path===le.path&&E.staged===Z.staged,onSelect:()=>me(le,Z.staged),actions:i.jsxs(i.Fragment,{children:[!Z.staged&&i.jsx(Qo,{title:r(le.status==="untracked"?"Delete untracked file":"Discard changes"),disabled:_e||le.status==="conflicted",onClick:()=>T(le),children:i.jsx(ua,{className:"size-3.5"})}),i.jsx(Qo,{title:r(Z.staged?"Unstage":"Stage"),disabled:_e,onClick:()=>{fe(Z.staged?"Unstage":"Stage",()=>window.electronAPI.git[Z.staged?"unstage":"stage"]({...a,paths:[le.path]}))},children:Z.staged?i.jsx(h0,{className:"size-3.5"}):i.jsx(ds,{className:"size-3.5"})})]})})},G)]},Z.id)),X===0&&i.jsx("p",{className:"m-1 rounded-md border border-dashed px-2 py-5 text-center text-xs text-muted-foreground",children:r(l.staged.length+l.unstaged.length===0?"Working tree clean.":"No matching files.")})]}),i.jsxs("div",{className:"flex shrink-0 items-end gap-1.5 border-t p-2",children:[i.jsx(ei,{size:"sm",rows:3,value:j,"aria-label":r("Commit message"),placeholder:r("Enter commit message…"),className:"min-w-0 flex-1 text-xs [&_textarea]:max-h-[calc(6lh+0.5rem)] [&_textarea]:min-h-[calc(3lh+0.5rem)] [&_textarea]:resize-none [&_textarea]:overflow-auto",disabled:x!==null,onChange:Z=>N(Z.target.value),onKeyDown:Z=>{(Z.ctrlKey||Z.metaKey)&&Z.key==="Enter"&&!Z.nativeEvent.isComposing&&(Z.preventDefault(),ie())}}),i.jsxs(ge,{size:"xs",className:"mb-0.5 shrink-0",title:r("{{count}} staged files",{count:l.staged.length}),"aria-label":r("Commit"),disabled:!Ee,onClick:ie,children:[i.jsx(b$,{className:"size-3.5"}),r("Commit"),l.staged.length>0&&i.jsx("span",{className:"font-mono text-[11px]",children:l.staged.length})]})]})]}),children:[E&&i.jsxs("div",{className:"shrink-0 truncate border-b px-3 py-1 text-[11px] text-muted-foreground",title:E.path,children:[r(E.staged?"Staged changes":"Unstaged changes")," · ",E.path]}),i.jsx($E,{result:z,loading:E!==null&&R})]})}),i.jsx(fs,{open:D!==null&&!_e,onOpenChange:Z=>{Z||T(null)},title:r(D?.status==="untracked"?"Delete untracked file":"Discard changes"),description:D?.status==="untracked"?r("Delete untracked file {{path}} permanently?",{path:D.path}):r("Restore {{path}} to its staged version? Unstaged changes will be lost.",{path:D?.path??""}),confirmLabel:r(D?.status==="untracked"?"Delete":"Discard"),onConfirm:()=>{D&&fe("Discard",()=>window.electronAPI.git.discard({...a,paths:[D.path],confirmUntracked:D.status==="untracked"}))}})]})}function Qo({title:e,disabled:t,onClick:n,children:s}){return i.jsx(ge,{variant:"ghost",size:"icon-xs",title:e,"aria-label":e,disabled:t,onClick:n,children:s})}const YE=28,Zie={theme:xa,diffStyle:"split",lineDiffType:"word",preferredHighlighter:"shiki-js",overflow:"scroll",stickyHeaders:!0,itemMetrics:{diffHeaderHeight:YE}},Jie={height:"max-content",overflow:"auto"},Qie={files:[],snapshots:{}},zC=[];function eoe(e,t){return t?t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)?t:e?`${e.replace(/[/\\]+$/,"")}/${t}`:null:null}function toe({conversationId:e,projectId:t}){const{t:n}=Q(),s=id(Zie),o=gn(te=>te.changesModeByConversation[e])??"all",r=gn(te=>te.setChangesMode),a=m.useRef(null),l=m.useRef(null),d=m.useRef(!1);m.useLayoutEffect(()=>{const te=a.current,O=l.current,V=te?.querySelector('[aria-selected="true"]');!te||!O||!V||(d.current||(O.style.transition="none"),O.style.transform=`translate(${V.offsetLeft}px, ${V.offsetTop}px)`,O.style.width=`${V.offsetWidth}px`,O.style.height=`${V.offsetHeight}px`,d.current||(O.offsetWidth,O.style.transition="",d.current=!0))},[o]);const c=gn(te=>te.snapshotsByConversation[e]),u=gn(te=>te.saveSnapshots),h=gn(te=>te.loadSnapshots),p=re(te=>Bj(te.conversations[e]?.messages??zC)),f=re(te=>te.workspaceRevisionByConversation[e]??0),g=re(te=>!!te.conversations[e]?.workspaceMigrating),x=Ce(te=>te.projects.find(O=>O.id===t)),v=re(te=>x?.kind==="scratch"?Pg({kind:"scratch",canonicalPath:x.path,conversationId:e})??void 0:te.conversations[e]?.worktree?.path??x?.path),y=re(te=>te.conversations[e]?.status==="running"),w=m.useRef([]),b=m.useMemo(()=>{const te=re.getState().conversations[e],V=xr(te?.messages??zC,y,te?.customEntries??[],v).flatMap(J=>J.kind!=="tool"?[]:J.name==="apply_patch"?(J.fileChanges??[]).map(pe=>({path:pe.path,edits:null,writeContent:null,fileChange:pe})):J.state!=="ok"||J.name!=="edit"&&J.name!=="write"?[]:J.summary?J.name==="edit"&&!(J.edits&&J.edits.length>0)?[]:J.name==="write"&&J.writeContent==null?[]:[{path:J.summary,edits:J.edits,writeContent:J.writeContent}]:[]);return y9(w.current,V)?w.current:(w.current=V,V)},[e,p,v,y]),[_,j]=m.useState(!1),[N,C]=m.useState({});m.useEffect(()=>{let te=!0;return ia().then(()=>{te&&j(!0)}),()=>{te=!1}},[]),m.useEffect(()=>{o==="all"&&h(e)},[e,h,o]),m.useEffect(()=>{if(o!=="all"||g)return;const te=[...new Set(b.map(V=>V.path))];let O=!0;return Promise.all(te.map(async V=>{const J=eoe(v,V),pe=J?await window.electronAPI.files.read(J):null;return[V,pe]})).then(V=>{if(!O)return;const J=Object.fromEntries(V);C(pe=>S9(pe,J)?pe:J)}),()=>{O=!1}},[o,v,b,g,f]);const S=m.useMemo(()=>c?C9({tools:b,snapshots:c,currentByPath:N}):Qie,[b,c,N]);m.useEffect(()=>{if(o!=="all"||!c)return;const te=S.snapshots,O=Object.keys(te);O.length===Object.keys(c).length&&O.every(V=>c[V]===te[V])||u(e,te)},[S.snapshots,e,o,u,c]);const A=S.files,E=S.incompletePaths??[],[I,D]=m.useState(()=>new Set),T=m.useCallback(te=>{D(O=>{const V=new Set(O);return V.delete(te)||V.add(te),V})},[]),z=m.useRef(new Map),$=m.useMemo(()=>VE(A,I,z.current),[A,I]),R=$.length>0&&$.every(te=>te.collapsed),B=()=>D(R?new Set:new Set($.map(te=>te.id))),H=m.useCallback(te=>i.jsx(noe,{item:te,onToggle:()=>T(te.id)}),[T]),oe=!_||!c;return i.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[i.jsxs("div",{className:"flex h-[36px] shrink-0 items-center gap-1 border-b px-2",children:[i.jsxs("div",{ref:a,role:"tablist",className:"t-tabs",children:[i.jsx("span",{ref:l,"aria-hidden":"true",className:"t-tabs-pill"}),i.jsx(GC,{active:o==="all",onClick:()=>r(e,"all"),children:n("Session")}),i.jsx(GC,{active:o==="git",onClick:()=>r(e,"git"),children:n("Git")})]}),o==="all"&&$.length>0&&i.jsx("button",{type:"button",onClick:B,title:n(R?"Expand all":"Collapse all"),className:"ml-auto inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:bg-muted/50 hover:text-foreground",children:R?i.jsx(pj,{className:"h-3.5 w-3.5"}):i.jsx(jV,{className:"h-3.5 w-3.5"})})]}),i.jsx("div",{className:"min-h-0 flex-1",children:o==="git"?i.jsx(Xie,{conversationId:e,projectId:t,disabled:g,unavailable:x?.kind==="ssh",editWriteKey:p},`${e}:${v}:${f}`):oe||A.length===0&&E.length===0?i.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center text-sm text-muted-foreground",children:n(oe?"Loading...":"No file changes in this conversation yet.")}):i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[E.map(te=>i.jsxs("div",{className:"m-2 flex shrink-0 items-start gap-2 rounded-md border border-dashed px-3 py-2 text-xs text-muted-foreground",children:[i.jsx(gr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),i.jsxs("div",{className:"min-w-0",children:[i.jsx("div",{className:"truncate font-mono text-foreground",title:te,children:te}),i.jsx("div",{children:n("Diff unavailable because the original snapshot was truncated.")})]})]},te)),A.length>0&&i.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-hidden",children:i.jsx(xT,{className:"min-h-0 w-full",items:$,style:Jie,options:s,renderCustomHeader:H})})]})})]})}function noe({item:e,onToggle:t}){const n=e.type==="diff"?e.fileDiff:null;let s=0,o=0;for(const a of n?.hunks??[])s+=a.additionLines,o+=a.deletionLines;const r=n?.name??(e.type==="file"?e.file.name:"");return i.jsxs("button",{type:"button",onClick:t,style:{height:YE},className:"flex w-full min-w-0 items-center gap-1.5 px-2 text-left font-mono text-xs hover:bg-muted/50",children:[e.collapsed?i.jsx(bn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}):i.jsx(Vn,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),i.jsx("span",{className:"min-w-0 flex-1 truncate",title:r,children:r}),o>0&&i.jsxs("span",{className:"shrink-0 text-red-500",children:["-",o]}),s>0&&i.jsxs("span",{className:"shrink-0 text-green-600",children:["+",s]})]})}function GC({active:e,onClick:t,children:n}){return i.jsx("button",{type:"button",role:"tab",onClick:t,"aria-selected":e,className:q("t-tab rounded-md px-2 py-1 text-xs transition-colors",e?"font-medium":"text-muted-foreground hover:bg-muted/50"),children:n})}function soe({conversationId:e,projectId:t,onOpenFile:n,onClose:s,menu:o}){const{t:r}=Q(),a=m.useRef(0),[l,d]=m.useState(""),[c,u]=m.useState("names"),[h,p]=m.useState(null),[f,g]=m.useState(!1);return m.useEffect(()=>{if(!l.trim()){a.current+=1,p(null),g(!1);return}const v=++a.current;g(!0);const y=setTimeout(()=>{window.electronAPI.workspaceFiles.search({conversationId:e,projectId:t,query:l,mode:c}).then(w=>{v===a.current&&(p(w),g(!1))})},150);return()=>clearTimeout(y)},[e,c,t,l]),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[i.jsxs("div",{className:"flex flex-col gap-1 px-1 pb-1",children:[i.jsx(Xt,{size:"sm",autoFocus:!0,value:l,onChange:x=>d(x.target.value),onKeyDown:x=>{x.key==="Escape"&&s()},placeholder:r(c==="names"?"Search file names":"Search file contents"),"aria-label":r("Search")}),i.jsxs("div",{className:"flex gap-0.5",children:[i.jsx(HC,{active:c==="names",onClick:()=>u("names"),label:r("File name"),icon:x5}),i.jsx(HC,{active:c==="content",onClick:()=>u("content"),label:r("Content"),icon:bo})]})]}),i.jsx("div",{className:"min-h-0 flex-1 overflow-auto px-1 pb-1",children:l.trim()?f&&!h?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Searching…")}):h&&!h.ok?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r(h.error==="unsupported"?"Search is not available for SSH workspaces.":"Could not complete the file action.")}):h?.ok&&h.hits.length===0?i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("No results")}):h?.ok&&h.mode==="names"?h.hits.map(x=>{const v=_d(x.name,!1);return i.jsx(FC,{rel:x.relativePath,name:x.name,menu:o,onOpenFile:n,children:i.jsxs("button",{type:"button","data-search-hit":x.relativePath,className:"flex w-full items-start gap-1 rounded-sm px-1 py-0.5 text-left hover:bg-muted",onClick:()=>n(x.relativePath),children:[i.jsx(v,{className:q("mt-0.5 size-3.5 shrink-0",Nd(x.name,!1))}),i.jsxs("span",{className:"min-w-0",children:[i.jsx("span",{className:"block truncate text-xs",children:x.name}),i.jsx("span",{className:"block truncate text-[10px] text-muted-foreground",children:x.relativePath})]})]})},x.relativePath)}):h?.ok&&h.mode==="content"?h.hits.map(x=>{const v=x.relativePath.split("/").pop()||x.relativePath;return i.jsx(FC,{rel:x.relativePath,name:v,menu:o,onOpenFile:n,children:ioe(x,n)},XE(x))}):null:i.jsx("p",{className:"px-1 py-2 text-muted-foreground text-xs",children:r("Type to search this workspace.")})})]})}function XE(e){return`${e.relativePath}:${e.line}:${e.column}`}function ioe(e,t){const n=e.relativePath.split("/").pop()||e.relativePath,s=_d(n,!1);return i.jsxs("button",{type:"button","data-search-hit":XE(e),className:"flex w-full items-start gap-1 rounded-sm px-1 py-0.5 text-left hover:bg-muted",onClick:()=>t(e.relativePath),children:[i.jsx(s,{className:q("mt-0.5 size-3.5 shrink-0",Nd(n,!1))}),i.jsxs("span",{className:"min-w-0",children:[i.jsxs("span",{className:"block truncate text-xs",children:[n,i.jsxs("span",{className:"text-muted-foreground",children:[":",e.line]})]}),i.jsx("span",{className:"block truncate font-mono text-[10px] text-muted-foreground",children:e.content.trim()})]})]})}function FC({rel:e,name:t,menu:n,onOpenFile:s,children:o}){return i.jsx(Qu,{target:{kind:"file",rel:e,name:t},local:n.local,onNewFile:n.onNewFile,onNewFolder:n.onNewFolder,onView:s,onPreview:n.onPreview,onBrowser:n.onBrowser,onCopyPath:n.onCopyPath,onCopyRel:n.onCopyRel,onCopyFile:n.onCopyFile,onReveal:n.onReveal,onRename:n.onRename,onDelete:n.onDelete,onSend:n.onSend,children:o})}function HC({active:e,onClick:t,label:n,icon:s}){return i.jsxs(ge,{type:"button",variant:"ghost",size:"sm",className:q("h-6 flex-1 px-1 text-xs",e&&"bg-muted"),"aria-pressed":e,onClick:t,children:[i.jsx(s,{className:"size-3.5"}),n]})}const ooe=/^data:image\/(png|jpe?g|gif|webp|bmp|x-icon|svg\+xml);/i;function roe(){return{...Ed,attributes:{...Ed.attributes,source:[]},protocols:{...Ed.protocols,src:[...Ed.protocols?.src??[],"data"]}}}function aoe(){return e=>{v5(e,"element",t=>{if(t.tagName!=="img")return;const n=t.properties?.src;typeof n!="string"||!n.startsWith("data:")||ooe.test(n)||delete t.properties.src})}}const loe=[k5],doe=roe(),coe=[S5,[C5,doe],aoe],uoe=({children:e,node:t,...n})=>i.jsx("p",{className:"my-1.5 leading-relaxed first:mt-0 last:mb-0",...n,children:e}),hoe=({children:e,node:t,...n})=>i.jsx("h1",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),poe=({children:e,node:t,...n})=>i.jsx("h2",{className:"mt-3 mb-1.5 text-base font-semibold",...n,children:e}),foe=({children:e,node:t,...n})=>i.jsx("h3",{className:"mt-2 mb-1 text-sm font-semibold",...n,children:e}),moe=({children:e,node:t,...n})=>i.jsx("ul",{className:"my-1.5 list-disc pl-5 space-y-0.5",...n,children:e}),goe=({children:e,node:t,...n})=>i.jsx("ol",{className:"my-1.5 list-decimal pl-5 space-y-0.5",...n,children:e}),xoe=({children:e,node:t,...n})=>i.jsx("th",{className:"whitespace-nowrap border-b border-border px-2 py-1 text-left font-medium",...n,children:e}),voe=({children:e,node:t,...n})=>i.jsx("td",{className:"whitespace-nowrap border-b border-border/50 px-2 py-1",...n,children:e}),boe={p:uoe,h1:hoe,h2:poe,h3:foe,ul:moe,ol:goe,th:xoe,td:voe};function woe({text:e,baseDirRel:t,resolveImage:n,resolveRemoteImage:s}){const o=m.useRef(new Map),r=m.useMemo(()=>({...b5,...boe,img:({node:d,src:c,alt:u,...h})=>i.jsx(yoe,{src:typeof c=="string"?c:void 0,alt:u,rest:h,baseDirRel:t,resolveImage:n,resolveRemoteImage:s,cache:o.current})}),[t,n,s]),a=m.useMemo(()=>({text:e,streaming:!1,searchQuery:"",activeNth:-1}),[e]);return i.jsx(w5.Provider,{value:a,children:i.jsx("div",{style:j5(_5),children:i.jsx(y5,{remarkPlugins:loe,rehypePlugins:coe,components:r,urlTransform:l=>l,children:e})})})}function yoe({src:e,alt:t,rest:n,baseDirRel:s,resolveImage:o,resolveRemoteImage:r,cache:a}){const l=e?N5(e):"unsupported",d=l==="local"&&e?`local:${p0(s,e)??""}`:e,[c,u]=m.useState(()=>l==="data"?e??null:d?a.get(d)??null:null);return m.useEffect(()=>{if(!e||l==="unsupported"){u(null);return}if(l==="data"){u(e);return}const h=d?a.get(d):void 0;if(h){u(h);return}let p=!0;return(l==="local"?(()=>{const g=p0(s,e);return g?o(g):Promise.resolve(null)})():r(T5(e))).then(g=>{p&&(g&&d&&a.set(d,g),u(g))}),()=>{p=!1}},[e,l,s,o,r,a,d]),c?i.jsx("img",{...n,src:c,alt:t,className:"max-w-full rounded",loading:"lazy"}):null}function ZE(e){const t=e.trim();if(!t||t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t))return null;const n=t.split(/[/\\]/).filter(s=>s&&s!==".");return n.length===0||n.includes("..")?null:n.join("/")}function gc(e){const t=ZE(e);if(!t)return[];const n=t.split("/");if(n.length<=1)return[];const s=[];let o="";for(let r=0;r<n.length-1;r++)o=o?`${o}/${n[r]}`:n[r],s.push(o);return s}function Soe(e,t,n=!0){if(!n)return{refreshRels:[],nextSeen:null};const s=[],o=a=>{for(const l of a){if(l.kind==="tool-group"){o(l.children);continue}l.kind!=="tool"||l.state!=="ok"||l.name!=="write"||l.output===null&&l.durationMs===null||l.summary&&s.push({key:l.key,rel:ZE(l.summary)})}};o(e);const r=new Set(s.map(a=>a.key));return t===null?{refreshRels:[],nextSeen:r}:{refreshRels:s.filter(a=>!t.has(a.key)&&a.rel).map(a=>a.rel),nextSeen:r}}const Tv="\0preview";function JE(e){return`${e}${Tv}`}function QE(e){return e.endsWith(Tv)}function Kr(e){return QE(e)?e.slice(0,-Tv.length):e}function Coe(e,t){return e===t||e.startsWith(`${t}/`)}function sg(e,t){return Coe(Kr(e),t)}function koe(e,t){const n=e.trim();return!n||n===t?"cancel":"commit"}function xc(e,t,n){const s=QE(e),o=Kr(e);let r=null;return o===t?r=n:o.startsWith(`${t}/`)&&(r=n+o.slice(t.length)),r==null?null:s?JE(r):r}function joe(e){return e==="preview"?"source":"preview"}function vc(e,t,n){return e.some(s=>s.epoch>n&&sg(t,s.rel))}async function _oe(e,t){const{revision:n,migrating:s}=t();if(s)return null;const o=await e(),r=t();return r.migrating||r.revision!==n?null:o}function BC(e,t){return t===null?{...e,conflict:!0}:e.dirty?t!==e.contents&&t!==e.draft?{...e,conflict:!0}:e:t===e.draft&&!e.tooLarge?e:{...e,contents:t,draft:t,version:e.version+1,conflict:!1,tooLarge:!1}}function ig(e,t,n,s){const o=e.indexOf(t);if(o<0)return[];switch(n){case"self":return[t];case"others":return e.filter(r=>r!==t);case"right":return e.slice(o+1);case"saved":return e.filter(r=>!0);case"all":return[...e]}}const Noe={theme:xa,disableFileHeader:!0,overflow:"scroll",preferredHighlighter:"shiki-js"};function Toe(e){return new L5(e)}function Doe(e,t){return e?`${e}/${t}`:t}function Rr(e){return e.split("/").pop()||e}function Ioe(e){const t=e.lastIndexOf("/");return t<0?"":e.slice(0,t)}const lf=[];function Eoe({conversationId:e,projectId:t}){const{t:n}=Q(),s=id(Noe),o=m.useMemo(()=>({conversationId:e,projectId:t}),[e,t]),r=re(Y=>Y.workspaceRevisionByConversation[e]??0),a=re(Y=>!!Y.conversations[e]?.workspaceMigrating),l=m.useCallback(Y=>_oe(()=>window.electronAPI.workspaceFiles.read({...o,rel:Y}),()=>{const U=re.getState();return{revision:U.workspaceRevisionByConversation[e]??0,migrating:!!U.conversations[e]?.workspaceMigrating}}),[e,o]),[d,c]=m.useState(!1),[u,h]=m.useState([]),[p,f]=m.useState(null),g=ba(),[x,v]=m.useState(!0),y=m.useCallback(Y=>{f(Y),v(!1)},[]);m.useEffect(()=>{p||v(!0)},[p]);const[w,b]=m.useState(0),[_,j]=m.useState(()=>new Set),[N,C]=m.useState(!1),[S,A]=m.useState(null),[E,I]=m.useState(null),[D,T]=m.useState(null),z=Ce(Y=>Y.projects.find(U=>U.id===t)),$=z?.kind!=="ssh",R=m.useRef(u);R.current=u;const B=m.useRef(p);B.current=p;const H=m.useRef(null),oe=m.useRef(null),te=m.useRef(null),O=m.useRef(0),V=m.useRef([]),J=m.useCallback(Y=>{O.current+=1,V.current.push({epoch:O.current,rel:Y}),V.current.length>200&&V.current.splice(0,100)},[]);m.useEffect(()=>{const Y=te.current;if(!Y||!p)return;Y.querySelector(`[data-file-tab="${CSS.escape(p)}"]`)?.scrollIntoView({inline:"nearest",block:"nearest"})},[p]),m.useEffect(()=>{let Y=!0;return ia().then(()=>{Y&&c(!0)}),()=>{Y=!1}},[]);const pe=m.useCallback((Y,U)=>{h(ue=>ue.map(je=>je.rel===Y?BC(je,U):je))},[]),fe=m.useCallback(Y=>{Be({title:n(Y==="exists"?"A file or folder with that name already exists.":Y==="invalid-name"?"Invalid name.":"Could not complete the file action.")})},[n]),_e=m.useCallback(async(Y,U)=>{if(R.current.find(Le=>Le.rel===Y)){U&&h(Le=>Le.map(tt=>tt.rel===Y?{...tt,viewMode:U}:tt)),y(Y);return}const je=O.current,De=await l(Y);if(!(!De||vc(V.current,Y,je))){if(!De.ok){if(De.error!=="too-large"){fe(De.error);return}h(Le=>[...Le,{rel:Y,contents:"",draft:"",version:0,dirty:!1,conflict:!1,tooLarge:!0}]),y(Y);return}h(Le=>[...Le,{rel:Y,contents:De.content,draft:De.content,version:0,dirty:!1,conflict:!1,viewMode:U}]),y(Y),window.electronAPI.workspaceFiles.watchStart({...o,rel:Y})}},[fe,l,o,y]),[Ee,me]=m.useState(null),W=m.useCallback(Y=>{const U=R.current,ue=U.filter(je=>!Y(je.rel));for(const je of U)Y(je.rel)&&window.electronAPI.workspaceFiles.watchStop({...o,rel:je.rel});h(ue),f(je=>je&&ue.some(De=>De.rel===je)?je:ue.at(-1)?.rel??null)},[o]),G=m.useCallback(Y=>{W(U=>U===Y)},[W]),de=m.useCallback(Y=>{if(R.current.find(ue=>ue.rel===Y)?.dirty){me({kind:"one",rel:Y});return}G(Y)},[G]);m.useEffect(()=>D5(e,()=>{const Y=B.current;return!Y||R.current.length===0?!1:(de(Y),!0)}),[e,de]),m.useEffect(()=>()=>{for(const Y of R.current)window.electronAPI.workspaceFiles.watchStop({...o,rel:Y.rel})},[o]),m.useEffect(()=>{let Y=!0;const U=window.electronAPI.workspaceFiles.onChange(ue=>{ue.conversationId!==e||!R.current.find(De=>De.rel===ue.rel)||l(ue.rel).then(De=>{Y&&De?.ok&&pe(ue.rel,De.content)})});return()=>{Y=!1,U()}},[pe,e,l]);const X=re(Y=>Y.conversations[e]?.status==="running"),ie=re(Y=>z?.kind==="scratch"?Pg({kind:"scratch",canonicalPath:z.path,conversationId:e})??void 0:Y.conversations[e]?.worktree?.path??z?.path),Z=re(Y=>Y.conversations[e]?.historyBaseIndex),le=re(Y=>Bj(Y.conversations[e]?.messages??lf)),be=m.useMemo(()=>{const Y=re.getState().conversations[e];return xr(Y?.messages??lf,X,Y?.customEntries??[],ie).flatMap(U=>U.kind!=="tool"||U.state!=="ok"?[]:U.name!=="edit"&&U.name!=="write"?[]:U.summary?[U.summary]:[]).join(`
|
|
112
|
-
`)},[e,le,ie,X]);m.useEffect(()=>{let Y=!0;const U=new Set(be?be.split(`
|
|
113
|
-
`):[]);for(const ue of U)R.current.some(je=>je.rel===ue)&&l(ue).then(je=>{Y&&je?.ok&&pe(ue,je.content)});return()=>{Y=!1}},[pe,l,be]);const Fe=m.useRef(null),Je=m.useRef(e),We=m.useRef(Z),et=m.useCallback(()=>b(Y=>Y+1),[]);m.useEffect(()=>{if(r===0||a)return;let Y=!0;et();for(const U of R.current){const ue=Kr(U.rel),je=O.current;l(ue).then(De=>{!Y||!De||vc(V.current,ue,je)||h(Le=>Le.map(tt=>tt.rel===U.rel?BC(tt,De.ok?De.content:null):tt))})}return()=>{Y=!1}},[et,l,a,r]);const qe=m.useCallback(Y=>{Y&&j(U=>{if(U.has(Y))return U;const ue=new Set(U);return ue.add(Y),ue})},[]),Lt=m.useCallback(Y=>{Y.length!==0&&j(U=>{let ue=!1;const je=new Set(U);for(const De of Y)!De||je.has(De)||(je.add(De),ue=!0);return ue?je:U})},[]);m.useEffect(()=>{const Y=re.getState().conversations[e],U=Z;(Je.current!==e||We.current!==U)&&(Je.current=e,We.current=U,Fe.current=null);const ue=xr(Y?.messages??lf,X,Y?.customEntries??[],ie),{refreshRels:je,nextSeen:De}=Soe(ue,Fe.current,I5(Y?.messages??[]));Fe.current=De,je.length!==0&&(Lt(je.flatMap(gc)),et())},[et,e,le,Lt,Z,ie,X]);const Bt=m.useCallback(Y=>{j(U=>{const ue=new Set(U);return ue.has(Y)?ue.delete(Y):ue.add(Y),ue})},[]),Mt=m.useCallback(Y=>{qe(Y),A({parent:Y,kind:"file"})},[qe]),ne=m.useCallback(Y=>{qe(Y),A({parent:Y,kind:"dir"})},[qe]),se=m.useCallback(async(Y,U=!1)=>{if(U){await _e(Y,"preview");return}const ue=JE(Y);if(R.current.find(tt=>tt.rel===ue)){y(ue);return}const De=O.current,Le=await l(Y);if(!(!Le||vc(V.current,Y,De))){if(!Le.ok){fe(Le.error);return}h(tt=>[...tt,{rel:ue,contents:Le.content,draft:Le.content,version:0,dirty:!1,conflict:!1,preview:!0}]),y(ue)}},[fe,l,_e,y]);m.useEffect(()=>E5(e,(Y,U,ue)=>{H.current=U?{rel:Y,line:U}:null;const je=oe.current,De=R.current.find(Le=>Le.rel===Y);if(U&&je?.rel===Y&&B.current===Y&&De?.viewMode!=="preview"){H.current=null,je.editor.focus({lineNumber:U});return}ue==="markdown"&&!U?se(Y,!0):_e(Y,"source")}),[e,_e,se]);const He=m.useCallback(Y=>window.electronAPI.workspaceFiles.readImage({...o,rel:Y}).then(U=>U.ok?U.dataUrl:null),[o]),kt=m.useCallback(Y=>window.electronAPI.workspaceFiles.fetchRemoteImage({...o,url:Y}).then(U=>U.ok?U.dataUrl:null),[o]),st=m.useCallback(async Y=>{const U=await window.electronAPI.workspaceFiles.absPath({...o,rel:Y});if(!U.ok||!U.local||!U.fileUrl){fe(U.ok?"unsupported":U.error);return}const ue=`browser:file:${e}:${Y}`;Eg({conversationId:e,tabId:ue,title:Rr(Y)});const je=await window.electronAPI.browser.navigate(ue,e,U.fileUrl);je.ok||fe(je.error)},[e,fe,o]),ke=m.useCallback(async Y=>{if(re.getState().conversations[e]?.workspaceMigrating){Be({type:"error",title:n("Wait for the workspace operation to finish before saving.")});return}const U=R.current.find(Le=>Le.rel===Y);if(!U||U.preview)return;const ue=U.draft,je=O.current,De=await window.electronAPI.workspaceFiles.write({...o,rel:Y,content:ue});if(!vc(V.current,Y,je)){if(!De.ok){fe(De.error);return}h(Le=>Le.map(tt=>tt.rel===Y?{...tt,contents:ue,dirty:tt.draft!==ue,conflict:!1}:tt))}},[e,fe,o,n]),ut=m.useCallback(Y=>{h(U=>U.map(ue=>ue.rel===Y?{...ue,viewMode:joe(ue.viewMode)}:ue))},[]);m.useEffect(()=>{const Y=U=>{!(U.metaKey||U.ctrlKey)||U.key.toLowerCase()!=="s"||p&&(U.preventDefault(),ke(p))};return window.addEventListener("keydown",Y),()=>window.removeEventListener("keydown",Y)},[p,ke]);const ft=u.find(Y=>Y.rel===p)??null,ze=m.useMemo(()=>({enabledSelectionAction:!0,renderSelectionAction(Y){const U=document.createElement("button");return U.type="button",U.style.cssText="appearance:none;border:0;margin:0;background:transparent;padding:2px 8px;font:inherit;font-size:12px;font-weight:500;line-height:20px;cursor:pointer;color:inherit;border-radius:6px",U.textContent=n("Send to conversation"),U.addEventListener("mouseenter",()=>{U.style.background="color-mix(in lab, currentColor 8%, transparent)"}),U.addEventListener("mouseleave",()=>{U.style.background="transparent"}),U.addEventListener("mousedown",ue=>ue.preventDefault()),U.addEventListener("click",()=>{const ue=Y.getSelectionText().trim(),je=p;if(!ue||!je){Y.close();return}const De=Y.selection.start.line+1;let Le=Y.selection.end.line+1;Y.selection.end.character===0&&Le>De&&(Le-=1);const tt=De===Le?`L${De}`:`L${De}-L${Le}`;Xl({kind:"file",id:`${je}#${tt}`,label:`${Rr(je)}#${tt}`,relativePath:`${je}#${tt}`}),wo(),Y.close()}),U},onChange(Y){const U=p;if(!U)return;const ue=Y.contents;h(je=>je.map(De=>De.rel===U?{...De,draft:ue,dirty:ue!==De.contents}:De))},onAttach(Y){if(!p)return;oe.current={rel:p,editor:Y};const U=H.current;U?.rel===p&&(H.current=null,Y.focus({lineNumber:U.line}))}}),[p,n]),wt=m.useCallback(async(Y,U)=>{const ue=await window.electronAPI.workspaceFiles.rename({...o,rel:Y,name:U});if(!ue.ok){fe(ue.error);return}I(null);const je=ue.rel;if(je){J(Y);for(const De of R.current){if(De.preview||De.tooLarge)continue;const Le=xc(De.rel,Y,je);Le!=null&&(window.electronAPI.workspaceFiles.watchStop({...o,rel:De.rel}),window.electronAPI.workspaceFiles.watchStart({...o,rel:Le}))}h(De=>De.map(Le=>{const tt=xc(Le.rel,Y,je);return tt==null?Le:{...Le,rel:tt}})),f(De=>De==null?De:xc(De,Y,je)??De),j(De=>{let Le=!1;const tt=new Set;for(const bt of De){const Vt=xc(bt,Y,je)??bt;Vt!==bt&&(Le=!0),tt.add(Vt)}return Le?tt:De})}et()},[et,fe,J,o]);return i.jsxs(P5,{createEditor:Toe,children:[i.jsxs("div",{className:"flex h-full min-h-0 bg-background",children:[i.jsxs("div",{className:q("flex shrink-0 flex-col overflow-hidden text-sm",g?x?"w-full":"hidden":"w-56 border-r"),children:[i.jsxs("div",{className:"flex justify-end gap-0.5 px-1 py-0.5",children:[i.jsx(ge,{variant:"ghost",size:"icon-sm",onClick:()=>C(Y=>!Y),"aria-label":n("Search"),"aria-pressed":N,children:i.jsx(ti,{})}),i.jsx(ge,{variant:"ghost",size:"icon-sm",onClick:et,"aria-label":n("Refresh"),children:i.jsx(Fo,{})})]}),N?i.jsx(soe,{conversationId:e,projectId:t,onOpenFile:Y=>{_e(Y)},onClose:()=>C(!1),menu:{local:$,onPreview:Y=>{se(Y)},onBrowser:Y=>{st(Y)},onCopyPath:Y=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:Y,mode:"absolute"})},onCopyRel:Y=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:Y,mode:"relative"})},onCopyFile:Y=>{window.electronAPI.workspaceFiles.copyFile({...o,rel:Y}).then(U=>{U.ok||fe(U.error)})},onReveal:Y=>{window.electronAPI.workspaceFiles.reveal({...o,rel:Y})},onNewFile:Y=>{C(!1),Lt(gc(Y)),Mt(Y)},onNewFolder:Y=>{C(!1),Lt(gc(Y)),ne(Y)},onRename:(Y,U)=>{C(!1),Lt(gc(Y)),I({rel:Y,name:U,at:"tree"})},onDelete:(Y,U)=>T({rel:Y,name:U}),onSend:(Y,U)=>{Xl({kind:"file",id:Y,label:U,relativePath:Y})}}}):i.jsx("div",{className:"min-h-0 flex-1 overflow-auto",children:i.jsx(Qu,{target:{kind:"blank"},local:$,onNewFile:Mt,onNewFolder:ne,onCopyPath:()=>{},onCopyRel:()=>{},children:i.jsx("div",{className:"min-h-full",children:i.jsx(eP,{rel:"",depth:0,conversationId:e,projectId:t,treeEpoch:w,draft:S,renaming:E,local:$,expandedDirs:_,onToggleDir:Bt,onOpen:_e,onPreview:se,onBrowser:st,onCopyPath:Y=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:Y,mode:"absolute"})},onCopyRel:Y=>{window.electronAPI.workspaceFiles.copyPath({...o,rel:Y,mode:"relative"})},onCopyFile:Y=>{window.electronAPI.workspaceFiles.copyFile({...o,rel:Y}).then(U=>{U.ok||fe(U.error)})},onReveal:Y=>{window.electronAPI.workspaceFiles.reveal({...o,rel:Y})},onNewFile:Mt,onNewFolder:ne,onRenameStart:(Y,U)=>I({rel:Y,name:U,at:"tree"}),onDelete:(Y,U)=>T({rel:Y,name:U}),onDraftCancel:()=>A(null),onRenameCancel:()=>I(null),onDraftCommit:async(Y,U,ue)=>{const De=await(U==="dir"?window.electronAPI.workspaceFiles.mkdir:window.electronAPI.workspaceFiles.createFile)({...o,rel:Y||void 0,name:ue});if(!De.ok){fe(De.error);return}A(null),et(),U==="file"&&De.rel&&_e(De.rel)},onRenameCommit:(Y,U)=>{wt(Y,U)}})})})})]}),i.jsxs("div",{className:q("flex min-w-0 flex-1 flex-col",g&&x&&"hidden"),children:[u.length>0&&i.jsxs("div",{ref:te,className:"flex h-[36px] shrink-0 items-center gap-1 overflow-x-auto border-b px-2",children:[g&&i.jsx("button",{type:"button",className:"flex shrink-0 items-center rounded-md px-1 text-muted-foreground hover:bg-muted/50",onClick:()=>v(!0),"aria-label":n("Files"),title:n("Files"),children:i.jsx(A5,{className:"h-4 w-4"})}),u.map(Y=>{const U=E?.rel===Y.rel&&E.at==="tab"&&!Y.preview,ue=i.jsxs("button",{type:"button","data-file-tab":Y.rel,className:q("flex items-center gap-1.5 rounded-md px-2 py-1 text-xs",Y.rel===p?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),onClick:()=>{U||f(Y.rel)},onDoubleClick:je=>{Y.preview||(je.preventDefault(),je.stopPropagation(),I({rel:Y.rel,name:Rr(Y.rel),at:"tab"}))},children:[U?i.jsx(Fu,{depth:0,kind:"file",variant:"tab",initial:E.name,onCancel:()=>I(null),onCommit:je=>{wt(Y.rel,je)}}):i.jsxs("span",{className:"max-w-36 truncate",children:[Rr(Y.preview?Kr(Y.rel):Y.rel),Y.preview?` ${n("Preview")}`:"",Y.dirty?"*":""]}),i.jsx("button",{type:"button",className:"text-muted-foreground hover:text-destructive",onClick:je=>{je.stopPropagation(),de(Y.rel)},children:"×"})]});return i.jsxs(uo,{children:[i.jsx(ho,{render:ue}),i.jsxs(po,{className:"min-w-40",children:[!Y.preview&&i.jsx(Ut,{onClick:()=>I({rel:Y.rel,name:Rr(Y.rel),at:"tab"}),children:n("Rename")}),i.jsx(Ut,{onClick:()=>de(Y.rel),children:n("Close")}),i.jsx(Ut,{onClick:()=>{const je=R.current,De=Y.rel,Le=je.some(tt=>tt.rel!==De&&tt.dirty);W(tt=>tt!==De&&!je.find(bt=>bt.rel===tt)?.dirty),Le&&me({kind:"others",rel:De})},children:n("Close others")}),i.jsx(Ut,{onClick:()=>{const je=R.current,De=ig(je.map(tt=>tt.rel),Y.rel,"right"),Le=De.some(tt=>je.find(bt=>bt.rel===tt)?.dirty);W(tt=>De.includes(tt)&&!je.find(bt=>bt.rel===tt)?.dirty),Le&&me({kind:"right",rel:Y.rel})},children:n("Close tabs to the right")}),i.jsx(Ut,{onClick:()=>{const je=R.current;W(De=>!je.find(Le=>Le.rel===De)?.dirty)},children:n("Close saved")}),i.jsx(Ut,{onClick:()=>{const je=R.current,De=je.some(Le=>Le.dirty);W(Le=>!je.find(tt=>tt.rel===Le)?.dirty),De&&me({kind:"all"})},children:n("Close all")}),i.jsx(Ut,{onClick:()=>W(je=>je!==Y.rel),children:n("Force close others")}),i.jsx(Ut,{onClick:()=>W(()=>!0),children:n("Force close all")})]})]},Y.rel)})]}),ft?.conflict&&i.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-b px-2 py-1 text-[11px]",children:[i.jsx("span",{children:n("This file changed on disk.")}),i.jsx("button",{type:"button",className:"underline",disabled:a,onClick:()=>{l(Kr(ft.rel)).then(Y=>{Y?.ok&&h(U=>U.map(ue=>ue.rel===ft.rel?{...ue,contents:Y.content,draft:Y.content,version:ue.version+1,dirty:!1,conflict:!1}:ue))})},children:n("Reload")})]}),i.jsxs("div",{className:"relative min-h-0 flex-1",children:[ft&&!ft.preview&&!ft.tooLarge&&f0(ft.rel)&&i.jsx("div",{className:"absolute top-2 right-2 z-10",children:i.jsxs(ge,{type:"button",variant:"outline",size:"sm","aria-label":ft.viewMode==="preview"?n("View Source"):n("Preview"),onClick:()=>ut(ft.rel),children:[ft.viewMode==="preview"?i.jsx(Q1,{className:"h-3.5 w-3.5"}):i.jsx(M5,{className:"h-3.5 w-3.5"}),ft.viewMode==="preview"?n("View Source"):n("Preview")]})}),!d||!ft?i.jsx("div",{className:"flex h-full items-center justify-center px-3 text-center text-sm text-muted-foreground",children:n(d?"Open a file from the tree.":"Loading...")}):ft.tooLarge?i.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center text-sm text-muted-foreground",children:n("This file is too large to open in the editor.")}):ft.preview||ft.viewMode==="preview"&&f0(ft.rel)?i.jsx("div",{className:"h-full overflow-auto px-3 py-2 text-sm",children:i.jsx(woe,{text:ft.preview?ft.contents:ft.draft,baseDirRel:Ioe(Kr(ft.rel)),resolveImage:He,resolveRemoteImage:kt})}):i.jsx(R5,{style:{height:"100%",overflow:"auto"},children:i.jsx(kk,{file:{name:Rr(ft.rel),contents:ft.draft},disableWorkerPool:!0,edit:!0,editorOptions:ze,options:s},`${ft.rel}:${ft.version}`)})]})]})]}),i.jsx(fs,{open:Ee!==null,onOpenChange:Y=>{Y||me(null)},title:n("Unsaved changes"),description:Ee?.kind==="one"?n("This file has unsaved changes. Close anyway?"):n("Some files have unsaved changes. Close anyway?"),confirmLabel:n("Close"),onConfirm:()=>{if(Ee){if(Ee.kind==="one"&&Ee.rel)G(Ee.rel);else if(Ee.kind==="others"&&Ee.rel){const Y=Ee.rel;W(U=>U!==Y)}else if(Ee.kind==="right"&&Ee.rel){const Y=Ee.rel,U=new Set(ig(R.current.map(ue=>ue.rel),Y,"right"));W(ue=>U.has(ue))}else W(()=>!0);me(null)}}}),i.jsx(fs,{open:D!==null,onOpenChange:Y=>{Y||T(null)},title:n("Delete"),description:n("Delete {{name}} permanently?",{name:D?.name??""}),confirmLabel:n("Delete"),onConfirm:()=>{if(!D)return;const{rel:Y}=D;window.electronAPI.workspaceFiles.remove({...o,rel:Y}).then(U=>{if(!U.ok){fe(U.error);return}J(Y),W(ue=>sg(ue,Y)),j(ue=>{let je=!1;const De=new Set;for(const Le of ue){if(sg(Le,Y)){je=!0;continue}De.add(Le)}return je?De:ue}),T(null),et()})}})]})}function Fu({depth:e,kind:t,initial:n,onCancel:s,onCommit:o,variant:r="tree"}){const[a,l]=m.useState(n),d=m.useRef(null),c=m.useRef(!0),u=m.useRef(!1);m.useEffect(()=>{const p=window.setTimeout(()=>{const g=d.current;g&&(g.focus(),g.select())},0),f=window.setTimeout(()=>{c.current=!1},50);return()=>{window.clearTimeout(p),window.clearTimeout(f)}},[]);const h=p=>{if(!u.current){if(p==="commit"&&koe(a,n)==="commit"){u.current=!0,o(a.trim());return}u.current=!0,s()}};return i.jsx("input",{ref:d,className:r==="tab"?"max-w-36 rounded-sm border bg-background px-1 py-0 text-xs outline-none":"mx-1 my-0.5 w-[calc(100%-0.5rem)] rounded-sm border bg-background px-1 py-0.5 text-sm outline-none",style:r==="tree"?{marginLeft:8+e*12}:void 0,value:a,onChange:p=>l(p.target.value),onPointerDown:p=>p.stopPropagation(),onClick:p=>p.stopPropagation(),onBlur:()=>{if(c.current){d.current?.focus();return}h("commit")},onKeyDown:p=>{p.nativeEvent.isComposing||(p.key==="Escape"&&(p.preventDefault(),h("cancel")),p.key==="Enter"&&(p.preventDefault(),h("commit")))},"aria-label":t==="dir"?"New Folder":"New File"})}function eP({rel:e,depth:t,conversationId:n,projectId:s,treeEpoch:o,...r}){const[a,l]=m.useState(null);if(m.useEffect(()=>{let c=!0;return window.electronAPI.workspaceFiles.listDir({conversationId:n,projectId:s,rel:e||void 0}).then(u=>{c&&l(u.ok?u.entries:[])}),()=>{c=!1}},[n,s,e,o]),!a)return i.jsx("div",{className:"px-2 py-1 text-muted-foreground",children:"…"});const d=r.draft?.parent===e;return i.jsxs("div",{children:[a.map(c=>{const u=Doe(e,c.name),h=r.expandedDirs.has(u);if(c.kind==="dir"){const f=r.renaming?.rel===u&&r.renaming.at==="tree"?i.jsx(Fu,{depth:t,kind:"dir",initial:c.name,onCancel:r.onRenameCancel,onCommit:g=>r.onRenameCommit(u,g)}):i.jsxs("button",{type:"button",className:"flex w-full items-center gap-1.5 px-2 py-1 text-left hover:bg-muted/60",style:{paddingLeft:8+t*12},onClick:()=>r.onToggleDir(u),children:[i.jsx(bn,{className:q("h-3.5 w-3.5 shrink-0",h&&"rotate-90")}),(()=>{const g=_d(c.name,!0,h);return i.jsx(g,{className:q("h-4 w-4 shrink-0",Nd(c.name,!0))})})(),i.jsx("span",{className:"truncate",children:c.name})]});return i.jsxs("div",{children:[i.jsx(Qu,{target:{kind:"dir",rel:u,name:c.name},local:r.local,onNewFile:r.onNewFile,onNewFolder:r.onNewFolder,onCopyPath:r.onCopyPath,onCopyRel:r.onCopyRel,onReveal:r.onReveal,onRename:r.onRenameStart,onDelete:r.onDelete,children:f}),h&&i.jsx(eP,{rel:u,depth:t+1,conversationId:n,projectId:s,treeEpoch:o,...r})]},u)}return i.jsx(Poe,{rel:u,name:c.name,depth:t,renaming:r.renaming?.rel===u&&r.renaming.at==="tree",handlers:r},u)}),d&&r.draft&&i.jsx(Fu,{depth:t,kind:r.draft.kind,initial:"",onCancel:r.onDraftCancel,onCommit:c=>r.onDraftCommit(e,r.draft.kind,c)})]})}function Poe({rel:e,name:t,depth:n,renaming:s,handlers:o}){const{setNodeRef:r,listeners:a,isDragging:l}=Fg({id:`workspace-file:${e}`,data:{type:"workspace-file",relativePath:e,name:t}}),d=s?i.jsx(Fu,{depth:n,kind:"file",initial:t,onCancel:o.onRenameCancel,onCommit:c=>o.onRenameCommit(e,c)}):i.jsxs("button",{type:"button",ref:r,...a,style:{paddingLeft:20+n*12,opacity:l?.4:void 0},className:"flex w-full cursor-default items-center gap-1.5 px-2 py-1 text-left hover:bg-muted/60",onClick:()=>o.onOpen(e),children:[(()=>{const c=_d(t,!1);return i.jsx(c,{className:q("h-4 w-4 shrink-0",Nd(t,!1))})})(),i.jsx("span",{className:"truncate",children:t})]});return i.jsx(Qu,{target:{kind:"file",rel:e,name:t},local:o.local,onNewFile:o.onNewFile,onNewFolder:o.onNewFolder,onView:o.onOpen,onPreview:o.onPreview,onBrowser:o.onBrowser,onCopyPath:o.onCopyPath,onCopyRel:o.onCopyRel,onCopyFile:o.onCopyFile,onReveal:o.onReveal,onRename:o.onRenameStart,onDelete:o.onDelete,onSend:(c,u)=>{Xl({kind:"file",id:c,label:u,relativePath:c})},children:d})}function Aoe({open:e,onClose:t,onFindNext:n,onFindPrevious:s,onClear:o,theme:r}){const{t:a}=Q(),l=m.useRef(null),[d,c]=m.useState(""),[u,h]=m.useState(!1),[p,f]=m.useState(!1),[g,x]=m.useState(!1),[v,y]=m.useState(null);m.useEffect(()=>{e?(l.current?.focus(),l.current?.select()):(o(),y(null))},[e,o]);const w=()=>({caseSensitive:u,wholeWord:p,regex:g}),b=N=>{if(!d){y(null);return}y(N==="next"?n(d,w()):s(d,w()))};if(!e)return null;const _=r?.background??"#1e1e1e",j=r?.foreground??"#d4d4d4";return i.jsxs("div",{className:"absolute top-2 right-2 z-10 flex items-center gap-1 rounded-md border px-2 py-1 shadow-lg",style:{backgroundColor:_,borderColor:`${j}30`},children:[i.jsx("input",{ref:l,value:d,onChange:N=>{const C=N.target.value;c(C),C?y(n(C,w())):(o(),y(null))},onKeyDown:N=>{N.key==="Enter"?(N.preventDefault(),b(N.shiftKey?"prev":"next")):N.key==="Escape"&&(N.preventDefault(),t())},placeholder:a("Search..."),className:q("w-40 bg-transparent text-sm outline-none placeholder:opacity-50",v===!1&&d&&"text-red-400"),style:{color:j}}),i.jsx("button",{type:"button",onClick:()=>h(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",u?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Case sensitive"),children:"Aa"}),i.jsx("button",{type:"button",onClick:()=>f(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",p?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Whole word"),children:"W"}),i.jsx("button",{type:"button",onClick:()=>x(N=>!N),className:q("flex h-6 w-6 items-center justify-center rounded text-xs font-bold",g?"bg-white/20":"opacity-50 hover:opacity-100"),style:{color:j},title:a("Regular expression"),children:".*"}),i.jsx("div",{className:"mx-1 h-4 w-px",style:{backgroundColor:`${j}30`}}),i.jsx("button",{type:"button",onClick:()=>b("prev"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Previous match"),children:i.jsx(wj,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:()=>b("next"),className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Next match"),children:i.jsx(Vn,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",onClick:t,className:"flex h-6 w-6 items-center justify-center rounded opacity-70 hover:opacity-100",style:{color:j},title:a("Close"),children:i.jsx(an,{className:"h-4 w-4"})})]})}function VC(e,t){const n=$u(e);return t?H5(n):n}function Moe({termId:e,conversationId:t,projectId:n,onTitle:s}){const{t:o}=Q(),r=m.useRef(null),a=m.useRef(null),l=m.useRef(""),[d,c]=m.useState(!1),u=m.useRef(t);u.current=t;const h=m.useRef(n);h.current=n;const p=m.useRef(s);p.current=s;const f=Ce(D=>D.terminalTheme),g=Ce(D=>D.terminalFontFamily),x=Ce(D=>D.terminalFontSize),v=rk()!==null,y=m.useRef(v);y.current=v;const[w,b]=m.useState(!1);m.useEffect(()=>{const D=r.current;if(!D)return;let T=!1,z=0,$;const R=()=>{if(T)return;if(!D.isConnected||D.clientWidth===0||D.clientHeight===0){z=requestAnimationFrame(R);return}const H=Ce.getState(),oe=F5(e,D,{theme:VC(H.terminalTheme,y.current),fontFamily:H.terminalFontFamily,fontSize:H.terminalFontSize});if(!oe.opened){z=requestAnimationFrame(R);return}oe.onTitle=O=>p.current?.(O);const te=()=>{!D.isConnected||D.clientWidth===0||(oe.fit.fit(),window.electronAPI.terminal.resize(e,oe.term.cols,oe.term.rows))};te(),window.electronAPI.terminal.create({termId:e,conversationId:u.current,projectId:h.current,cols:oe.term.cols,rows:oe.term.rows}),oe.term.focus(),a.current=oe.term,$=new ResizeObserver(te),$.observe(D)};document.fonts.load('14px "Enso Nerd Symbols"',"").then(R,H=>{console.warn("Failed to load terminal icon font",H),R()});const B=H=>{(H.metaKey||H.ctrlKey)&&H.key==="f"&&(H.preventDefault(),H.stopPropagation(),b(!0))};return D.addEventListener("keydown",B,!0),()=>{T=!0,cancelAnimationFrame(z),$?.disconnect(),D.removeEventListener("keydown",B,!0),a.current=null,O5(e)}},[e]),m.useEffect(()=>{z5(VC(f,v),g,x)},[f,g,x,v]);const _=m.useCallback((D,T)=>m0(e,D,"next",T),[e]),j=m.useCallback((D,T)=>m0(e,D,"prev",T),[e]),N=m.useCallback(()=>G5(e),[e]),C=()=>{const D=a.current?.getSelection().trim()??"";l.current=D,c(D.length>0)},S=()=>{const D=l.current||a.current?.getSelection().trim()||"";D&&(wh(D),wo(),a.current?.clearSelection(),c(!1))},A=()=>{const D=l.current||a.current?.getSelection().trim()||"";D&&navigator.clipboard.writeText(D)},E=$u(f),I=i.jsx("div",{ref:r,"data-slot":"terminal-pane",className:"relative h-full w-full overflow-hidden p-2",style:{backgroundColor:E?.background,"--terminal-bg":E?.background},onContextMenu:C,children:i.jsx(Aoe,{open:w,onClose:()=>b(!1),onFindNext:_,onFindPrevious:j,onClear:N,theme:E})});return i.jsxs(uo,{children:[i.jsx(ho,{render:I}),i.jsxs(po,{className:"min-w-40",children:[i.jsx(Ut,{disabled:!d,onClick:A,children:o("Copy")}),i.jsx(Ut,{disabled:!d,onClick:S,children:o("Send to conversation")})]})]})}const tP={running:"bg-amber-500",completed:"bg-emerald-500",failed:"bg-destructive",cancelled:"bg-muted-foreground"},Roe=[],Loe={project:"Project",custom:"Custom",global:"Global",builtin:"Built-in"};function Ooe(e,t,n,s){const o=re.getState(),r=o.conversations[e],a=Ce.getState(),l=a.projects.find(u=>u.id===r?.projectId);if(!r||!l)return!1;const d=Al({defaultModel:a.defaultModel,...Zc(l,a.projectGroups),lastProviderId:r.lastProviderId,lastModelId:r.lastModelId,providers:Vj(),credentials:aa(Fi.getState().snapshot),virtualModels:a.virtualModels});if(d.source==="none")return Be({type:"warning",title:s("No usable model is available. Configure provider credentials and enable a model first.")}),!1;const c={};for(const u of t.args){const h=n[u.key]?.trim();h&&(c[u.key]=h)}return o.send(B5({id:t.id,name:t.source==="builtin"?s(t.name):t.name,args:c}),{providerId:d.providerId,modelId:d.modelId,cwd:l.path},void 0,e),!0}function zoe({conversationId:e,preset:t,open:n,onToggle:s}){const{t:o}=Q(),[r,a]=m.useState({}),l=t.args.some(u=>u.required&&!u.default?.trim()&&!r[u.key]?.trim()),d=t.source==="builtin"?o(t.name):t.name,c=t.source==="builtin"?o(t.description):t.description;return i.jsxs("li",{className:"rounded-md border",children:[i.jsxs("button",{type:"button",className:"w-full px-2 py-1.5 text-left text-xs hover:bg-muted/60",onClick:s,children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:"min-w-0 flex-1 truncate font-medium",children:d}),i.jsx("span",{className:"shrink-0 text-muted-foreground",children:o(Loe[t.source])})]}),i.jsx("p",{className:"mt-0.5 line-clamp-2 text-muted-foreground",children:c})]}),n?i.jsxs("form",{className:"space-y-2 border-t px-2 py-2",onSubmit:u=>{u.preventDefault(),!(l||!Ooe(e,t,r,o))&&(a({}),s())},children:[t.args.map(u=>i.jsxs("label",{className:"block text-xs",children:[i.jsxs("span",{className:"text-muted-foreground",children:[t.source==="builtin"?o(u.label):u.label,u.required?" *":""]}),i.jsx(Xt,{size:"sm",className:"mt-1",value:r[u.key]??"",placeholder:u.default,onChange:h=>a(p=>({...p,[u.key]:h.target.value}))})]},u.key)),i.jsx("div",{className:"flex justify-end",children:i.jsxs(ge,{type:"submit",size:"xs",disabled:l,children:[i.jsx(pg,{}),o("Run")]})})]}):null]})}function Goe({conversationId:e}){const{t}=Q(),[n,s]=m.useState([]),[o,r]=m.useState(null),a=Ce(c=>c.disabledWorkflowPresets),l=m.useCallback(()=>{let c=!1;return window.electronAPI.assets.listWorkflowPresets(e).then(u=>{c||s(u)}).catch(()=>{c||s([])}),()=>{c=!0}},[e]);m.useEffect(l,[l]);const d=n.filter(c=>c.source!=="builtin"||!a.includes(c.id));return i.jsxs("section",{children:[i.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[i.jsx("h3",{className:"flex-1 text-xs font-medium text-muted-foreground",children:t("Presets")}),i.jsx(ge,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Manage workflow presets"),title:t("Manage workflow presets"),onClick:()=>{window.electronAPI.window.openSettings({category:"workflows",rowId:"workflows.root"})},children:i.jsx(Nj,{})}),i.jsx(ge,{type:"button",variant:"ghost",size:"icon-xs","aria-label":t("Refresh"),onClick:()=>l(),children:i.jsx(Fo,{})})]}),i.jsx("ul",{className:"space-y-1.5",children:d.map(c=>i.jsx(zoe,{conversationId:e,preset:c,open:o===c.id,onToggle:()=>r(u=>u===c.id?null:c.id)},`${c.source}:${c.id}`))})]})}function Foe(e,t){const n=re.getState();n.activeId!==e&&n.selectConversation(e),n.selectTab(e,t)}function Hoe({conversationId:e,member:t}){const{t:n}=Q(),s=i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:q("h-1.5 w-1.5 shrink-0 rounded-full",tP[t.status])}),i.jsx("span",{className:"min-w-0 flex-1 truncate",children:t.label}),i.jsx("span",{className:"text-muted-foreground",children:n(t.status)})]}),t.prompt?i.jsx("p",{className:"mt-0.5 truncate pl-3.5 text-muted-foreground",children:t.prompt}):null,t.result?i.jsx("p",{className:"mt-0.5 line-clamp-3 whitespace-pre-wrap pl-3.5 text-foreground/80",children:t.result}):null]}),o=t.childId;return o?i.jsx("li",{children:i.jsx("button",{type:"button",className:"w-full rounded px-1 py-0.5 text-left text-xs hover:bg-muted/60",onClick:()=>Foe(e,o),children:s})}):i.jsx("li",{className:"text-xs",children:s})}function Boe({conversationId:e}){const{t}=Q(),n=Tf(r=>r.byConversation[e])??Roe,s=Tf(r=>r.clearFinished),o=n.some(r=>r.status!=="running");return i.jsx("div",{className:"h-full overflow-auto bg-background p-3",children:i.jsxs("div",{className:"space-y-3",children:[i.jsx(Goe,{conversationId:e}),o?i.jsx("div",{className:"flex justify-end",children:i.jsxs(ge,{type:"button",variant:"ghost",size:"xs",className:"text-muted-foreground",onClick:()=>s(e),children:[i.jsx(Ig,{}),t("Clear finished runs")]})}):null,n.length===0?i.jsx("p",{className:"py-4 text-center text-sm text-muted-foreground",children:t("No workflow runs")}):null,n.map(r=>i.jsxs("section",{className:"rounded-md border px-3 py-2",children:[i.jsxs("div",{className:"flex items-center gap-2",children:[i.jsx("span",{className:q("h-2 w-2 shrink-0 rounded-full",tP[r.status])}),i.jsx("h3",{className:"min-w-0 flex-1 truncate text-sm font-medium",children:r.name}),i.jsx("span",{className:"text-xs text-muted-foreground",children:t(r.status)}),r.status==="running"?i.jsx(ge,{type:"button",variant:"ghost",size:"icon-xs",className:"text-muted-foreground hover:text-destructive","aria-label":t("Stop"),title:t("Stop"),onClick:()=>{window.electronAPI.agent.stopWorkflow(e,r.runId)},children:i.jsx(ld,{})}):null]}),i.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r.description}),i.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:t("{{count}} agents",{count:r.members.length})}),i.jsx("div",{className:"mt-2 space-y-2",children:j6(r.members).map((a,l,d)=>{const c=!!a.phase&&a.phase!==d[l-1]?.phase;return i.jsxs("div",{children:[i.jsxs("div",{className:"mb-1 flex items-center gap-2 text-xs",children:[c?i.jsx("span",{className:"font-medium",children:a.phase}):null,a.members.length>1?i.jsx("span",{className:"text-muted-foreground",children:t("Parallel")}):null]}),i.jsx("ul",{className:"space-y-1",children:a.members.map(u=>i.jsx(Hoe,{conversationId:e,member:u},u.seq))})]},`${a.batch}:${a.phase??""}`)})}),r.error?i.jsx("p",{className:"mt-2 text-xs text-destructive",children:r.error}):null,r.logs.length>0?i.jsx("p",{className:"mt-2 whitespace-pre-wrap text-xs text-muted-foreground",children:r.logs.join(`
|
|
114
|
-
`)}):null]},r.runId))]})})}const Dv=m.createContext({}),nP=m.createContext(!1);function Voe(e,t){const[n,s]=m.useState(!t);return m.useEffect(()=>{if(!t)return;const o=()=>{const a=t.element.closest(".dv-dockview")?.getBoundingClientRect(),l=t.element.getBoundingClientRect();s(!!a&&Math.abs(l.top-a.top)<1&&Math.abs(l.right-a.right)<1)};o();const r=e.onDidLayoutChange(o);return()=>r.dispose()},[e,t]),n}function sP(e,t){const n=e.panels.length;return n===0?t:`${t} ${n+1}`}function iP(e,t,n,s){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:sP(e,s),params:{conversationId:t,projectId:n}})}function oP(e,t,n,s){const o=e.getPanel("changes");if(o){o.focus();return}e.addPanel({id:"changes",component:"changes",title:s,params:{conversationId:t,projectId:n}})}function $oe(e){return i.jsx(Moe,{termId:e.api.id,conversationId:e.params.conversationId,projectId:e.params.projectId,onTitle:t=>e.api.setTitle(t)})}function Woe(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(toe,{conversationId:t,projectId:n})}function rP(e,t,n,s){const o=e.getPanel("files");if(o){o.focus();return}e.addPanel({id:"files",component:"files",title:s,params:{conversationId:t,projectId:n}})}function Uoe(e){const{conversationId:t,projectId:n}=e.params;return!t||!n?null:i.jsx(Eoe,{conversationId:t,projectId:n})}function aP(e,t,n,s){const o=e.panels.filter(r=>r.id.startsWith("btw:")).length;e.addPanel({id:`btw:${crypto.randomUUID()}`,component:"btw",title:o===0?s:`${s} ${o+1}`,params:{conversationId:t,projectId:n}})}function Koe(e){const{conversationId:t}=e.params;return t?i.jsx($ie,{conversationId:t,panelApi:e.api}):null}function lP(e,t,n,s,o){const r=`browser:${crypto.randomUUID()}`,a=e.getPanel(r);if(a){a.focus();return}e.addPanel({id:r,component:"browser",title:s,params:{conversationId:t,projectId:n}})}function qoe(e){const{conversationId:t}=e.params;return t?i.jsx(ZT,{conversationId:t,panelApi:e.api}):null}function dP(e,t,n,s){const o=e.getPanel("workflow");if(o){o.focus();return}e.addPanel({id:"workflow",component:"workflow",title:s,params:{conversationId:t,projectId:n}})}function Iv(e){return Ce(t=>U5(t,e))}function cP(e,t,n,s,o){const r=`plugin:${s.pluginId}:${s.id}`,a=e.getPanel(r);if(a){a.focus();return}e.addPanel({id:r,component:"plugin",title:s.title,params:{conversationId:t,projectId:n,pluginId:s.pluginId,viewId:s.id},renderer:"always",...o?{position:{referenceGroup:o}}:{}})}function Yoe(e){const{conversationId:t,pluginId:n,viewId:s}=e.params;return m.useEffect(()=>{e.api.renderer!=="always"&&e.api.setRenderer("always")},[e.api]),!n||!s?null:i.jsx(Vie,{pluginId:n,viewId:s,sessionId:t??null})}function Xoe(e){const{conversationId:t}=e.params;return t?i.jsx(Boe,{conversationId:t}):null}function bc(e,t){const n=e.group.panels.map(o=>o.id),s=new Set(ig(n,e.id,t));for(const o of[...e.group.panels])s.has(o.id)&&o.api.close()}function Zoe(e){const{t}=Q(),[n,s]=m.useState(e.api.isActive),[o,r]=m.useState(e.api.title??""),[a,l]=m.useState(e.params.favicon??null),[d,c]=m.useState(!1);m.useEffect(()=>{const p=e.api.onDidActiveChange(()=>s(e.api.isActive)),f=e.api.onDidTitleChange(()=>r(e.api.title??"")),g=e.api.onDidParametersChange(x=>{const v=x&&typeof x=="object"&&"favicon"in x?x.favicon??null:e.api.getParameters()?.favicon??null;l(v??null),c(!1)});return()=>{p.dispose(),f.dispose(),g.dispose()}},[e.api]);const u=e.api.id==="browser"||e.api.id.startsWith("browser:"),h=i.jsxs("div",{"data-side-tab":!0,"data-active":n||void 0,className:q("group/tab relative flex min-w-0 items-center gap-1.5 rounded-md px-2 py-1 text-xs transition-colors",n?"bg-muted font-medium":"text-muted-foreground hover:bg-muted/50"),children:[e.api.id==="changes"?i.jsx(xx,{className:"h-3 w-3 shrink-0"}):e.api.id==="files"?i.jsx(ni,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("btw:")?i.jsx(vr,{className:"h-3 w-3 shrink-0"}):e.api.id==="workflow"?i.jsx(cg,{className:"h-3 w-3 shrink-0"}):e.api.id.startsWith("plugin:")?i.jsx(dg,{pluginId:e.api.id.split(":")[1]??"",className:"h-3 w-3 shrink-0"}):u&&a&&!d?i.jsx("img",{src:a,alt:"",className:"h-3 w-3 shrink-0",onError:()=>c(!0)}):u?i.jsx(fo,{className:"h-3 w-3 shrink-0"}):i.jsx(Go,{className:"h-3 w-3 shrink-0"}),i.jsx("span",{className:"max-w-32 truncate",children:o}),i.jsx("button",{type:"button",className:"rounded p-0.5 text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/tab:opacity-100",onPointerDown:p=>p.stopPropagation(),onClick:p=>{p.stopPropagation(),e.api.close()},children:i.jsx(an,{className:"h-3 w-3"})})]});return i.jsxs(uo,{children:[i.jsx(ho,{render:h}),i.jsxs(po,{className:"min-w-40",children:[i.jsx(Ut,{onClick:()=>bc(e.api,"self"),children:t("Close")}),i.jsx(Ut,{onClick:()=>bc(e.api,"others"),children:t("Close others")}),i.jsx(Ut,{onClick:()=>bc(e.api,"right"),children:t("Close tabs to the right")}),i.jsx(Ut,{onClick:()=>bc(e.api,"all"),children:t("Close all")})]})]})}function uP({onNewTerminal:e,onNewChanges:t,onNewFiles:n,onNewBrowser:s,onNewBtw:o,onNewWorkflow:r,onNewPluginView:a,compact:l}){const{t:d}=Q(),c=Hj();return i.jsxs(Hi,{children:[i.jsxs(Bi,{className:q("flex items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",l?"h-6 w-6 rounded p-1 hover:bg-muted":"h-8 gap-1.5 border border-dashed px-3 text-sm hover:border-solid"),"aria-label":d("New tab"),children:[i.jsx(ds,{className:"h-4 w-4"}),!l&&i.jsx("span",{children:d("New tab")})]}),i.jsxs(Vi,{align:l?"end":"center",className:"min-w-36",children:[i.jsxs(pn,{onClick:e,children:[i.jsx(Go,{className:"h-4 w-4"}),d("Terminal")]}),i.jsxs(pn,{onClick:t,children:[i.jsx(xx,{className:"h-4 w-4"}),d("Changes")]}),i.jsxs(pn,{onClick:n,children:[i.jsx(ni,{className:"h-4 w-4"}),d("Files")]}),i.jsxs(pn,{onClick:s,children:[i.jsx(fo,{className:"h-4 w-4"}),d("Browser")]}),i.jsxs(pn,{onClick:o,children:[i.jsx(vr,{className:"h-4 w-4"}),d("Btw")]}),r?i.jsxs(pn,{onClick:r,children:[i.jsx(cg,{className:"h-4 w-4"}),d("Workflow")]}):null,a?c.map(u=>i.jsxs(pn,{onClick:()=>a(u),children:[i.jsx(dg,{pluginId:u.pluginId,className:"h-4 w-4"}),u.title]},`${u.pluginId}:${u.id}`)):null]})]})}function hP({containerApi:e,group:t}){const{t:n}=Q(),{conversationId:s,projectId:o}=m.useContext(Dv),r=gn(f=>f.fullscreen),a=gn(f=>f.toggleFullscreen),l=Iv(o),d=ba(),c=m.useContext(nP),u=Voe(e,t),h=gn(f=>f.toggleOpen),p=Zu()==="windows";return i.jsxs("div",{className:"flex h-full items-center gap-0.5",children:[i.jsx(uP,{compact:!0,onNewTerminal:()=>{if(t){e.addPanel({id:crypto.randomUUID(),component:"terminal",title:sP(e,n("Terminal")),params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}iP(e,s,o,n("Terminal"))},onNewChanges:()=>oP(e,s,o,n("Changes")),onNewFiles:()=>rP(e,s,o,n("Files")),onNewBrowser:()=>lP(e,s,o,n("Browser")),onNewBtw:()=>{if(t){const f=e.panels.filter(g=>g.id.startsWith("btw:")).length;e.addPanel({id:`btw:${crypto.randomUUID()}`,component:"btw",title:f===0?n("Btw"):`${n("Btw")} ${f+1}`,params:{conversationId:s,projectId:o},position:{referenceGroup:t}});return}aP(e,s,o,n("Btw"))},onNewWorkflow:l?()=>dP(e,s,o,n("Workflow")):void 0,onNewPluginView:f=>cP(e,s,o,f,t)}),i.jsx("button",{type:"button",className:q("flex h-6 w-6 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",d&&"hidden"),onClick:a,"aria-label":n(r?"Exit side panel fullscreen":"Expand side panel"),title:n(r?"Exit side panel fullscreen":"Expand side panel"),children:r?i.jsx(Y5,{className:"h-3.5 w-3.5"}):i.jsx(X5,{className:"h-3.5 w-3.5"})}),c&&u&&i.jsx("button",{type:"button",className:"ml-1 flex h-8 w-8 items-center justify-center rounded-md text-foreground transition-colors hover:bg-muted",onClick:h,"aria-label":n("Toggle side panel"),title:n("Toggle side panel"),children:i.jsx(nN,{className:"h-4 w-4"})}),c&&u&&p&&i.jsx("span",{"aria-hidden":!0,className:"shrink-0",style:{width:`calc(100vw - env(titlebar-area-width, calc(100vw - ${Z5}px)) - 19px)`}})]})}function Joe(e){const{t}=Q(),{conversationId:n,projectId:s}=m.useContext(Dv),o=Iv(s);return i.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[i.jsx("div",{className:"enso-side-dock-header flex shrink-0 items-center justify-end border-b bg-background px-2 py-1",children:i.jsx(hP,{containerApi:e.containerApi})}),i.jsxs("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-background px-6 text-center",children:[i.jsx("p",{className:"text-sm text-muted-foreground",children:t("No tabs yet. Create one to get started.")}),i.jsx(uP,{onNewTerminal:()=>iP(e.containerApi,n,s,t("Terminal")),onNewChanges:()=>oP(e.containerApi,n,s,t("Changes")),onNewFiles:()=>rP(e.containerApi,n,s,t("Files")),onNewBrowser:()=>lP(e.containerApi,n,s,t("Browser")),onNewBtw:()=>aP(e.containerApi,n,s,t("Btw")),onNewWorkflow:o?()=>dP(e.containerApi,n,s,t("Workflow")):void 0,onNewPluginView:r=>cP(e.containerApi,n,s,r)})]})]})}function Qoe(e){return i.jsx(hP,{containerApi:e.containerApi,group:e.group})}const $C={terminal:$oe,changes:Woe,files:Uoe,browser:qoe,btw:Koe,workflow:Xoe,plugin:Yoe};function ere(){const[e,t]=m.useState(()=>document.documentElement.classList.contains("dark"));return m.useEffect(()=>{const n=new MutationObserver(()=>t(document.documentElement.classList.contains("dark")));return n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),()=>n.disconnect()},[]),e}function tre({conversationId:e,hidden:t}){const n=re(s=>s.conversations[e]?.projectId);return n?i.jsx("div",{className:q("absolute inset-0",t&&"hidden"),children:i.jsx(nre,{conversationId:e,projectId:n})}):null}function nre({conversationId:e,projectId:t}){const n=ere(),s=Iv(t),[o,r]=m.useState(null);m.useEffect(()=>{s||o?.getPanel("workflow")?.api.close()},[o,s]);const a=l=>{K5(e,l.api);const d=gn.getState().layouts[e],c=Rie(d,new Set(Object.keys($C)));let u=!!d&&!c;if(c)try{l.api.fromJSON(c)}catch{u=!0}l.api.onDidLayoutChange(()=>{const h=l.api.toJSON();u&&Object.keys(h.panels??{}).length===0||(u=!1,gn.getState().saveLayout(e,h))}),l.api.onDidRemovePanel(h=>{if(!(h.id==="changes"||h.id==="files"||h.id.startsWith("plugin:"))){if(h.id==="browser"||h.id.startsWith("browser:")){window.electronAPI.browser.closeTab(h.id);return}if(h.id.startsWith("btw:")){re.getState().disposeBtwConversation(h.id.slice(4));return}q5(h.id),window.electronAPI.terminal.dispose(h.id)}}),r(l.api)};return i.jsx(Dv.Provider,{value:{conversationId:e,projectId:t},children:i.jsx("div",{className:"enso-side-dock h-full",children:i.jsx(HE,{components:$C,defaultTabComponent:Zoe,watermarkComponent:Joe,rightHeaderActionsComponent:Qoe,theme:n?use:hse,onReady:a})})})}function sre({width:e,resizing:t=!1,card:n=!1,titleRow:s=!1}){const{t:o}=Q(),r=re(T=>T.activeId),a=gn(T=>r?!!T.uiByConversation[r]?.open:!1),l=ba(),c=gn(T=>T.fullscreen)||l&&a;m.useEffect(()=>{const T=window.electronAPI.browser.onReveal($=>{Fj($.conversationId)||Eg({conversationId:$.conversationId,tabId:$.tabId})}),z=window.electronAPI.browser.onTabClosed($=>{V5($.conversationId,$.tabId)});return window.electronAPI.browser.restoreTabs(),()=>{T(),z()}},[]),m.useEffect(()=>Tf.subscribe((T,z)=>{for(const[$,R]of Object.entries(T.byConversation)){if(z.byConversation[$]===R)continue;const B=R.find(H=>H.status==="running");B&&$5({conversationId:$,runId:B.runId,title:o("Workflow")})}}),[o]),m.useEffect(()=>re.subscribe((T,z)=>{for(const $ of Object.keys(z.conversations))T.conversations[$]||W5($)}),[]);const u=re(T=>T.activeId),[h,p]=m.useState([]),f=re(T=>h.filter(z=>!!T.conversations[z]).join(`
|
|
115
|
-
`)),[g,x]=m.useState(c),[v,y]=m.useState(0),w=n&&!s?$j:yg,b=uj(e,v,w),_=m.useRef(null),[j,N]=m.useState({id:u,from:u});u!==j.id&&N({id:u,from:j.id}),c&&!g&&x(!0),m.useEffect(()=>{const T=_.current?.parentElement;if(!T)return;const z=()=>{const R=getComputedStyle(T);y(T.clientWidth-parseFloat(R.paddingLeft)-parseFloat(R.paddingRight))};z();const $=new ResizeObserver(z);return $.observe(T),()=>$.disconnect()},[]),m.useEffect(()=>{j.from!==j.id&&N(T=>T.from===T.id?T:{...T,from:T.id})},[j.from,j.id]);const C=g?void 0:Math.max(0,b-(a&&!n?1:0)),S=u,A=YK({resizing:t,conversationId:j.id??void 0,previousConversationId:j.from??void 0}),E=c?v||b:a?b:0,I=!!s&&!l;S&&!h.includes(S)&&p(T=>T.includes(S)?T:[...T,S]);const D=f===""?[]:f.split(`
|
|
116
|
-
`);return i.jsxs(i.Fragment,{children:[g&&!l?i.jsx("div",{className:"shrink-0",style:{width:b},"aria-hidden":!0}):null,i.jsxs(Ms.aside,{ref:_,"data-slot":"side-panel",initial:!1,animate:{width:E},style:g?{position:"absolute"}:{position:"relative",maxWidth:`max(0px, calc(100% - ${cj+w}px))`},transition:VT({skip:A,cover:g,targetW:E}),onAnimationComplete:()=>{c||x(!1)},className:q("flex min-h-0 flex-col",I&&a?"overflow-clip [overflow-clip-margin:4px]":"overflow-hidden",a&&(I||!g)?"bg-transparent":I?"":"bg-background",g?I?"top-px right-[8px] bottom-[8px]":n?"top-0 right-[8px] bottom-[8px]":"inset-y-0 right-0":"shrink-0",I?q("no-drag -mt-[44px]",g?"rounded-b-[10px]":"rounded-br-[10px]"):n?q("rounded-[10px]",a&&"shadow-surface"):a&&"border-l"),"data-enso":"side-panel","data-title-row":I||void 0,children:[a&&(I||!g)?i.jsx(rre,{titleRow:I,full:g}):null,a&&!g&&C!==void 0?i.jsx("div",{"aria-hidden":!0,className:q("pointer-events-none absolute right-0 bottom-0 bg-background",s?"top-[44px]":"top-0"),style:{left:C}}):null,i.jsx("div",{className:q("relative flex h-full min-h-0 flex-col",g&&"w-full",!a&&"invisible"),style:{width:C,clipPath:I?g?ore:ire:void 0},children:D.length>0?i.jsx("div",{className:"relative min-h-0 flex-1",children:i.jsx(nP.Provider,{value:I,children:D.map(T=>i.jsx(tre,{conversationId:T,hidden:T!==S},T))})}):i.jsx("div",{className:"flex flex-1 items-center justify-center px-6 text-center text-sm text-muted-foreground",children:o("Select a conversation to use the side panel.")})})]})]})}const ire="shape(from 0 0, hline to 100%, vline to 44px, hline to calc(100% - 10px), arc to 100% 54px of 10px cw, vline to calc(100% - 10px), arc to calc(100% - 10px) 100% of 10px cw, hline to 0, close)",ore="shape(from 0 0, hline to 100%, vline to 44px, hline to calc(100% - 10px), arc to 100% 54px of 10px cw, vline to calc(100% - 10px), arc to calc(100% - 10px) 100% of 10px cw, hline to 10px, arc to 0 calc(100% - 10px) of 10px cw, vline to 54px, arc to 10px 44px of 10px cw, hline to 0, close)";function rre({titleRow:e,full:t}){const n=m.useRef(null),s=gn(o=>o.browserHoles);return m.useLayoutEffect(()=>{const o=n.current;if(!o)return;const{left:r,top:a}=o.getBoundingClientRect(),l=Object.values(s).map(u=>({...u,x:u.x-r,y:u.y-a})),d=rN(l)??"";o.style.clipPath=d;const c=o.closest('[data-enso="side-panel"]');return c&&(d?c.style.setProperty("--enso-side-panel-holes-clip",d):c.style.removeProperty("--enso-side-panel-holes-clip")),()=>{c?.style.removeProperty("--enso-side-panel-holes-clip")}},[s]),i.jsxs(i.Fragment,{children:[e&&i.jsx("div",{"aria-hidden":!0,className:q("pointer-events-none absolute inset-x-0 top-[44px] bottom-0 shadow-surface",t?"rounded-[10px]":"rounded-r-[10px]"),style:t?void 0:{clipPath:"inset(-24px -24px -24px 0)"}}),i.jsx("div",{ref:n,"aria-hidden":!0,className:q("pointer-events-none absolute inset-x-0 bottom-0 bg-background",e?q("top-[44px]",t?"rounded-[10px]":"rounded-r-[10px]"):"top-0")})]})}function Ev(){return Io()&&re.persist.hasHydrated()&&Ce.persist.hasHydrated()}function WC(e,t){Ev()&&e>0&&(async()=>(t&&await re.getState().refreshWorktreeStatuses(),await re.getState().autoArchiveStaleConversations()))()}function UC(e){!Ev()||!(e>0)||re.getState().autoDeleteStaleArchived()}function are(){const e=Ce(s=>s.autoArchiveIdleDays),t=Ce(s=>s.autoArchiveMergedWorktrees),n=Ce(s=>s.autoDeleteArchivedDays);m.useEffect(()=>{if(Ev()){WC(e,t),UC(n);return}const s=()=>{WC(e,t),UC(n)},o=[re.persist.onFinishHydration(s),Ce.persist.onFinishHydration(s)];return()=>{for(const r of o)r()}},[e,t,n])}function lre(){const e=re(t=>Math.min(999,J5(t.order,ov(t.conversations))));m.useEffect(()=>{window.electronAPI.app.setBadgeCount(e)},[e])}function dre(){const e=Ce(n=>n.generationStallTimeoutMin),{t}=Q();m.useEffect(()=>{if(e<=0)return;const n=new Set,s=new Set,o=new Map,r=setInterval(()=>{if(!Io())return;const a=e*6e4,l=Date.now(),d=re.getState();for(const c of Object.values(d.conversations)){c.status==="running"&&c.lastOutputAt&&o.delete(c.id);const u=(c.coworkerIds??[]).some(p=>!!d.conversations[p]?.spawning),h=Q5({shouldAbort:eO({status:c.status,spawning:c.spawning,lastOutputAt:sO(c,d.conversations),now:l,timeoutMs:a,hasLiveWork:tO({...nO(c),spawningCoworker:u})}),status:c.status,spawning:c.spawning,pendingRetry:s.has(c.id),attempts:o.get(c.id)??0});if(h==="abort"){if(n.has(c.id))continue;n.add(c.id),s.add(c.id),window.electronAPI.agent.abort(c.id).finally(()=>{n.delete(c.id)}),Be(KC(c,t("No output for {{minutes}} minutes — retrying",{minutes:e})));continue}if(h==="retry"){s.delete(c.id),o.set(c.id,(o.get(c.id)??0)+1),d.retry(c.id);continue}h==="give-up"&&(s.delete(c.id),o.delete(c.id),Be(KC(c,t("Stopped after repeated stalls"))))}},1e3);return()=>clearInterval(r)},[e,t])}function KC(e,t){const n=(e.coworkerName||e.title).split(`
|
|
117
|
-
`)[0].trim();return n?{type:"warning",title:n,description:t}:{type:"warning",title:t}}async function cre(e,t){const n=[];for(const s of e){const o=t.conversation(s);!o||o.archived||(!o.started&&!o.spawning&&await t.resume(s),!await t.waitUntil(()=>{const a=t.conversation(s);return!!(a?.started&&!a.spawning)})||t.conversation(s)?.status==="running")||(await t.retry(s)).ok&&n.push(s)}return n}const ure=3e4;function qC(e,t=ure){return e()?Promise.resolve(!0):new Promise(n=>{const s=l=>{clearTimeout(a);for(const d of r)d();n(l)},o=()=>e()&&s(!0),r=[re.subscribe(o),Fi.subscribe(o),Ce.subscribe(o)],a=setTimeout(()=>s(e()),t)})}function hre(){const e=Fi.getState().snapshot.availability.status;return re.persist.hasHydrated()&&Ce.persist.hasHydrated()&&e!=="unloaded"&&e!=="loading"}function pre(){const{t:e}=Q();m.useEffect(()=>{Io()&&(async()=>{const t=await window.electronAPI.updater.takeInterruptedSessions().catch(()=>[]);if(t.length===0||!await qC(hre))return;const n=re.getState,s=await cre(t,{conversation:o=>n().conversations[o],resume:o=>n().resumeConversation(o),retry:o=>window.electronAPI.agent.retry(o,{unfinishedOnly:!0}),waitUntil:qC});s.length!==0&&Be({type:"info",title:e("Continued {{count}} conversation(s) interrupted by the update",{count:s.length})})})()},[e])}const YC="enso-win",pP="enso-win-flush",wc="enso-win-pending",XC="enso-win-native";function fre(e,t,n){return{maximized:n.maximized?e.maximized:t.maximized,fullscreen:n.fullscreen?e.fullscreen:t.fullscreen}}function mre(e,t){return e||t}function gre(e,t){document.documentElement.classList.toggle(pP,mre(e,t))}function xre(){m.useEffect(()=>{if(window.electronAPI?.env.platform!=="win32")return;const e=document.documentElement;e.classList.add(YC,wc),e.classList.add(XC);let t={maximized:!1,fullscreen:!1};const n={maximized:0,fullscreen:0};let s=!1,o=0,r;const a=()=>gre(t.maximized,t.fullscreen),l=window.electronAPI.window,d=()=>{const p=++o,f={...n};Promise.all([l.isMaximized(),l.isFullScreen()]).then(([g,x])=>{s||p!==o||(t=fre(t,{maximized:g,fullscreen:x},{maximized:n.maximized!==f.maximized,fullscreen:n.fullscreen!==f.fullscreen}),e.classList.remove(wc),a())}).catch(()=>{!s&&p===o&&e.classList.remove(wc)})};d();const c=()=>{r&&clearTimeout(r),r=setTimeout(d,50)};window.addEventListener("resize",c);const u=l.onMaximizedChange(p=>{n.maximized+=1,t.maximized=p,a()}),h=l.onFullScreenChange(p=>{n.fullscreen+=1,t.fullscreen=p,a()});return()=>{s=!0,r&&clearTimeout(r),window.removeEventListener("resize",c),u(),h(),e.classList.remove(YC,pP,wc,XC)}},[])}function vre(e){return{category:"plugins",rowId:"plugins.enso",pluginId:e}}const df=e=>typeof e=="string"&&e.length>0?e:null;function bre(e){if(!e||typeof e!="object")return null;const t=e,n=df(t.pluginId),s=df(t.name);if(!n||!s)return null;if(t.kind==="inject-denied")return{type:"warning",titleKey:"{{name}} tried to message another session and was blocked",params:{name:s},actionKey:"Turn on",pluginId:n};const o=df(t.version);return o?t.kind==="update-needs-approval"?{type:"warning",titleKey:"{{name}} {{version}} needs new permissions",params:{name:s,version:o},actionKey:"Review permissions",pluginId:n}:t.kind==="auto-updated"?{type:"success",titleKey:"{{name}} updated to {{version}}",params:{name:s,version:o},actionKey:"View",pluginId:n}:null:null}function wre(){const{t:e}=Q();return m.useEffect(()=>window.electronAPI.extensionPlugins.onNotice(t=>{const n=bre(t);n&&Be({type:n.type,title:e(n.titleKey,n.params),...n.actionKey?{actions:[{label:e(n.actionKey),onClick:()=>{window.electronAPI.window.openSettings(vre(n.pluginId))}}]}:{}})}),[e]),null}function yre(e,t){const n=new Set,s=[];for(const o of e)for(const r of o.interceptBreakers??[]){const a=`${o.id}:${r.event}:${r.until}`;n.add(a),t.has(a)||s.push({pluginName:o.name,event:r.event})}t.clear();for(const o of n)t.add(o);return s}function ZC(e){const t=e.permissions.includes("composer.draft")?"1":"0";return`${e.id}\0${e.version}\0${e.build}\0${e.renderer??""}\0${t}`}async function Sre(e,t,n,s){if(!s())return;const o=new Map;for(const a of t)a.state==="enabled"&&a.renderer&&o.set(a.id,{...a,renderer:a.renderer});const r=[];for(const[a,l]of e){const d=o.get(a);(!d||ZC(d)!==l.key)&&r.push(a)}for(const a of r)e.get(a)?.dispose(),e.delete(a);await Promise.allSettled([...o.values()].filter(a=>!e.has(a.id)).map(async a=>{if(!s())return;let l;try{l=await n(a)}catch(u){if(!s())return;console.warn(`[plugin] ${a.id} 渲染模块加载失败`,u);return}if(!s()){l.dispose();return}const d=ZC(a),c=e.get(a.id);if(c?.key===d){l.dispose();return}c?.dispose(),e.set(a.id,{key:d,dispose:()=>l.dispose()})}))}const As=(e,t)=>({ok:!1,code:e,error:t});async function Cre(e,t){if(e.op==="focusSession"){const a=e.payload.sessionId;if(typeof a!="string"||!a)return As("BAD_REQUEST","缺少会话 id");const l=t.conversation(a);if(l)return t.focus(l.parentId??a,a),{ok:!0,value:null};const d=a.indexOf("::");if(d>0){const c=a.slice(0,d);return t.conversation(c)?(t.focusSubagent(c,a),{ok:!0,value:null}):As("NOT_FOUND","会话不在本窗口")}return As("NOT_FOUND","会话不在本窗口")}if(e.op==="openChildRun"){const a=e.payload.parentId,l=e.payload.childId;return typeof a!="string"||!a?As("BAD_REQUEST","缺少父会话 id"):typeof l!="string"||!l?As("BAD_REQUEST","缺少子会话 id"):t.conversation(a)?(t.openChildRun(a,l),{ok:!0,value:null}):As("NOT_FOUND","会话不在本窗口")}if(e.op==="focusSubagent"){const a=e.payload.sessionId,l=e.payload.agentId;return typeof a!="string"||!t.conversation(a)?As("NOT_FOUND","会话不在本窗口"):typeof l!="string"||!l?As("BAD_REQUEST","缺少子代理 id"):(t.focusSubagent(a,l),{ok:!0,value:null})}if(e.op==="ensureSession"){const a=t.conversation(e.sessionId);if(!a)return As("NOT_FOUND","会话不在本窗口");if(a.parentId)return As("UNSUPPORTED","子会话随主会话恢复");const l=await t.ensure(e.sessionId);return l?As("SESSION_FAILED",l):{ok:!0,value:null}}const n=t.conversation(e.sessionId);if(!n)return As("NO_SESSION","发起调用的会话不在本窗口");const s=typeof e.payload.presetId=="string"?e.payload.presetId:void 0,o=await t.create(n.projectId,s);if(!o)return As("CREATE_FAILED","新建会话失败");const r=e.payload.text;return typeof r=="string"&&r&&t.prefill(o,r),{ok:!0,value:{sessionId:o}}}const kre={conversation:e=>re.getState().conversations[e]??null,focus:(e,t)=>{const n=re.getState();n.selectConversation(e),t!==e&&n.selectTab(e,t)},focusSubagent:(e,t)=>re.getState().focusSubagent(e,t),openChildRun:(e,t)=>re.getState().openChildRun(e,t),create:(e,t)=>re.getState().newConversation(e,t?{presetId:t}:void 0),prefill:rO,ensure:async e=>{const t=re.getState(),n=t.conversations[e];if(n?.started||n?.spawning)return null;await t.resumeConversation(e,{fresh:!0});const s=re.getState().conversations[e];return s?.started||s?.spawning?null:s?.error??"无法启动会话:请检查默认模型与登录状态"}};function jre(){return m.useEffect(()=>{const e=lO(()=>XZ(re.getState()));let t=0;const n=new Map,s=new Set,o=()=>{const l=++t;window.electronAPI.extensionPlugins.list().then(async d=>{if(l!==t)return;for(const{pluginName:u,event:h}of yre(d,s))Be({type:"warning",title:`插件 ${u} 的检查连续失败,已临时放行`,description:`${h} 事件 30 秒内不再经过该插件;详情见设置里的插件日志`});const c=d.filter(u=>u.state==="enabled");oO(Object.fromEntries(d.flatMap(u=>u.icon?[[u.id,u.icon]]:[]))),fS(c.flatMap(u=>iJ(u.commands,u.dynamicCommands).map(h=>({pluginId:u.id,pluginName:u.name,...h})))),g0(c.flatMap(u=>u.views.map(h=>({pluginId:u.id,pluginName:u.name,...h})))),vS(c.flatMap(u=>u.triggers.filter(h=>h.symbol==="#").map(h=>({pluginId:u.id,name:h.name})))),await Sre(n,d,u=>aO(u.id,u.renderer,e,{draft:u.permissions.includes("composer.draft")}),()=>l===t)})};o();const r=window.electronAPI.extensionPlugins.onChanged(o),a=window.electronAPI.extensionPlugins.onDraftRequest(l=>{if(l.op==="focusSession"||l.op==="focusSubagent"||l.op==="openChildRun"||l.op==="createSession"||l.op==="ensureSession"){Cre(l,kre).catch(d=>({ok:!1,code:"SESSION_FAILED",error:d instanceof Error?d.message:String(d)})).then(d=>window.electronAPI.extensionPlugins.respondDraft({requestId:l.requestId,...d}));return}window.electronAPI.extensionPlugins.respondDraft({requestId:l.requestId,...iO(l)})});return()=>{t+=1,r(),a(),fS([]),vS([]),g0([]);for(const l of n.values())l.dispose();n.clear()}},[]),null}function _re(e,t=[]){return JSON.stringify({pinnedOrder:t,entries:e.map(n=>{const{updatedAt:s,...o}=n;return o})})}function Nre(e){return JSON.stringify(e)}function Tre(e,t,n=[]){const s=dO(e,t).map(r=>({id:r.id,name:r.name,models:r.models.map(a=>({id:a.id,...a.label?{label:a.label}:{}}))})),o=n.filter(r=>r.enabled&&s.some(a=>a.id===r.primary.providerId&&a.models.some(l=>l.id===r.primary.modelId)));return o.length>0&&s.unshift({id:_j,name:"Auto",models:o.map(r=>({id:r.id,label:r.name}))}),s}function Dre(e,t,n=[]){const s=Tre(e,t,n),o=t.availability.status,r=o==="unloaded"||o==="loading",a=e.some(l=>l.enabled&&l.oauthAccountKey);return{entries:s,settled:!(r&&a&&s.length===0)}}const Ire=300;let yc=null,JC=!1,og=null;function Ere(){const e=Ce.getState(),t=re.getState(),n=pv(e.projects,ur(Uc)),s=new Set(e.projects.filter(b=>b.kind==="scratch").map(b=>b.id)),o=n.filter(b=>b.kind!=="scratch"),r=new Set(ur(el)),a=hO(pO(e.language),"Temporary chats"),l=new Map(e.projects.map(b=>[b.id,b.kind==="scratch"?a:Po(b)])),d=new Map(e.projects.map(b=>[b.id,b.path])),c=new Map(e.projects.map(b=>[b.id,b.kind])),u=b=>{const _=(b.parentId?t.conversations[b.parentId]:void 0)??b;return c.get(_.projectId)==="scratch"?Pg({kind:"scratch",canonicalPath:d.get(_.projectId)??"",conversationId:_.id})??void 0:_.worktree?.path??d.get(b.projectId)},h=e.skills.filter(b=>b.enabled!==!1).map(b=>({name:`/skill:${b.name}`,description:b.description})),p=b=>{const _=kI(b.occupancy,b.contextWindow);return{id:b.id,title:b.parentId&&b.coworkerName||b.title,projectName:l.get(b.projectId)??"",projectId:b.projectId,...u(b)?{cwd:u(b)}:{},status:b.spawning?"running":b.status,updatedAt:Wj(b),...b.parentId?{parentId:b.parentId}:{},...b.pinned===!0?{pinned:!0}:{},...b.archived===!0?{archived:!0}:{},...b.lastProviderId?{providerId:b.lastProviderId}:{},...b.lastModelId?{modelId:b.lastModelId}:{},...b.reasoningEnabled!==void 0?{reasoningEnabled:b.reasoningEnabled}:{},...b.thinkingLevel?{thinkingLevel:b.thinkingLevel}:{},...b.unread===!0?{unread:!0}:{},...b.pendingAsks&&b.pendingAsks.length>0?{pendingAskCount:b.pendingAsks.length}:{},...b.pendingApprovals&&b.pendingApprovals.length>0?{pendingApprovalCount:b.pendingApprovals.length}:{},...b.queuedMessages?.length?{queued:b.queuedMessages.map(j=>({id:j.id,text:j.text,...j.images?.length?{hasImages:!0}:{}}))}:{},...b.goal?{goal:{text:b.goal.text,status:b.goal.status,...b.goal.note?{note:b.goal.note}:{},autoTurns:b.goal.autoTurns}}:{},...h.length?{slashCommands:h}:{},..._?{context:_}:{},...b.usageTotals?{usageTotals:b.usageTotals}:{}}},f=t.order.map(b=>t.conversations[b]).filter(b=>!!b),g=new Set(t.order),x=Object.values(t.conversations).filter(b=>!!(b?.parentId&&g.has(b.parentId))),v=[...f,...x].map(p),y=e.scratchSessionsEnabled?v:v.filter(b=>!s.has(b.projectId)),w=Dre(Vj(),Fi.getState().snapshot,e.virtualModels);return{catalog:y,pinnedOrder:ur(Bm),projects:o.map(b=>({...lte(b),...r.has(b.id)?{archived:!0}:{}})),projectGroups:e.projectGroups,providers:w.entries,providersSettled:w.settled,projectPaths:e.projects.map(b=>({id:b.id,path:b.path})),theme:e.theme,terminal:$u(e.terminalTheme),terminalFontFamily:e.terminalFontFamily,compactReadOnlyTools:e.compactReadOnlyTools,expandLiveEdits:e.expandLiveEdits,expandLiveReasoning:e.expandLiveReasoning,autoCollapseTurns:e.autoCollapseTurns,collapseCompletedActivity:e.collapseCompletedActivity,collapseLiveActivity:e.collapseLiveActivity,pinUnfinishedTodos:e.pinUnfinishedTodos}}function Pre(e){return Nre({catalog:_re(e.catalog,e.pinnedOrder??[]),projects:e.projects,projectGroups:e.projectGroups,providers:e.providers,providersSettled:e.providersSettled,projectPaths:e.projectPaths,theme:e.theme,terminal:e.terminal,terminalFontFamily:e.terminalFontFamily,compactReadOnlyTools:e.compactReadOnlyTools,expandLiveEdits:e.expandLiveEdits,expandLiveReasoning:e.expandLiveReasoning,autoCollapseTurns:e.autoCollapseTurns,collapseCompletedActivity:e.collapseCompletedActivity,collapseLiveActivity:e.collapseLiveActivity,pinUnfinishedTodos:e.pinUnfinishedTodos})}function Are(){return re.persist.hasHydrated()&&Ce.persist.hasHydrated()}function Qi(){yc&&clearTimeout(yc),yc=setTimeout(()=>{if(yc=null,!Io()||!Are())return;const e=Ere(),t=Pre(e);t!==og&&(og=t,window.electronAPI.pair.pushCatalog(e))},Ire)}function Mre(){JC||(JC=!0,Qi(),re.persist.onFinishHydration(Qi),Ce.persist.onFinishHydration(Qi),re.subscribe((e,t)=>{(e.conversations!==t.conversations||e.order!==t.order)&&Qi()}),Fi.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),cO.subscribe((e,t)=>{e.snapshot!==t.snapshot&&Qi()}),Ce.subscribe((e,t)=>{(e.projects!==t.projects||e.projectGroups!==t.projectGroups||e.providers!==t.providers||e.theme!==t.theme||e.terminalTheme!==t.terminalTheme||e.terminalFontFamily!==t.terminalFontFamily||e.compactReadOnlyTools!==t.compactReadOnlyTools||e.expandLiveEdits!==t.expandLiveEdits||e.expandLiveReasoning!==t.expandLiveReasoning||e.autoCollapseTurns!==t.autoCollapseTurns||e.collapseCompletedActivity!==t.collapseCompletedActivity||e.collapseLiveActivity!==t.collapseLiveActivity||e.pinUnfinishedTodos!==t.pinUnfinishedTodos||e.skills!==t.skills)&&Qi()}),Uee(Qi),uO(e=>{e&&(og=null,Qi())}),window.electronAPI.pair.onResumeSession(e=>{x0(e),Io()&&(re.getState().markConversationRead(e),re.getState().resumeConversation(e))}),window.electronAPI.pair.onSessionCreated(e=>{x0(e.sessionId),Io()&&re.getState().adoptPairSession(e)}),window.electronAPI.pair.onSessionConfig(e=>{if(!Io())return;const t=re.getState();e.type==="set-model"?t.setModel(e.sessionId,e.providerId,e.modelId):e.type==="set-reasoning"?t.setReasoning(e.sessionId,e.enabled):t.setThinking(e.sessionId,e.level)}),window.electronAPI.pair.onQueueAction(e=>{if(!Io())return;const t=re.getState();switch(e.type){case"enqueue":t.enqueueMessage(e.sessionId,e.text,e.images);break;case"queue-remove":t.removeQueuedMessage(e.sessionId,e.messageId);break;case"queue-update":t.updateQueuedMessage(e.sessionId,e.messageId,e.text);break;case"queue-send-now":t.sendQueuedNow(e.sessionId,e.messageId);break;case"queue-interrupt-send":t.interruptAndSendQueued(e.sessionId,e.messageId);break;case"goal-pause":t.pauseGoal(e.sessionId);break;case"goal-resume":t.resumeGoal(e.sessionId);break;case"goal-clear":t.clearGoal(e.sessionId);break;case"goal-set":t.setGoal(e.sessionId,e.text);break;case"compact":t.compact(e.sessionId,e.instructions);break;case"rewind":t.rewind(e.sessionId,e.userIndexFromEnd,e.restoreFiles);break;case"retry":t.retry(e.sessionId);break;case"task-stop":window.electronAPI.agent.stopTask(e.sessionId,e.taskId);break;case"subagent-stop":window.electronAPI.agent.stopSubagent(e.sessionId,e.agentId);break}}))}const Rre=3e4;async function Lre(e,t=Date.now()){const{order:n,conversations:s,activeId:o}=re.getState(),r=n.flatMap(u=>{const h=s[u];return!h||h.parentId?[]:(u===o||h.status==="running"||h.spawning===!0||h.workspaceMigrating===!0||(h.pendingAsks?.length??0)>0||(h.pendingApprovals?.length??0)>0)&&e.kind==="stale"?[]:[{id:u,projectId:h.projectId,archived:h.archived,archivedAt:h.archivedAt,pinned:h.pinned,lastActiveAt:Wj(h)}]}),a=fO(r,e,t),l=re.getState();for(const u of a)l.removeConversation(u);const d=Date.now()+Rre,c=()=>a.filter(u=>re.getState().conversations[u]);for(;c().length>0&&Date.now()<d;)await new Promise(u=>setTimeout(u,200));return a.length-c().length}const Ore=e=>{const t=tz(e);return t.length>0?t:Xj(e)},QC="enso-sidebar-width",ek="enso-sidebar-collapsed";function cf(){const e=re.getState(),n=(e.activeId?e.conversations[e.activeId]:null)?.projectId??Ce.getState().projects[0]?.id;n&&e.newConversation(n)}const Sc="no-drag flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",tk=200,nk=420;function zre(){const e=Ce(G=>G.onboarded),t=m.useSyncExternalStore(G=>Ce.persist?.onFinishHydration?.(G)??(()=>{}),()=>Ce.persist?.hasHydrated?.()??!0);mO(),dre(),are(),pre(),lre();const[n,s]=m.useState(!1),[o,r]=m.useState(null);xre();const[a,l]=m.useState(()=>{const G=Number(localStorage.getItem(QC));return Number.isFinite(G)&&G>=tk?Math.min(G,nk):280}),[d,c]=m.useState(()=>localStorage.getItem(ek)==="1"),u=ba(),h=gO(),[p,f]=m.useState(!1),g=m.useCallback(()=>f(!1),[]);m.useEffect(()=>{u||f(!1)},[u]),m.useEffect(()=>re.subscribe((G,de)=>{G.activeId!==de.activeId&&f(!1)}),[]);const{t:x}=Q(),v=Ce(G=>G.chatWide),y=re(G=>G.activeId),w=gn(G=>y?!!G.uiByConversation[y]?.open:!1),b=gn(G=>G.uiByConversation[y??""]?.width??G.lastWidth),_=gn(G=>G.fullscreen),j=gn(G=>G.toggleOpen),N=ce(G=>G.panelOpen),C=ce(G=>G.togglePanel);m.useEffect(()=>{_&&!w&&gn.getState().setFullscreen(!1)},[w,_]),m.useEffect(()=>(document.documentElement.classList.add("enso-main-shell"),()=>document.documentElement.classList.remove("enso-main-shell")),[]),m.useEffect(()=>window.electronAPI.app.onCloseRequest(r),[]),m.useEffect(()=>window.electronAPI.app.onFlushPersist(G=>{xO().finally(()=>{window.electronAPI.app.respondFlushPersist(G)})}),[]);const S=G=>{const de=o;de&&(r(null),window.electronAPI.app.respondCloseRequest(de,{action:G}))},[A,E]=m.useState(!1),I=m.useRef(null);m.useEffect(()=>{localStorage.setItem(QC,String(a))},[a]),m.useEffect(()=>{localStorage.setItem(ek,d?"1":"0")},[d]),m.useEffect(()=>window.electronAPI.window.onAgentComposerPrefill(G=>{re.getState().prefillAgent(G.typeKey,G.prompt)}),[]),m.useEffect(()=>window.electronAPI.resources.onSessionsCleanRequest(({requestId:G,request:de})=>{Lre(de).catch(()=>0).then(X=>window.electronAPI.resources.sessionsCleanDone(G,X))}),[]),m.useEffect(()=>{Mre()},[]),m.useEffect(()=>ts.getState().bind(),[]);const D=ts(G=>G.activeNodeId),T=D!=="local",z=OZ(),$=Ce(G=>G.botModeEnabled),R=lo(G=>G.mode);m.useEffect(()=>{const G=Ce.persist?.hasHydrated?.()??!0;R==="bot"&&(G&&!$||T)&&lo.getState().setMode("code")},[R,$,T]),m.useEffect(()=>{if(!$)return;const G=ce.getState().bind(),de=window.electronAPI.bots.onEvent(X=>{X.kind==="open"&&zZ(X)});return()=>{G(),de()}},[$]),m.useEffect(()=>window.electronAPI.agent.onFocusSession(G=>{re.getState().conversations[G]&&GZ()}),[]);const B=m.useCallback(G=>{l(de=>Math.min(nk,Math.max(tk,de+G)))},[]),H=Ce(G=>G.keybindings);m.useEffect(()=>{const G=Ai(H),de=ie=>{const Z=re.getState(),le=Z.activeId?Z.conversations[Z.activeId]:null;if(!le)return;const be=[void 0,...le.coworkerIds??[]];if(be.length<=1)return;const Fe=be.indexOf(le.activeTabId);Z.selectTab(le.id,be[(Fe+ie+be.length)%be.length])},X=ie=>{const Z=Il(ie);if(!Z)return;if(Z===G["toggle-app-mode"]){if(!Ce.getState().botModeEnabled||ts.getState().activeNodeId!=="local")return;ie.preventDefault();const Fe=lo.getState();Fe.setMode(Fe.mode==="bot"?"code":"bot");return}const le=ts.getState().activeNodeId!=="local"||Qd();if(Qd()&&Z===G["toggle-side-panel"]){ie.preventDefault(),ce.getState().togglePanel();return}if(Qd()&&Z===G["search-workspace"]){ie.preventDefault(),ce.getState().setSearchOpen(!0);return}le&&["new-conversation","next-tab","prev-tab","toggle-side-panel","toggle-side-panel-fullscreen","new-side-tab","new-btw-tab","close-side-tab","find-in-chat","search-workspace"].some(be=>Z===G[be])||(Z===G["toggle-sidebar"]?(ie.preventDefault(),SO(window.innerWidth)?f(be=>!be):c(be=>!be)):Z===G["open-settings"]?(ie.preventDefault(),window.electronAPI.window.openSettings()):Z===G["new-conversation"]?(ie.preventDefault(),cf()):Z===G["new-side-tab"]?(ie.preventDefault(),CO(ie.target)?kO():cf()):Z===G["new-btw-tab"]?(ie.preventDefault(),jO()):Z===G["next-tab"]?(ie.preventDefault(),de(1)):Z===G["prev-tab"]?(ie.preventDefault(),de(-1)):Z===G["toggle-side-panel"]?(ie.preventDefault(),gn.getState().toggleOpen()):Z===G["toggle-side-panel-fullscreen"]?(ie.preventDefault(),gn.getState().toggleFullscreen()):Z===G["close-side-tab"]?(ie.preventDefault(),_O()):Z===G["focus-composer"]?(ie.preventDefault(),wo()):Z===G["find-in-chat"]?(ie.preventDefault(),rI()):Z===G["search-workspace"]&&(ie.preventDefault(),s(!0)))};return window.addEventListener("keydown",X),()=>window.removeEventListener("keydown",X)},[H]),m.useEffect(()=>{if(!w||!_)return;const G=de=>{de.key==="Escape"&&ts.getState().activeNodeId==="local"&&(Qd()||(de.preventDefault(),gn.getState().setFullscreen(!1)))};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[w,_]);const oe=UO(WO(zg,{activationConstraint:{distance:6}})),te=Zu(),O=te!=="mobile"&&!T&&!z,V=m.useCallback(G=>{const de=I.current;if(!de)return;const X=getComputedStyle(de),ie=de.clientWidth-parseFloat(X.paddingLeft)-parseFloat(X.paddingRight);gn.getState().nudgeWidth(-G,ie,O?$j:yg)},[O]),J=$&&!T?i.jsx($Z,{}):null,pe=O&&(te==="mac"||te==="windows"||te==="web"),fe=pe&&w&&!u&&!z&&!T,_e=T?null:i.jsx("button",{type:"button",className:q("flex items-center justify-center rounded-md transition-colors hover:bg-accent/50",u?"h-9 w-9":O?Sc:"h-7 w-7",(z?N:w)?"text-foreground":"text-muted-foreground"),onClick:z?C:j,"aria-label":x("Toggle side panel"),title:x("Toggle side panel"),children:i.jsx(nN,{className:"h-4 w-4"})}),Ee=i.jsx("button",{type:"button",className:q("flex h-7 w-7 items-center justify-center rounded-md transition-colors hover:bg-accent/50",v?"text-foreground":"text-muted-foreground",u&&"hidden"),onClick:()=>Ce.getState().setChatWide(!v),"aria-label":x(v?"Use reading width":"Use full chat width"),title:x(v?"Use reading width":"Use full chat width"),children:v?i.jsx(l$,{className:"h-4 w-4"}):i.jsx(m6,{className:"h-4 w-4"})}),me=i.jsxs(i.Fragment,{children:[Ee,_e]}),W=O?{trailing:Ee}:null;return i.jsxs("div",{"data-enso":"canvas",className:q("relative isolate flex flex-col",u?"h-dvh":"h-screen"),children:[i.jsx(vO,{}),i.jsx(wre,{}),i.jsx(H6,{}),i.jsx(bO,{}),te!=="mobile"?i.jsx(v0,{leading:i.jsxs("div",{className:"flex items-center gap-0.5",children:[!T&&i.jsx("div",{className:q(te!=="mac"&&"flex justify-center",te!=="mac"&&(O?"w-[48px]":"w-12")),children:i.jsx("button",{type:"button",className:Sc,onClick:()=>c(G=>!G),title:x(d?"Expand sidebar":"Collapse sidebar"),children:d?i.jsx(tN,{className:"h-4 w-4"}):i.jsx(wx,{className:"h-4 w-4"})})}),O&&i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button",className:Sc,onClick:()=>s(!0),title:x("Search anything"),children:i.jsx(ti,{className:"h-4 w-4"})}),i.jsx("button",{type:"button",className:Sc,onClick:cf,title:x("New conversation"),children:i.jsx(sN,{className:"h-4 w-4"})})]})]}),centered:(fe&&_?null:J)??void 0,className:q(te!=="mac"&&!T&&"pl-0",O&&"border-b-0",O&&"bg-transparent",O&&te==="mac"&&"pr-4"),actions:O?fe?void 0:_e:me}):i.jsx(v0,{title:"EnsoCode",centered:J??void 0,leading:u&&!T&&!z?i.jsxs("div",{className:"flex items-center gap-1.5",children:[i.jsx("button",{type:"button",className:"-ml-1.5 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground",onClick:()=>f(!0),"aria-label":x("Conversations"),title:x("Conversations"),children:i.jsx(L$,{className:"h-5 w-5"})}),!J&&i.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:"EnsoCode"})]}):void 0,actions:me}),!O&&i.jsx(iw,{}),!O&&i.jsx(ow,{}),i.jsx("div",{className:"flex min-h-0 flex-1",children:T?i.jsx(gte,{nodeId:D,sidebarWidth:a}):z?i.jsx(LZ,{sidebarWidth:a,collapsed:d,onToggleCollapse:()=>c(G=>!G),onResize:B}):i.jsxs(Kz,{sensors:oe,collisionDetection:Ore,children:[u?i.jsxs(i.Fragment,{children:[i.jsx(hl,{children:p&&i.jsx(Ms.div,{className:"fixed inset-0 bg-black/40",style:{zIndex:kn.MOBILE_DRAWER},initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:g},"drawer-backdrop")}),i.jsx(Ms.div,{className:"fixed inset-y-0 left-0 flex bg-background shadow-xl",style:{zIndex:kn.MOBILE_DRAWER},initial:!1,animate:{x:p?0:"-105%"},transition:Jr,inert:!p,children:i.jsx($S,{width:Math.min(320,Math.round(h*.85)),collapsed:!1,onToggleCollapse:g,onOpenSearch:()=>s(!0),onNavigate:g})})]}):i.jsxs(i.Fragment,{children:[i.jsx($S,{width:d?void 0:a,collapsed:d,onToggleCollapse:()=>c(G=>!G),onOpenSearch:()=>s(!0)}),!d&&i.jsx(wu,{edge:O,onResize:B})]}),i.jsxs("div",{ref:I,className:q("relative flex min-h-0 min-w-0 flex-1",pe?"overflow-x-clip":"overflow-hidden",O&&"-mt-px -ml-px pt-px pr-[8px] pb-[8px] pl-px"),children:[i.jsxs("div",{"data-enso":"main",className:q("flex min-h-0 min-w-0 flex-1 flex-col bg-background",O&&"overflow-hidden rounded-[10px] shadow-surface",fe&&"rounded-r-none"),style:w&&_?{visibility:"hidden",transition:`visibility 0s ${Nu.duration}s`}:void 0,children:[i.jsx(jre,{}),i.jsx(wO.Provider,{value:W,children:i.jsx(uee,{})}),O&&i.jsx(iw,{}),O&&i.jsx(ow,{})]}),w&&!_&&!u&&i.jsx(wu,{gap:O&&!fe,onResize:V,onResizingChange:E}),i.jsx(sre,{width:b,resizing:A,card:O,titleRow:pe})]})]})}),t&&!e&&!window.electronAPI.remote&&i.jsx(vte,{}),i.jsx(Hte,{open:n,onOpenChange:s}),i.jsx(Dj,{open:o!==null,onOpenChange:G=>{!G&&o&&S("cancel")},children:i.jsxs(Ij,{className:"sm:max-w-sm",children:[i.jsxs(Ej,{children:[i.jsx(Pj,{className:"text-base",children:x("Confirm exit")}),i.jsx(Aj,{children:x("Exit closes the app completely, so your phone can no longer connect. Minimize to tray keeps the app running in the background so your phone can still connect.")})]}),i.jsxs(Mj,{variant:"bare",children:[i.jsx(yO,{render:i.jsx(ge,{variant:"outline",size:"sm"}),children:x("Cancel")}),i.jsx(ge,{size:"sm",onClick:()=>S("tray"),children:x("Minimize to tray")}),i.jsx(ge,{variant:"destructive",size:"sm",onClick:()=>S("quit"),children:x("Exit")})]})]})})]})}function Gre(e){return new Worker(""+new URL("worker-DsKBD11i.js",import.meta.url).href,{type:"module",name:e?.name})}const Fre={workerFactory:()=>new Gre,poolSize:2},Hre={theme:xa,langs:[...TO],preferredHighlighter:"shiki-js"};function Bre({children:e}){return i.jsx(NO,{poolOptions:Fre,highlighterOptions:Hre,children:e})}const sk=["idle","running","waiting","error"];function fP(e,t){if(!e)return"idle";const n=Dg({status:e.status??"idle",spawning:e.spawning,pendingAskCount:(e.pendingAsks?.length??0)+(e.pendingApprovals?.length??0)+(e.pendingCapabilityAsks?.length??0),hasRunningChild:kg({...e,status:e.status??"idle"},t)});return n==="failed"?"error":n==="unread"?"idle":n}function Vre(e){let t=0;for(const n of Object.values(e))!n||n.parentId||n.btwParentId||(t=Math.max(t,sk.indexOf(fP(n,e))));return sk[t]}function ik({conversations:e,activeId:t}){const n=document.documentElement.dataset,s=Vre(e),o=fP(t?e[t]:void 0,e);n.ensoActivity!==s&&(n.ensoActivity=s),n.ensoSession!==o&&(n.ensoSession=o)}function $re(){ik(re.getState()),re.subscribe((e,t)=>{(e.conversations!==t.conversations||e.activeId!==t.activeId)&&ik(e)})}DO();$re();IO();zk();EO.createRoot(document.getElementById("root")).render(i.jsx(m.StrictMode,{children:i.jsx(Bre,{children:i.jsx(zre,{})})}));
|